• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #ifdef HAVE_LIBELF
47 #include <libelf.h>
48 #include <gelf.h>
49 #endif
50 
51 #include <zlib.h>
52 
53 #include "libbpf.h"
54 #include "bpf.h"
55 #include "btf.h"
56 #include "str_error.h"
57 #include "libbpf_internal.h"
58 #include "hashmap.h"
59 #include "bpf_gen_internal.h"
60 
61 #ifdef HAVE_ELFIO
62 #include "elfio_c_wrapper.h"
63 #include <linux/memfd.h>
64 #include <sys/syscall.h>
65 #include <limits.h>
66 
67 typedef struct Elf64_Ehdr Elf64_Ehdr;
68 typedef struct Elf64_Shdr Elf64_Shdr;
69 typedef struct Elf64_Sym Elf64_Sym;
70 typedef struct Elf64_Rel Elf64_Rel;
71 typedef struct {
72   void *d_buf;
73   size_t d_size;
74 } Elf_Data;
75 
76 #define ELF64_ST_TYPE(val) ELF_ST_TYPE (val)
77 #define ELF64_ST_BIND(val) ELF_ST_BIND (val)
78 #define elf_errmsg(val) "error"
79 
80 #endif
81 
82 
83 #ifndef BPF_FS_MAGIC
84 #define BPF_FS_MAGIC		0xcafe4a11
85 #endif
86 
87 #define BPF_INSN_SZ (sizeof(struct bpf_insn))
88 
89 /* vsprintf() in __base_pr() uses nonliteral format string. It may break
90  * compilation if user enables corresponding warning. Disable it explicitly.
91  */
92 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
93 
94 #define __printf(a, b)	__attribute__((format(printf, a, b)))
95 
96 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj);
97 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog);
98 
99 static const char * const attach_type_name[] = {
100 	[BPF_CGROUP_INET_INGRESS]	= "cgroup_inet_ingress",
101 	[BPF_CGROUP_INET_EGRESS]	= "cgroup_inet_egress",
102 	[BPF_CGROUP_INET_SOCK_CREATE]	= "cgroup_inet_sock_create",
103 	[BPF_CGROUP_INET_SOCK_RELEASE]	= "cgroup_inet_sock_release",
104 	[BPF_CGROUP_SOCK_OPS]		= "cgroup_sock_ops",
105 	[BPF_CGROUP_DEVICE]		= "cgroup_device",
106 	[BPF_CGROUP_INET4_BIND]		= "cgroup_inet4_bind",
107 	[BPF_CGROUP_INET6_BIND]		= "cgroup_inet6_bind",
108 	[BPF_CGROUP_INET4_CONNECT]	= "cgroup_inet4_connect",
109 	[BPF_CGROUP_INET6_CONNECT]	= "cgroup_inet6_connect",
110 	[BPF_CGROUP_INET4_POST_BIND]	= "cgroup_inet4_post_bind",
111 	[BPF_CGROUP_INET6_POST_BIND]	= "cgroup_inet6_post_bind",
112 	[BPF_CGROUP_INET4_GETPEERNAME]	= "cgroup_inet4_getpeername",
113 	[BPF_CGROUP_INET6_GETPEERNAME]	= "cgroup_inet6_getpeername",
114 	[BPF_CGROUP_INET4_GETSOCKNAME]	= "cgroup_inet4_getsockname",
115 	[BPF_CGROUP_INET6_GETSOCKNAME]	= "cgroup_inet6_getsockname",
116 	[BPF_CGROUP_UDP4_SENDMSG]	= "cgroup_udp4_sendmsg",
117 	[BPF_CGROUP_UDP6_SENDMSG]	= "cgroup_udp6_sendmsg",
118 	[BPF_CGROUP_SYSCTL]		= "cgroup_sysctl",
119 	[BPF_CGROUP_UDP4_RECVMSG]	= "cgroup_udp4_recvmsg",
120 	[BPF_CGROUP_UDP6_RECVMSG]	= "cgroup_udp6_recvmsg",
121 	[BPF_CGROUP_GETSOCKOPT]		= "cgroup_getsockopt",
122 	[BPF_CGROUP_SETSOCKOPT]		= "cgroup_setsockopt",
123 	[BPF_SK_SKB_STREAM_PARSER]	= "sk_skb_stream_parser",
124 	[BPF_SK_SKB_STREAM_VERDICT]	= "sk_skb_stream_verdict",
125 	[BPF_SK_SKB_VERDICT]		= "sk_skb_verdict",
126 	[BPF_SK_MSG_VERDICT]		= "sk_msg_verdict",
127 	[BPF_LIRC_MODE2]		= "lirc_mode2",
128 	[BPF_FLOW_DISSECTOR]		= "flow_dissector",
129 	[BPF_TRACE_RAW_TP]		= "trace_raw_tp",
130 	[BPF_TRACE_FENTRY]		= "trace_fentry",
131 	[BPF_TRACE_FEXIT]		= "trace_fexit",
132 	[BPF_MODIFY_RETURN]		= "modify_return",
133 	[BPF_LSM_MAC]			= "lsm_mac",
134 	[BPF_LSM_CGROUP]		= "lsm_cgroup",
135 	[BPF_SK_LOOKUP]			= "sk_lookup",
136 	[BPF_TRACE_ITER]		= "trace_iter",
137 	[BPF_XDP_DEVMAP]		= "xdp_devmap",
138 	[BPF_XDP_CPUMAP]		= "xdp_cpumap",
139 	[BPF_XDP]			= "xdp",
140 	[BPF_SK_REUSEPORT_SELECT]	= "sk_reuseport_select",
141 	[BPF_SK_REUSEPORT_SELECT_OR_MIGRATE]	= "sk_reuseport_select_or_migrate",
142 	[BPF_PERF_EVENT]		= "perf_event",
143 	[BPF_TRACE_KPROBE_MULTI]	= "trace_kprobe_multi",
144 };
145 
146 static const char * const link_type_name[] = {
147 	[BPF_LINK_TYPE_UNSPEC]			= "unspec",
148 	[BPF_LINK_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
149 	[BPF_LINK_TYPE_TRACING]			= "tracing",
150 	[BPF_LINK_TYPE_CGROUP]			= "cgroup",
151 	[BPF_LINK_TYPE_ITER]			= "iter",
152 	[BPF_LINK_TYPE_NETNS]			= "netns",
153 	[BPF_LINK_TYPE_XDP]			= "xdp",
154 	[BPF_LINK_TYPE_PERF_EVENT]		= "perf_event",
155 	[BPF_LINK_TYPE_KPROBE_MULTI]		= "kprobe_multi",
156 	[BPF_LINK_TYPE_STRUCT_OPS]		= "struct_ops",
157 };
158 
159 static const char * const map_type_name[] = {
160 	[BPF_MAP_TYPE_UNSPEC]			= "unspec",
161 	[BPF_MAP_TYPE_HASH]			= "hash",
162 	[BPF_MAP_TYPE_ARRAY]			= "array",
163 	[BPF_MAP_TYPE_PROG_ARRAY]		= "prog_array",
164 	[BPF_MAP_TYPE_PERF_EVENT_ARRAY]		= "perf_event_array",
165 	[BPF_MAP_TYPE_PERCPU_HASH]		= "percpu_hash",
166 	[BPF_MAP_TYPE_PERCPU_ARRAY]		= "percpu_array",
167 	[BPF_MAP_TYPE_STACK_TRACE]		= "stack_trace",
168 	[BPF_MAP_TYPE_CGROUP_ARRAY]		= "cgroup_array",
169 	[BPF_MAP_TYPE_LRU_HASH]			= "lru_hash",
170 	[BPF_MAP_TYPE_LRU_PERCPU_HASH]		= "lru_percpu_hash",
171 	[BPF_MAP_TYPE_LPM_TRIE]			= "lpm_trie",
172 	[BPF_MAP_TYPE_ARRAY_OF_MAPS]		= "array_of_maps",
173 	[BPF_MAP_TYPE_HASH_OF_MAPS]		= "hash_of_maps",
174 	[BPF_MAP_TYPE_DEVMAP]			= "devmap",
175 	[BPF_MAP_TYPE_DEVMAP_HASH]		= "devmap_hash",
176 	[BPF_MAP_TYPE_SOCKMAP]			= "sockmap",
177 	[BPF_MAP_TYPE_CPUMAP]			= "cpumap",
178 	[BPF_MAP_TYPE_XSKMAP]			= "xskmap",
179 	[BPF_MAP_TYPE_SOCKHASH]			= "sockhash",
180 	[BPF_MAP_TYPE_CGROUP_STORAGE]		= "cgroup_storage",
181 	[BPF_MAP_TYPE_REUSEPORT_SOCKARRAY]	= "reuseport_sockarray",
182 	[BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE]	= "percpu_cgroup_storage",
183 	[BPF_MAP_TYPE_QUEUE]			= "queue",
184 	[BPF_MAP_TYPE_STACK]			= "stack",
185 	[BPF_MAP_TYPE_SK_STORAGE]		= "sk_storage",
186 	[BPF_MAP_TYPE_STRUCT_OPS]		= "struct_ops",
187 	[BPF_MAP_TYPE_RINGBUF]			= "ringbuf",
188 	[BPF_MAP_TYPE_INODE_STORAGE]		= "inode_storage",
189 	[BPF_MAP_TYPE_TASK_STORAGE]		= "task_storage",
190 	[BPF_MAP_TYPE_BLOOM_FILTER]		= "bloom_filter",
191 	[BPF_MAP_TYPE_USER_RINGBUF]             = "user_ringbuf",
192 	[BPF_MAP_TYPE_CGRP_STORAGE]		= "cgrp_storage",
193 };
194 
195 static const char * const prog_type_name[] = {
196 	[BPF_PROG_TYPE_UNSPEC]			= "unspec",
197 	[BPF_PROG_TYPE_SOCKET_FILTER]		= "socket_filter",
198 	[BPF_PROG_TYPE_KPROBE]			= "kprobe",
199 	[BPF_PROG_TYPE_SCHED_CLS]		= "sched_cls",
200 	[BPF_PROG_TYPE_SCHED_ACT]		= "sched_act",
201 	[BPF_PROG_TYPE_TRACEPOINT]		= "tracepoint",
202 	[BPF_PROG_TYPE_XDP]			= "xdp",
203 	[BPF_PROG_TYPE_PERF_EVENT]		= "perf_event",
204 	[BPF_PROG_TYPE_CGROUP_SKB]		= "cgroup_skb",
205 	[BPF_PROG_TYPE_CGROUP_SOCK]		= "cgroup_sock",
206 	[BPF_PROG_TYPE_LWT_IN]			= "lwt_in",
207 	[BPF_PROG_TYPE_LWT_OUT]			= "lwt_out",
208 	[BPF_PROG_TYPE_LWT_XMIT]		= "lwt_xmit",
209 	[BPF_PROG_TYPE_SOCK_OPS]		= "sock_ops",
210 	[BPF_PROG_TYPE_SK_SKB]			= "sk_skb",
211 	[BPF_PROG_TYPE_CGROUP_DEVICE]		= "cgroup_device",
212 	[BPF_PROG_TYPE_SK_MSG]			= "sk_msg",
213 	[BPF_PROG_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
214 	[BPF_PROG_TYPE_CGROUP_SOCK_ADDR]	= "cgroup_sock_addr",
215 	[BPF_PROG_TYPE_LWT_SEG6LOCAL]		= "lwt_seg6local",
216 	[BPF_PROG_TYPE_LIRC_MODE2]		= "lirc_mode2",
217 	[BPF_PROG_TYPE_SK_REUSEPORT]		= "sk_reuseport",
218 	[BPF_PROG_TYPE_FLOW_DISSECTOR]		= "flow_dissector",
219 	[BPF_PROG_TYPE_CGROUP_SYSCTL]		= "cgroup_sysctl",
220 	[BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE]	= "raw_tracepoint_writable",
221 	[BPF_PROG_TYPE_CGROUP_SOCKOPT]		= "cgroup_sockopt",
222 	[BPF_PROG_TYPE_TRACING]			= "tracing",
223 	[BPF_PROG_TYPE_STRUCT_OPS]		= "struct_ops",
224 	[BPF_PROG_TYPE_EXT]			= "ext",
225 	[BPF_PROG_TYPE_LSM]			= "lsm",
226 	[BPF_PROG_TYPE_SK_LOOKUP]		= "sk_lookup",
227 	[BPF_PROG_TYPE_SYSCALL]			= "syscall",
228 };
229 
__base_pr(enum libbpf_print_level level,const char * format,va_list args)230 static int __base_pr(enum libbpf_print_level level, const char *format,
231 		     va_list args)
232 {
233 	if (level == LIBBPF_DEBUG)
234 		return 0;
235 
236 	return vfprintf(stderr, format, args);
237 }
238 
239 static libbpf_print_fn_t __libbpf_pr = __base_pr;
240 
libbpf_set_print(libbpf_print_fn_t fn)241 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
242 {
243 	libbpf_print_fn_t old_print_fn = __libbpf_pr;
244 
245 	__libbpf_pr = fn;
246 	return old_print_fn;
247 }
248 
249 __printf(2, 3)
libbpf_print(enum libbpf_print_level level,const char * format,...)250 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
251 {
252 	va_list args;
253 	int old_errno;
254 
255 	if (!__libbpf_pr)
256 		return;
257 
258 	old_errno = errno;
259 
260 	va_start(args, format);
261 	__libbpf_pr(level, format, args);
262 	va_end(args);
263 
264 	errno = old_errno;
265 }
266 
pr_perm_msg(int err)267 static void pr_perm_msg(int err)
268 {
269 	struct rlimit limit;
270 	char buf[100];
271 
272 	if (err != -EPERM || geteuid() != 0)
273 		return;
274 
275 	err = getrlimit(RLIMIT_MEMLOCK, &limit);
276 	if (err)
277 		return;
278 
279 	if (limit.rlim_cur == RLIM_INFINITY)
280 		return;
281 
282 	if (limit.rlim_cur < 1024)
283 		snprintf(buf, sizeof(buf), "%zu bytes", (size_t)limit.rlim_cur);
284 	else if (limit.rlim_cur < 1024*1024)
285 		snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
286 	else
287 		snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
288 
289 	pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
290 		buf);
291 }
292 
293 #define STRERR_BUFSIZE  128
294 
295 /* Copied from tools/perf/util/util.h */
296 #ifndef zfree
297 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
298 #endif
299 
300 #ifndef zclose
301 # define zclose(fd) ({			\
302 	int ___err = 0;			\
303 	if ((fd) >= 0)			\
304 		___err = close((fd));	\
305 	fd = -1;			\
306 	___err; })
307 #endif
308 
ptr_to_u64(const void * ptr)309 static inline __u64 ptr_to_u64(const void *ptr)
310 {
311 	return (__u64) (unsigned long) ptr;
312 }
313 
libbpf_set_strict_mode(enum libbpf_strict_mode mode)314 int libbpf_set_strict_mode(enum libbpf_strict_mode mode)
315 {
316 	/* as of v1.0 libbpf_set_strict_mode() is a no-op */
317 	return 0;
318 }
319 
libbpf_major_version(void)320 __u32 libbpf_major_version(void)
321 {
322 	return LIBBPF_MAJOR_VERSION;
323 }
324 
libbpf_minor_version(void)325 __u32 libbpf_minor_version(void)
326 {
327 	return LIBBPF_MINOR_VERSION;
328 }
329 
libbpf_version_string(void)330 const char *libbpf_version_string(void)
331 {
332 #define __S(X) #X
333 #define _S(X) __S(X)
334 	return  "v" _S(LIBBPF_MAJOR_VERSION) "." _S(LIBBPF_MINOR_VERSION);
335 #undef _S
336 #undef __S
337 }
338 
339 enum reloc_type {
340 	RELO_LD64,
341 	RELO_CALL,
342 	RELO_DATA,
343 	RELO_EXTERN_VAR,
344 	RELO_EXTERN_FUNC,
345 	RELO_SUBPROG_ADDR,
346 	RELO_CORE,
347 };
348 
349 struct reloc_desc {
350 	enum reloc_type type;
351 	int insn_idx;
352 	union {
353 		const struct bpf_core_relo *core_relo; /* used when type == RELO_CORE */
354 		struct {
355 			int map_idx;
356 			int sym_off;
357 		};
358 	};
359 };
360 
361 /* stored as sec_def->cookie for all libbpf-supported SEC()s */
362 enum sec_def_flags {
363 	SEC_NONE = 0,
364 	/* expected_attach_type is optional, if kernel doesn't support that */
365 	SEC_EXP_ATTACH_OPT = 1,
366 	/* legacy, only used by libbpf_get_type_names() and
367 	 * libbpf_attach_type_by_name(), not used by libbpf itself at all.
368 	 * This used to be associated with cgroup (and few other) BPF programs
369 	 * that were attachable through BPF_PROG_ATTACH command. Pretty
370 	 * meaningless nowadays, though.
371 	 */
372 	SEC_ATTACHABLE = 2,
373 	SEC_ATTACHABLE_OPT = SEC_ATTACHABLE | SEC_EXP_ATTACH_OPT,
374 	/* attachment target is specified through BTF ID in either kernel or
375 	 * other BPF program's BTF object
376 	 */
377 	SEC_ATTACH_BTF = 4,
378 	/* BPF program type allows sleeping/blocking in kernel */
379 	SEC_SLEEPABLE = 8,
380 	/* BPF program support non-linear XDP buffer */
381 	SEC_XDP_FRAGS = 16,
382 };
383 
384 struct bpf_sec_def {
385 	char *sec;
386 	enum bpf_prog_type prog_type;
387 	enum bpf_attach_type expected_attach_type;
388 	long cookie;
389 	int handler_id;
390 
391 	libbpf_prog_setup_fn_t prog_setup_fn;
392 	libbpf_prog_prepare_load_fn_t prog_prepare_load_fn;
393 	libbpf_prog_attach_fn_t prog_attach_fn;
394 };
395 
396 /*
397  * bpf_prog should be a better name but it has been used in
398  * linux/filter.h.
399  */
400 struct bpf_program {
401 	char *name;
402 	char *sec_name;
403 	size_t sec_idx;
404 	const struct bpf_sec_def *sec_def;
405 	/* this program's instruction offset (in number of instructions)
406 	 * within its containing ELF section
407 	 */
408 	size_t sec_insn_off;
409 	/* number of original instructions in ELF section belonging to this
410 	 * program, not taking into account subprogram instructions possible
411 	 * appended later during relocation
412 	 */
413 	size_t sec_insn_cnt;
414 	/* Offset (in number of instructions) of the start of instruction
415 	 * belonging to this BPF program  within its containing main BPF
416 	 * program. For the entry-point (main) BPF program, this is always
417 	 * zero. For a sub-program, this gets reset before each of main BPF
418 	 * programs are processed and relocated and is used to determined
419 	 * whether sub-program was already appended to the main program, and
420 	 * if yes, at which instruction offset.
421 	 */
422 	size_t sub_insn_off;
423 
424 	/* instructions that belong to BPF program; insns[0] is located at
425 	 * sec_insn_off instruction within its ELF section in ELF file, so
426 	 * when mapping ELF file instruction index to the local instruction,
427 	 * one needs to subtract sec_insn_off; and vice versa.
428 	 */
429 	struct bpf_insn *insns;
430 	/* actual number of instruction in this BPF program's image; for
431 	 * entry-point BPF programs this includes the size of main program
432 	 * itself plus all the used sub-programs, appended at the end
433 	 */
434 	size_t insns_cnt;
435 
436 	struct reloc_desc *reloc_desc;
437 	int nr_reloc;
438 
439 	/* BPF verifier log settings */
440 	char *log_buf;
441 	size_t log_size;
442 	__u32 log_level;
443 
444 	struct bpf_object *obj;
445 
446 	int fd;
447 	bool autoload;
448 	bool autoattach;
449 	bool mark_btf_static;
450 	enum bpf_prog_type type;
451 	enum bpf_attach_type expected_attach_type;
452 
453 	int prog_ifindex;
454 	__u32 attach_btf_obj_fd;
455 	__u32 attach_btf_id;
456 	__u32 attach_prog_fd;
457 
458 	void *func_info;
459 	__u32 func_info_rec_size;
460 	__u32 func_info_cnt;
461 
462 	void *line_info;
463 	__u32 line_info_rec_size;
464 	__u32 line_info_cnt;
465 	__u32 prog_flags;
466 };
467 
468 struct bpf_struct_ops {
469 	const char *tname;
470 	const struct btf_type *type;
471 	struct bpf_program **progs;
472 	__u32 *kern_func_off;
473 	/* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
474 	void *data;
475 	/* e.g. struct bpf_struct_ops_tcp_congestion_ops in
476 	 *      btf_vmlinux's format.
477 	 * struct bpf_struct_ops_tcp_congestion_ops {
478 	 *	[... some other kernel fields ...]
479 	 *	struct tcp_congestion_ops data;
480 	 * }
481 	 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
482 	 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
483 	 * from "data".
484 	 */
485 	void *kern_vdata;
486 	__u32 type_id;
487 };
488 
489 #define DATA_SEC ".data"
490 #define BSS_SEC ".bss"
491 #define RODATA_SEC ".rodata"
492 #define KCONFIG_SEC ".kconfig"
493 #define KSYMS_SEC ".ksyms"
494 #define STRUCT_OPS_SEC ".struct_ops"
495 
496 enum libbpf_map_type {
497 	LIBBPF_MAP_UNSPEC,
498 	LIBBPF_MAP_DATA,
499 	LIBBPF_MAP_BSS,
500 	LIBBPF_MAP_RODATA,
501 	LIBBPF_MAP_KCONFIG,
502 };
503 
504 struct bpf_map_def {
505 	unsigned int type;
506 	unsigned int key_size;
507 	unsigned int value_size;
508 	unsigned int max_entries;
509 	unsigned int map_flags;
510 };
511 
512 struct bpf_map {
513 	struct bpf_object *obj;
514 	char *name;
515 	/* real_name is defined for special internal maps (.rodata*,
516 	 * .data*, .bss, .kconfig) and preserves their original ELF section
517 	 * name. This is important to be able to find corresponding BTF
518 	 * DATASEC information.
519 	 */
520 	char *real_name;
521 	int fd;
522 	int sec_idx;
523 	size_t sec_offset;
524 	int map_ifindex;
525 	int inner_map_fd;
526 	struct bpf_map_def def;
527 	__u32 numa_node;
528 	__u32 btf_var_idx;
529 	__u32 btf_key_type_id;
530 	__u32 btf_value_type_id;
531 	__u32 btf_vmlinux_value_type_id;
532 	enum libbpf_map_type libbpf_type;
533 	void *mmaped;
534 	struct bpf_struct_ops *st_ops;
535 	struct bpf_map *inner_map;
536 	void **init_slots;
537 	int init_slots_sz;
538 	char *pin_path;
539 	bool pinned;
540 	bool reused;
541 	bool autocreate;
542 	__u64 map_extra;
543 };
544 
545 enum extern_type {
546 	EXT_UNKNOWN,
547 	EXT_KCFG,
548 	EXT_KSYM,
549 };
550 
551 enum kcfg_type {
552 	KCFG_UNKNOWN,
553 	KCFG_CHAR,
554 	KCFG_BOOL,
555 	KCFG_INT,
556 	KCFG_TRISTATE,
557 	KCFG_CHAR_ARR,
558 };
559 
560 struct extern_desc {
561 	enum extern_type type;
562 	int sym_idx;
563 	int btf_id;
564 	int sec_btf_id;
565 	const char *name;
566 	bool is_set;
567 	bool is_weak;
568 	union {
569 		struct {
570 			enum kcfg_type type;
571 			int sz;
572 			int align;
573 			int data_off;
574 			bool is_signed;
575 		} kcfg;
576 		struct {
577 			unsigned long long addr;
578 
579 			/* target btf_id of the corresponding kernel var. */
580 			int kernel_btf_obj_fd;
581 			int kernel_btf_id;
582 
583 			/* local btf_id of the ksym extern's type. */
584 			__u32 type_id;
585 			/* BTF fd index to be patched in for insn->off, this is
586 			 * 0 for vmlinux BTF, index in obj->fd_array for module
587 			 * BTF
588 			 */
589 			__s16 btf_fd_idx;
590 		} ksym;
591 	};
592 };
593 
594 struct module_btf {
595 	struct btf *btf;
596 	char *name;
597 	__u32 id;
598 	int fd;
599 	int fd_array_idx;
600 };
601 
602 enum sec_type {
603 	SEC_UNUSED = 0,
604 	SEC_RELO,
605 	SEC_BSS,
606 	SEC_DATA,
607 	SEC_RODATA,
608 };
609 
610 struct elf_sec_desc {
611 	enum sec_type sec_type;
612 #if defined HAVE_LIBELF
613 	Elf64_Shdr *shdr;
614 #elif defined HAVE_ELFIO
615 	psection_t psection;
616 	Elf_Data realdata;
617 #endif
618 	Elf_Data *data;
619 };
620 
621 struct elf_state {
622 	int fd;
623 	const void *obj_buf;
624 	size_t obj_buf_sz;
625 #if defined HAVE_LIBELF
626 	Elf *elf;
627 #elif defined HAVE_ELFIO
628 	pelfio_t elf;
629 	Elf64_Ehdr eheader;
630 	pstring_t shstring;
631 	pstring_t strstring;
632 	Elf_Data realsymbols;
633 	Elf_Data realst_ops_data;
634 #endif
635 	Elf64_Ehdr *ehdr;
636 	Elf_Data *symbols;
637 	Elf_Data *st_ops_data;
638 	size_t shstrndx; /* section index for section name strings */
639 	size_t strtabidx;
640 	struct elf_sec_desc *secs;
641 	size_t sec_cnt;
642 	int btf_maps_shndx;
643 	__u32 btf_maps_sec_btf_id;
644 	int text_shndx;
645 	int symbols_shndx;
646 	int st_ops_shndx;
647 };
648 
649 struct usdt_manager;
650 
651 struct bpf_object {
652 	char name[BPF_OBJ_NAME_LEN];
653 	char license[64];
654 	__u32 kern_version;
655 
656 	struct bpf_program *programs;
657 	size_t nr_programs;
658 	struct bpf_map *maps;
659 	size_t nr_maps;
660 	size_t maps_cap;
661 
662 	char *kconfig;
663 	struct extern_desc *externs;
664 	int nr_extern;
665 	int kconfig_map_idx;
666 
667 	bool loaded;
668 	bool has_subcalls;
669 	bool has_rodata;
670 
671 	struct bpf_gen *gen_loader;
672 
673 	/* Information when doing ELF related work. Only valid if efile.elf is not NULL */
674 	struct elf_state efile;
675 
676 	struct btf *btf;
677 	struct btf_ext *btf_ext;
678 
679 	/* Parse and load BTF vmlinux if any of the programs in the object need
680 	 * it at load time.
681 	 */
682 	struct btf *btf_vmlinux;
683 	/* Path to the custom BTF to be used for BPF CO-RE relocations as an
684 	 * override for vmlinux BTF.
685 	 */
686 	char *btf_custom_path;
687 	/* vmlinux BTF override for CO-RE relocations */
688 	struct btf *btf_vmlinux_override;
689 	/* Lazily initialized kernel module BTFs */
690 	struct module_btf *btf_modules;
691 	bool btf_modules_loaded;
692 	size_t btf_module_cnt;
693 	size_t btf_module_cap;
694 
695 	/* optional log settings passed to BPF_BTF_LOAD and BPF_PROG_LOAD commands */
696 	char *log_buf;
697 	size_t log_size;
698 	__u32 log_level;
699 
700 	int *fd_array;
701 	size_t fd_array_cap;
702 	size_t fd_array_cnt;
703 
704 	struct usdt_manager *usdt_man;
705 
706 	char path[];
707 };
708 
709 static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
710 static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
711 #ifdef HAVE_LIBELF
712 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
713 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
714 #endif
715 #if defined HAVE_LIBELF
716 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn);
717 #elif defined HAVE_ELFIO
718 static Elf64_Shdr *elf_sec_hdr_by_idx(const struct bpf_object *obj, size_t idx, Elf64_Shdr *sheader);
719 #endif
720 #if defined HAVE_LIBELF
721 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
722 #elif defined HAVE_ELFIO
723 static const char *elf_sec_name_by_idx(const struct bpf_object *obj, size_t idx);
724 #endif
725 #if defined HAVE_LIBELF
726 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
727 #elif defined HAVE_ELFIO
728 static Elf_Data *elf_sec_data_by_name(const struct bpf_object *obj, const char *name, Elf_Data *data);
729 static Elf_Data *elf_sec_data_by_idx(const struct bpf_object *obj, size_t idx, Elf_Data *data);
730 #endif
731 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx);
732 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx);
733 
bpf_program__unload(struct bpf_program * prog)734 void bpf_program__unload(struct bpf_program *prog)
735 {
736 	if (!prog)
737 		return;
738 
739 	zclose(prog->fd);
740 
741 	zfree(&prog->func_info);
742 	zfree(&prog->line_info);
743 }
744 
bpf_program__exit(struct bpf_program * prog)745 static void bpf_program__exit(struct bpf_program *prog)
746 {
747 	if (!prog)
748 		return;
749 
750 	bpf_program__unload(prog);
751 	zfree(&prog->name);
752 	zfree(&prog->sec_name);
753 	zfree(&prog->insns);
754 	zfree(&prog->reloc_desc);
755 
756 	prog->nr_reloc = 0;
757 	prog->insns_cnt = 0;
758 	prog->sec_idx = -1;
759 }
760 
insn_is_subprog_call(const struct bpf_insn * insn)761 static bool insn_is_subprog_call(const struct bpf_insn *insn)
762 {
763 	return BPF_CLASS(insn->code) == BPF_JMP &&
764 	       BPF_OP(insn->code) == BPF_CALL &&
765 	       BPF_SRC(insn->code) == BPF_K &&
766 	       insn->src_reg == BPF_PSEUDO_CALL &&
767 	       insn->dst_reg == 0 &&
768 	       insn->off == 0;
769 }
770 
is_call_insn(const struct bpf_insn * insn)771 static bool is_call_insn(const struct bpf_insn *insn)
772 {
773 	return insn->code == (BPF_JMP | BPF_CALL);
774 }
775 
insn_is_pseudo_func(struct bpf_insn * insn)776 static bool insn_is_pseudo_func(struct bpf_insn *insn)
777 {
778 	return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
779 }
780 
781 static int
bpf_object__init_prog(struct bpf_object * obj,struct bpf_program * prog,const char * name,size_t sec_idx,const char * sec_name,size_t sec_off,void * insn_data,size_t insn_data_sz)782 bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
783 		      const char *name, size_t sec_idx, const char *sec_name,
784 		      size_t sec_off, void *insn_data, size_t insn_data_sz)
785 {
786 	if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
787 		pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
788 			sec_name, name, sec_off, insn_data_sz);
789 		return -EINVAL;
790 	}
791 
792 	memset(prog, 0, sizeof(*prog));
793 	prog->obj = obj;
794 
795 	prog->sec_idx = sec_idx;
796 	prog->sec_insn_off = sec_off / BPF_INSN_SZ;
797 	prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
798 	/* insns_cnt can later be increased by appending used subprograms */
799 	prog->insns_cnt = prog->sec_insn_cnt;
800 
801 	prog->type = BPF_PROG_TYPE_UNSPEC;
802 	prog->fd = -1;
803 
804 	/* libbpf's convention for SEC("?abc...") is that it's just like
805 	 * SEC("abc...") but the corresponding bpf_program starts out with
806 	 * autoload set to false.
807 	 */
808 	if (sec_name[0] == '?') {
809 		prog->autoload = false;
810 		/* from now on forget there was ? in section name */
811 		sec_name++;
812 	} else {
813 		prog->autoload = true;
814 	}
815 
816 	prog->autoattach = true;
817 
818 	/* inherit object's log_level */
819 	prog->log_level = obj->log_level;
820 
821 	prog->sec_name = strdup(sec_name);
822 	if (!prog->sec_name)
823 		goto errout;
824 
825 	prog->name = strdup(name);
826 	if (!prog->name)
827 		goto errout;
828 
829 	prog->insns = malloc(insn_data_sz);
830 	if (!prog->insns)
831 		goto errout;
832 	memcpy(prog->insns, insn_data, insn_data_sz);
833 
834 	return 0;
835 errout:
836 	pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
837 	bpf_program__exit(prog);
838 	return -ENOMEM;
839 }
840 
841 static int
bpf_object__add_programs(struct bpf_object * obj,Elf_Data * sec_data,const char * sec_name,int sec_idx)842 bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
843 			 const char *sec_name, int sec_idx)
844 {
845 	Elf_Data *symbols = obj->efile.symbols;
846 	struct bpf_program *prog, *progs;
847 	void *data = sec_data->d_buf;
848 	size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
849 	int nr_progs, err, i;
850 	const char *name;
851 	Elf64_Sym *sym;
852 
853 	progs = obj->programs;
854 	nr_progs = obj->nr_programs;
855 	nr_syms = symbols->d_size / sizeof(Elf64_Sym);
856 	sec_off = 0;
857 
858 	for (i = 0; i < nr_syms; i++) {
859 		sym = elf_sym_by_idx(obj, i);
860 
861 		if (sym->st_shndx != sec_idx)
862 			continue;
863 		if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC)
864 			continue;
865 
866 		prog_sz = sym->st_size;
867 		sec_off = sym->st_value;
868 
869 		name = elf_sym_str(obj, sym->st_name);
870 		if (!name) {
871 			pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
872 				sec_name, sec_off);
873 			return -LIBBPF_ERRNO__FORMAT;
874 		}
875 
876 		if (sec_off + prog_sz > sec_sz) {
877 			pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
878 				sec_name, sec_off);
879 			return -LIBBPF_ERRNO__FORMAT;
880 		}
881 
882 		if (sec_idx != obj->efile.text_shndx && ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
883 			pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
884 			return -ENOTSUP;
885 		}
886 
887 		pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
888 			 sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
889 
890 		progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
891 		if (!progs) {
892 			/*
893 			 * In this case the original obj->programs
894 			 * is still valid, so don't need special treat for
895 			 * bpf_close_object().
896 			 */
897 			pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
898 				sec_name, name);
899 			return -ENOMEM;
900 		}
901 		obj->programs = progs;
902 
903 		prog = &progs[nr_progs];
904 
905 		err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
906 					    sec_off, data + sec_off, prog_sz);
907 		if (err)
908 			return err;
909 
910 		/* if function is a global/weak symbol, but has restricted
911 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
912 		 * as static to enable more permissive BPF verification mode
913 		 * with more outside context available to BPF verifier
914 		 */
915 		if (ELF64_ST_BIND(sym->st_info) != STB_LOCAL
916 		    && (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
917 			|| ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL))
918 			prog->mark_btf_static = true;
919 
920 		nr_progs++;
921 		obj->nr_programs = nr_progs;
922 	}
923 
924 	return 0;
925 }
926 
get_kernel_version(void)927 __u32 get_kernel_version(void)
928 {
929 	/* On Ubuntu LINUX_VERSION_CODE doesn't correspond to info.release,
930 	 * but Ubuntu provides /proc/version_signature file, as described at
931 	 * https://ubuntu.com/kernel, with an example contents below, which we
932 	 * can use to get a proper LINUX_VERSION_CODE.
933 	 *
934 	 *   Ubuntu 5.4.0-12.15-generic 5.4.8
935 	 *
936 	 * In the above, 5.4.8 is what kernel is actually expecting, while
937 	 * uname() call will return 5.4.0 in info.release.
938 	 */
939 	const char *ubuntu_kver_file = "/proc/version_signature";
940 	__u32 major, minor, patch;
941 	struct utsname info;
942 
943 	if (faccessat(AT_FDCWD, ubuntu_kver_file, R_OK, AT_EACCESS) == 0) {
944 		FILE *f;
945 
946 		f = fopen(ubuntu_kver_file, "r");
947 		if (f) {
948 			if (fscanf(f, "%*s %*s %d.%d.%d\n", &major, &minor, &patch) == 3) {
949 				fclose(f);
950 				return KERNEL_VERSION(major, minor, patch);
951 			}
952 			fclose(f);
953 		}
954 		/* something went wrong, fall back to uname() approach */
955 	}
956 
957 	uname(&info);
958 	if (sscanf(info.release, "%u.%u.%u", &major, &minor, &patch) != 3)
959 		return 0;
960 	return KERNEL_VERSION(major, minor, patch);
961 }
962 
963 static const struct btf_member *
find_member_by_offset(const struct btf_type * t,__u32 bit_offset)964 find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
965 {
966 	struct btf_member *m;
967 	int i;
968 
969 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
970 		if (btf_member_bit_offset(t, i) == bit_offset)
971 			return m;
972 	}
973 
974 	return NULL;
975 }
976 
977 static const struct btf_member *
find_member_by_name(const struct btf * btf,const struct btf_type * t,const char * name)978 find_member_by_name(const struct btf *btf, const struct btf_type *t,
979 		    const char *name)
980 {
981 	struct btf_member *m;
982 	int i;
983 
984 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
985 		if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
986 			return m;
987 	}
988 
989 	return NULL;
990 }
991 
992 #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
993 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
994 				   const char *name, __u32 kind);
995 
996 static int
find_struct_ops_kern_types(const struct btf * btf,const char * tname,const struct btf_type ** type,__u32 * type_id,const struct btf_type ** vtype,__u32 * vtype_id,const struct btf_member ** data_member)997 find_struct_ops_kern_types(const struct btf *btf, const char *tname,
998 			   const struct btf_type **type, __u32 *type_id,
999 			   const struct btf_type **vtype, __u32 *vtype_id,
1000 			   const struct btf_member **data_member)
1001 {
1002 	const struct btf_type *kern_type, *kern_vtype;
1003 	const struct btf_member *kern_data_member;
1004 	__s32 kern_vtype_id, kern_type_id;
1005 	__u32 i;
1006 
1007 	kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
1008 	if (kern_type_id < 0) {
1009 		pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n",
1010 			tname);
1011 		return kern_type_id;
1012 	}
1013 	kern_type = btf__type_by_id(btf, kern_type_id);
1014 
1015 	/* Find the corresponding "map_value" type that will be used
1016 	 * in map_update(BPF_MAP_TYPE_STRUCT_OPS).  For example,
1017 	 * find "struct bpf_struct_ops_tcp_congestion_ops" from the
1018 	 * btf_vmlinux.
1019 	 */
1020 	kern_vtype_id = find_btf_by_prefix_kind(btf, STRUCT_OPS_VALUE_PREFIX,
1021 						tname, BTF_KIND_STRUCT);
1022 	if (kern_vtype_id < 0) {
1023 		pr_warn("struct_ops init_kern: struct %s%s is not found in kernel BTF\n",
1024 			STRUCT_OPS_VALUE_PREFIX, tname);
1025 		return kern_vtype_id;
1026 	}
1027 	kern_vtype = btf__type_by_id(btf, kern_vtype_id);
1028 
1029 	/* Find "struct tcp_congestion_ops" from
1030 	 * struct bpf_struct_ops_tcp_congestion_ops {
1031 	 *	[ ... ]
1032 	 *	struct tcp_congestion_ops data;
1033 	 * }
1034 	 */
1035 	kern_data_member = btf_members(kern_vtype);
1036 	for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
1037 		if (kern_data_member->type == kern_type_id)
1038 			break;
1039 	}
1040 	if (i == btf_vlen(kern_vtype)) {
1041 		pr_warn("struct_ops init_kern: struct %s data is not found in struct %s%s\n",
1042 			tname, STRUCT_OPS_VALUE_PREFIX, tname);
1043 		return -EINVAL;
1044 	}
1045 
1046 	*type = kern_type;
1047 	*type_id = kern_type_id;
1048 	*vtype = kern_vtype;
1049 	*vtype_id = kern_vtype_id;
1050 	*data_member = kern_data_member;
1051 
1052 	return 0;
1053 }
1054 
bpf_map__is_struct_ops(const struct bpf_map * map)1055 static bool bpf_map__is_struct_ops(const struct bpf_map *map)
1056 {
1057 	return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
1058 }
1059 
1060 /* Init the map's fields that depend on kern_btf */
bpf_map__init_kern_struct_ops(struct bpf_map * map,const struct btf * btf,const struct btf * kern_btf)1061 static int bpf_map__init_kern_struct_ops(struct bpf_map *map,
1062 					 const struct btf *btf,
1063 					 const struct btf *kern_btf)
1064 {
1065 	const struct btf_member *member, *kern_member, *kern_data_member;
1066 	const struct btf_type *type, *kern_type, *kern_vtype;
1067 	__u32 i, kern_type_id, kern_vtype_id, kern_data_off;
1068 	struct bpf_struct_ops *st_ops;
1069 	void *data, *kern_data;
1070 	const char *tname;
1071 	int err;
1072 
1073 	st_ops = map->st_ops;
1074 	type = st_ops->type;
1075 	tname = st_ops->tname;
1076 	err = find_struct_ops_kern_types(kern_btf, tname,
1077 					 &kern_type, &kern_type_id,
1078 					 &kern_vtype, &kern_vtype_id,
1079 					 &kern_data_member);
1080 	if (err)
1081 		return err;
1082 
1083 	pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
1084 		 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
1085 
1086 	map->def.value_size = kern_vtype->size;
1087 	map->btf_vmlinux_value_type_id = kern_vtype_id;
1088 
1089 	st_ops->kern_vdata = calloc(1, kern_vtype->size);
1090 	if (!st_ops->kern_vdata)
1091 		return -ENOMEM;
1092 
1093 	data = st_ops->data;
1094 	kern_data_off = kern_data_member->offset / 8;
1095 	kern_data = st_ops->kern_vdata + kern_data_off;
1096 
1097 	member = btf_members(type);
1098 	for (i = 0; i < btf_vlen(type); i++, member++) {
1099 		const struct btf_type *mtype, *kern_mtype;
1100 		__u32 mtype_id, kern_mtype_id;
1101 		void *mdata, *kern_mdata;
1102 		__s64 msize, kern_msize;
1103 		__u32 moff, kern_moff;
1104 		__u32 kern_member_idx;
1105 		const char *mname;
1106 
1107 		mname = btf__name_by_offset(btf, member->name_off);
1108 		kern_member = find_member_by_name(kern_btf, kern_type, mname);
1109 		if (!kern_member) {
1110 			pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
1111 				map->name, mname);
1112 			return -ENOTSUP;
1113 		}
1114 
1115 		kern_member_idx = kern_member - btf_members(kern_type);
1116 		if (btf_member_bitfield_size(type, i) ||
1117 		    btf_member_bitfield_size(kern_type, kern_member_idx)) {
1118 			pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
1119 				map->name, mname);
1120 			return -ENOTSUP;
1121 		}
1122 
1123 		moff = member->offset / 8;
1124 		kern_moff = kern_member->offset / 8;
1125 
1126 		mdata = data + moff;
1127 		kern_mdata = kern_data + kern_moff;
1128 
1129 		mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
1130 		kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
1131 						    &kern_mtype_id);
1132 		if (BTF_INFO_KIND(mtype->info) !=
1133 		    BTF_INFO_KIND(kern_mtype->info)) {
1134 			pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
1135 				map->name, mname, BTF_INFO_KIND(mtype->info),
1136 				BTF_INFO_KIND(kern_mtype->info));
1137 			return -ENOTSUP;
1138 		}
1139 
1140 		if (btf_is_ptr(mtype)) {
1141 			struct bpf_program *prog;
1142 
1143 			prog = st_ops->progs[i];
1144 			if (!prog)
1145 				continue;
1146 
1147 			kern_mtype = skip_mods_and_typedefs(kern_btf,
1148 							    kern_mtype->type,
1149 							    &kern_mtype_id);
1150 
1151 			/* mtype->type must be a func_proto which was
1152 			 * guaranteed in bpf_object__collect_st_ops_relos(),
1153 			 * so only check kern_mtype for func_proto here.
1154 			 */
1155 			if (!btf_is_func_proto(kern_mtype)) {
1156 				pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
1157 					map->name, mname);
1158 				return -ENOTSUP;
1159 			}
1160 
1161 			prog->attach_btf_id = kern_type_id;
1162 			prog->expected_attach_type = kern_member_idx;
1163 
1164 			st_ops->kern_func_off[i] = kern_data_off + kern_moff;
1165 
1166 			pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
1167 				 map->name, mname, prog->name, moff,
1168 				 kern_moff);
1169 
1170 			continue;
1171 		}
1172 
1173 		msize = btf__resolve_size(btf, mtype_id);
1174 		kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
1175 		if (msize < 0 || kern_msize < 0 || msize != kern_msize) {
1176 			pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
1177 				map->name, mname, (ssize_t)msize,
1178 				(ssize_t)kern_msize);
1179 			return -ENOTSUP;
1180 		}
1181 
1182 		pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
1183 			 map->name, mname, (unsigned int)msize,
1184 			 moff, kern_moff);
1185 		memcpy(kern_mdata, mdata, msize);
1186 	}
1187 
1188 	return 0;
1189 }
1190 
bpf_object__init_kern_struct_ops_maps(struct bpf_object * obj)1191 static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
1192 {
1193 	struct bpf_map *map;
1194 	size_t i;
1195 	int err;
1196 
1197 	for (i = 0; i < obj->nr_maps; i++) {
1198 		map = &obj->maps[i];
1199 
1200 		if (!bpf_map__is_struct_ops(map))
1201 			continue;
1202 
1203 		err = bpf_map__init_kern_struct_ops(map, obj->btf,
1204 						    obj->btf_vmlinux);
1205 		if (err)
1206 			return err;
1207 	}
1208 
1209 	return 0;
1210 }
1211 
bpf_object__init_struct_ops_maps(struct bpf_object * obj)1212 static int bpf_object__init_struct_ops_maps(struct bpf_object *obj)
1213 {
1214 	const struct btf_type *type, *datasec;
1215 	const struct btf_var_secinfo *vsi;
1216 	struct bpf_struct_ops *st_ops;
1217 	const char *tname, *var_name;
1218 	__s32 type_id, datasec_id;
1219 	const struct btf *btf;
1220 	struct bpf_map *map;
1221 	__u32 i;
1222 
1223 	if (obj->efile.st_ops_shndx == -1)
1224 		return 0;
1225 
1226 	btf = obj->btf;
1227 	datasec_id = btf__find_by_name_kind(btf, STRUCT_OPS_SEC,
1228 					    BTF_KIND_DATASEC);
1229 	if (datasec_id < 0) {
1230 		pr_warn("struct_ops init: DATASEC %s not found\n",
1231 			STRUCT_OPS_SEC);
1232 		return -EINVAL;
1233 	}
1234 
1235 	datasec = btf__type_by_id(btf, datasec_id);
1236 	vsi = btf_var_secinfos(datasec);
1237 	for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
1238 		type = btf__type_by_id(obj->btf, vsi->type);
1239 		var_name = btf__name_by_offset(obj->btf, type->name_off);
1240 
1241 		type_id = btf__resolve_type(obj->btf, vsi->type);
1242 		if (type_id < 0) {
1243 			pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
1244 				vsi->type, STRUCT_OPS_SEC);
1245 			return -EINVAL;
1246 		}
1247 
1248 		type = btf__type_by_id(obj->btf, type_id);
1249 		tname = btf__name_by_offset(obj->btf, type->name_off);
1250 		if (!tname[0]) {
1251 			pr_warn("struct_ops init: anonymous type is not supported\n");
1252 			return -ENOTSUP;
1253 		}
1254 		if (!btf_is_struct(type)) {
1255 			pr_warn("struct_ops init: %s is not a struct\n", tname);
1256 			return -EINVAL;
1257 		}
1258 
1259 		map = bpf_object__add_map(obj);
1260 		if (IS_ERR(map))
1261 			return PTR_ERR(map);
1262 
1263 		map->sec_idx = obj->efile.st_ops_shndx;
1264 		map->sec_offset = vsi->offset;
1265 		map->name = strdup(var_name);
1266 		if (!map->name)
1267 			return -ENOMEM;
1268 
1269 		map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
1270 		map->def.key_size = sizeof(int);
1271 		map->def.value_size = type->size;
1272 		map->def.max_entries = 1;
1273 
1274 		map->st_ops = calloc(1, sizeof(*map->st_ops));
1275 		if (!map->st_ops)
1276 			return -ENOMEM;
1277 		st_ops = map->st_ops;
1278 		st_ops->data = malloc(type->size);
1279 		st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1280 		st_ops->kern_func_off = malloc(btf_vlen(type) *
1281 					       sizeof(*st_ops->kern_func_off));
1282 		if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1283 			return -ENOMEM;
1284 
1285 		if (vsi->offset + type->size > obj->efile.st_ops_data->d_size) {
1286 			pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1287 				var_name, STRUCT_OPS_SEC);
1288 			return -EINVAL;
1289 		}
1290 
1291 		memcpy(st_ops->data,
1292 		       obj->efile.st_ops_data->d_buf + vsi->offset,
1293 		       type->size);
1294 		st_ops->tname = tname;
1295 		st_ops->type = type;
1296 		st_ops->type_id = type_id;
1297 
1298 		pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
1299 			 tname, type_id, var_name, vsi->offset);
1300 	}
1301 
1302 	return 0;
1303 }
1304 
bpf_object__new(const char * path,const void * obj_buf,size_t obj_buf_sz,const char * obj_name)1305 static struct bpf_object *bpf_object__new(const char *path,
1306 					  const void *obj_buf,
1307 					  size_t obj_buf_sz,
1308 					  const char *obj_name)
1309 {
1310 	struct bpf_object *obj;
1311 	char *end;
1312 
1313 	obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1314 	if (!obj) {
1315 		pr_warn("alloc memory failed for %s\n", path);
1316 		return ERR_PTR(-ENOMEM);
1317 	}
1318 
1319 	strcpy(obj->path, path);
1320 	if (obj_name) {
1321 		libbpf_strlcpy(obj->name, obj_name, sizeof(obj->name));
1322 	} else {
1323 		/* Using basename() GNU version which doesn't modify arg. */
1324 		libbpf_strlcpy(obj->name, basename((void *)path), sizeof(obj->name));
1325 		end = strchr(obj->name, '.');
1326 		if (end)
1327 			*end = 0;
1328 	}
1329 
1330 	obj->efile.fd = -1;
1331 	/*
1332 	 * Caller of this function should also call
1333 	 * bpf_object__elf_finish() after data collection to return
1334 	 * obj_buf to user. If not, we should duplicate the buffer to
1335 	 * avoid user freeing them before elf finish.
1336 	 */
1337 	obj->efile.obj_buf = obj_buf;
1338 	obj->efile.obj_buf_sz = obj_buf_sz;
1339 	obj->efile.btf_maps_shndx = -1;
1340 	obj->efile.st_ops_shndx = -1;
1341 	obj->kconfig_map_idx = -1;
1342 
1343 	obj->kern_version = get_kernel_version();
1344 	obj->loaded = false;
1345 
1346 	return obj;
1347 }
1348 
bpf_object__elf_finish(struct bpf_object * obj)1349 static void bpf_object__elf_finish(struct bpf_object *obj)
1350 {
1351 	if (!obj->efile.elf)
1352 		return;
1353 #if defined HAVE_LIBELF
1354 	elf_end(obj->efile.elf);
1355 #elif defined HAVE_ELFIO
1356 		if (obj->efile.shstring) {
1357 			elfio_string_section_accessor_delete(obj->efile.shstring);
1358 		}
1359 		if (obj->efile.strstring) {
1360 			elfio_string_section_accessor_delete(obj->efile.strstring);
1361 		}
1362 		elfio_delete(obj->efile.elf);
1363 #endif
1364 	obj->efile.elf = NULL;
1365 	obj->efile.symbols = NULL;
1366 	obj->efile.st_ops_data = NULL;
1367 
1368 	zfree(&obj->efile.secs);
1369 	obj->efile.sec_cnt = 0;
1370 	zclose(obj->efile.fd);
1371 	obj->efile.obj_buf = NULL;
1372 	obj->efile.obj_buf_sz = 0;
1373 }
1374 
bpf_object__elf_init(struct bpf_object * obj)1375 static int bpf_object__elf_init(struct bpf_object *obj)
1376 {
1377 	Elf64_Ehdr *ehdr;
1378 	int err = 0;
1379 #ifdef HAVE_LIBELF
1380 	Elf *elf;
1381 #elif defined HAVE_ELFIO
1382 	pelfio_t elf;
1383 #endif
1384 
1385 	if (obj->efile.elf) {
1386 		pr_warn("elf: init internal error\n");
1387 		return -LIBBPF_ERRNO__LIBELF;
1388 	}
1389 
1390 	if (obj->efile.obj_buf_sz > 0) {
1391 		/* obj_buf should have been validated by bpf_object__open_mem(). */
1392 #ifdef HAVE_LIBELF
1393 		elf = elf_memory((char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
1394 #elif defined HAVE_ELFIO
1395 		char  memfd_path[PATH_MAX] = {0};
1396 		elf = elfio_new();
1397 		int fdm = syscall(__NR_memfd_create, "bpfelf", MFD_CLOEXEC);
1398 		ftruncate(fdm, obj->efile.obj_buf_sz);
1399 		write(fdm, (char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
1400 		snprintf(memfd_path, PATH_MAX, "/proc/self/fd/%d", fdm);
1401 		elfio_load(elf, memfd_path);
1402 #endif
1403 	} else {
1404 		obj->efile.fd = open(obj->path, O_RDONLY | O_CLOEXEC);
1405 		if (obj->efile.fd < 0) {
1406 			char errmsg[STRERR_BUFSIZE], *cp;
1407 
1408 			err = -errno;
1409 			cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
1410 			pr_warn("elf: failed to open %s: %s\n", obj->path, cp);
1411 			return err;
1412 		}
1413 #ifdef HAVE_LIBELF
1414 		elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1415 #endif
1416 	}
1417 
1418 	if (!elf) {
1419 		pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
1420 		err = -LIBBPF_ERRNO__LIBELF;
1421 		goto errout;
1422 	}
1423 
1424 	obj->efile.elf = elf;
1425 #ifdef HAVE_LIBELF
1426 	if (elf_kind(elf) != ELF_K_ELF) {
1427 		err = -LIBBPF_ERRNO__FORMAT;
1428 		pr_warn("elf: '%s' is not a proper ELF object\n", obj->path);
1429 		goto errout;
1430 	}
1431 
1432 	if (gelf_getclass(elf) != ELFCLASS64) {
1433 #elif defined HAVE_ELFIO
1434 	if (elfio_get_class(elf) != ELFCLASS64 ) {
1435 #endif
1436 		err = -LIBBPF_ERRNO__FORMAT;
1437 		pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path);
1438 		goto errout;
1439 	}
1440 #ifdef HAVE_LIBELF
1441 	obj->efile.ehdr = ehdr = elf64_getehdr(elf);
1442 #elif defined HAVE_ELFIO
1443 	obj->efile.ehdr = ehdr = (Elf64_Ehdr*)obj->efile.obj_buf;
1444 #endif
1445 	if (!obj->efile.ehdr) {
1446 		pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
1447 		err = -LIBBPF_ERRNO__FORMAT;
1448 		goto errout;
1449 	}
1450 
1451 #ifdef HAVE_LIBELF
1452 	if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
1453 		pr_warn("elf: failed to get section names section index for %s: %s\n",
1454 			obj->path, elf_errmsg(-1));
1455 		err = -LIBBPF_ERRNO__FORMAT;
1456 		goto errout;
1457 	}
1458 
1459 	/* Elf is corrupted/truncated, avoid calling elf_strptr. */
1460 	if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
1461 		pr_warn("elf: failed to get section names strings from %s: %s\n",
1462 			obj->path, elf_errmsg(-1));
1463 		err = -LIBBPF_ERRNO__FORMAT;
1464 		goto errout;
1465 	}
1466 #elif defined HAVE_ELFIO
1467      obj->efile.shstrndx = elfio_get_section_name_str_index(elf);
1468 #endif
1469 	/* Old LLVM set e_machine to EM_NONE */
1470 	if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
1471 		pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
1472 		err = -LIBBPF_ERRNO__FORMAT;
1473 		goto errout;
1474 	}
1475 
1476 	return 0;
1477 errout:
1478 	bpf_object__elf_finish(obj);
1479 	return err;
1480 }
1481 
1482 static int bpf_object__check_endianness(struct bpf_object *obj)
1483 {
1484 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1485 	if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2LSB)
1486 		return 0;
1487 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1488 	if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2MSB)
1489 		return 0;
1490 #else
1491 # error "Unrecognized __BYTE_ORDER__"
1492 #endif
1493 	pr_warn("elf: endianness mismatch in %s.\n", obj->path);
1494 	return -LIBBPF_ERRNO__ENDIAN;
1495 }
1496 
1497 static int
1498 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1499 {
1500 	if (!data) {
1501 		pr_warn("invalid license section in %s\n", obj->path);
1502 		return -LIBBPF_ERRNO__FORMAT;
1503 	}
1504 	/* libbpf_strlcpy() only copies first N - 1 bytes, so size + 1 won't
1505 	 * go over allowed ELF data section buffer
1506 	 */
1507 	libbpf_strlcpy(obj->license, data, min(size + 1, sizeof(obj->license)));
1508 	pr_debug("license of %s is %s\n", obj->path, obj->license);
1509 	return 0;
1510 }
1511 
1512 static int
1513 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1514 {
1515 	__u32 kver;
1516 
1517 	if (!data || size != sizeof(kver)) {
1518 		pr_warn("invalid kver section in %s\n", obj->path);
1519 		return -LIBBPF_ERRNO__FORMAT;
1520 	}
1521 	memcpy(&kver, data, sizeof(kver));
1522 	obj->kern_version = kver;
1523 	pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1524 	return 0;
1525 }
1526 
1527 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1528 {
1529 	if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1530 	    type == BPF_MAP_TYPE_HASH_OF_MAPS)
1531 		return true;
1532 	return false;
1533 }
1534 
1535 static int find_elf_sec_sz(const struct bpf_object *obj, const char *name, __u32 *size)
1536 {
1537 	Elf_Data *data;
1538 #ifdef HAVE_LIBELF
1539 	Elf_Scn *scn;
1540 #endif
1541 
1542 	if (!name)
1543 		return -EINVAL;
1544 #if defined HAVE_LIBELF
1545 	scn = elf_sec_by_name(obj, name);
1546 	data = elf_sec_data(obj, scn);
1547 #elif defined HAVE_ELFIO
1548 	Elf_Data realdata;
1549 	data = &realdata;
1550 	data = elf_sec_data_by_name(obj, name, data);
1551 #endif
1552 	if (data) {
1553 		*size = data->d_size;
1554 		return 0; /* found it */
1555 	}
1556 
1557 	return -ENOENT;
1558 }
1559 
1560 static Elf64_Sym *find_elf_var_sym(const struct bpf_object *obj, const char *name)
1561 {
1562 	Elf_Data *symbols = obj->efile.symbols;
1563 	const char *sname;
1564 	size_t si;
1565 
1566 	for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
1567 		Elf64_Sym *sym = elf_sym_by_idx(obj, si);
1568 
1569 		if (ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)
1570 			continue;
1571 
1572 		if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL &&
1573 		    ELF64_ST_BIND(sym->st_info) != STB_WEAK)
1574 			continue;
1575 
1576 		sname = elf_sym_str(obj, sym->st_name);
1577 		if (!sname) {
1578 			pr_warn("failed to get sym name string for var %s\n", name);
1579 			return ERR_PTR(-EIO);
1580 		}
1581 		if (strcmp(name, sname) == 0)
1582 			return sym;
1583 	}
1584 
1585 	return ERR_PTR(-ENOENT);
1586 }
1587 
1588 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1589 {
1590 	struct bpf_map *map;
1591 	int err;
1592 
1593 	err = libbpf_ensure_mem((void **)&obj->maps, &obj->maps_cap,
1594 				sizeof(*obj->maps), obj->nr_maps + 1);
1595 	if (err)
1596 		return ERR_PTR(err);
1597 
1598 	map = &obj->maps[obj->nr_maps++];
1599 	map->obj = obj;
1600 	map->fd = -1;
1601 	map->inner_map_fd = -1;
1602 	map->autocreate = true;
1603 
1604 	return map;
1605 }
1606 
1607 static size_t bpf_map_mmap_sz(const struct bpf_map *map)
1608 {
1609 	long page_sz = sysconf(_SC_PAGE_SIZE);
1610 	size_t map_sz;
1611 
1612 	map_sz = (size_t)roundup(map->def.value_size, 8) * map->def.max_entries;
1613 	map_sz = roundup(map_sz, page_sz);
1614 	return map_sz;
1615 }
1616 
1617 static char *internal_map_name(struct bpf_object *obj, const char *real_name)
1618 {
1619 	char map_name[BPF_OBJ_NAME_LEN], *p;
1620 	int pfx_len, sfx_len = max((size_t)7, strlen(real_name));
1621 
1622 	/* This is one of the more confusing parts of libbpf for various
1623 	 * reasons, some of which are historical. The original idea for naming
1624 	 * internal names was to include as much of BPF object name prefix as
1625 	 * possible, so that it can be distinguished from similar internal
1626 	 * maps of a different BPF object.
1627 	 * As an example, let's say we have bpf_object named 'my_object_name'
1628 	 * and internal map corresponding to '.rodata' ELF section. The final
1629 	 * map name advertised to user and to the kernel will be
1630 	 * 'my_objec.rodata', taking first 8 characters of object name and
1631 	 * entire 7 characters of '.rodata'.
1632 	 * Somewhat confusingly, if internal map ELF section name is shorter
1633 	 * than 7 characters, e.g., '.bss', we still reserve 7 characters
1634 	 * for the suffix, even though we only have 4 actual characters, and
1635 	 * resulting map will be called 'my_objec.bss', not even using all 15
1636 	 * characters allowed by the kernel. Oh well, at least the truncated
1637 	 * object name is somewhat consistent in this case. But if the map
1638 	 * name is '.kconfig', we'll still have entirety of '.kconfig' added
1639 	 * (8 chars) and thus will be left with only first 7 characters of the
1640 	 * object name ('my_obje'). Happy guessing, user, that the final map
1641 	 * name will be "my_obje.kconfig".
1642 	 * Now, with libbpf starting to support arbitrarily named .rodata.*
1643 	 * and .data.* data sections, it's possible that ELF section name is
1644 	 * longer than allowed 15 chars, so we now need to be careful to take
1645 	 * only up to 15 first characters of ELF name, taking no BPF object
1646 	 * name characters at all. So '.rodata.abracadabra' will result in
1647 	 * '.rodata.abracad' kernel and user-visible name.
1648 	 * We need to keep this convoluted logic intact for .data, .bss and
1649 	 * .rodata maps, but for new custom .data.custom and .rodata.custom
1650 	 * maps we use their ELF names as is, not prepending bpf_object name
1651 	 * in front. We still need to truncate them to 15 characters for the
1652 	 * kernel. Full name can be recovered for such maps by using DATASEC
1653 	 * BTF type associated with such map's value type, though.
1654 	 */
1655 	if (sfx_len >= BPF_OBJ_NAME_LEN)
1656 		sfx_len = BPF_OBJ_NAME_LEN - 1;
1657 
1658 	/* if there are two or more dots in map name, it's a custom dot map */
1659 	if (strchr(real_name + 1, '.') != NULL)
1660 		pfx_len = 0;
1661 	else
1662 		pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
1663 
1664 	snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1665 		 sfx_len, real_name);
1666 
1667 	/* sanitise map name to characters allowed by kernel */
1668 	for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1669 		if (!isalnum(*p) && *p != '_' && *p != '.')
1670 			*p = '_';
1671 
1672 	return strdup(map_name);
1673 }
1674 
1675 static int
1676 map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map);
1677 
1678 /* Internal BPF map is mmap()'able only if at least one of corresponding
1679  * DATASEC's VARs are to be exposed through BPF skeleton. I.e., it's a GLOBAL
1680  * variable and it's not marked as __hidden (which turns it into, effectively,
1681  * a STATIC variable).
1682  */
1683 static bool map_is_mmapable(struct bpf_object *obj, struct bpf_map *map)
1684 {
1685 	const struct btf_type *t, *vt;
1686 	struct btf_var_secinfo *vsi;
1687 	int i, n;
1688 
1689 	if (!map->btf_value_type_id)
1690 		return false;
1691 
1692 	t = btf__type_by_id(obj->btf, map->btf_value_type_id);
1693 	if (!btf_is_datasec(t))
1694 		return false;
1695 
1696 	vsi = btf_var_secinfos(t);
1697 	for (i = 0, n = btf_vlen(t); i < n; i++, vsi++) {
1698 		vt = btf__type_by_id(obj->btf, vsi->type);
1699 		if (!btf_is_var(vt))
1700 			continue;
1701 
1702 		if (btf_var(vt)->linkage != BTF_VAR_STATIC)
1703 			return true;
1704 	}
1705 
1706 	return false;
1707 }
1708 
1709 static int
1710 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
1711 			      const char *real_name, int sec_idx, void *data, size_t data_sz)
1712 {
1713 	struct bpf_map_def *def;
1714 	struct bpf_map *map;
1715 	int err;
1716 
1717 	map = bpf_object__add_map(obj);
1718 	if (IS_ERR(map))
1719 		return PTR_ERR(map);
1720 
1721 	map->libbpf_type = type;
1722 	map->sec_idx = sec_idx;
1723 	map->sec_offset = 0;
1724 	map->real_name = strdup(real_name);
1725 	map->name = internal_map_name(obj, real_name);
1726 	if (!map->real_name || !map->name) {
1727 		zfree(&map->real_name);
1728 		zfree(&map->name);
1729 		return -ENOMEM;
1730 	}
1731 
1732 	def = &map->def;
1733 	def->type = BPF_MAP_TYPE_ARRAY;
1734 	def->key_size = sizeof(int);
1735 	def->value_size = data_sz;
1736 	def->max_entries = 1;
1737 	def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
1738 			 ? BPF_F_RDONLY_PROG : 0;
1739 
1740 	/* failures are fine because of maps like .rodata.str1.1 */
1741 	(void) map_fill_btf_type_info(obj, map);
1742 
1743 	if (map_is_mmapable(obj, map))
1744 		def->map_flags |= BPF_F_MMAPABLE;
1745 
1746 	pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
1747 		 map->name, map->sec_idx, map->sec_offset, def->map_flags);
1748 
1749 	map->mmaped = mmap(NULL, bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
1750 			   MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1751 	if (map->mmaped == MAP_FAILED) {
1752 		err = -errno;
1753 		map->mmaped = NULL;
1754 		pr_warn("failed to alloc map '%s' content buffer: %d\n",
1755 			map->name, err);
1756 		zfree(&map->real_name);
1757 		zfree(&map->name);
1758 		return err;
1759 	}
1760 
1761 	if (data)
1762 		memcpy(map->mmaped, data, data_sz);
1763 
1764 	pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
1765 	return 0;
1766 }
1767 
1768 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
1769 {
1770 	struct elf_sec_desc *sec_desc;
1771 	const char *sec_name;
1772 	int err = 0, sec_idx;
1773 
1774 	/*
1775 	 * Populate obj->maps with libbpf internal maps.
1776 	 */
1777 	for (sec_idx = 1; sec_idx < obj->efile.sec_cnt; sec_idx++) {
1778 		sec_desc = &obj->efile.secs[sec_idx];
1779 
1780 		/* Skip recognized sections with size 0. */
1781 		if (!sec_desc->data || sec_desc->data->d_size == 0)
1782 			continue;
1783 
1784 		switch (sec_desc->sec_type) {
1785 		case SEC_DATA:
1786 #if defined HAVE_LIBELF
1787 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1788 #elif defined HAVE_ELFIO
1789 			sec_name = elf_sec_name_by_idx(obj, sec_idx);
1790 #endif
1791 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
1792 							    sec_name, sec_idx,
1793 							    sec_desc->data->d_buf,
1794 							    sec_desc->data->d_size);
1795 			break;
1796 		case SEC_RODATA:
1797 			obj->has_rodata = true;
1798 #if defined HAVE_LIBELF
1799 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1800 #elif defined HAVE_ELFIO
1801 			sec_name = elf_sec_name_by_idx(obj, sec_idx);
1802 #endif
1803 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
1804 							    sec_name, sec_idx,
1805 							    sec_desc->data->d_buf,
1806 							    sec_desc->data->d_size);
1807 			break;
1808 		case SEC_BSS:
1809 #if defined HAVE_LIBELF
1810 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1811 #elif defined HAVE_ELFIO
1812 			sec_name = elf_sec_name_by_idx(obj, sec_idx);
1813 #endif
1814 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
1815 							    sec_name, sec_idx,
1816 							    NULL,
1817 							    sec_desc->data->d_size);
1818 			break;
1819 		default:
1820 			/* skip */
1821 			break;
1822 		}
1823 		if (err)
1824 			return err;
1825 	}
1826 	return 0;
1827 }
1828 
1829 
1830 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
1831 					       const void *name)
1832 {
1833 	int i;
1834 
1835 	for (i = 0; i < obj->nr_extern; i++) {
1836 		if (strcmp(obj->externs[i].name, name) == 0)
1837 			return &obj->externs[i];
1838 	}
1839 	return NULL;
1840 }
1841 
1842 static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
1843 			      char value)
1844 {
1845 	switch (ext->kcfg.type) {
1846 	case KCFG_BOOL:
1847 		if (value == 'm') {
1848 			pr_warn("extern (kcfg) '%s': value '%c' implies tristate or char type\n",
1849 				ext->name, value);
1850 			return -EINVAL;
1851 		}
1852 		*(bool *)ext_val = value == 'y' ? true : false;
1853 		break;
1854 	case KCFG_TRISTATE:
1855 		if (value == 'y')
1856 			*(enum libbpf_tristate *)ext_val = TRI_YES;
1857 		else if (value == 'm')
1858 			*(enum libbpf_tristate *)ext_val = TRI_MODULE;
1859 		else /* value == 'n' */
1860 			*(enum libbpf_tristate *)ext_val = TRI_NO;
1861 		break;
1862 	case KCFG_CHAR:
1863 		*(char *)ext_val = value;
1864 		break;
1865 	case KCFG_UNKNOWN:
1866 	case KCFG_INT:
1867 	case KCFG_CHAR_ARR:
1868 	default:
1869 		pr_warn("extern (kcfg) '%s': value '%c' implies bool, tristate, or char type\n",
1870 			ext->name, value);
1871 		return -EINVAL;
1872 	}
1873 	ext->is_set = true;
1874 	return 0;
1875 }
1876 
1877 static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
1878 			      const char *value)
1879 {
1880 	size_t len;
1881 
1882 	if (ext->kcfg.type != KCFG_CHAR_ARR) {
1883 		pr_warn("extern (kcfg) '%s': value '%s' implies char array type\n",
1884 			ext->name, value);
1885 		return -EINVAL;
1886 	}
1887 
1888 	len = strlen(value);
1889 	if (value[len - 1] != '"') {
1890 		pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
1891 			ext->name, value);
1892 		return -EINVAL;
1893 	}
1894 
1895 	/* strip quotes */
1896 	len -= 2;
1897 	if (len >= ext->kcfg.sz) {
1898 		pr_warn("extern (kcfg) '%s': long string '%s' of (%zu bytes) truncated to %d bytes\n",
1899 			ext->name, value, len, ext->kcfg.sz - 1);
1900 		len = ext->kcfg.sz - 1;
1901 	}
1902 	memcpy(ext_val, value + 1, len);
1903 	ext_val[len] = '\0';
1904 	ext->is_set = true;
1905 	return 0;
1906 }
1907 
1908 static int parse_u64(const char *value, __u64 *res)
1909 {
1910 	char *value_end;
1911 	int err;
1912 
1913 	errno = 0;
1914 	*res = strtoull(value, &value_end, 0);
1915 	if (errno) {
1916 		err = -errno;
1917 		pr_warn("failed to parse '%s' as integer: %d\n", value, err);
1918 		return err;
1919 	}
1920 	if (*value_end) {
1921 		pr_warn("failed to parse '%s' as integer completely\n", value);
1922 		return -EINVAL;
1923 	}
1924 	return 0;
1925 }
1926 
1927 static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
1928 {
1929 	int bit_sz = ext->kcfg.sz * 8;
1930 
1931 	if (ext->kcfg.sz == 8)
1932 		return true;
1933 
1934 	/* Validate that value stored in u64 fits in integer of `ext->sz`
1935 	 * bytes size without any loss of information. If the target integer
1936 	 * is signed, we rely on the following limits of integer type of
1937 	 * Y bits and subsequent transformation:
1938 	 *
1939 	 *     -2^(Y-1) <= X           <= 2^(Y-1) - 1
1940 	 *            0 <= X + 2^(Y-1) <= 2^Y - 1
1941 	 *            0 <= X + 2^(Y-1) <  2^Y
1942 	 *
1943 	 *  For unsigned target integer, check that all the (64 - Y) bits are
1944 	 *  zero.
1945 	 */
1946 	if (ext->kcfg.is_signed)
1947 		return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
1948 	else
1949 		return (v >> bit_sz) == 0;
1950 }
1951 
1952 static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
1953 			      __u64 value)
1954 {
1955 	if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR &&
1956 	    ext->kcfg.type != KCFG_BOOL) {
1957 		pr_warn("extern (kcfg) '%s': value '%llu' implies integer, char, or boolean type\n",
1958 			ext->name, (unsigned long long)value);
1959 		return -EINVAL;
1960 	}
1961 	if (ext->kcfg.type == KCFG_BOOL && value > 1) {
1962 		pr_warn("extern (kcfg) '%s': value '%llu' isn't boolean compatible\n",
1963 			ext->name, (unsigned long long)value);
1964 		return -EINVAL;
1965 
1966 	}
1967 	if (!is_kcfg_value_in_range(ext, value)) {
1968 		pr_warn("extern (kcfg) '%s': value '%llu' doesn't fit in %d bytes\n",
1969 			ext->name, (unsigned long long)value, ext->kcfg.sz);
1970 		return -ERANGE;
1971 	}
1972 	switch (ext->kcfg.sz) {
1973 	case 1:
1974 		*(__u8 *)ext_val = value;
1975 		break;
1976 	case 2:
1977 		*(__u16 *)ext_val = value;
1978 		break;
1979 	case 4:
1980 		*(__u32 *)ext_val = value;
1981 		break;
1982 	case 8:
1983 		*(__u64 *)ext_val = value;
1984 		break;
1985 	default:
1986 		return -EINVAL;
1987 	}
1988 	ext->is_set = true;
1989 	return 0;
1990 }
1991 
1992 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
1993 					    char *buf, void *data)
1994 {
1995 	struct extern_desc *ext;
1996 	char *sep, *value;
1997 	int len, err = 0;
1998 	void *ext_val;
1999 	__u64 num;
2000 
2001 	if (!str_has_pfx(buf, "CONFIG_"))
2002 		return 0;
2003 
2004 	sep = strchr(buf, '=');
2005 	if (!sep) {
2006 		pr_warn("failed to parse '%s': no separator\n", buf);
2007 		return -EINVAL;
2008 	}
2009 
2010 	/* Trim ending '\n' */
2011 	len = strlen(buf);
2012 	if (buf[len - 1] == '\n')
2013 		buf[len - 1] = '\0';
2014 	/* Split on '=' and ensure that a value is present. */
2015 	*sep = '\0';
2016 	if (!sep[1]) {
2017 		*sep = '=';
2018 		pr_warn("failed to parse '%s': no value\n", buf);
2019 		return -EINVAL;
2020 	}
2021 
2022 	ext = find_extern_by_name(obj, buf);
2023 	if (!ext || ext->is_set)
2024 		return 0;
2025 
2026 	ext_val = data + ext->kcfg.data_off;
2027 	value = sep + 1;
2028 
2029 	switch (*value) {
2030 	case 'y': case 'n': case 'm':
2031 		err = set_kcfg_value_tri(ext, ext_val, *value);
2032 		break;
2033 	case '"':
2034 		err = set_kcfg_value_str(ext, ext_val, value);
2035 		break;
2036 	default:
2037 		/* assume integer */
2038 		err = parse_u64(value, &num);
2039 		if (err) {
2040 			pr_warn("extern (kcfg) '%s': value '%s' isn't a valid integer\n", ext->name, value);
2041 			return err;
2042 		}
2043 		if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
2044 			pr_warn("extern (kcfg) '%s': value '%s' implies integer type\n", ext->name, value);
2045 			return -EINVAL;
2046 		}
2047 		err = set_kcfg_value_num(ext, ext_val, num);
2048 		break;
2049 	}
2050 	if (err)
2051 		return err;
2052 	pr_debug("extern (kcfg) '%s': set to %s\n", ext->name, value);
2053 	return 0;
2054 }
2055 
2056 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
2057 {
2058 	char buf[PATH_MAX];
2059 	struct utsname uts;
2060 	int len, err = 0;
2061 	gzFile file;
2062 
2063 	uname(&uts);
2064 	len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
2065 	if (len < 0)
2066 		return -EINVAL;
2067 	else if (len >= PATH_MAX)
2068 		return -ENAMETOOLONG;
2069 
2070 	/* gzopen also accepts uncompressed files. */
2071 	file = gzopen(buf, "r");
2072 	if (!file)
2073 		file = gzopen("/proc/config.gz", "r");
2074 
2075 	if (!file) {
2076 		pr_warn("failed to open system Kconfig\n");
2077 		return -ENOENT;
2078 	}
2079 
2080 	while (gzgets(file, buf, sizeof(buf))) {
2081 		err = bpf_object__process_kconfig_line(obj, buf, data);
2082 		if (err) {
2083 			pr_warn("error parsing system Kconfig line '%s': %d\n",
2084 				buf, err);
2085 			goto out;
2086 		}
2087 	}
2088 
2089 out:
2090 	gzclose(file);
2091 	return err;
2092 }
2093 
2094 static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
2095 					const char *config, void *data)
2096 {
2097 	char buf[PATH_MAX];
2098 	int err = 0;
2099 	FILE *file;
2100 
2101 	file = fmemopen((void *)config, strlen(config), "r");
2102 	if (!file) {
2103 		err = -errno;
2104 		pr_warn("failed to open in-memory Kconfig: %d\n", err);
2105 		return err;
2106 	}
2107 
2108 	while (fgets(buf, sizeof(buf), file)) {
2109 		err = bpf_object__process_kconfig_line(obj, buf, data);
2110 		if (err) {
2111 			pr_warn("error parsing in-memory Kconfig line '%s': %d\n",
2112 				buf, err);
2113 			break;
2114 		}
2115 	}
2116 
2117 	fclose(file);
2118 	return err;
2119 }
2120 
2121 static int bpf_object__init_kconfig_map(struct bpf_object *obj)
2122 {
2123 	struct extern_desc *last_ext = NULL, *ext;
2124 	size_t map_sz;
2125 	int i, err;
2126 
2127 	for (i = 0; i < obj->nr_extern; i++) {
2128 		ext = &obj->externs[i];
2129 		if (ext->type == EXT_KCFG)
2130 			last_ext = ext;
2131 	}
2132 
2133 	if (!last_ext)
2134 		return 0;
2135 
2136 	map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
2137 	err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
2138 					    ".kconfig", obj->efile.symbols_shndx,
2139 					    NULL, map_sz);
2140 	if (err)
2141 		return err;
2142 
2143 	obj->kconfig_map_idx = obj->nr_maps - 1;
2144 
2145 	return 0;
2146 }
2147 
2148 const struct btf_type *
2149 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
2150 {
2151 	const struct btf_type *t = btf__type_by_id(btf, id);
2152 
2153 	if (res_id)
2154 		*res_id = id;
2155 
2156 	while (btf_is_mod(t) || btf_is_typedef(t)) {
2157 		if (res_id)
2158 			*res_id = t->type;
2159 		t = btf__type_by_id(btf, t->type);
2160 	}
2161 
2162 	return t;
2163 }
2164 
2165 static const struct btf_type *
2166 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
2167 {
2168 	const struct btf_type *t;
2169 
2170 	t = skip_mods_and_typedefs(btf, id, NULL);
2171 	if (!btf_is_ptr(t))
2172 		return NULL;
2173 
2174 	t = skip_mods_and_typedefs(btf, t->type, res_id);
2175 
2176 	return btf_is_func_proto(t) ? t : NULL;
2177 }
2178 
2179 static const char *__btf_kind_str(__u16 kind)
2180 {
2181 	switch (kind) {
2182 	case BTF_KIND_UNKN: return "void";
2183 	case BTF_KIND_INT: return "int";
2184 	case BTF_KIND_PTR: return "ptr";
2185 	case BTF_KIND_ARRAY: return "array";
2186 	case BTF_KIND_STRUCT: return "struct";
2187 	case BTF_KIND_UNION: return "union";
2188 	case BTF_KIND_ENUM: return "enum";
2189 	case BTF_KIND_FWD: return "fwd";
2190 	case BTF_KIND_TYPEDEF: return "typedef";
2191 	case BTF_KIND_VOLATILE: return "volatile";
2192 	case BTF_KIND_CONST: return "const";
2193 	case BTF_KIND_RESTRICT: return "restrict";
2194 	case BTF_KIND_FUNC: return "func";
2195 	case BTF_KIND_FUNC_PROTO: return "func_proto";
2196 	case BTF_KIND_VAR: return "var";
2197 	case BTF_KIND_DATASEC: return "datasec";
2198 	case BTF_KIND_FLOAT: return "float";
2199 	case BTF_KIND_DECL_TAG: return "decl_tag";
2200 	case BTF_KIND_TYPE_TAG: return "type_tag";
2201 	case BTF_KIND_ENUM64: return "enum64";
2202 	default: return "unknown";
2203 	}
2204 }
2205 
2206 const char *btf_kind_str(const struct btf_type *t)
2207 {
2208 	return __btf_kind_str(btf_kind(t));
2209 }
2210 
2211 /*
2212  * Fetch integer attribute of BTF map definition. Such attributes are
2213  * represented using a pointer to an array, in which dimensionality of array
2214  * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2215  * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2216  * type definition, while using only sizeof(void *) space in ELF data section.
2217  */
2218 static bool get_map_field_int(const char *map_name, const struct btf *btf,
2219 			      const struct btf_member *m, __u32 *res)
2220 {
2221 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2222 	const char *name = btf__name_by_offset(btf, m->name_off);
2223 	const struct btf_array *arr_info;
2224 	const struct btf_type *arr_t;
2225 
2226 	if (!btf_is_ptr(t)) {
2227 		pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2228 			map_name, name, btf_kind_str(t));
2229 		return false;
2230 	}
2231 
2232 	arr_t = btf__type_by_id(btf, t->type);
2233 	if (!arr_t) {
2234 		pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2235 			map_name, name, t->type);
2236 		return false;
2237 	}
2238 	if (!btf_is_array(arr_t)) {
2239 		pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2240 			map_name, name, btf_kind_str(arr_t));
2241 		return false;
2242 	}
2243 	arr_info = btf_array(arr_t);
2244 	*res = arr_info->nelems;
2245 	return true;
2246 }
2247 
2248 static int pathname_concat(char *buf, size_t buf_sz, const char *path, const char *name)
2249 {
2250 	int len;
2251 
2252 	len = snprintf(buf, buf_sz, "%s/%s", path, name);
2253 	if (len < 0)
2254 		return -EINVAL;
2255 	if (len >= buf_sz)
2256 		return -ENAMETOOLONG;
2257 
2258 	return 0;
2259 }
2260 
2261 static int build_map_pin_path(struct bpf_map *map, const char *path)
2262 {
2263 	char buf[PATH_MAX];
2264 	int err;
2265 
2266 	if (!path)
2267 		path = "/sys/fs/bpf";
2268 
2269 	err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
2270 	if (err)
2271 		return err;
2272 
2273 	return bpf_map__set_pin_path(map, buf);
2274 }
2275 
2276 /* should match definition in bpf_helpers.h */
2277 enum libbpf_pin_type {
2278 	LIBBPF_PIN_NONE,
2279 	/* PIN_BY_NAME: pin maps by name (in /sys/fs/bpf by default) */
2280 	LIBBPF_PIN_BY_NAME,
2281 };
2282 
2283 int parse_btf_map_def(const char *map_name, struct btf *btf,
2284 		      const struct btf_type *def_t, bool strict,
2285 		      struct btf_map_def *map_def, struct btf_map_def *inner_def)
2286 {
2287 	const struct btf_type *t;
2288 	const struct btf_member *m;
2289 	bool is_inner = inner_def == NULL;
2290 	int vlen, i;
2291 
2292 	vlen = btf_vlen(def_t);
2293 	m = btf_members(def_t);
2294 	for (i = 0; i < vlen; i++, m++) {
2295 		const char *name = btf__name_by_offset(btf, m->name_off);
2296 
2297 		if (!name) {
2298 			pr_warn("map '%s': invalid field #%d.\n", map_name, i);
2299 			return -EINVAL;
2300 		}
2301 		if (strcmp(name, "type") == 0) {
2302 			if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
2303 				return -EINVAL;
2304 			map_def->parts |= MAP_DEF_MAP_TYPE;
2305 		} else if (strcmp(name, "max_entries") == 0) {
2306 			if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
2307 				return -EINVAL;
2308 			map_def->parts |= MAP_DEF_MAX_ENTRIES;
2309 		} else if (strcmp(name, "map_flags") == 0) {
2310 			if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
2311 				return -EINVAL;
2312 			map_def->parts |= MAP_DEF_MAP_FLAGS;
2313 		} else if (strcmp(name, "numa_node") == 0) {
2314 			if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
2315 				return -EINVAL;
2316 			map_def->parts |= MAP_DEF_NUMA_NODE;
2317 		} else if (strcmp(name, "key_size") == 0) {
2318 			__u32 sz;
2319 
2320 			if (!get_map_field_int(map_name, btf, m, &sz))
2321 				return -EINVAL;
2322 			if (map_def->key_size && map_def->key_size != sz) {
2323 				pr_warn("map '%s': conflicting key size %u != %u.\n",
2324 					map_name, map_def->key_size, sz);
2325 				return -EINVAL;
2326 			}
2327 			map_def->key_size = sz;
2328 			map_def->parts |= MAP_DEF_KEY_SIZE;
2329 		} else if (strcmp(name, "key") == 0) {
2330 			__s64 sz;
2331 
2332 			t = btf__type_by_id(btf, m->type);
2333 			if (!t) {
2334 				pr_warn("map '%s': key type [%d] not found.\n",
2335 					map_name, m->type);
2336 				return -EINVAL;
2337 			}
2338 			if (!btf_is_ptr(t)) {
2339 				pr_warn("map '%s': key spec is not PTR: %s.\n",
2340 					map_name, btf_kind_str(t));
2341 				return -EINVAL;
2342 			}
2343 			sz = btf__resolve_size(btf, t->type);
2344 			if (sz < 0) {
2345 				pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2346 					map_name, t->type, (ssize_t)sz);
2347 				return sz;
2348 			}
2349 			if (map_def->key_size && map_def->key_size != sz) {
2350 				pr_warn("map '%s': conflicting key size %u != %zd.\n",
2351 					map_name, map_def->key_size, (ssize_t)sz);
2352 				return -EINVAL;
2353 			}
2354 			map_def->key_size = sz;
2355 			map_def->key_type_id = t->type;
2356 			map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
2357 		} else if (strcmp(name, "value_size") == 0) {
2358 			__u32 sz;
2359 
2360 			if (!get_map_field_int(map_name, btf, m, &sz))
2361 				return -EINVAL;
2362 			if (map_def->value_size && map_def->value_size != sz) {
2363 				pr_warn("map '%s': conflicting value size %u != %u.\n",
2364 					map_name, map_def->value_size, sz);
2365 				return -EINVAL;
2366 			}
2367 			map_def->value_size = sz;
2368 			map_def->parts |= MAP_DEF_VALUE_SIZE;
2369 		} else if (strcmp(name, "value") == 0) {
2370 			__s64 sz;
2371 
2372 			t = btf__type_by_id(btf, m->type);
2373 			if (!t) {
2374 				pr_warn("map '%s': value type [%d] not found.\n",
2375 					map_name, m->type);
2376 				return -EINVAL;
2377 			}
2378 			if (!btf_is_ptr(t)) {
2379 				pr_warn("map '%s': value spec is not PTR: %s.\n",
2380 					map_name, btf_kind_str(t));
2381 				return -EINVAL;
2382 			}
2383 			sz = btf__resolve_size(btf, t->type);
2384 			if (sz < 0) {
2385 				pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2386 					map_name, t->type, (ssize_t)sz);
2387 				return sz;
2388 			}
2389 			if (map_def->value_size && map_def->value_size != sz) {
2390 				pr_warn("map '%s': conflicting value size %u != %zd.\n",
2391 					map_name, map_def->value_size, (ssize_t)sz);
2392 				return -EINVAL;
2393 			}
2394 			map_def->value_size = sz;
2395 			map_def->value_type_id = t->type;
2396 			map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
2397 		}
2398 		else if (strcmp(name, "values") == 0) {
2399 			bool is_map_in_map = bpf_map_type__is_map_in_map(map_def->map_type);
2400 			bool is_prog_array = map_def->map_type == BPF_MAP_TYPE_PROG_ARRAY;
2401 			const char *desc = is_map_in_map ? "map-in-map inner" : "prog-array value";
2402 			char inner_map_name[128];
2403 			int err;
2404 
2405 			if (is_inner) {
2406 				pr_warn("map '%s': multi-level inner maps not supported.\n",
2407 					map_name);
2408 				return -ENOTSUP;
2409 			}
2410 			if (i != vlen - 1) {
2411 				pr_warn("map '%s': '%s' member should be last.\n",
2412 					map_name, name);
2413 				return -EINVAL;
2414 			}
2415 			if (!is_map_in_map && !is_prog_array) {
2416 				pr_warn("map '%s': should be map-in-map or prog-array.\n",
2417 					map_name);
2418 				return -ENOTSUP;
2419 			}
2420 			if (map_def->value_size && map_def->value_size != 4) {
2421 				pr_warn("map '%s': conflicting value size %u != 4.\n",
2422 					map_name, map_def->value_size);
2423 				return -EINVAL;
2424 			}
2425 			map_def->value_size = 4;
2426 			t = btf__type_by_id(btf, m->type);
2427 			if (!t) {
2428 				pr_warn("map '%s': %s type [%d] not found.\n",
2429 					map_name, desc, m->type);
2430 				return -EINVAL;
2431 			}
2432 			if (!btf_is_array(t) || btf_array(t)->nelems) {
2433 				pr_warn("map '%s': %s spec is not a zero-sized array.\n",
2434 					map_name, desc);
2435 				return -EINVAL;
2436 			}
2437 			t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
2438 			if (!btf_is_ptr(t)) {
2439 				pr_warn("map '%s': %s def is of unexpected kind %s.\n",
2440 					map_name, desc, btf_kind_str(t));
2441 				return -EINVAL;
2442 			}
2443 			t = skip_mods_and_typedefs(btf, t->type, NULL);
2444 			if (is_prog_array) {
2445 				if (!btf_is_func_proto(t)) {
2446 					pr_warn("map '%s': prog-array value def is of unexpected kind %s.\n",
2447 						map_name, btf_kind_str(t));
2448 					return -EINVAL;
2449 				}
2450 				continue;
2451 			}
2452 			if (!btf_is_struct(t)) {
2453 				pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2454 					map_name, btf_kind_str(t));
2455 				return -EINVAL;
2456 			}
2457 
2458 			snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2459 			err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
2460 			if (err)
2461 				return err;
2462 
2463 			map_def->parts |= MAP_DEF_INNER_MAP;
2464 		} else if (strcmp(name, "pinning") == 0) {
2465 			__u32 val;
2466 
2467 			if (is_inner) {
2468 				pr_warn("map '%s': inner def can't be pinned.\n", map_name);
2469 				return -EINVAL;
2470 			}
2471 			if (!get_map_field_int(map_name, btf, m, &val))
2472 				return -EINVAL;
2473 			if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
2474 				pr_warn("map '%s': invalid pinning value %u.\n",
2475 					map_name, val);
2476 				return -EINVAL;
2477 			}
2478 			map_def->pinning = val;
2479 			map_def->parts |= MAP_DEF_PINNING;
2480 		} else if (strcmp(name, "map_extra") == 0) {
2481 			__u32 map_extra;
2482 
2483 			if (!get_map_field_int(map_name, btf, m, &map_extra))
2484 				return -EINVAL;
2485 			map_def->map_extra = map_extra;
2486 			map_def->parts |= MAP_DEF_MAP_EXTRA;
2487 		} else {
2488 			if (strict) {
2489 				pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
2490 				return -ENOTSUP;
2491 			}
2492 			pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
2493 		}
2494 	}
2495 
2496 	if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2497 		pr_warn("map '%s': map type isn't specified.\n", map_name);
2498 		return -EINVAL;
2499 	}
2500 
2501 	return 0;
2502 }
2503 
2504 static size_t adjust_ringbuf_sz(size_t sz)
2505 {
2506 	__u32 page_sz = sysconf(_SC_PAGE_SIZE);
2507 	__u32 mul;
2508 
2509 	/* if user forgot to set any size, make sure they see error */
2510 	if (sz == 0)
2511 		return 0;
2512 	/* Kernel expects BPF_MAP_TYPE_RINGBUF's max_entries to be
2513 	 * a power-of-2 multiple of kernel's page size. If user diligently
2514 	 * satisified these conditions, pass the size through.
2515 	 */
2516 	if ((sz % page_sz) == 0 && is_pow_of_2(sz / page_sz))
2517 		return sz;
2518 
2519 	/* Otherwise find closest (page_sz * power_of_2) product bigger than
2520 	 * user-set size to satisfy both user size request and kernel
2521 	 * requirements and substitute correct max_entries for map creation.
2522 	 */
2523 	for (mul = 1; mul <= UINT_MAX / page_sz; mul <<= 1) {
2524 		if (mul * page_sz > sz)
2525 			return mul * page_sz;
2526 	}
2527 
2528 	/* if it's impossible to satisfy the conditions (i.e., user size is
2529 	 * very close to UINT_MAX but is not a power-of-2 multiple of
2530 	 * page_size) then just return original size and let kernel reject it
2531 	 */
2532 	return sz;
2533 }
2534 
2535 static bool map_is_ringbuf(const struct bpf_map *map)
2536 {
2537 	return map->def.type == BPF_MAP_TYPE_RINGBUF ||
2538 	       map->def.type == BPF_MAP_TYPE_USER_RINGBUF;
2539 }
2540 
2541 static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2542 {
2543 	map->def.type = def->map_type;
2544 	map->def.key_size = def->key_size;
2545 	map->def.value_size = def->value_size;
2546 	map->def.max_entries = def->max_entries;
2547 	map->def.map_flags = def->map_flags;
2548 	map->map_extra = def->map_extra;
2549 
2550 	map->numa_node = def->numa_node;
2551 	map->btf_key_type_id = def->key_type_id;
2552 	map->btf_value_type_id = def->value_type_id;
2553 
2554 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
2555 	if (map_is_ringbuf(map))
2556 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
2557 
2558 	if (def->parts & MAP_DEF_MAP_TYPE)
2559 		pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2560 
2561 	if (def->parts & MAP_DEF_KEY_TYPE)
2562 		pr_debug("map '%s': found key [%u], sz = %u.\n",
2563 			 map->name, def->key_type_id, def->key_size);
2564 	else if (def->parts & MAP_DEF_KEY_SIZE)
2565 		pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2566 
2567 	if (def->parts & MAP_DEF_VALUE_TYPE)
2568 		pr_debug("map '%s': found value [%u], sz = %u.\n",
2569 			 map->name, def->value_type_id, def->value_size);
2570 	else if (def->parts & MAP_DEF_VALUE_SIZE)
2571 		pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2572 
2573 	if (def->parts & MAP_DEF_MAX_ENTRIES)
2574 		pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2575 	if (def->parts & MAP_DEF_MAP_FLAGS)
2576 		pr_debug("map '%s': found map_flags = 0x%x.\n", map->name, def->map_flags);
2577 	if (def->parts & MAP_DEF_MAP_EXTRA)
2578 		pr_debug("map '%s': found map_extra = 0x%llx.\n", map->name,
2579 			 (unsigned long long)def->map_extra);
2580 	if (def->parts & MAP_DEF_PINNING)
2581 		pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2582 	if (def->parts & MAP_DEF_NUMA_NODE)
2583 		pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2584 
2585 	if (def->parts & MAP_DEF_INNER_MAP)
2586 		pr_debug("map '%s': found inner map definition.\n", map->name);
2587 }
2588 
2589 static const char *btf_var_linkage_str(__u32 linkage)
2590 {
2591 	switch (linkage) {
2592 	case BTF_VAR_STATIC: return "static";
2593 	case BTF_VAR_GLOBAL_ALLOCATED: return "global";
2594 	case BTF_VAR_GLOBAL_EXTERN: return "extern";
2595 	default: return "unknown";
2596 	}
2597 }
2598 
2599 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2600 					 const struct btf_type *sec,
2601 					 int var_idx, int sec_idx,
2602 					 const Elf_Data *data, bool strict,
2603 					 const char *pin_root_path)
2604 {
2605 	struct btf_map_def map_def = {}, inner_def = {};
2606 	const struct btf_type *var, *def;
2607 	const struct btf_var_secinfo *vi;
2608 	const struct btf_var *var_extra;
2609 	const char *map_name;
2610 	struct bpf_map *map;
2611 	int err;
2612 
2613 	vi = btf_var_secinfos(sec) + var_idx;
2614 	var = btf__type_by_id(obj->btf, vi->type);
2615 	var_extra = btf_var(var);
2616 	map_name = btf__name_by_offset(obj->btf, var->name_off);
2617 
2618 	if (map_name == NULL || map_name[0] == '\0') {
2619 		pr_warn("map #%d: empty name.\n", var_idx);
2620 		return -EINVAL;
2621 	}
2622 	if ((__u64)vi->offset + vi->size > data->d_size) {
2623 		pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2624 		return -EINVAL;
2625 	}
2626 	if (!btf_is_var(var)) {
2627 		pr_warn("map '%s': unexpected var kind %s.\n",
2628 			map_name, btf_kind_str(var));
2629 		return -EINVAL;
2630 	}
2631 	if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
2632 		pr_warn("map '%s': unsupported map linkage %s.\n",
2633 			map_name, btf_var_linkage_str(var_extra->linkage));
2634 		return -EOPNOTSUPP;
2635 	}
2636 
2637 	def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2638 	if (!btf_is_struct(def)) {
2639 		pr_warn("map '%s': unexpected def kind %s.\n",
2640 			map_name, btf_kind_str(var));
2641 		return -EINVAL;
2642 	}
2643 	if (def->size > vi->size) {
2644 		pr_warn("map '%s': invalid def size.\n", map_name);
2645 		return -EINVAL;
2646 	}
2647 
2648 	map = bpf_object__add_map(obj);
2649 	if (IS_ERR(map))
2650 		return PTR_ERR(map);
2651 	map->name = strdup(map_name);
2652 	if (!map->name) {
2653 		pr_warn("map '%s': failed to alloc map name.\n", map_name);
2654 		return -ENOMEM;
2655 	}
2656 	map->libbpf_type = LIBBPF_MAP_UNSPEC;
2657 	map->def.type = BPF_MAP_TYPE_UNSPEC;
2658 	map->sec_idx = sec_idx;
2659 	map->sec_offset = vi->offset;
2660 	map->btf_var_idx = var_idx;
2661 	pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2662 		 map_name, map->sec_idx, map->sec_offset);
2663 
2664 	err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
2665 	if (err)
2666 		return err;
2667 
2668 	fill_map_from_def(map, &map_def);
2669 
2670 	if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
2671 		err = build_map_pin_path(map, pin_root_path);
2672 		if (err) {
2673 			pr_warn("map '%s': couldn't build pin path.\n", map->name);
2674 			return err;
2675 		}
2676 	}
2677 
2678 	if (map_def.parts & MAP_DEF_INNER_MAP) {
2679 		map->inner_map = calloc(1, sizeof(*map->inner_map));
2680 		if (!map->inner_map)
2681 			return -ENOMEM;
2682 		map->inner_map->fd = -1;
2683 		map->inner_map->sec_idx = sec_idx;
2684 		map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
2685 		if (!map->inner_map->name)
2686 			return -ENOMEM;
2687 		sprintf(map->inner_map->name, "%s.inner", map_name);
2688 
2689 		fill_map_from_def(map->inner_map, &inner_def);
2690 	}
2691 
2692 	err = map_fill_btf_type_info(obj, map);
2693 	if (err)
2694 		return err;
2695 
2696 	return 0;
2697 }
2698 
2699 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
2700 					  const char *pin_root_path)
2701 {
2702 	const struct btf_type *sec = NULL;
2703 	int nr_types, i, vlen, err;
2704 	const struct btf_type *t;
2705 	const char *name;
2706 	Elf_Data *data;
2707 #ifdef HAVE_LIBELF
2708 	Elf_Scn *scn;
2709 #endif
2710 
2711 	if (obj->efile.btf_maps_shndx < 0)
2712 		return 0;
2713 #if defined HAVE_LIBELF
2714 	scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
2715 	data = elf_sec_data(obj, scn);
2716 	if (!scn || !data) {
2717 #elif defined HAVE_ELFIO
2718 	Elf_Data realdata;
2719 	data = elf_sec_data_by_idx(obj, obj->efile.btf_maps_shndx, &realdata);
2720 	if (!data) {
2721 #endif
2722 		pr_warn("elf: failed to get %s map definitions for %s\n",
2723 			MAPS_ELF_SEC, obj->path);
2724 		return -EINVAL;
2725 	}
2726 
2727 	nr_types = btf__type_cnt(obj->btf);
2728 	for (i = 1; i < nr_types; i++) {
2729 		t = btf__type_by_id(obj->btf, i);
2730 		if (!btf_is_datasec(t))
2731 			continue;
2732 		name = btf__name_by_offset(obj->btf, t->name_off);
2733 		if (strcmp(name, MAPS_ELF_SEC) == 0) {
2734 			sec = t;
2735 			obj->efile.btf_maps_sec_btf_id = i;
2736 			break;
2737 		}
2738 	}
2739 
2740 	if (!sec) {
2741 		pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
2742 		return -ENOENT;
2743 	}
2744 
2745 	vlen = btf_vlen(sec);
2746 	for (i = 0; i < vlen; i++) {
2747 		err = bpf_object__init_user_btf_map(obj, sec, i,
2748 						    obj->efile.btf_maps_shndx,
2749 						    data, strict,
2750 						    pin_root_path);
2751 		if (err)
2752 			return err;
2753 	}
2754 
2755 	return 0;
2756 }
2757 
2758 static int bpf_object__init_maps(struct bpf_object *obj,
2759 				 const struct bpf_object_open_opts *opts)
2760 {
2761 	const char *pin_root_path;
2762 	bool strict;
2763 	int err = 0;
2764 
2765 	strict = !OPTS_GET(opts, relaxed_maps, false);
2766 	pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
2767 
2768 	err = err ?: bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
2769 	err = err ?: bpf_object__init_global_data_maps(obj);
2770 	err = err ?: bpf_object__init_kconfig_map(obj);
2771 	err = err ?: bpf_object__init_struct_ops_maps(obj);
2772 
2773 	return err;
2774 }
2775 
2776 static bool section_have_execinstr(struct bpf_object *obj, int idx)
2777 {
2778 	Elf64_Shdr *sh;
2779 #if defined HAVE_LIBELF
2780 	sh = elf_sec_hdr(obj, elf_sec_by_idx(obj, idx));
2781 #elif defined HAVE_ELFIO
2782 	Elf64_Shdr header;
2783 	sh = elf_sec_hdr_by_idx(obj, idx, &header);
2784 #endif
2785 	if (!sh)
2786 		return false;
2787 
2788 	return sh->sh_flags & SHF_EXECINSTR;
2789 }
2790 
2791 static bool btf_needs_sanitization(struct bpf_object *obj)
2792 {
2793 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2794 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2795 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2796 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2797 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2798 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2799 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
2800 
2801 	return !has_func || !has_datasec || !has_func_global || !has_float ||
2802 	       !has_decl_tag || !has_type_tag || !has_enum64;
2803 }
2804 
2805 static int bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *btf)
2806 {
2807 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2808 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2809 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2810 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2811 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2812 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2813 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
2814 	int enum64_placeholder_id = 0;
2815 	struct btf_type *t;
2816 	int i, j, vlen;
2817 
2818 	for (i = 1; i < btf__type_cnt(btf); i++) {
2819 		t = (struct btf_type *)btf__type_by_id(btf, i);
2820 
2821 		if ((!has_datasec && btf_is_var(t)) || (!has_decl_tag && btf_is_decl_tag(t))) {
2822 			/* replace VAR/DECL_TAG with INT */
2823 			t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
2824 			/*
2825 			 * using size = 1 is the safest choice, 4 will be too
2826 			 * big and cause kernel BTF validation failure if
2827 			 * original variable took less than 4 bytes
2828 			 */
2829 			t->size = 1;
2830 			*(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
2831 		} else if (!has_datasec && btf_is_datasec(t)) {
2832 			/* replace DATASEC with STRUCT */
2833 			const struct btf_var_secinfo *v = btf_var_secinfos(t);
2834 			struct btf_member *m = btf_members(t);
2835 			struct btf_type *vt;
2836 			char *name;
2837 
2838 			name = (char *)btf__name_by_offset(btf, t->name_off);
2839 			while (*name) {
2840 				if (*name == '.')
2841 					*name = '_';
2842 				name++;
2843 			}
2844 
2845 			vlen = btf_vlen(t);
2846 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
2847 			for (j = 0; j < vlen; j++, v++, m++) {
2848 				/* order of field assignments is important */
2849 				m->offset = v->offset * 8;
2850 				m->type = v->type;
2851 				/* preserve variable name as member name */
2852 				vt = (void *)btf__type_by_id(btf, v->type);
2853 				m->name_off = vt->name_off;
2854 			}
2855 		} else if (!has_func && btf_is_func_proto(t)) {
2856 			/* replace FUNC_PROTO with ENUM */
2857 			vlen = btf_vlen(t);
2858 			t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
2859 			t->size = sizeof(__u32); /* kernel enforced */
2860 		} else if (!has_func && btf_is_func(t)) {
2861 			/* replace FUNC with TYPEDEF */
2862 			t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
2863 		} else if (!has_func_global && btf_is_func(t)) {
2864 			/* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
2865 			t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
2866 		} else if (!has_float && btf_is_float(t)) {
2867 			/* replace FLOAT with an equally-sized empty STRUCT;
2868 			 * since C compilers do not accept e.g. "float" as a
2869 			 * valid struct name, make it anonymous
2870 			 */
2871 			t->name_off = 0;
2872 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
2873 		} else if (!has_type_tag && btf_is_type_tag(t)) {
2874 			/* replace TYPE_TAG with a CONST */
2875 			t->name_off = 0;
2876 			t->info = BTF_INFO_ENC(BTF_KIND_CONST, 0, 0);
2877 		} else if (!has_enum64 && btf_is_enum(t)) {
2878 			/* clear the kflag */
2879 			t->info = btf_type_info(btf_kind(t), btf_vlen(t), false);
2880 		} else if (!has_enum64 && btf_is_enum64(t)) {
2881 			/* replace ENUM64 with a union */
2882 			struct btf_member *m;
2883 
2884 			if (enum64_placeholder_id == 0) {
2885 				enum64_placeholder_id = btf__add_int(btf, "enum64_placeholder", 1, 0);
2886 				if (enum64_placeholder_id < 0)
2887 					return enum64_placeholder_id;
2888 
2889 				t = (struct btf_type *)btf__type_by_id(btf, i);
2890 			}
2891 
2892 			m = btf_members(t);
2893 			vlen = btf_vlen(t);
2894 			t->info = BTF_INFO_ENC(BTF_KIND_UNION, 0, vlen);
2895 			for (j = 0; j < vlen; j++, m++) {
2896 				m->type = enum64_placeholder_id;
2897 				m->offset = 0;
2898 			}
2899 		}
2900 	}
2901 
2902 	return 0;
2903 }
2904 
2905 static bool libbpf_needs_btf(const struct bpf_object *obj)
2906 {
2907 	return obj->efile.btf_maps_shndx >= 0 ||
2908 	       obj->efile.st_ops_shndx >= 0 ||
2909 	       obj->nr_extern > 0;
2910 }
2911 
2912 static bool kernel_needs_btf(const struct bpf_object *obj)
2913 {
2914 	return obj->efile.st_ops_shndx >= 0;
2915 }
2916 
2917 static int bpf_object__init_btf(struct bpf_object *obj,
2918 				Elf_Data *btf_data,
2919 				Elf_Data *btf_ext_data)
2920 {
2921 	int err = -ENOENT;
2922 
2923 	if (btf_data) {
2924 		obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
2925 		err = libbpf_get_error(obj->btf);
2926 		if (err) {
2927 			obj->btf = NULL;
2928 			pr_warn("Error loading ELF section %s: %d.\n", BTF_ELF_SEC, err);
2929 			goto out;
2930 		}
2931 		/* enforce 8-byte pointers for BPF-targeted BTFs */
2932 		btf__set_pointer_size(obj->btf, 8);
2933 	}
2934 	if (btf_ext_data) {
2935 		struct btf_ext_info *ext_segs[3];
2936 		int seg_num, sec_num;
2937 
2938 		if (!obj->btf) {
2939 			pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
2940 				 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
2941 			goto out;
2942 		}
2943 		obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
2944 		err = libbpf_get_error(obj->btf_ext);
2945 		if (err) {
2946 			pr_warn("Error loading ELF section %s: %d. Ignored and continue.\n",
2947 				BTF_EXT_ELF_SEC, err);
2948 			obj->btf_ext = NULL;
2949 			goto out;
2950 		}
2951 
2952 		/* setup .BTF.ext to ELF section mapping */
2953 		ext_segs[0] = &obj->btf_ext->func_info;
2954 		ext_segs[1] = &obj->btf_ext->line_info;
2955 		ext_segs[2] = &obj->btf_ext->core_relo_info;
2956 		for (seg_num = 0; seg_num < ARRAY_SIZE(ext_segs); seg_num++) {
2957 			struct btf_ext_info *seg = ext_segs[seg_num];
2958 			const struct btf_ext_info_sec *sec;
2959 			const char *sec_name;
2960 #ifdef HAVE_LIBELF
2961 			Elf_Scn *scn;
2962 #elif defined HAVE_ELFIO
2963 			psection_t sec_obj;
2964 #endif
2965 
2966 			if (seg->sec_cnt == 0)
2967 				continue;
2968 
2969 			seg->sec_idxs = calloc(seg->sec_cnt, sizeof(*seg->sec_idxs));
2970 			if (!seg->sec_idxs) {
2971 				err = -ENOMEM;
2972 				goto out;
2973 			}
2974 
2975 			sec_num = 0;
2976 			for_each_btf_ext_sec(seg, sec) {
2977 				/* preventively increment index to avoid doing
2978 				 * this before every continue below
2979 				 */
2980 				sec_num++;
2981 
2982 				sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
2983 				if (str_is_empty(sec_name))
2984 					continue;
2985 #ifdef  HAVE_LIBELF
2986 				scn = elf_sec_by_name(obj, sec_name);
2987 				if (!scn)
2988 					continue;
2989 #elif defined HAVE_ELFIO
2990 				pelfio_t elf = obj->efile.elf;
2991 				sec_obj = elfio_get_section_by_name(elf, sec_name);
2992 				if (!sec_obj)
2993 					continue;
2994 #endif
2995 #ifdef  HAVE_LIBELF
2996 				seg->sec_idxs[sec_num - 1] = elf_ndxscn(scn);
2997 #elif defined HAVE_ELFIO
2998 				seg->sec_idxs[sec_num - 1] = elfio_section_get_index(sec_obj);
2999 #endif
3000 			}
3001 		}
3002 	}
3003 out:
3004 	if (err && libbpf_needs_btf(obj)) {
3005 		pr_warn("BTF is required, but is missing or corrupted.\n");
3006 		return err;
3007 	}
3008 	return 0;
3009 }
3010 
3011 static int compare_vsi_off(const void *_a, const void *_b)
3012 {
3013 	const struct btf_var_secinfo *a = _a;
3014 	const struct btf_var_secinfo *b = _b;
3015 
3016 	return a->offset - b->offset;
3017 }
3018 
3019 static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
3020 			     struct btf_type *t)
3021 {
3022 	__u32 size = 0, i, vars = btf_vlen(t);
3023 	const char *sec_name = btf__name_by_offset(btf, t->name_off);
3024 	struct btf_var_secinfo *vsi;
3025 	bool fixup_offsets = false;
3026 	int err;
3027 
3028 	if (!sec_name) {
3029 		pr_debug("No name found in string section for DATASEC kind.\n");
3030 		return -ENOENT;
3031 	}
3032 
3033 	/* Extern-backing datasecs (.ksyms, .kconfig) have their size and
3034 	 * variable offsets set at the previous step. Further, not every
3035 	 * extern BTF VAR has corresponding ELF symbol preserved, so we skip
3036 	 * all fixups altogether for such sections and go straight to sorting
3037 	 * VARs within their DATASEC.
3038 	 */
3039 	if (strcmp(sec_name, KCONFIG_SEC) == 0 || strcmp(sec_name, KSYMS_SEC) == 0)
3040 		goto sort_vars;
3041 
3042 	/* Clang leaves DATASEC size and VAR offsets as zeroes, so we need to
3043 	 * fix this up. But BPF static linker already fixes this up and fills
3044 	 * all the sizes and offsets during static linking. So this step has
3045 	 * to be optional. But the STV_HIDDEN handling is non-optional for any
3046 	 * non-extern DATASEC, so the variable fixup loop below handles both
3047 	 * functions at the same time, paying the cost of BTF VAR <-> ELF
3048 	 * symbol matching just once.
3049 	 */
3050 	if (t->size == 0) {
3051 		err = find_elf_sec_sz(obj, sec_name, &size);
3052 		if (err || !size) {
3053 			pr_debug("sec '%s': failed to determine size from ELF: size %u, err %d\n",
3054 				 sec_name, size, err);
3055 			return -ENOENT;
3056 		}
3057 
3058 		t->size = size;
3059 		fixup_offsets = true;
3060 	}
3061 
3062 	for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
3063 		const struct btf_type *t_var;
3064 		struct btf_var *var;
3065 		const char *var_name;
3066 		Elf64_Sym *sym;
3067 
3068 		t_var = btf__type_by_id(btf, vsi->type);
3069 		if (!t_var || !btf_is_var(t_var)) {
3070 			pr_debug("sec '%s': unexpected non-VAR type found\n", sec_name);
3071 			return -EINVAL;
3072 		}
3073 
3074 		var = btf_var(t_var);
3075 		if (var->linkage == BTF_VAR_STATIC || var->linkage == BTF_VAR_GLOBAL_EXTERN)
3076 			continue;
3077 
3078 		var_name = btf__name_by_offset(btf, t_var->name_off);
3079 		if (!var_name) {
3080 			pr_debug("sec '%s': failed to find name of DATASEC's member #%d\n",
3081 				 sec_name, i);
3082 			return -ENOENT;
3083 		}
3084 
3085 		sym = find_elf_var_sym(obj, var_name);
3086 		if (IS_ERR(sym)) {
3087 			pr_debug("sec '%s': failed to find ELF symbol for VAR '%s'\n",
3088 				 sec_name, var_name);
3089 			return -ENOENT;
3090 		}
3091 
3092 		if (fixup_offsets)
3093 			vsi->offset = sym->st_value;
3094 
3095 		/* if variable is a global/weak symbol, but has restricted
3096 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF VAR
3097 		 * as static. This follows similar logic for functions (BPF
3098 		 * subprogs) and influences libbpf's further decisions about
3099 		 * whether to make global data BPF array maps as
3100 		 * BPF_F_MMAPABLE.
3101 		 */
3102 		if (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
3103 		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL)
3104 			var->linkage = BTF_VAR_STATIC;
3105 	}
3106 
3107 sort_vars:
3108 	qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
3109 	return 0;
3110 }
3111 
3112 static int bpf_object_fixup_btf(struct bpf_object *obj)
3113 {
3114 	int i, n, err = 0;
3115 
3116 	if (!obj->btf)
3117 		return 0;
3118 
3119 	n = btf__type_cnt(obj->btf);
3120 	for (i = 1; i < n; i++) {
3121 		struct btf_type *t = btf_type_by_id(obj->btf, i);
3122 
3123 		/* Loader needs to fix up some of the things compiler
3124 		 * couldn't get its hands on while emitting BTF. This
3125 		 * is section size and global variable offset. We use
3126 		 * the info from the ELF itself for this purpose.
3127 		 */
3128 		if (btf_is_datasec(t)) {
3129 			err = btf_fixup_datasec(obj, obj->btf, t);
3130 			if (err)
3131 				return err;
3132 		}
3133 	}
3134 
3135 	return 0;
3136 }
3137 
3138 static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
3139 {
3140 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
3141 	    prog->type == BPF_PROG_TYPE_LSM)
3142 		return true;
3143 
3144 	/* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
3145 	 * also need vmlinux BTF
3146 	 */
3147 	if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
3148 		return true;
3149 
3150 	return false;
3151 }
3152 
3153 static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
3154 {
3155 	struct bpf_program *prog;
3156 	int i;
3157 
3158 	/* CO-RE relocations need kernel BTF, only when btf_custom_path
3159 	 * is not specified
3160 	 */
3161 	if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
3162 		return true;
3163 
3164 	/* Support for typed ksyms needs kernel BTF */
3165 	for (i = 0; i < obj->nr_extern; i++) {
3166 		const struct extern_desc *ext;
3167 
3168 		ext = &obj->externs[i];
3169 		if (ext->type == EXT_KSYM && ext->ksym.type_id)
3170 			return true;
3171 	}
3172 
3173 	bpf_object__for_each_program(prog, obj) {
3174 		if (!prog->autoload)
3175 			continue;
3176 		if (prog_needs_vmlinux_btf(prog))
3177 			return true;
3178 	}
3179 
3180 	return false;
3181 }
3182 
3183 static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
3184 {
3185 	int err;
3186 
3187 	/* btf_vmlinux could be loaded earlier */
3188 	if (obj->btf_vmlinux || obj->gen_loader)
3189 		return 0;
3190 
3191 	if (!force && !obj_needs_vmlinux_btf(obj))
3192 		return 0;
3193 
3194 	obj->btf_vmlinux = btf__load_vmlinux_btf();
3195 	err = libbpf_get_error(obj->btf_vmlinux);
3196 	if (err) {
3197 		pr_warn("Error loading vmlinux BTF: %d\n", err);
3198 		obj->btf_vmlinux = NULL;
3199 		return err;
3200 	}
3201 	return 0;
3202 }
3203 
3204 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
3205 {
3206 	struct btf *kern_btf = obj->btf;
3207 	bool btf_mandatory, sanitize;
3208 	int i, err = 0;
3209 
3210 	if (!obj->btf)
3211 		return 0;
3212 
3213 	if (!kernel_supports(obj, FEAT_BTF)) {
3214 		if (kernel_needs_btf(obj)) {
3215 			err = -EOPNOTSUPP;
3216 			goto report;
3217 		}
3218 		pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
3219 		return 0;
3220 	}
3221 
3222 	/* Even though some subprogs are global/weak, user might prefer more
3223 	 * permissive BPF verification process that BPF verifier performs for
3224 	 * static functions, taking into account more context from the caller
3225 	 * functions. In such case, they need to mark such subprogs with
3226 	 * __attribute__((visibility("hidden"))) and libbpf will adjust
3227 	 * corresponding FUNC BTF type to be marked as static and trigger more
3228 	 * involved BPF verification process.
3229 	 */
3230 	for (i = 0; i < obj->nr_programs; i++) {
3231 		struct bpf_program *prog = &obj->programs[i];
3232 		struct btf_type *t;
3233 		const char *name;
3234 		int j, n;
3235 
3236 		if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
3237 			continue;
3238 
3239 		n = btf__type_cnt(obj->btf);
3240 		for (j = 1; j < n; j++) {
3241 			t = btf_type_by_id(obj->btf, j);
3242 			if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
3243 				continue;
3244 
3245 			name = btf__str_by_offset(obj->btf, t->name_off);
3246 			if (strcmp(name, prog->name) != 0)
3247 				continue;
3248 
3249 			t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
3250 			break;
3251 		}
3252 	}
3253 
3254 	sanitize = btf_needs_sanitization(obj);
3255 	if (sanitize) {
3256 		const void *raw_data;
3257 		__u32 sz;
3258 
3259 		/* clone BTF to sanitize a copy and leave the original intact */
3260 		raw_data = btf__raw_data(obj->btf, &sz);
3261 		kern_btf = btf__new(raw_data, sz);
3262 		err = libbpf_get_error(kern_btf);
3263 		if (err)
3264 			return err;
3265 
3266 		/* enforce 8-byte pointers for BPF-targeted BTFs */
3267 		btf__set_pointer_size(obj->btf, 8);
3268 		err = bpf_object__sanitize_btf(obj, kern_btf);
3269 		if (err)
3270 			return err;
3271 	}
3272 
3273 	if (obj->gen_loader) {
3274 		__u32 raw_size = 0;
3275 		const void *raw_data = btf__raw_data(kern_btf, &raw_size);
3276 
3277 		if (!raw_data)
3278 			return -ENOMEM;
3279 		bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
3280 		/* Pretend to have valid FD to pass various fd >= 0 checks.
3281 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
3282 		 */
3283 		btf__set_fd(kern_btf, 0);
3284 	} else {
3285 		/* currently BPF_BTF_LOAD only supports log_level 1 */
3286 		err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
3287 					   obj->log_level ? 1 : 0);
3288 	}
3289 	if (sanitize) {
3290 		if (!err) {
3291 			/* move fd to libbpf's BTF */
3292 			btf__set_fd(obj->btf, btf__fd(kern_btf));
3293 			btf__set_fd(kern_btf, -1);
3294 		}
3295 		btf__free(kern_btf);
3296 	}
3297 report:
3298 	if (err) {
3299 		btf_mandatory = kernel_needs_btf(obj);
3300 		pr_warn("Error loading .BTF into kernel: %d. %s\n", err,
3301 			btf_mandatory ? "BTF is mandatory, can't proceed."
3302 				      : "BTF is optional, ignoring.");
3303 		if (!btf_mandatory)
3304 			err = 0;
3305 	}
3306 	return err;
3307 }
3308 
3309 static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
3310 {
3311 	const char *name;
3312 #if defined HAVE_LIBELF
3313 	name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
3314 #elif defined HAVE_ELFIO
3315 	name = elfio_string_get_string(obj->efile.strstring, off);
3316 #endif
3317 	if (!name) {
3318 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3319 			off, obj->path, elf_errmsg(-1));
3320 		return NULL;
3321 	}
3322 
3323 	return name;
3324 }
3325 
3326 static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
3327 {
3328 	const char *name;
3329 #if defined HAVE_LIBELF
3330 	name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
3331 #elif defined HAVE_ELFIO
3332 	name = elfio_string_get_string(obj->efile.shstring, off);
3333 #endif
3334 
3335 	if (!name) {
3336 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3337 			off, obj->path, elf_errmsg(-1));
3338 		return NULL;
3339 	}
3340 
3341 	return name;
3342 }
3343 
3344 #ifdef HAVE_LIBELF
3345 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
3346 {
3347 	Elf_Scn *scn;
3348 
3349 	scn = elf_getscn(obj->efile.elf, idx);
3350 	if (!scn) {
3351 		pr_warn("elf: failed to get section(%zu) from %s: %s\n",
3352 			idx, obj->path, elf_errmsg(-1));
3353 		return NULL;
3354 	}
3355 	return scn;
3356 }
3357 
3358 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
3359 {
3360 	Elf_Scn *scn = NULL;
3361 	Elf *elf = obj->efile.elf;
3362 	const char *sec_name;
3363 
3364 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3365 		sec_name = elf_sec_name(obj, scn);
3366 		if (!sec_name)
3367 			return NULL;
3368 
3369 		if (strcmp(sec_name, name) != 0)
3370 			continue;
3371 
3372 		return scn;
3373 	}
3374 	return NULL;
3375 }
3376 
3377 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn)
3378 {
3379 	Elf64_Shdr *shdr;
3380 
3381 	if (!scn)
3382 		return NULL;
3383 
3384 	shdr = elf64_getshdr(scn);
3385 	if (!shdr) {
3386 		pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
3387 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3388 		return NULL;
3389 	}
3390 
3391 	return shdr;
3392 }
3393 
3394 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
3395 {
3396 	const char *name;
3397 	Elf64_Shdr *sh;
3398 
3399 	if (!scn)
3400 		return NULL;
3401 
3402 	sh = elf_sec_hdr(obj, scn);
3403 	if (!sh)
3404 		return NULL;
3405 
3406 	name = elf_sec_str(obj, sh->sh_name);
3407 	if (!name) {
3408 		pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
3409 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3410 		return NULL;
3411 	}
3412 
3413 	return name;
3414 }
3415 #elif defined HAVE_ELFIO
3416 static Elf64_Shdr *elf_sec_hdr_by_idx(const struct bpf_object *obj, size_t idx, Elf64_Shdr *sheader)
3417 {
3418 	psection_t psection = elfio_get_section_by_index(obj->efile.elf, idx);
3419 
3420 	sheader->sh_name = elfio_section_get_name_string_offset(psection);
3421 	sheader->sh_type = elfio_section_get_type(psection);
3422 	sheader->sh_flags = elfio_section_get_flags(psection);
3423 	sheader->sh_addr = elfio_section_get_address(psection);
3424 	sheader->sh_offset = elfio_section_get_offset(psection);
3425 	sheader->sh_size = elfio_section_get_size(psection);
3426 	sheader->sh_link = elfio_section_get_link(psection);
3427 	sheader->sh_info = elfio_section_get_info(psection);
3428 	sheader->sh_addralign = elfio_section_get_addr_align(psection);
3429 	sheader->sh_entsize = elfio_section_get_entry_size(psection);
3430 
3431 	return sheader;
3432 }
3433 
3434 static const char *elf_sec_name_by_idx(const struct bpf_object *obj, size_t idx)
3435 {
3436 	const char *name;
3437 	Elf64_Shdr sh;
3438 
3439 	elf_sec_hdr_by_idx(obj, idx, &sh);
3440 
3441 	name = elf_sec_str(obj, sh.sh_name);
3442 	if (!name) {
3443 		pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
3444 			idx, obj->path, elf_errmsg(-1));
3445 		return NULL;
3446 	}
3447 
3448 	return name;
3449 }
3450 #endif
3451 
3452 #if defined HAVE_LIBELF
3453 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
3454 {
3455 	Elf_Data *data;
3456 
3457 	if (!scn)
3458 		return NULL;
3459 
3460 	data = elf_getdata(scn, 0);
3461 	if (!data) {
3462 		pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
3463 			elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
3464 			obj->path, elf_errmsg(-1));
3465 		return NULL;
3466 	}
3467 
3468 	return data;
3469 }
3470 #elif defined HAVE_ELFIO
3471 static Elf_Data *elf_sec_data_by_name(const struct bpf_object *obj, const char *name, Elf_Data *data)
3472 {
3473 	pelfio_t elf = obj->efile.elf;
3474 	psection_t psection_name = elfio_get_section_by_name(elf, name);
3475 	data->d_buf = (void*)elfio_section_get_data(psection_name);
3476 	data->d_size = elfio_section_get_size(psection_name);
3477 
3478 	return data;
3479 }
3480 
3481 static Elf_Data *elf_sec_data_by_idx(const struct bpf_object *obj, size_t idx, Elf_Data *data)
3482 {
3483 	pelfio_t elf = obj->efile.elf;
3484 	psection_t psection_index = elfio_get_section_by_index(elf, idx);
3485 	data->d_buf = (void*)elfio_section_get_data(psection_index);
3486 	data->d_size = elfio_section_get_size(psection_index);
3487 
3488 	return data;
3489 }
3490 #endif
3491 
3492 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx)
3493 {
3494 	if (idx >= obj->efile.symbols->d_size / sizeof(Elf64_Sym))
3495 		return NULL;
3496 
3497 	return (Elf64_Sym *)obj->efile.symbols->d_buf + idx;
3498 }
3499 
3500 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx)
3501 {
3502 	if (idx >= data->d_size / sizeof(Elf64_Rel))
3503 		return NULL;
3504 
3505 	return (Elf64_Rel *)data->d_buf + idx;
3506 }
3507 
3508 static bool is_sec_name_dwarf(const char *name)
3509 {
3510 	/* approximation, but the actual list is too long */
3511 	return str_has_pfx(name, ".debug_");
3512 }
3513 
3514 static bool ignore_elf_section(Elf64_Shdr *hdr, const char *name)
3515 {
3516 	/* no special handling of .strtab */
3517 	if (hdr->sh_type == SHT_STRTAB)
3518 		return true;
3519 
3520 	/* ignore .llvm_addrsig section as well */
3521 	if (hdr->sh_type == SHT_LLVM_ADDRSIG)
3522 		return true;
3523 
3524 	/* no subprograms will lead to an empty .text section, ignore it */
3525 	if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
3526 	    strcmp(name, ".text") == 0)
3527 		return true;
3528 
3529 	/* DWARF sections */
3530 	if (is_sec_name_dwarf(name))
3531 		return true;
3532 
3533 	if (str_has_pfx(name, ".rel")) {
3534 		name += sizeof(".rel") - 1;
3535 		/* DWARF section relocations */
3536 		if (is_sec_name_dwarf(name))
3537 			return true;
3538 
3539 		/* .BTF and .BTF.ext don't need relocations */
3540 		if (strcmp(name, BTF_ELF_SEC) == 0 ||
3541 		    strcmp(name, BTF_EXT_ELF_SEC) == 0)
3542 			return true;
3543 	}
3544 
3545 	return false;
3546 }
3547 
3548 static int cmp_progs(const void *_a, const void *_b)
3549 {
3550 	const struct bpf_program *a = _a;
3551 	const struct bpf_program *b = _b;
3552 
3553 	if (a->sec_idx != b->sec_idx)
3554 		return a->sec_idx < b->sec_idx ? -1 : 1;
3555 
3556 	/* sec_insn_off can't be the same within the section */
3557 	return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
3558 }
3559 
3560 static int bpf_object__elf_collect(struct bpf_object *obj)
3561 {
3562 	struct elf_sec_desc *sec_desc;
3563 #if defined HAVE_LIBELF
3564 	Elf *elf = obj->efile.elf;
3565 #elif defined HAVE_ELFIO
3566 	pelfio_t elf = obj->efile.elf;
3567 #endif
3568 	Elf_Data *btf_ext_data = NULL;
3569 	Elf_Data *btf_data = NULL;
3570 	int idx = 0, err = 0;
3571 	const char *name;
3572 	Elf_Data *data;
3573 #ifdef HAVE_LIBELF
3574 	Elf_Scn *scn;
3575 #endif
3576 	Elf64_Shdr *sh;
3577 #ifdef HAVE_ELFIO
3578 	Elf64_Shdr secHeader = {0};
3579 	sh = &secHeader;
3580 #endif
3581 
3582 	/* ELF section indices are 0-based, but sec #0 is special "invalid"
3583 	 * section. Since section count retrieved by elf_getshdrnum() does
3584 	 * include sec #0, it is already the necessary size of an array to keep
3585 	 * all the sections.
3586 	 */
3587 #ifdef HAVE_LIBELF
3588 	if (elf_getshdrnum(obj->efile.elf, &obj->efile.sec_cnt)) {
3589 		pr_warn("elf: failed to get the number of sections for %s: %s\n",
3590 			obj->path, elf_errmsg(-1));
3591 		return -LIBBPF_ERRNO__FORMAT;
3592 	}
3593 #elif defined HAVE_ELFIO
3594 	obj->efile.sec_cnt = elfio_get_sections_num(elf);
3595 #endif
3596 	obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs));
3597 	if (!obj->efile.secs)
3598 		return -ENOMEM;
3599 
3600 	/* a bunch of ELF parsing functionality depends on processing symbols,
3601 	 * so do the first pass and find the symbol table
3602 	 */
3603 #if defined HAVE_LIBELF
3604 	scn = NULL;
3605 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3606 		sh = elf_sec_hdr(obj, scn);
3607 #elif defined HAVE_ELFIO
3608 	int secno = elfio_get_sections_num(elf);
3609     for ( int i = 0; i < secno; i++ ) {
3610 		Elf_Data realdata;
3611 		sh = elf_sec_hdr_by_idx(obj, i, sh);
3612 #endif
3613 		if (!sh)
3614 			return -LIBBPF_ERRNO__FORMAT;
3615 
3616 		if (sh->sh_type == SHT_SYMTAB) {
3617 			if (obj->efile.symbols) {
3618 				pr_warn("elf: multiple symbol tables in %s\n", obj->path);
3619 				return -LIBBPF_ERRNO__FORMAT;
3620 			}
3621 #if defined HAVE_LIBELF
3622 			data = elf_sec_data(obj, scn);
3623 #elif defined HAVE_ELFIO
3624 			data = elf_sec_data_by_idx(obj, i, &realdata);
3625 #endif
3626 			if (!data)
3627 				return -LIBBPF_ERRNO__FORMAT;
3628 #ifdef HAVE_LIBELF
3629 			idx = elf_ndxscn(scn);
3630 #endif
3631 
3632 #if defined HAVE_LIBELF
3633 			obj->efile.symbols = data;
3634 #elif defined HAVE_ELFIO
3635 			obj->efile.realsymbols.d_buf = data->d_buf;
3636 			obj->efile.realsymbols.d_size = data->d_size;
3637 			obj->efile.symbols = &(obj->efile.realsymbols);
3638 #endif
3639 
3640 #if defined HAVE_LIBELF
3641 			obj->efile.symbols_shndx = idx;
3642 #elif defined HAVE_ELFIO
3643 			obj->efile.symbols_shndx = i;
3644 #endif
3645 			obj->efile.strtabidx = sh->sh_link;
3646 		}
3647 	}
3648 
3649 #ifdef HAVE_ELFIO
3650 	pstring_t shstring;
3651 	pstring_t strstring;
3652 
3653 	psection_t psection = elfio_get_section_by_index(elf, obj->efile.strtabidx);
3654 	if (!psection)
3655 		return -LIBBPF_ERRNO__FORMAT;
3656 	strstring = elfio_string_section_accessor_new(psection);
3657 
3658 	psection = elfio_get_section_by_index(elf, obj->efile.shstrndx);
3659 	if (!psection)
3660 		return -LIBBPF_ERRNO__FORMAT;
3661 	shstring = elfio_string_section_accessor_new(psection);
3662 
3663 	if (!strstring || !shstring)
3664 		return -LIBBPF_ERRNO__FORMAT;
3665 	obj->efile.strstring = strstring;
3666 	obj->efile.shstring = shstring;
3667 #endif
3668 
3669 	if (!obj->efile.symbols) {
3670 		pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
3671 			obj->path);
3672 		return -ENOENT;
3673 	}
3674 
3675 #ifdef HAVE_LIBELF
3676 	scn = NULL;
3677 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3678 #elif defined HAVE_ELFIO
3679 	for ( int i = 0; i < secno; i++ ) {
3680 		psection_t ptmpsection = elfio_get_section_by_index(elf, i);
3681 		elf_sec_hdr_by_idx(obj, i, sh);
3682 #endif
3683 
3684 #if defined HAVE_LIBELF
3685 		idx = elf_ndxscn(scn);
3686 #elif defined HAVE_ELFIO
3687 		idx = i;
3688 #endif
3689 		sec_desc = &obj->efile.secs[idx];
3690 
3691 #if defined HAVE_LIBELF
3692 		sh = elf_sec_hdr(obj, scn);
3693 #elif defined HAVE_ELFIO
3694 		sh = elf_sec_hdr_by_idx(obj, i, sh);
3695 #endif
3696 
3697 		if (!sh)
3698 			return -LIBBPF_ERRNO__FORMAT;
3699 
3700 		name = elf_sec_str(obj, sh->sh_name);
3701 		if (!name)
3702 			return -LIBBPF_ERRNO__FORMAT;
3703 
3704 		if (ignore_elf_section(sh, name))
3705 			continue;
3706 
3707 #if defined HAVE_LIBELF
3708 		data = elf_sec_data(obj, scn);
3709 #elif defined HAVE_ELFIO
3710 		data = elf_sec_data_by_idx(obj, i, &sec_desc->realdata);
3711 #endif
3712 		if (!data)
3713 			return -LIBBPF_ERRNO__FORMAT;
3714 
3715 		pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
3716 			 idx, name, (unsigned long)data->d_size,
3717 			 (int)sh->sh_link, (unsigned long)sh->sh_flags,
3718 			 (int)sh->sh_type);
3719 
3720 		if (strcmp(name, "license") == 0) {
3721 			err = bpf_object__init_license(obj, data->d_buf, data->d_size);
3722 			if (err)
3723 				return err;
3724 		} else if (strcmp(name, "version") == 0) {
3725 			err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
3726 			if (err)
3727 				return err;
3728 		} else if (strcmp(name, "maps") == 0) {
3729 			pr_warn("elf: legacy map definitions in 'maps' section are not supported by libbpf v1.0+\n");
3730 			return -ENOTSUP;
3731 		} else if (strcmp(name, MAPS_ELF_SEC) == 0) {
3732 			obj->efile.btf_maps_shndx = idx;
3733 		} else if (strcmp(name, BTF_ELF_SEC) == 0) {
3734 			if (sh->sh_type != SHT_PROGBITS)
3735 				return -LIBBPF_ERRNO__FORMAT;
3736 			btf_data = data;
3737 		} else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
3738 			if (sh->sh_type != SHT_PROGBITS)
3739 				return -LIBBPF_ERRNO__FORMAT;
3740 			btf_ext_data = data;
3741 		} else if (sh->sh_type == SHT_SYMTAB) {
3742 			/* already processed during the first pass above */
3743 		} else if (sh->sh_type == SHT_PROGBITS && data->d_size > 0) {
3744 			if (sh->sh_flags & SHF_EXECINSTR) {
3745 				if (strcmp(name, ".text") == 0)
3746 					obj->efile.text_shndx = idx;
3747 				err = bpf_object__add_programs(obj, data, name, idx);
3748 				if (err)
3749 					return err;
3750 			} else if (strcmp(name, DATA_SEC) == 0 ||
3751 				   str_has_pfx(name, DATA_SEC ".")) {
3752 				sec_desc->sec_type = SEC_DATA;
3753 #if defined HAVE_LIBELF
3754 				sec_desc->shdr = sh;
3755 				sec_desc->data = data;
3756 #elif defined HAVE_ELFIO
3757 				sec_desc->psection = ptmpsection;
3758 				sec_desc->realdata.d_buf = data->d_buf;
3759 				sec_desc->realdata.d_size = data->d_size;
3760 				sec_desc->data = &(sec_desc->realdata);
3761 #endif
3762 			} else if (strcmp(name, RODATA_SEC) == 0 ||
3763 				   str_has_pfx(name, RODATA_SEC ".")) {
3764 				sec_desc->sec_type = SEC_RODATA;
3765 #if defined HAVE_LIBELF
3766 				sec_desc->shdr = sh;
3767 				sec_desc->data = data;
3768 #elif defined HAVE_ELFIO
3769 				sec_desc->psection = ptmpsection;
3770 				sec_desc->realdata.d_buf = data->d_buf;
3771 				sec_desc->realdata.d_size = data->d_size;
3772 				sec_desc->data = &(sec_desc->realdata);
3773 #endif
3774 
3775 			} else if (strcmp(name, STRUCT_OPS_SEC) == 0) {
3776 #if defined HAVE_LIBELF
3777 				obj->efile.st_ops_data = data;
3778 #elif defined HAVE_ELFIO
3779 				obj->efile.realst_ops_data.d_buf = data->d_buf;
3780 				obj->efile.realst_ops_data.d_size = data->d_size;
3781 				obj->efile.st_ops_data = &(obj->efile.realst_ops_data);
3782 #endif
3783 				obj->efile.st_ops_shndx = idx;
3784 			} else {
3785 				pr_info("elf: skipping unrecognized data section(%d) %s\n",
3786 					idx, name);
3787 			}
3788 		} else if (sh->sh_type == SHT_REL) {
3789 			int targ_sec_idx = sh->sh_info; /* points to other section */
3790 
3791 			if (sh->sh_entsize != sizeof(Elf64_Rel) ||
3792 			    targ_sec_idx >= obj->efile.sec_cnt)
3793 				return -LIBBPF_ERRNO__FORMAT;
3794 
3795 			/* Only do relo for section with exec instructions */
3796 			if (!section_have_execinstr(obj, targ_sec_idx) &&
3797 			    strcmp(name, ".rel" STRUCT_OPS_SEC) &&
3798 			    strcmp(name, ".rel" MAPS_ELF_SEC)) {
3799 #if defined HAVE_LIBELF
3800 				pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
3801 					idx, name, targ_sec_idx,
3802 					elf_sec_name(obj, elf_sec_by_idx(obj, targ_sec_idx)) ?: "<?>");
3803 #elif defined HAVE_ELFIO
3804 				pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
3805 					idx, name, targ_sec_idx,
3806 					elf_sec_name_by_idx(obj, targ_sec_idx) ?: "<?>");
3807 #endif
3808 				continue;
3809 			}
3810 
3811 			sec_desc->sec_type = SEC_RELO;
3812 #if defined HAVE_LIBELF
3813 			sec_desc->shdr = sh;
3814 #elif defined HAVE_ELFIO
3815 			sec_desc->psection = ptmpsection;
3816 #endif
3817 			sec_desc->data = data;
3818 		} else if (sh->sh_type == SHT_NOBITS && (strcmp(name, BSS_SEC) == 0 ||
3819 							 str_has_pfx(name, BSS_SEC "."))) {
3820 			sec_desc->sec_type = SEC_BSS;
3821 #if defined HAVE_LIBELF
3822 			sec_desc->shdr = sh;
3823 #elif defined HAVE_ELFIO
3824 			sec_desc->psection = ptmpsection;
3825 #endif
3826 			sec_desc->data = data;
3827 		} else {
3828 			pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
3829 				(size_t)sh->sh_size);
3830 		}
3831 	}
3832 
3833 	if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
3834 		pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
3835 		return -LIBBPF_ERRNO__FORMAT;
3836 	}
3837 
3838 	/* sort BPF programs by section name and in-section instruction offset
3839 	 * for faster search
3840 	 */
3841 	if (obj->nr_programs)
3842 		qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
3843 
3844 	return bpf_object__init_btf(obj, btf_data, btf_ext_data);
3845 }
3846 
3847 static bool sym_is_extern(const Elf64_Sym *sym)
3848 {
3849 	int bind = ELF64_ST_BIND(sym->st_info);
3850 	/* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
3851 	return sym->st_shndx == SHN_UNDEF &&
3852 	       (bind == STB_GLOBAL || bind == STB_WEAK) &&
3853 	       ELF64_ST_TYPE(sym->st_info) == STT_NOTYPE;
3854 }
3855 
3856 static bool sym_is_subprog(const Elf64_Sym *sym, int text_shndx)
3857 {
3858 	int bind = ELF64_ST_BIND(sym->st_info);
3859 	int type = ELF64_ST_TYPE(sym->st_info);
3860 
3861 	/* in .text section */
3862 	if (sym->st_shndx != text_shndx)
3863 		return false;
3864 
3865 	/* local function */
3866 	if (bind == STB_LOCAL && type == STT_SECTION)
3867 		return true;
3868 
3869 	/* global function */
3870 	return bind == STB_GLOBAL && type == STT_FUNC;
3871 }
3872 
3873 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
3874 {
3875 	const struct btf_type *t;
3876 	const char *tname;
3877 	int i, n;
3878 
3879 	if (!btf)
3880 		return -ESRCH;
3881 
3882 	n = btf__type_cnt(btf);
3883 	for (i = 1; i < n; i++) {
3884 		t = btf__type_by_id(btf, i);
3885 
3886 		if (!btf_is_var(t) && !btf_is_func(t))
3887 			continue;
3888 
3889 		tname = btf__name_by_offset(btf, t->name_off);
3890 		if (strcmp(tname, ext_name))
3891 			continue;
3892 
3893 		if (btf_is_var(t) &&
3894 		    btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
3895 			return -EINVAL;
3896 
3897 		if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
3898 			return -EINVAL;
3899 
3900 		return i;
3901 	}
3902 
3903 	return -ENOENT;
3904 }
3905 
3906 static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
3907 	const struct btf_var_secinfo *vs;
3908 	const struct btf_type *t;
3909 	int i, j, n;
3910 
3911 	if (!btf)
3912 		return -ESRCH;
3913 
3914 	n = btf__type_cnt(btf);
3915 	for (i = 1; i < n; i++) {
3916 		t = btf__type_by_id(btf, i);
3917 
3918 		if (!btf_is_datasec(t))
3919 			continue;
3920 
3921 		vs = btf_var_secinfos(t);
3922 		for (j = 0; j < btf_vlen(t); j++, vs++) {
3923 			if (vs->type == ext_btf_id)
3924 				return i;
3925 		}
3926 	}
3927 
3928 	return -ENOENT;
3929 }
3930 
3931 static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
3932 				     bool *is_signed)
3933 {
3934 	const struct btf_type *t;
3935 	const char *name;
3936 
3937 	t = skip_mods_and_typedefs(btf, id, NULL);
3938 	name = btf__name_by_offset(btf, t->name_off);
3939 
3940 	if (is_signed)
3941 		*is_signed = false;
3942 	switch (btf_kind(t)) {
3943 	case BTF_KIND_INT: {
3944 		int enc = btf_int_encoding(t);
3945 
3946 		if (enc & BTF_INT_BOOL)
3947 			return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
3948 		if (is_signed)
3949 			*is_signed = enc & BTF_INT_SIGNED;
3950 		if (t->size == 1)
3951 			return KCFG_CHAR;
3952 		if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
3953 			return KCFG_UNKNOWN;
3954 		return KCFG_INT;
3955 	}
3956 	case BTF_KIND_ENUM:
3957 		if (t->size != 4)
3958 			return KCFG_UNKNOWN;
3959 		if (strcmp(name, "libbpf_tristate"))
3960 			return KCFG_UNKNOWN;
3961 		return KCFG_TRISTATE;
3962 	case BTF_KIND_ENUM64:
3963 		if (strcmp(name, "libbpf_tristate"))
3964 			return KCFG_UNKNOWN;
3965 		return KCFG_TRISTATE;
3966 	case BTF_KIND_ARRAY:
3967 		if (btf_array(t)->nelems == 0)
3968 			return KCFG_UNKNOWN;
3969 		if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
3970 			return KCFG_UNKNOWN;
3971 		return KCFG_CHAR_ARR;
3972 	default:
3973 		return KCFG_UNKNOWN;
3974 	}
3975 }
3976 
3977 static int cmp_externs(const void *_a, const void *_b)
3978 {
3979 	const struct extern_desc *a = _a;
3980 	const struct extern_desc *b = _b;
3981 
3982 	if (a->type != b->type)
3983 		return a->type < b->type ? -1 : 1;
3984 
3985 	if (a->type == EXT_KCFG) {
3986 		/* descending order by alignment requirements */
3987 		if (a->kcfg.align != b->kcfg.align)
3988 			return a->kcfg.align > b->kcfg.align ? -1 : 1;
3989 		/* ascending order by size, within same alignment class */
3990 		if (a->kcfg.sz != b->kcfg.sz)
3991 			return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
3992 	}
3993 
3994 	/* resolve ties by name */
3995 	return strcmp(a->name, b->name);
3996 }
3997 
3998 static int find_int_btf_id(const struct btf *btf)
3999 {
4000 	const struct btf_type *t;
4001 	int i, n;
4002 
4003 	n = btf__type_cnt(btf);
4004 	for (i = 1; i < n; i++) {
4005 		t = btf__type_by_id(btf, i);
4006 
4007 		if (btf_is_int(t) && btf_int_bits(t) == 32)
4008 			return i;
4009 	}
4010 
4011 	return 0;
4012 }
4013 
4014 static int add_dummy_ksym_var(struct btf *btf)
4015 {
4016 	int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
4017 	const struct btf_var_secinfo *vs;
4018 	const struct btf_type *sec;
4019 
4020 	if (!btf)
4021 		return 0;
4022 
4023 	sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
4024 					    BTF_KIND_DATASEC);
4025 	if (sec_btf_id < 0)
4026 		return 0;
4027 
4028 	sec = btf__type_by_id(btf, sec_btf_id);
4029 	vs = btf_var_secinfos(sec);
4030 	for (i = 0; i < btf_vlen(sec); i++, vs++) {
4031 		const struct btf_type *vt;
4032 
4033 		vt = btf__type_by_id(btf, vs->type);
4034 		if (btf_is_func(vt))
4035 			break;
4036 	}
4037 
4038 	/* No func in ksyms sec.  No need to add dummy var. */
4039 	if (i == btf_vlen(sec))
4040 		return 0;
4041 
4042 	int_btf_id = find_int_btf_id(btf);
4043 	dummy_var_btf_id = btf__add_var(btf,
4044 					"dummy_ksym",
4045 					BTF_VAR_GLOBAL_ALLOCATED,
4046 					int_btf_id);
4047 	if (dummy_var_btf_id < 0)
4048 		pr_warn("cannot create a dummy_ksym var\n");
4049 
4050 	return dummy_var_btf_id;
4051 }
4052 
4053 static int bpf_object__collect_externs(struct bpf_object *obj)
4054 {
4055 	struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
4056 	const struct btf_type *t;
4057 	struct extern_desc *ext;
4058 	int i, n, off, dummy_var_btf_id;
4059 	const char *ext_name, *sec_name;
4060 #ifdef HAVE_LIBELF
4061 	Elf_Scn *scn;
4062 #endif
4063 	Elf64_Shdr *sh;
4064 	Elf64_Shdr shheader;
4065 
4066 	if (!obj->efile.symbols)
4067 		return 0;
4068 
4069 #if defined HAVE_LIBELF
4070 	scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
4071 	sh = elf_sec_hdr(obj, scn);
4072 #elif defined HAVE_ELFIO
4073 	sh = &shheader;
4074 	sh = elf_sec_hdr_by_idx(obj, obj->efile.symbols_shndx, sh);
4075 #endif
4076 
4077 	if (!sh || sh->sh_entsize != sizeof(Elf64_Sym))
4078 		return -LIBBPF_ERRNO__FORMAT;
4079 
4080 	dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
4081 	if (dummy_var_btf_id < 0)
4082 		return dummy_var_btf_id;
4083 
4084 	n = sh->sh_size / sh->sh_entsize;
4085 	pr_debug("looking for externs among %d symbols...\n", n);
4086 
4087 	for (i = 0; i < n; i++) {
4088 		Elf64_Sym *sym = elf_sym_by_idx(obj, i);
4089 
4090 		if (!sym)
4091 			return -LIBBPF_ERRNO__FORMAT;
4092 		if (!sym_is_extern(sym))
4093 			continue;
4094 		ext_name = elf_sym_str(obj, sym->st_name);
4095 		if (!ext_name || !ext_name[0])
4096 			continue;
4097 
4098 		ext = obj->externs;
4099 		ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
4100 		if (!ext)
4101 			return -ENOMEM;
4102 		obj->externs = ext;
4103 		ext = &ext[obj->nr_extern];
4104 		memset(ext, 0, sizeof(*ext));
4105 		obj->nr_extern++;
4106 
4107 		ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
4108 		if (ext->btf_id <= 0) {
4109 			pr_warn("failed to find BTF for extern '%s': %d\n",
4110 				ext_name, ext->btf_id);
4111 			return ext->btf_id;
4112 		}
4113 		t = btf__type_by_id(obj->btf, ext->btf_id);
4114 		ext->name = btf__name_by_offset(obj->btf, t->name_off);
4115 		ext->sym_idx = i;
4116 		ext->is_weak = ELF64_ST_BIND(sym->st_info) == STB_WEAK;
4117 
4118 		ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
4119 		if (ext->sec_btf_id <= 0) {
4120 			pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
4121 				ext_name, ext->btf_id, ext->sec_btf_id);
4122 			return ext->sec_btf_id;
4123 		}
4124 		sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
4125 		sec_name = btf__name_by_offset(obj->btf, sec->name_off);
4126 
4127 		if (strcmp(sec_name, KCONFIG_SEC) == 0) {
4128 			if (btf_is_func(t)) {
4129 				pr_warn("extern function %s is unsupported under %s section\n",
4130 					ext->name, KCONFIG_SEC);
4131 				return -ENOTSUP;
4132 			}
4133 			kcfg_sec = sec;
4134 			ext->type = EXT_KCFG;
4135 			ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
4136 			if (ext->kcfg.sz <= 0) {
4137 				pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
4138 					ext_name, ext->kcfg.sz);
4139 				return ext->kcfg.sz;
4140 			}
4141 			ext->kcfg.align = btf__align_of(obj->btf, t->type);
4142 			if (ext->kcfg.align <= 0) {
4143 				pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
4144 					ext_name, ext->kcfg.align);
4145 				return -EINVAL;
4146 			}
4147 			ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
4148 							&ext->kcfg.is_signed);
4149 			if (ext->kcfg.type == KCFG_UNKNOWN) {
4150 				pr_warn("extern (kcfg) '%s': type is unsupported\n", ext_name);
4151 				return -ENOTSUP;
4152 			}
4153 		} else if (strcmp(sec_name, KSYMS_SEC) == 0) {
4154 			ksym_sec = sec;
4155 			ext->type = EXT_KSYM;
4156 			skip_mods_and_typedefs(obj->btf, t->type,
4157 					       &ext->ksym.type_id);
4158 		} else {
4159 			pr_warn("unrecognized extern section '%s'\n", sec_name);
4160 			return -ENOTSUP;
4161 		}
4162 	}
4163 	pr_debug("collected %d externs total\n", obj->nr_extern);
4164 
4165 	if (!obj->nr_extern)
4166 		return 0;
4167 
4168 	/* sort externs by type, for kcfg ones also by (align, size, name) */
4169 	qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
4170 
4171 	/* for .ksyms section, we need to turn all externs into allocated
4172 	 * variables in BTF to pass kernel verification; we do this by
4173 	 * pretending that each extern is a 8-byte variable
4174 	 */
4175 	if (ksym_sec) {
4176 		/* find existing 4-byte integer type in BTF to use for fake
4177 		 * extern variables in DATASEC
4178 		 */
4179 		int int_btf_id = find_int_btf_id(obj->btf);
4180 		/* For extern function, a dummy_var added earlier
4181 		 * will be used to replace the vs->type and
4182 		 * its name string will be used to refill
4183 		 * the missing param's name.
4184 		 */
4185 		const struct btf_type *dummy_var;
4186 
4187 		dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
4188 		for (i = 0; i < obj->nr_extern; i++) {
4189 			ext = &obj->externs[i];
4190 			if (ext->type != EXT_KSYM)
4191 				continue;
4192 			pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
4193 				 i, ext->sym_idx, ext->name);
4194 		}
4195 
4196 		sec = ksym_sec;
4197 		n = btf_vlen(sec);
4198 		for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
4199 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4200 			struct btf_type *vt;
4201 
4202 			vt = (void *)btf__type_by_id(obj->btf, vs->type);
4203 			ext_name = btf__name_by_offset(obj->btf, vt->name_off);
4204 			ext = find_extern_by_name(obj, ext_name);
4205 			if (!ext) {
4206 				pr_warn("failed to find extern definition for BTF %s '%s'\n",
4207 					btf_kind_str(vt), ext_name);
4208 				return -ESRCH;
4209 			}
4210 			if (btf_is_func(vt)) {
4211 				const struct btf_type *func_proto;
4212 				struct btf_param *param;
4213 				int j;
4214 
4215 				func_proto = btf__type_by_id(obj->btf,
4216 							     vt->type);
4217 				param = btf_params(func_proto);
4218 				/* Reuse the dummy_var string if the
4219 				 * func proto does not have param name.
4220 				 */
4221 				for (j = 0; j < btf_vlen(func_proto); j++)
4222 					if (param[j].type && !param[j].name_off)
4223 						param[j].name_off =
4224 							dummy_var->name_off;
4225 				vs->type = dummy_var_btf_id;
4226 				vt->info &= ~0xffff;
4227 				vt->info |= BTF_FUNC_GLOBAL;
4228 			} else {
4229 				btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4230 				vt->type = int_btf_id;
4231 			}
4232 			vs->offset = off;
4233 			vs->size = sizeof(int);
4234 		}
4235 		sec->size = off;
4236 	}
4237 
4238 	if (kcfg_sec) {
4239 		sec = kcfg_sec;
4240 		/* for kcfg externs calculate their offsets within a .kconfig map */
4241 		off = 0;
4242 		for (i = 0; i < obj->nr_extern; i++) {
4243 			ext = &obj->externs[i];
4244 			if (ext->type != EXT_KCFG)
4245 				continue;
4246 
4247 			ext->kcfg.data_off = roundup(off, ext->kcfg.align);
4248 			off = ext->kcfg.data_off + ext->kcfg.sz;
4249 			pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
4250 				 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
4251 		}
4252 		sec->size = off;
4253 		n = btf_vlen(sec);
4254 		for (i = 0; i < n; i++) {
4255 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4256 
4257 			t = btf__type_by_id(obj->btf, vs->type);
4258 			ext_name = btf__name_by_offset(obj->btf, t->name_off);
4259 			ext = find_extern_by_name(obj, ext_name);
4260 			if (!ext) {
4261 				pr_warn("failed to find extern definition for BTF var '%s'\n",
4262 					ext_name);
4263 				return -ESRCH;
4264 			}
4265 			btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4266 			vs->offset = ext->kcfg.data_off;
4267 		}
4268 	}
4269 	return 0;
4270 }
4271 
4272 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog)
4273 {
4274 	return prog->sec_idx == obj->efile.text_shndx && obj->nr_programs > 1;
4275 }
4276 
4277 struct bpf_program *
4278 bpf_object__find_program_by_name(const struct bpf_object *obj,
4279 				 const char *name)
4280 {
4281 	struct bpf_program *prog;
4282 
4283 	bpf_object__for_each_program(prog, obj) {
4284 		if (prog_is_subprog(obj, prog))
4285 			continue;
4286 		if (!strcmp(prog->name, name))
4287 			return prog;
4288 	}
4289 	return errno = ENOENT, NULL;
4290 }
4291 
4292 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
4293 				      int shndx)
4294 {
4295 	switch (obj->efile.secs[shndx].sec_type) {
4296 	case SEC_BSS:
4297 	case SEC_DATA:
4298 	case SEC_RODATA:
4299 		return true;
4300 	default:
4301 		return false;
4302 	}
4303 }
4304 
4305 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
4306 				      int shndx)
4307 {
4308 	return shndx == obj->efile.btf_maps_shndx;
4309 }
4310 
4311 static enum libbpf_map_type
4312 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
4313 {
4314 	if (shndx == obj->efile.symbols_shndx)
4315 		return LIBBPF_MAP_KCONFIG;
4316 
4317 	switch (obj->efile.secs[shndx].sec_type) {
4318 	case SEC_BSS:
4319 		return LIBBPF_MAP_BSS;
4320 	case SEC_DATA:
4321 		return LIBBPF_MAP_DATA;
4322 	case SEC_RODATA:
4323 		return LIBBPF_MAP_RODATA;
4324 	default:
4325 		return LIBBPF_MAP_UNSPEC;
4326 	}
4327 }
4328 
4329 static int bpf_program__record_reloc(struct bpf_program *prog,
4330 				     struct reloc_desc *reloc_desc,
4331 				     __u32 insn_idx, const char *sym_name,
4332 				     const Elf64_Sym *sym, const Elf64_Rel *rel)
4333 {
4334 	struct bpf_insn *insn = &prog->insns[insn_idx];
4335 	size_t map_idx, nr_maps = prog->obj->nr_maps;
4336 	struct bpf_object *obj = prog->obj;
4337 	__u32 shdr_idx = sym->st_shndx;
4338 	enum libbpf_map_type type;
4339 	const char *sym_sec_name;
4340 	struct bpf_map *map;
4341 
4342 	if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
4343 		pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n",
4344 			prog->name, sym_name, insn_idx, insn->code);
4345 		return -LIBBPF_ERRNO__RELOC;
4346 	}
4347 
4348 	if (sym_is_extern(sym)) {
4349 		int sym_idx = ELF64_R_SYM(rel->r_info);
4350 		int i, n = obj->nr_extern;
4351 		struct extern_desc *ext;
4352 
4353 		for (i = 0; i < n; i++) {
4354 			ext = &obj->externs[i];
4355 			if (ext->sym_idx == sym_idx)
4356 				break;
4357 		}
4358 		if (i >= n) {
4359 			pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
4360 				prog->name, sym_name, sym_idx);
4361 			return -LIBBPF_ERRNO__RELOC;
4362 		}
4363 		pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
4364 			 prog->name, i, ext->name, ext->sym_idx, insn_idx);
4365 		if (insn->code == (BPF_JMP | BPF_CALL))
4366 			reloc_desc->type = RELO_EXTERN_FUNC;
4367 		else
4368 			reloc_desc->type = RELO_EXTERN_VAR;
4369 		reloc_desc->insn_idx = insn_idx;
4370 		reloc_desc->sym_off = i; /* sym_off stores extern index */
4371 		return 0;
4372 	}
4373 
4374 	/* sub-program call relocation */
4375 	if (is_call_insn(insn)) {
4376 		if (insn->src_reg != BPF_PSEUDO_CALL) {
4377 			pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
4378 			return -LIBBPF_ERRNO__RELOC;
4379 		}
4380 		/* text_shndx can be 0, if no default "main" program exists */
4381 		if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
4382 #if defined HAVE_LIBELF
4383 			sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4384 #elif defined HAVE_ELFIO
4385 			sym_sec_name = elf_sec_name_by_idx(obj, shdr_idx);
4386 #endif
4387 			pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
4388 				prog->name, sym_name, sym_sec_name);
4389 			return -LIBBPF_ERRNO__RELOC;
4390 		}
4391 		if (sym->st_value % BPF_INSN_SZ) {
4392 			pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
4393 				prog->name, sym_name, (size_t)sym->st_value);
4394 			return -LIBBPF_ERRNO__RELOC;
4395 		}
4396 		reloc_desc->type = RELO_CALL;
4397 		reloc_desc->insn_idx = insn_idx;
4398 		reloc_desc->sym_off = sym->st_value;
4399 		return 0;
4400 	}
4401 
4402 	if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
4403 		pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
4404 			prog->name, sym_name, shdr_idx);
4405 		return -LIBBPF_ERRNO__RELOC;
4406 	}
4407 
4408 	/* loading subprog addresses */
4409 	if (sym_is_subprog(sym, obj->efile.text_shndx)) {
4410 		/* global_func: sym->st_value = offset in the section, insn->imm = 0.
4411 		 * local_func: sym->st_value = 0, insn->imm = offset in the section.
4412 		 */
4413 		if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
4414 			pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
4415 				prog->name, sym_name, (size_t)sym->st_value, insn->imm);
4416 			return -LIBBPF_ERRNO__RELOC;
4417 		}
4418 
4419 		reloc_desc->type = RELO_SUBPROG_ADDR;
4420 		reloc_desc->insn_idx = insn_idx;
4421 		reloc_desc->sym_off = sym->st_value;
4422 		return 0;
4423 	}
4424 
4425 	type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
4426 #if defined HAVE_LIBELF
4427 	sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4428 #elif defined HAVE_ELFIO
4429 	sym_sec_name = elf_sec_name_by_idx(obj, shdr_idx);
4430 #endif
4431 	/* generic map reference relocation */
4432 	if (type == LIBBPF_MAP_UNSPEC) {
4433 		if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
4434 			pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
4435 				prog->name, sym_name, sym_sec_name);
4436 			return -LIBBPF_ERRNO__RELOC;
4437 		}
4438 		for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4439 			map = &obj->maps[map_idx];
4440 			if (map->libbpf_type != type ||
4441 			    map->sec_idx != sym->st_shndx ||
4442 			    map->sec_offset != sym->st_value)
4443 				continue;
4444 			pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n",
4445 				 prog->name, map_idx, map->name, map->sec_idx,
4446 				 map->sec_offset, insn_idx);
4447 			break;
4448 		}
4449 		if (map_idx >= nr_maps) {
4450 			pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
4451 				prog->name, sym_sec_name, (size_t)sym->st_value);
4452 			return -LIBBPF_ERRNO__RELOC;
4453 		}
4454 		reloc_desc->type = RELO_LD64;
4455 		reloc_desc->insn_idx = insn_idx;
4456 		reloc_desc->map_idx = map_idx;
4457 		reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
4458 		return 0;
4459 	}
4460 
4461 	/* global data map relocation */
4462 	if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
4463 		pr_warn("prog '%s': bad data relo against section '%s'\n",
4464 			prog->name, sym_sec_name);
4465 		return -LIBBPF_ERRNO__RELOC;
4466 	}
4467 	for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4468 		map = &obj->maps[map_idx];
4469 		if (map->libbpf_type != type || map->sec_idx != sym->st_shndx)
4470 			continue;
4471 		pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n",
4472 			 prog->name, map_idx, map->name, map->sec_idx,
4473 			 map->sec_offset, insn_idx);
4474 		break;
4475 	}
4476 	if (map_idx >= nr_maps) {
4477 		pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
4478 			prog->name, sym_sec_name);
4479 		return -LIBBPF_ERRNO__RELOC;
4480 	}
4481 
4482 	reloc_desc->type = RELO_DATA;
4483 	reloc_desc->insn_idx = insn_idx;
4484 	reloc_desc->map_idx = map_idx;
4485 	reloc_desc->sym_off = sym->st_value;
4486 	return 0;
4487 }
4488 
4489 static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
4490 {
4491 	return insn_idx >= prog->sec_insn_off &&
4492 	       insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
4493 }
4494 
4495 static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
4496 						 size_t sec_idx, size_t insn_idx)
4497 {
4498 	int l = 0, r = obj->nr_programs - 1, m;
4499 	struct bpf_program *prog;
4500 
4501 	if (!obj->nr_programs)
4502 		return NULL;
4503 
4504 	while (l < r) {
4505 		m = l + (r - l + 1) / 2;
4506 		prog = &obj->programs[m];
4507 
4508 		if (prog->sec_idx < sec_idx ||
4509 		    (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
4510 			l = m;
4511 		else
4512 			r = m - 1;
4513 	}
4514 	/* matching program could be at index l, but it still might be the
4515 	 * wrong one, so we need to double check conditions for the last time
4516 	 */
4517 	prog = &obj->programs[l];
4518 	if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
4519 		return prog;
4520 	return NULL;
4521 }
4522 
4523 static int
4524 bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
4525 {
4526 	const char *relo_sec_name, *sec_name;
4527 	size_t sec_idx = shdr->sh_info, sym_idx;
4528 	struct bpf_program *prog;
4529 	struct reloc_desc *relos;
4530 	int err, i, nrels;
4531 	const char *sym_name;
4532 	__u32 insn_idx;
4533 #ifdef HAVE_LIBELF
4534 	Elf_Scn *scn;
4535 #endif
4536 	Elf_Data *scn_data;
4537 	Elf64_Sym *sym;
4538 	Elf64_Rel *rel;
4539 
4540 	if (sec_idx >= obj->efile.sec_cnt)
4541 		return -EINVAL;
4542 
4543 #if defined HAVE_LIBELF
4544 	scn = elf_sec_by_idx(obj, sec_idx);
4545 	scn_data = elf_sec_data(obj, scn);
4546 
4547 	relo_sec_name = elf_sec_str(obj, shdr->sh_name);
4548 	sec_name = elf_sec_name(obj, scn);
4549 	if (!relo_sec_name || !sec_name)
4550 		return -EINVAL;
4551 #elif defined HAVE_ELFIO
4552 	Elf_Data realdata;
4553 	scn_data = elf_sec_data_by_idx(obj, sec_idx, &realdata);
4554 
4555 	relo_sec_name = elf_sec_str(obj, shdr->sh_name);
4556 	sec_name = elf_sec_name_by_idx(obj, sec_idx);
4557 	if (!relo_sec_name || !sec_name)
4558 		return -EINVAL;
4559 #endif
4560 
4561 	pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
4562 		 relo_sec_name, sec_idx, sec_name);
4563 	nrels = shdr->sh_size / shdr->sh_entsize;
4564 
4565 	for (i = 0; i < nrels; i++) {
4566 		rel = elf_rel_by_idx(data, i);
4567 		if (!rel) {
4568 			pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
4569 			return -LIBBPF_ERRNO__FORMAT;
4570 		}
4571 
4572 		sym_idx = ELF64_R_SYM(rel->r_info);
4573 		sym = elf_sym_by_idx(obj, sym_idx);
4574 		if (!sym) {
4575 			pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
4576 				relo_sec_name, sym_idx, i);
4577 			return -LIBBPF_ERRNO__FORMAT;
4578 		}
4579 
4580 		if (sym->st_shndx >= obj->efile.sec_cnt) {
4581 			pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
4582 				relo_sec_name, sym_idx, (size_t)sym->st_shndx, i);
4583 			return -LIBBPF_ERRNO__FORMAT;
4584 		}
4585 
4586 		if (rel->r_offset % BPF_INSN_SZ || rel->r_offset >= scn_data->d_size) {
4587 			pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
4588 				relo_sec_name, (size_t)rel->r_offset, i);
4589 			return -LIBBPF_ERRNO__FORMAT;
4590 		}
4591 
4592 		insn_idx = rel->r_offset / BPF_INSN_SZ;
4593 		/* relocations against static functions are recorded as
4594 		 * relocations against the section that contains a function;
4595 		 * in such case, symbol will be STT_SECTION and sym.st_name
4596 		 * will point to empty string (0), so fetch section name
4597 		 * instead
4598 		 */
4599 		if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
4600 #if defined HAVE_LIBELF
4601 			sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx));
4602 #elif defined HAVE_ELFIO
4603 			sym_name = elf_sec_name_by_idx(obj, sym->st_shndx);
4604 #endif
4605 		else
4606 			sym_name = elf_sym_str(obj, sym->st_name);
4607 		sym_name = sym_name ?: "<?";
4608 
4609 		pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
4610 			 relo_sec_name, i, insn_idx, sym_name);
4611 
4612 		prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
4613 		if (!prog) {
4614 			pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
4615 				relo_sec_name, i, sec_name, insn_idx);
4616 			continue;
4617 		}
4618 
4619 		relos = libbpf_reallocarray(prog->reloc_desc,
4620 					    prog->nr_reloc + 1, sizeof(*relos));
4621 		if (!relos)
4622 			return -ENOMEM;
4623 		prog->reloc_desc = relos;
4624 
4625 		/* adjust insn_idx to local BPF program frame of reference */
4626 		insn_idx -= prog->sec_insn_off;
4627 		err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
4628 						insn_idx, sym_name, sym, rel);
4629 		if (err)
4630 			return err;
4631 
4632 		prog->nr_reloc++;
4633 	}
4634 	return 0;
4635 }
4636 
4637 static int map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map)
4638 {
4639 	int id;
4640 
4641 	if (!obj->btf)
4642 		return -ENOENT;
4643 
4644 	/* if it's BTF-defined map, we don't need to search for type IDs.
4645 	 * For struct_ops map, it does not need btf_key_type_id and
4646 	 * btf_value_type_id.
4647 	 */
4648 	if (map->sec_idx == obj->efile.btf_maps_shndx || bpf_map__is_struct_ops(map))
4649 		return 0;
4650 
4651 	/*
4652 	 * LLVM annotates global data differently in BTF, that is,
4653 	 * only as '.data', '.bss' or '.rodata'.
4654 	 */
4655 	if (!bpf_map__is_internal(map))
4656 		return -ENOENT;
4657 
4658 	id = btf__find_by_name(obj->btf, map->real_name);
4659 	if (id < 0)
4660 		return id;
4661 
4662 	map->btf_key_type_id = 0;
4663 	map->btf_value_type_id = id;
4664 	return 0;
4665 }
4666 
4667 static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
4668 {
4669 	char file[PATH_MAX], buff[4096];
4670 	FILE *fp;
4671 	__u32 val;
4672 	int err;
4673 
4674 	snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
4675 	memset(info, 0, sizeof(*info));
4676 
4677 	fp = fopen(file, "r");
4678 	if (!fp) {
4679 		err = -errno;
4680 		pr_warn("failed to open %s: %d. No procfs support?\n", file,
4681 			err);
4682 		return err;
4683 	}
4684 
4685 	while (fgets(buff, sizeof(buff), fp)) {
4686 		if (sscanf(buff, "map_type:\t%u", &val) == 1)
4687 			info->type = val;
4688 		else if (sscanf(buff, "key_size:\t%u", &val) == 1)
4689 			info->key_size = val;
4690 		else if (sscanf(buff, "value_size:\t%u", &val) == 1)
4691 			info->value_size = val;
4692 		else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
4693 			info->max_entries = val;
4694 		else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
4695 			info->map_flags = val;
4696 	}
4697 
4698 	fclose(fp);
4699 
4700 	return 0;
4701 }
4702 
4703 bool bpf_map__autocreate(const struct bpf_map *map)
4704 {
4705 	return map->autocreate;
4706 }
4707 
4708 int bpf_map__set_autocreate(struct bpf_map *map, bool autocreate)
4709 {
4710 	if (map->obj->loaded)
4711 		return libbpf_err(-EBUSY);
4712 
4713 	map->autocreate = autocreate;
4714 	return 0;
4715 }
4716 
4717 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
4718 {
4719 	struct bpf_map_info info;
4720 	__u32 len = sizeof(info), name_len;
4721 	int new_fd, err;
4722 	char *new_name;
4723 
4724 	memset(&info, 0, len);
4725 	err = bpf_obj_get_info_by_fd(fd, &info, &len);
4726 	if (err && errno == EINVAL)
4727 		err = bpf_get_map_info_from_fdinfo(fd, &info);
4728 	if (err)
4729 		return libbpf_err(err);
4730 
4731 	name_len = strlen(info.name);
4732 	if (name_len == BPF_OBJ_NAME_LEN - 1 && strncmp(map->name, info.name, name_len) == 0)
4733 		new_name = strdup(map->name);
4734 	else
4735 		new_name = strdup(info.name);
4736 
4737 	if (!new_name)
4738 		return libbpf_err(-errno);
4739 
4740 	new_fd = open("/", O_RDONLY | O_CLOEXEC);
4741 	if (new_fd < 0) {
4742 		err = -errno;
4743 		goto err_free_new_name;
4744 	}
4745 
4746 	new_fd = dup3(fd, new_fd, O_CLOEXEC);
4747 	if (new_fd < 0) {
4748 		err = -errno;
4749 		goto err_close_new_fd;
4750 	}
4751 
4752 	err = zclose(map->fd);
4753 	if (err) {
4754 		err = -errno;
4755 		goto err_close_new_fd;
4756 	}
4757 	free(map->name);
4758 
4759 	map->fd = new_fd;
4760 	map->name = new_name;
4761 	map->def.type = info.type;
4762 	map->def.key_size = info.key_size;
4763 	map->def.value_size = info.value_size;
4764 	map->def.max_entries = info.max_entries;
4765 	map->def.map_flags = info.map_flags;
4766 	map->btf_key_type_id = info.btf_key_type_id;
4767 	map->btf_value_type_id = info.btf_value_type_id;
4768 	map->reused = true;
4769 	map->map_extra = info.map_extra;
4770 
4771 	return 0;
4772 
4773 err_close_new_fd:
4774 	close(new_fd);
4775 err_free_new_name:
4776 	free(new_name);
4777 	return libbpf_err(err);
4778 }
4779 
4780 __u32 bpf_map__max_entries(const struct bpf_map *map)
4781 {
4782 	return map->def.max_entries;
4783 }
4784 
4785 struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
4786 {
4787 	if (!bpf_map_type__is_map_in_map(map->def.type))
4788 		return errno = EINVAL, NULL;
4789 
4790 	return map->inner_map;
4791 }
4792 
4793 int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
4794 {
4795 	if (map->obj->loaded)
4796 		return libbpf_err(-EBUSY);
4797 
4798 	map->def.max_entries = max_entries;
4799 
4800 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
4801 	if (map_is_ringbuf(map))
4802 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
4803 
4804 	return 0;
4805 }
4806 
4807 static int
4808 bpf_object__probe_loading(struct bpf_object *obj)
4809 {
4810 	char *cp, errmsg[STRERR_BUFSIZE];
4811 	struct bpf_insn insns[] = {
4812 		BPF_MOV64_IMM(BPF_REG_0, 0),
4813 		BPF_EXIT_INSN(),
4814 	};
4815 	int ret, insn_cnt = ARRAY_SIZE(insns);
4816 
4817 	if (obj->gen_loader)
4818 		return 0;
4819 
4820 	ret = bump_rlimit_memlock();
4821 	if (ret)
4822 		pr_warn("Failed to bump RLIMIT_MEMLOCK (err = %d), you might need to do it explicitly!\n", ret);
4823 
4824 	/* make sure basic loading works */
4825 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4826 	if (ret < 0)
4827 		ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
4828 	if (ret < 0) {
4829 		ret = errno;
4830 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4831 		pr_warn("Error in %s():%s(%d). Couldn't load trivial BPF "
4832 			"program. Make sure your kernel supports BPF "
4833 			"(CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is "
4834 			"set to big enough value.\n", __func__, cp, ret);
4835 		return -ret;
4836 	}
4837 	close(ret);
4838 
4839 	return 0;
4840 }
4841 
4842 static int probe_fd(int fd)
4843 {
4844 	if (fd >= 0)
4845 		close(fd);
4846 	return fd >= 0;
4847 }
4848 
4849 static int probe_kern_prog_name(void)
4850 {
4851 	const size_t attr_sz = offsetofend(union bpf_attr, prog_name);
4852 	struct bpf_insn insns[] = {
4853 		BPF_MOV64_IMM(BPF_REG_0, 0),
4854 		BPF_EXIT_INSN(),
4855 	};
4856 	union bpf_attr attr;
4857 	int ret;
4858 
4859 	memset(&attr, 0, attr_sz);
4860 	attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
4861 	attr.license = ptr_to_u64("GPL");
4862 	attr.insns = ptr_to_u64(insns);
4863 	attr.insn_cnt = (__u32)ARRAY_SIZE(insns);
4864 	libbpf_strlcpy(attr.prog_name, "libbpf_nametest", sizeof(attr.prog_name));
4865 
4866 	/* make sure loading with name works */
4867 	ret = sys_bpf_prog_load(&attr, attr_sz, PROG_LOAD_ATTEMPTS);
4868 	return probe_fd(ret);
4869 }
4870 
4871 static int probe_kern_global_data(void)
4872 {
4873 	char *cp, errmsg[STRERR_BUFSIZE];
4874 	struct bpf_insn insns[] = {
4875 		BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
4876 		BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
4877 		BPF_MOV64_IMM(BPF_REG_0, 0),
4878 		BPF_EXIT_INSN(),
4879 	};
4880 	int ret, map, insn_cnt = ARRAY_SIZE(insns);
4881 
4882 	map = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_global", sizeof(int), 32, 1, NULL);
4883 	if (map < 0) {
4884 		ret = -errno;
4885 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4886 		pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4887 			__func__, cp, -ret);
4888 		return ret;
4889 	}
4890 
4891 	insns[0].imm = map;
4892 
4893 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4894 	close(map);
4895 	return probe_fd(ret);
4896 }
4897 
4898 static int probe_kern_btf(void)
4899 {
4900 	static const char strs[] = "\0int";
4901 	__u32 types[] = {
4902 		/* int */
4903 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4904 	};
4905 
4906 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4907 					     strs, sizeof(strs)));
4908 }
4909 
4910 static int probe_kern_btf_func(void)
4911 {
4912 	static const char strs[] = "\0int\0x\0a";
4913 	/* void x(int a) {} */
4914 	__u32 types[] = {
4915 		/* int */
4916 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4917 		/* FUNC_PROTO */                                /* [2] */
4918 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4919 		BTF_PARAM_ENC(7, 1),
4920 		/* FUNC x */                                    /* [3] */
4921 		BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
4922 	};
4923 
4924 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4925 					     strs, sizeof(strs)));
4926 }
4927 
4928 static int probe_kern_btf_func_global(void)
4929 {
4930 	static const char strs[] = "\0int\0x\0a";
4931 	/* static void x(int a) {} */
4932 	__u32 types[] = {
4933 		/* int */
4934 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4935 		/* FUNC_PROTO */                                /* [2] */
4936 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4937 		BTF_PARAM_ENC(7, 1),
4938 		/* FUNC x BTF_FUNC_GLOBAL */                    /* [3] */
4939 		BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, BTF_FUNC_GLOBAL), 2),
4940 	};
4941 
4942 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4943 					     strs, sizeof(strs)));
4944 }
4945 
4946 static int probe_kern_btf_datasec(void)
4947 {
4948 	static const char strs[] = "\0x\0.data";
4949 	/* static int a; */
4950 	__u32 types[] = {
4951 		/* int */
4952 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4953 		/* VAR x */                                     /* [2] */
4954 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4955 		BTF_VAR_STATIC,
4956 		/* DATASEC val */                               /* [3] */
4957 		BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
4958 		BTF_VAR_SECINFO_ENC(2, 0, 4),
4959 	};
4960 
4961 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4962 					     strs, sizeof(strs)));
4963 }
4964 
4965 static int probe_kern_btf_float(void)
4966 {
4967 	static const char strs[] = "\0float";
4968 	__u32 types[] = {
4969 		/* float */
4970 		BTF_TYPE_FLOAT_ENC(1, 4),
4971 	};
4972 
4973 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4974 					     strs, sizeof(strs)));
4975 }
4976 
4977 static int probe_kern_btf_decl_tag(void)
4978 {
4979 	static const char strs[] = "\0tag";
4980 	__u32 types[] = {
4981 		/* int */
4982 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4983 		/* VAR x */                                     /* [2] */
4984 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4985 		BTF_VAR_STATIC,
4986 		/* attr */
4987 		BTF_TYPE_DECL_TAG_ENC(1, 2, -1),
4988 	};
4989 
4990 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4991 					     strs, sizeof(strs)));
4992 }
4993 
4994 static int probe_kern_btf_type_tag(void)
4995 {
4996 	static const char strs[] = "\0tag";
4997 	__u32 types[] = {
4998 		/* int */
4999 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),		/* [1] */
5000 		/* attr */
5001 		BTF_TYPE_TYPE_TAG_ENC(1, 1),				/* [2] */
5002 		/* ptr */
5003 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_PTR, 0, 0), 2),	/* [3] */
5004 	};
5005 
5006 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
5007 					     strs, sizeof(strs)));
5008 }
5009 
5010 static int probe_kern_array_mmap(void)
5011 {
5012 	LIBBPF_OPTS(bpf_map_create_opts, opts, .map_flags = BPF_F_MMAPABLE);
5013 	int fd;
5014 
5015 	fd = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_mmap", sizeof(int), sizeof(int), 1, &opts);
5016 	return probe_fd(fd);
5017 }
5018 
5019 static int probe_kern_exp_attach_type(void)
5020 {
5021 	LIBBPF_OPTS(bpf_prog_load_opts, opts, .expected_attach_type = BPF_CGROUP_INET_SOCK_CREATE);
5022 	struct bpf_insn insns[] = {
5023 		BPF_MOV64_IMM(BPF_REG_0, 0),
5024 		BPF_EXIT_INSN(),
5025 	};
5026 	int fd, insn_cnt = ARRAY_SIZE(insns);
5027 
5028 	/* use any valid combination of program type and (optional)
5029 	 * non-zero expected attach type (i.e., not a BPF_CGROUP_INET_INGRESS)
5030 	 * to see if kernel supports expected_attach_type field for
5031 	 * BPF_PROG_LOAD command
5032 	 */
5033 	fd = bpf_prog_load(BPF_PROG_TYPE_CGROUP_SOCK, NULL, "GPL", insns, insn_cnt, &opts);
5034 	return probe_fd(fd);
5035 }
5036 
5037 static int probe_kern_probe_read_kernel(void)
5038 {
5039 	struct bpf_insn insns[] = {
5040 		BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),	/* r1 = r10 (fp) */
5041 		BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -8),	/* r1 += -8 */
5042 		BPF_MOV64_IMM(BPF_REG_2, 8),		/* r2 = 8 */
5043 		BPF_MOV64_IMM(BPF_REG_3, 0),		/* r3 = 0 */
5044 		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_probe_read_kernel),
5045 		BPF_EXIT_INSN(),
5046 	};
5047 	int fd, insn_cnt = ARRAY_SIZE(insns);
5048 
5049 	fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
5050 	return probe_fd(fd);
5051 }
5052 
5053 static int probe_prog_bind_map(void)
5054 {
5055 	char *cp, errmsg[STRERR_BUFSIZE];
5056 	struct bpf_insn insns[] = {
5057 		BPF_MOV64_IMM(BPF_REG_0, 0),
5058 		BPF_EXIT_INSN(),
5059 	};
5060 	int ret, map, prog, insn_cnt = ARRAY_SIZE(insns);
5061 
5062 	map = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_det_bind", sizeof(int), 32, 1, NULL);
5063 	if (map < 0) {
5064 		ret = -errno;
5065 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
5066 		pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
5067 			__func__, cp, -ret);
5068 		return ret;
5069 	}
5070 
5071 	prog = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
5072 	if (prog < 0) {
5073 		close(map);
5074 		return 0;
5075 	}
5076 
5077 	ret = bpf_prog_bind_map(prog, map, NULL);
5078 
5079 	close(map);
5080 	close(prog);
5081 
5082 	return ret >= 0;
5083 }
5084 
5085 static int probe_module_btf(void)
5086 {
5087 	static const char strs[] = "\0int";
5088 	__u32 types[] = {
5089 		/* int */
5090 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
5091 	};
5092 	struct bpf_btf_info info;
5093 	__u32 len = sizeof(info);
5094 	char name[16];
5095 	int fd, err;
5096 
5097 	fd = libbpf__load_raw_btf((char *)types, sizeof(types), strs, sizeof(strs));
5098 	if (fd < 0)
5099 		return 0; /* BTF not supported at all */
5100 
5101 	memset(&info, 0, sizeof(info));
5102 	info.name = ptr_to_u64(name);
5103 	info.name_len = sizeof(name);
5104 
5105 	/* check that BPF_OBJ_GET_INFO_BY_FD supports specifying name pointer;
5106 	 * kernel's module BTF support coincides with support for
5107 	 * name/name_len fields in struct bpf_btf_info.
5108 	 */
5109 	err = bpf_obj_get_info_by_fd(fd, &info, &len);
5110 	close(fd);
5111 	return !err;
5112 }
5113 
5114 static int probe_perf_link(void)
5115 {
5116 	struct bpf_insn insns[] = {
5117 		BPF_MOV64_IMM(BPF_REG_0, 0),
5118 		BPF_EXIT_INSN(),
5119 	};
5120 	int prog_fd, link_fd, err;
5121 
5122 	prog_fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL",
5123 				insns, ARRAY_SIZE(insns), NULL);
5124 	if (prog_fd < 0)
5125 		return -errno;
5126 
5127 	/* use invalid perf_event FD to get EBADF, if link is supported;
5128 	 * otherwise EINVAL should be returned
5129 	 */
5130 	link_fd = bpf_link_create(prog_fd, -1, BPF_PERF_EVENT, NULL);
5131 	err = -errno; /* close() can clobber errno */
5132 
5133 	if (link_fd >= 0)
5134 		close(link_fd);
5135 	close(prog_fd);
5136 
5137 	return link_fd < 0 && err == -EBADF;
5138 }
5139 
5140 static int probe_kern_bpf_cookie(void)
5141 {
5142 	struct bpf_insn insns[] = {
5143 		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_get_attach_cookie),
5144 		BPF_EXIT_INSN(),
5145 	};
5146 	int ret, insn_cnt = ARRAY_SIZE(insns);
5147 
5148 	ret = bpf_prog_load(BPF_PROG_TYPE_KPROBE, NULL, "GPL", insns, insn_cnt, NULL);
5149 	return probe_fd(ret);
5150 }
5151 
5152 static int probe_kern_btf_enum64(void)
5153 {
5154 	static const char strs[] = "\0enum64";
5155 	__u32 types[] = {
5156 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_ENUM64, 0, 0), 8),
5157 	};
5158 
5159 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
5160 					     strs, sizeof(strs)));
5161 }
5162 
5163 static int probe_kern_syscall_wrapper(void);
5164 
5165 enum kern_feature_result {
5166 	FEAT_UNKNOWN = 0,
5167 	FEAT_SUPPORTED = 1,
5168 	FEAT_MISSING = 2,
5169 };
5170 
5171 typedef int (*feature_probe_fn)(void);
5172 
5173 static struct kern_feature_desc {
5174 	const char *desc;
5175 	feature_probe_fn probe;
5176 	enum kern_feature_result res;
5177 } feature_probes[__FEAT_CNT] = {
5178 	[FEAT_PROG_NAME] = {
5179 		"BPF program name", probe_kern_prog_name,
5180 	},
5181 	[FEAT_GLOBAL_DATA] = {
5182 		"global variables", probe_kern_global_data,
5183 	},
5184 	[FEAT_BTF] = {
5185 		"minimal BTF", probe_kern_btf,
5186 	},
5187 	[FEAT_BTF_FUNC] = {
5188 		"BTF functions", probe_kern_btf_func,
5189 	},
5190 	[FEAT_BTF_GLOBAL_FUNC] = {
5191 		"BTF global function", probe_kern_btf_func_global,
5192 	},
5193 	[FEAT_BTF_DATASEC] = {
5194 		"BTF data section and variable", probe_kern_btf_datasec,
5195 	},
5196 	[FEAT_ARRAY_MMAP] = {
5197 		"ARRAY map mmap()", probe_kern_array_mmap,
5198 	},
5199 	[FEAT_EXP_ATTACH_TYPE] = {
5200 		"BPF_PROG_LOAD expected_attach_type attribute",
5201 		probe_kern_exp_attach_type,
5202 	},
5203 	[FEAT_PROBE_READ_KERN] = {
5204 		"bpf_probe_read_kernel() helper", probe_kern_probe_read_kernel,
5205 	},
5206 	[FEAT_PROG_BIND_MAP] = {
5207 		"BPF_PROG_BIND_MAP support", probe_prog_bind_map,
5208 	},
5209 	[FEAT_MODULE_BTF] = {
5210 		"module BTF support", probe_module_btf,
5211 	},
5212 	[FEAT_BTF_FLOAT] = {
5213 		"BTF_KIND_FLOAT support", probe_kern_btf_float,
5214 	},
5215 	[FEAT_PERF_LINK] = {
5216 		"BPF perf link support", probe_perf_link,
5217 	},
5218 	[FEAT_BTF_DECL_TAG] = {
5219 		"BTF_KIND_DECL_TAG support", probe_kern_btf_decl_tag,
5220 	},
5221 	[FEAT_BTF_TYPE_TAG] = {
5222 		"BTF_KIND_TYPE_TAG support", probe_kern_btf_type_tag,
5223 	},
5224 	[FEAT_MEMCG_ACCOUNT] = {
5225 		"memcg-based memory accounting", probe_memcg_account,
5226 	},
5227 	[FEAT_BPF_COOKIE] = {
5228 		"BPF cookie support", probe_kern_bpf_cookie,
5229 	},
5230 	[FEAT_BTF_ENUM64] = {
5231 		"BTF_KIND_ENUM64 support", probe_kern_btf_enum64,
5232 	},
5233 	[FEAT_SYSCALL_WRAPPER] = {
5234 		"Kernel using syscall wrapper", probe_kern_syscall_wrapper,
5235 	},
5236 };
5237 
5238 bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
5239 {
5240 	struct kern_feature_desc *feat = &feature_probes[feat_id];
5241 	int ret;
5242 
5243 	if (obj && obj->gen_loader)
5244 		/* To generate loader program assume the latest kernel
5245 		 * to avoid doing extra prog_load, map_create syscalls.
5246 		 */
5247 		return true;
5248 
5249 	if (READ_ONCE(feat->res) == FEAT_UNKNOWN) {
5250 		ret = feat->probe();
5251 		if (ret > 0) {
5252 			WRITE_ONCE(feat->res, FEAT_SUPPORTED);
5253 		} else if (ret == 0) {
5254 			WRITE_ONCE(feat->res, FEAT_MISSING);
5255 		} else {
5256 			pr_warn("Detection of kernel %s support failed: %d\n", feat->desc, ret);
5257 			WRITE_ONCE(feat->res, FEAT_MISSING);
5258 		}
5259 	}
5260 
5261 	return READ_ONCE(feat->res) == FEAT_SUPPORTED;
5262 }
5263 
5264 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
5265 {
5266 	struct bpf_map_info map_info;
5267 	char msg[STRERR_BUFSIZE];
5268 	__u32 map_info_len = sizeof(map_info);
5269 	int err;
5270 
5271 	memset(&map_info, 0, map_info_len);
5272 	err = bpf_obj_get_info_by_fd(map_fd, &map_info, &map_info_len);
5273 	if (err && errno == EINVAL)
5274 		err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
5275 	if (err) {
5276 		pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
5277 			libbpf_strerror_r(errno, msg, sizeof(msg)));
5278 		return false;
5279 	}
5280 
5281 	return (map_info.type == map->def.type &&
5282 		map_info.key_size == map->def.key_size &&
5283 		map_info.value_size == map->def.value_size &&
5284 		map_info.max_entries == map->def.max_entries &&
5285 		map_info.map_flags == map->def.map_flags &&
5286 		map_info.map_extra == map->map_extra);
5287 }
5288 
5289 static int
5290 bpf_object__reuse_map(struct bpf_map *map)
5291 {
5292 	char *cp, errmsg[STRERR_BUFSIZE];
5293 	int err, pin_fd;
5294 
5295 	pin_fd = bpf_obj_get(map->pin_path);
5296 	if (pin_fd < 0) {
5297 		err = -errno;
5298 		if (err == -ENOENT) {
5299 			pr_debug("found no pinned map to reuse at '%s'\n",
5300 				 map->pin_path);
5301 			return 0;
5302 		}
5303 
5304 		cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
5305 		pr_warn("couldn't retrieve pinned map '%s': %s\n",
5306 			map->pin_path, cp);
5307 		return err;
5308 	}
5309 
5310 	if (!map_is_reuse_compat(map, pin_fd)) {
5311 		pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
5312 			map->pin_path);
5313 		close(pin_fd);
5314 		return -EINVAL;
5315 	}
5316 
5317 	err = bpf_map__reuse_fd(map, pin_fd);
5318 	close(pin_fd);
5319 	if (err)
5320 		return err;
5321 
5322 	map->pinned = true;
5323 	pr_debug("reused pinned map at '%s'\n", map->pin_path);
5324 
5325 	return 0;
5326 }
5327 
5328 static int
5329 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
5330 {
5331 	enum libbpf_map_type map_type = map->libbpf_type;
5332 	char *cp, errmsg[STRERR_BUFSIZE];
5333 	int err, zero = 0;
5334 
5335 	if (obj->gen_loader) {
5336 		bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
5337 					 map->mmaped, map->def.value_size);
5338 		if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
5339 			bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
5340 		return 0;
5341 	}
5342 	err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
5343 	if (err) {
5344 		err = -errno;
5345 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5346 		pr_warn("Error setting initial map(%s) contents: %s\n",
5347 			map->name, cp);
5348 		return err;
5349 	}
5350 
5351 	/* Freeze .rodata and .kconfig map as read-only from syscall side. */
5352 	if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
5353 		err = bpf_map_freeze(map->fd);
5354 		if (err) {
5355 			err = -errno;
5356 			cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5357 			pr_warn("Error freezing map(%s) as read-only: %s\n",
5358 				map->name, cp);
5359 			return err;
5360 		}
5361 	}
5362 	return 0;
5363 }
5364 
5365 static void bpf_map__destroy(struct bpf_map *map);
5366 
5367 static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
5368 {
5369 	LIBBPF_OPTS(bpf_map_create_opts, create_attr);
5370 	struct bpf_map_def *def = &map->def;
5371 	const char *map_name = NULL;
5372 	int err = 0;
5373 
5374 	if (kernel_supports(obj, FEAT_PROG_NAME))
5375 		map_name = map->name;
5376 	create_attr.map_ifindex = map->map_ifindex;
5377 	create_attr.map_flags = def->map_flags;
5378 	create_attr.numa_node = map->numa_node;
5379 	create_attr.map_extra = map->map_extra;
5380 
5381 	if (bpf_map__is_struct_ops(map))
5382 		create_attr.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
5383 
5384 	if (obj->btf && btf__fd(obj->btf) >= 0) {
5385 		create_attr.btf_fd = btf__fd(obj->btf);
5386 		create_attr.btf_key_type_id = map->btf_key_type_id;
5387 		create_attr.btf_value_type_id = map->btf_value_type_id;
5388 	}
5389 
5390 	if (bpf_map_type__is_map_in_map(def->type)) {
5391 		if (map->inner_map) {
5392 			err = bpf_object__create_map(obj, map->inner_map, true);
5393 			if (err) {
5394 				pr_warn("map '%s': failed to create inner map: %d\n",
5395 					map->name, err);
5396 				return err;
5397 			}
5398 			map->inner_map_fd = bpf_map__fd(map->inner_map);
5399 		}
5400 		if (map->inner_map_fd >= 0)
5401 			create_attr.inner_map_fd = map->inner_map_fd;
5402 	}
5403 
5404 	switch (def->type) {
5405 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5406 	case BPF_MAP_TYPE_CGROUP_ARRAY:
5407 	case BPF_MAP_TYPE_STACK_TRACE:
5408 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5409 	case BPF_MAP_TYPE_HASH_OF_MAPS:
5410 	case BPF_MAP_TYPE_DEVMAP:
5411 	case BPF_MAP_TYPE_DEVMAP_HASH:
5412 	case BPF_MAP_TYPE_CPUMAP:
5413 	case BPF_MAP_TYPE_XSKMAP:
5414 	case BPF_MAP_TYPE_SOCKMAP:
5415 	case BPF_MAP_TYPE_SOCKHASH:
5416 	case BPF_MAP_TYPE_QUEUE:
5417 	case BPF_MAP_TYPE_STACK:
5418 		create_attr.btf_fd = 0;
5419 		create_attr.btf_key_type_id = 0;
5420 		create_attr.btf_value_type_id = 0;
5421 		map->btf_key_type_id = 0;
5422 		map->btf_value_type_id = 0;
5423 		break;
5424 	default:
5425 		break;
5426 	}
5427 
5428 	if (obj->gen_loader) {
5429 		bpf_gen__map_create(obj->gen_loader, def->type, map_name,
5430 				    def->key_size, def->value_size, def->max_entries,
5431 				    &create_attr, is_inner ? -1 : map - obj->maps);
5432 		/* Pretend to have valid FD to pass various fd >= 0 checks.
5433 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
5434 		 */
5435 		map->fd = 0;
5436 	} else {
5437 		map->fd = bpf_map_create(def->type, map_name,
5438 					 def->key_size, def->value_size,
5439 					 def->max_entries, &create_attr);
5440 	}
5441 	if (map->fd < 0 && (create_attr.btf_key_type_id ||
5442 			    create_attr.btf_value_type_id)) {
5443 		char *cp, errmsg[STRERR_BUFSIZE];
5444 
5445 		err = -errno;
5446 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5447 		pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
5448 			map->name, cp, err);
5449 		create_attr.btf_fd = 0;
5450 		create_attr.btf_key_type_id = 0;
5451 		create_attr.btf_value_type_id = 0;
5452 		map->btf_key_type_id = 0;
5453 		map->btf_value_type_id = 0;
5454 		map->fd = bpf_map_create(def->type, map_name,
5455 					 def->key_size, def->value_size,
5456 					 def->max_entries, &create_attr);
5457 	}
5458 
5459 	err = map->fd < 0 ? -errno : 0;
5460 
5461 	if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
5462 		if (obj->gen_loader)
5463 			map->inner_map->fd = -1;
5464 		bpf_map__destroy(map->inner_map);
5465 		zfree(&map->inner_map);
5466 	}
5467 
5468 	return err;
5469 }
5470 
5471 static int init_map_in_map_slots(struct bpf_object *obj, struct bpf_map *map)
5472 {
5473 	const struct bpf_map *targ_map;
5474 	unsigned int i;
5475 	int fd, err = 0;
5476 
5477 	for (i = 0; i < map->init_slots_sz; i++) {
5478 		if (!map->init_slots[i])
5479 			continue;
5480 
5481 		targ_map = map->init_slots[i];
5482 		fd = bpf_map__fd(targ_map);
5483 
5484 		if (obj->gen_loader) {
5485 			bpf_gen__populate_outer_map(obj->gen_loader,
5486 						    map - obj->maps, i,
5487 						    targ_map - obj->maps);
5488 		} else {
5489 			err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5490 		}
5491 		if (err) {
5492 			err = -errno;
5493 			pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %d\n",
5494 				map->name, i, targ_map->name, fd, err);
5495 			return err;
5496 		}
5497 		pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
5498 			 map->name, i, targ_map->name, fd);
5499 	}
5500 
5501 	zfree(&map->init_slots);
5502 	map->init_slots_sz = 0;
5503 
5504 	return 0;
5505 }
5506 
5507 static int init_prog_array_slots(struct bpf_object *obj, struct bpf_map *map)
5508 {
5509 	const struct bpf_program *targ_prog;
5510 	unsigned int i;
5511 	int fd, err;
5512 
5513 	if (obj->gen_loader)
5514 		return -ENOTSUP;
5515 
5516 	for (i = 0; i < map->init_slots_sz; i++) {
5517 		if (!map->init_slots[i])
5518 			continue;
5519 
5520 		targ_prog = map->init_slots[i];
5521 		fd = bpf_program__fd(targ_prog);
5522 
5523 		err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5524 		if (err) {
5525 			err = -errno;
5526 			pr_warn("map '%s': failed to initialize slot [%d] to prog '%s' fd=%d: %d\n",
5527 				map->name, i, targ_prog->name, fd, err);
5528 			return err;
5529 		}
5530 		pr_debug("map '%s': slot [%d] set to prog '%s' fd=%d\n",
5531 			 map->name, i, targ_prog->name, fd);
5532 	}
5533 
5534 	zfree(&map->init_slots);
5535 	map->init_slots_sz = 0;
5536 
5537 	return 0;
5538 }
5539 
5540 static int bpf_object_init_prog_arrays(struct bpf_object *obj)
5541 {
5542 	struct bpf_map *map;
5543 	int i, err;
5544 
5545 	for (i = 0; i < obj->nr_maps; i++) {
5546 		map = &obj->maps[i];
5547 
5548 		if (!map->init_slots_sz || map->def.type != BPF_MAP_TYPE_PROG_ARRAY)
5549 			continue;
5550 
5551 		err = init_prog_array_slots(obj, map);
5552 		if (err < 0) {
5553 			zclose(map->fd);
5554 			return err;
5555 		}
5556 	}
5557 	return 0;
5558 }
5559 
5560 static int map_set_def_max_entries(struct bpf_map *map)
5561 {
5562 	if (map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !map->def.max_entries) {
5563 		int nr_cpus;
5564 
5565 		nr_cpus = libbpf_num_possible_cpus();
5566 		if (nr_cpus < 0) {
5567 			pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
5568 				map->name, nr_cpus);
5569 			return nr_cpus;
5570 		}
5571 		pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
5572 		map->def.max_entries = nr_cpus;
5573 	}
5574 
5575 	return 0;
5576 }
5577 
5578 static int
5579 bpf_object__create_maps(struct bpf_object *obj)
5580 {
5581 	struct bpf_map *map;
5582 	char *cp, errmsg[STRERR_BUFSIZE];
5583 	unsigned int i, j;
5584 	int err;
5585 	bool retried;
5586 
5587 	for (i = 0; i < obj->nr_maps; i++) {
5588 		map = &obj->maps[i];
5589 
5590 		/* To support old kernels, we skip creating global data maps
5591 		 * (.rodata, .data, .kconfig, etc); later on, during program
5592 		 * loading, if we detect that at least one of the to-be-loaded
5593 		 * programs is referencing any global data map, we'll error
5594 		 * out with program name and relocation index logged.
5595 		 * This approach allows to accommodate Clang emitting
5596 		 * unnecessary .rodata.str1.1 sections for string literals,
5597 		 * but also it allows to have CO-RE applications that use
5598 		 * global variables in some of BPF programs, but not others.
5599 		 * If those global variable-using programs are not loaded at
5600 		 * runtime due to bpf_program__set_autoload(prog, false),
5601 		 * bpf_object loading will succeed just fine even on old
5602 		 * kernels.
5603 		 */
5604 		if (bpf_map__is_internal(map) && !kernel_supports(obj, FEAT_GLOBAL_DATA))
5605 			map->autocreate = false;
5606 
5607 		if (!map->autocreate) {
5608 			pr_debug("map '%s': skipped auto-creating...\n", map->name);
5609 			continue;
5610 		}
5611 
5612 		err = map_set_def_max_entries(map);
5613 		if (err)
5614 			goto err_out;
5615 
5616 		retried = false;
5617 retry:
5618 		if (map->pin_path) {
5619 			err = bpf_object__reuse_map(map);
5620 			if (err) {
5621 				pr_warn("map '%s': error reusing pinned map\n",
5622 					map->name);
5623 				goto err_out;
5624 			}
5625 			if (retried && map->fd < 0) {
5626 				pr_warn("map '%s': cannot find pinned map\n",
5627 					map->name);
5628 				err = -ENOENT;
5629 				goto err_out;
5630 			}
5631 		}
5632 
5633 		if (map->fd >= 0) {
5634 			pr_debug("map '%s': skipping creation (preset fd=%d)\n",
5635 				 map->name, map->fd);
5636 		} else {
5637 			err = bpf_object__create_map(obj, map, false);
5638 			if (err)
5639 				goto err_out;
5640 
5641 			pr_debug("map '%s': created successfully, fd=%d\n",
5642 				 map->name, map->fd);
5643 
5644 			if (bpf_map__is_internal(map)) {
5645 				err = bpf_object__populate_internal_map(obj, map);
5646 				if (err < 0) {
5647 					zclose(map->fd);
5648 					goto err_out;
5649 				}
5650 			}
5651 
5652 			if (map->init_slots_sz && map->def.type != BPF_MAP_TYPE_PROG_ARRAY) {
5653 				err = init_map_in_map_slots(obj, map);
5654 				if (err < 0) {
5655 					zclose(map->fd);
5656 					goto err_out;
5657 				}
5658 			}
5659 		}
5660 
5661 		if (map->pin_path && !map->pinned) {
5662 			err = bpf_map__pin(map, NULL);
5663 			if (err) {
5664 				zclose(map->fd);
5665 				if (!retried && err == -EEXIST) {
5666 					retried = true;
5667 					goto retry;
5668 				}
5669 				pr_warn("map '%s': failed to auto-pin at '%s': %d\n",
5670 					map->name, map->pin_path, err);
5671 				goto err_out;
5672 			}
5673 		}
5674 	}
5675 
5676 	return 0;
5677 
5678 err_out:
5679 	cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5680 	pr_warn("map '%s': failed to create: %s(%d)\n", map->name, cp, err);
5681 	pr_perm_msg(err);
5682 	for (j = 0; j < i; j++)
5683 		zclose(obj->maps[j].fd);
5684 	return err;
5685 }
5686 
5687 static bool bpf_core_is_flavor_sep(const char *s)
5688 {
5689 	/* check X___Y name pattern, where X and Y are not underscores */
5690 	return s[0] != '_' &&				      /* X */
5691 	       s[1] == '_' && s[2] == '_' && s[3] == '_' &&   /* ___ */
5692 	       s[4] != '_';				      /* Y */
5693 }
5694 
5695 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
5696  * before last triple underscore. Struct name part after last triple
5697  * underscore is ignored by BPF CO-RE relocation during relocation matching.
5698  */
5699 size_t bpf_core_essential_name_len(const char *name)
5700 {
5701 	size_t n = strlen(name);
5702 	int i;
5703 
5704 	for (i = n - 5; i >= 0; i--) {
5705 		if (bpf_core_is_flavor_sep(name + i))
5706 			return i + 1;
5707 	}
5708 	return n;
5709 }
5710 
5711 void bpf_core_free_cands(struct bpf_core_cand_list *cands)
5712 {
5713 	if (!cands)
5714 		return;
5715 
5716 	free(cands->cands);
5717 	free(cands);
5718 }
5719 
5720 int bpf_core_add_cands(struct bpf_core_cand *local_cand,
5721 		       size_t local_essent_len,
5722 		       const struct btf *targ_btf,
5723 		       const char *targ_btf_name,
5724 		       int targ_start_id,
5725 		       struct bpf_core_cand_list *cands)
5726 {
5727 	struct bpf_core_cand *new_cands, *cand;
5728 	const struct btf_type *t, *local_t;
5729 	const char *targ_name, *local_name;
5730 	size_t targ_essent_len;
5731 	int n, i;
5732 
5733 	local_t = btf__type_by_id(local_cand->btf, local_cand->id);
5734 	local_name = btf__str_by_offset(local_cand->btf, local_t->name_off);
5735 
5736 	n = btf__type_cnt(targ_btf);
5737 	for (i = targ_start_id; i < n; i++) {
5738 		t = btf__type_by_id(targ_btf, i);
5739 		if (!btf_kind_core_compat(t, local_t))
5740 			continue;
5741 
5742 		targ_name = btf__name_by_offset(targ_btf, t->name_off);
5743 		if (str_is_empty(targ_name))
5744 			continue;
5745 
5746 		targ_essent_len = bpf_core_essential_name_len(targ_name);
5747 		if (targ_essent_len != local_essent_len)
5748 			continue;
5749 
5750 		if (strncmp(local_name, targ_name, local_essent_len) != 0)
5751 			continue;
5752 
5753 		pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s in [%s]\n",
5754 			 local_cand->id, btf_kind_str(local_t),
5755 			 local_name, i, btf_kind_str(t), targ_name,
5756 			 targ_btf_name);
5757 		new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
5758 					      sizeof(*cands->cands));
5759 		if (!new_cands)
5760 			return -ENOMEM;
5761 
5762 		cand = &new_cands[cands->len];
5763 		cand->btf = targ_btf;
5764 		cand->id = i;
5765 
5766 		cands->cands = new_cands;
5767 		cands->len++;
5768 	}
5769 	return 0;
5770 }
5771 
5772 static int load_module_btfs(struct bpf_object *obj)
5773 {
5774 	struct bpf_btf_info info;
5775 	struct module_btf *mod_btf;
5776 	struct btf *btf;
5777 	char name[64];
5778 	__u32 id = 0, len;
5779 	int err, fd;
5780 
5781 	if (obj->btf_modules_loaded)
5782 		return 0;
5783 
5784 	if (obj->gen_loader)
5785 		return 0;
5786 
5787 	/* don't do this again, even if we find no module BTFs */
5788 	obj->btf_modules_loaded = true;
5789 
5790 	/* kernel too old to support module BTFs */
5791 	if (!kernel_supports(obj, FEAT_MODULE_BTF))
5792 		return 0;
5793 
5794 	while (true) {
5795 		err = bpf_btf_get_next_id(id, &id);
5796 		if (err && errno == ENOENT)
5797 			return 0;
5798 		if (err) {
5799 			err = -errno;
5800 			pr_warn("failed to iterate BTF objects: %d\n", err);
5801 			return err;
5802 		}
5803 
5804 		fd = bpf_btf_get_fd_by_id(id);
5805 		if (fd < 0) {
5806 			if (errno == ENOENT)
5807 				continue; /* expected race: BTF was unloaded */
5808 			err = -errno;
5809 			pr_warn("failed to get BTF object #%d FD: %d\n", id, err);
5810 			return err;
5811 		}
5812 
5813 		len = sizeof(info);
5814 		memset(&info, 0, sizeof(info));
5815 		info.name = ptr_to_u64(name);
5816 		info.name_len = sizeof(name);
5817 
5818 		err = bpf_obj_get_info_by_fd(fd, &info, &len);
5819 		if (err) {
5820 			err = -errno;
5821 			pr_warn("failed to get BTF object #%d info: %d\n", id, err);
5822 			goto err_out;
5823 		}
5824 
5825 		/* ignore non-module BTFs */
5826 		if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
5827 			close(fd);
5828 			continue;
5829 		}
5830 
5831 		btf = btf_get_from_fd(fd, obj->btf_vmlinux);
5832 		err = libbpf_get_error(btf);
5833 		if (err) {
5834 			pr_warn("failed to load module [%s]'s BTF object #%d: %d\n",
5835 				name, id, err);
5836 			goto err_out;
5837 		}
5838 
5839 		err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
5840 					sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
5841 		if (err)
5842 			goto err_out;
5843 
5844 		mod_btf = &obj->btf_modules[obj->btf_module_cnt++];
5845 
5846 		mod_btf->btf = btf;
5847 		mod_btf->id = id;
5848 		mod_btf->fd = fd;
5849 		mod_btf->name = strdup(name);
5850 		if (!mod_btf->name) {
5851 			err = -ENOMEM;
5852 			goto err_out;
5853 		}
5854 		continue;
5855 
5856 err_out:
5857 		close(fd);
5858 		return err;
5859 	}
5860 
5861 	return 0;
5862 }
5863 
5864 static struct bpf_core_cand_list *
5865 bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
5866 {
5867 	struct bpf_core_cand local_cand = {};
5868 	struct bpf_core_cand_list *cands;
5869 	const struct btf *main_btf;
5870 	const struct btf_type *local_t;
5871 	const char *local_name;
5872 	size_t local_essent_len;
5873 	int err, i;
5874 
5875 	local_cand.btf = local_btf;
5876 	local_cand.id = local_type_id;
5877 	local_t = btf__type_by_id(local_btf, local_type_id);
5878 	if (!local_t)
5879 		return ERR_PTR(-EINVAL);
5880 
5881 	local_name = btf__name_by_offset(local_btf, local_t->name_off);
5882 	if (str_is_empty(local_name))
5883 		return ERR_PTR(-EINVAL);
5884 	local_essent_len = bpf_core_essential_name_len(local_name);
5885 
5886 	cands = calloc(1, sizeof(*cands));
5887 	if (!cands)
5888 		return ERR_PTR(-ENOMEM);
5889 
5890 	/* Attempt to find target candidates in vmlinux BTF first */
5891 	main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
5892 	err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
5893 	if (err)
5894 		goto err_out;
5895 
5896 	/* if vmlinux BTF has any candidate, don't got for module BTFs */
5897 	if (cands->len)
5898 		return cands;
5899 
5900 	/* if vmlinux BTF was overridden, don't attempt to load module BTFs */
5901 	if (obj->btf_vmlinux_override)
5902 		return cands;
5903 
5904 	/* now look through module BTFs, trying to still find candidates */
5905 	err = load_module_btfs(obj);
5906 	if (err)
5907 		goto err_out;
5908 
5909 	for (i = 0; i < obj->btf_module_cnt; i++) {
5910 		err = bpf_core_add_cands(&local_cand, local_essent_len,
5911 					 obj->btf_modules[i].btf,
5912 					 obj->btf_modules[i].name,
5913 					 btf__type_cnt(obj->btf_vmlinux),
5914 					 cands);
5915 		if (err)
5916 			goto err_out;
5917 	}
5918 
5919 	return cands;
5920 err_out:
5921 	bpf_core_free_cands(cands);
5922 	return ERR_PTR(err);
5923 }
5924 
5925 /* Check local and target types for compatibility. This check is used for
5926  * type-based CO-RE relocations and follow slightly different rules than
5927  * field-based relocations. This function assumes that root types were already
5928  * checked for name match. Beyond that initial root-level name check, names
5929  * are completely ignored. Compatibility rules are as follows:
5930  *   - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
5931  *     kind should match for local and target types (i.e., STRUCT is not
5932  *     compatible with UNION);
5933  *   - for ENUMs, the size is ignored;
5934  *   - for INT, size and signedness are ignored;
5935  *   - for ARRAY, dimensionality is ignored, element types are checked for
5936  *     compatibility recursively;
5937  *   - CONST/VOLATILE/RESTRICT modifiers are ignored;
5938  *   - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
5939  *   - FUNC_PROTOs are compatible if they have compatible signature: same
5940  *     number of input args and compatible return and argument types.
5941  * These rules are not set in stone and probably will be adjusted as we get
5942  * more experience with using BPF CO-RE relocations.
5943  */
5944 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
5945 			      const struct btf *targ_btf, __u32 targ_id)
5946 {
5947 	return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id, 32);
5948 }
5949 
5950 int bpf_core_types_match(const struct btf *local_btf, __u32 local_id,
5951 			 const struct btf *targ_btf, __u32 targ_id)
5952 {
5953 	return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false, 32);
5954 }
5955 
5956 static size_t bpf_core_hash_fn(const long key, void *ctx)
5957 {
5958 	return key;
5959 }
5960 
5961 static bool bpf_core_equal_fn(const long k1, const long k2, void *ctx)
5962 {
5963 	return k1 == k2;
5964 }
5965 
5966 static int record_relo_core(struct bpf_program *prog,
5967 			    const struct bpf_core_relo *core_relo, int insn_idx)
5968 {
5969 	struct reloc_desc *relos, *relo;
5970 
5971 	relos = libbpf_reallocarray(prog->reloc_desc,
5972 				    prog->nr_reloc + 1, sizeof(*relos));
5973 	if (!relos)
5974 		return -ENOMEM;
5975 	relo = &relos[prog->nr_reloc];
5976 	relo->type = RELO_CORE;
5977 	relo->insn_idx = insn_idx;
5978 	relo->core_relo = core_relo;
5979 	prog->reloc_desc = relos;
5980 	prog->nr_reloc++;
5981 	return 0;
5982 }
5983 
5984 static const struct bpf_core_relo *find_relo_core(struct bpf_program *prog, int insn_idx)
5985 {
5986 	struct reloc_desc *relo;
5987 	int i;
5988 
5989 	for (i = 0; i < prog->nr_reloc; i++) {
5990 		relo = &prog->reloc_desc[i];
5991 		if (relo->type != RELO_CORE || relo->insn_idx != insn_idx)
5992 			continue;
5993 
5994 		return relo->core_relo;
5995 	}
5996 
5997 	return NULL;
5998 }
5999 
6000 static int bpf_core_resolve_relo(struct bpf_program *prog,
6001 				 const struct bpf_core_relo *relo,
6002 				 int relo_idx,
6003 				 const struct btf *local_btf,
6004 				 struct hashmap *cand_cache,
6005 				 struct bpf_core_relo_res *targ_res)
6006 {
6007 	struct bpf_core_spec specs_scratch[3] = {};
6008 	struct bpf_core_cand_list *cands = NULL;
6009 	const char *prog_name = prog->name;
6010 	const struct btf_type *local_type;
6011 	const char *local_name;
6012 	__u32 local_id = relo->type_id;
6013 	int err;
6014 
6015 	local_type = btf__type_by_id(local_btf, local_id);
6016 	if (!local_type)
6017 		return -EINVAL;
6018 
6019 	local_name = btf__name_by_offset(local_btf, local_type->name_off);
6020 	if (!local_name)
6021 		return -EINVAL;
6022 
6023 	if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
6024 	    !hashmap__find(cand_cache, local_id, &cands)) {
6025 		cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
6026 		if (IS_ERR(cands)) {
6027 			pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n",
6028 				prog_name, relo_idx, local_id, btf_kind_str(local_type),
6029 				local_name, PTR_ERR(cands));
6030 			return PTR_ERR(cands);
6031 		}
6032 		err = hashmap__set(cand_cache, local_id, cands, NULL, NULL);
6033 		if (err) {
6034 			bpf_core_free_cands(cands);
6035 			return err;
6036 		}
6037 	}
6038 
6039 	return bpf_core_calc_relo_insn(prog_name, relo, relo_idx, local_btf, cands, specs_scratch,
6040 				       targ_res);
6041 }
6042 
6043 static int
6044 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
6045 {
6046 	const struct btf_ext_info_sec *sec;
6047 	struct bpf_core_relo_res targ_res;
6048 	const struct bpf_core_relo *rec;
6049 	const struct btf_ext_info *seg;
6050 	struct hashmap_entry *entry;
6051 	struct hashmap *cand_cache = NULL;
6052 	struct bpf_program *prog;
6053 	struct bpf_insn *insn;
6054 	const char *sec_name;
6055 	int i, err = 0, insn_idx, sec_idx, sec_num;
6056 
6057 	if (obj->btf_ext->core_relo_info.len == 0)
6058 		return 0;
6059 
6060 	if (targ_btf_path) {
6061 #ifdef  HAVE_LIBELF
6062 		obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
6063 #endif
6064 		err = libbpf_get_error(obj->btf_vmlinux_override);
6065 		if (err) {
6066 			pr_warn("failed to parse target BTF: %d\n", err);
6067 			return err;
6068 		}
6069 	}
6070 
6071 	cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
6072 	if (IS_ERR(cand_cache)) {
6073 		err = PTR_ERR(cand_cache);
6074 		goto out;
6075 	}
6076 
6077 	seg = &obj->btf_ext->core_relo_info;
6078 	sec_num = 0;
6079 	for_each_btf_ext_sec(seg, sec) {
6080 		sec_idx = seg->sec_idxs[sec_num];
6081 		sec_num++;
6082 
6083 		sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
6084 		if (str_is_empty(sec_name)) {
6085 			err = -EINVAL;
6086 			goto out;
6087 		}
6088 
6089 		pr_debug("sec '%s': found %d CO-RE relocations\n", sec_name, sec->num_info);
6090 
6091 		for_each_btf_ext_rec(seg, sec, i, rec) {
6092 			if (rec->insn_off % BPF_INSN_SZ)
6093 				return -EINVAL;
6094 			insn_idx = rec->insn_off / BPF_INSN_SZ;
6095 			prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
6096 			if (!prog) {
6097 				/* When __weak subprog is "overridden" by another instance
6098 				 * of the subprog from a different object file, linker still
6099 				 * appends all the .BTF.ext info that used to belong to that
6100 				 * eliminated subprogram.
6101 				 * This is similar to what x86-64 linker does for relocations.
6102 				 * So just ignore such relocations just like we ignore
6103 				 * subprog instructions when discovering subprograms.
6104 				 */
6105 				pr_debug("sec '%s': skipping CO-RE relocation #%d for insn #%d belonging to eliminated weak subprogram\n",
6106 					 sec_name, i, insn_idx);
6107 				continue;
6108 			}
6109 			/* no need to apply CO-RE relocation if the program is
6110 			 * not going to be loaded
6111 			 */
6112 			if (!prog->autoload)
6113 				continue;
6114 
6115 			/* adjust insn_idx from section frame of reference to the local
6116 			 * program's frame of reference; (sub-)program code is not yet
6117 			 * relocated, so it's enough to just subtract in-section offset
6118 			 */
6119 			insn_idx = insn_idx - prog->sec_insn_off;
6120 			if (insn_idx >= prog->insns_cnt)
6121 				return -EINVAL;
6122 			insn = &prog->insns[insn_idx];
6123 
6124 			err = record_relo_core(prog, rec, insn_idx);
6125 			if (err) {
6126 				pr_warn("prog '%s': relo #%d: failed to record relocation: %d\n",
6127 					prog->name, i, err);
6128 				goto out;
6129 			}
6130 
6131 			if (prog->obj->gen_loader)
6132 				continue;
6133 
6134 			err = bpf_core_resolve_relo(prog, rec, i, obj->btf, cand_cache, &targ_res);
6135 			if (err) {
6136 				pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
6137 					prog->name, i, err);
6138 				goto out;
6139 			}
6140 
6141 			err = bpf_core_patch_insn(prog->name, insn, insn_idx, rec, i, &targ_res);
6142 			if (err) {
6143 				pr_warn("prog '%s': relo #%d: failed to patch insn #%u: %d\n",
6144 					prog->name, i, insn_idx, err);
6145 				goto out;
6146 			}
6147 		}
6148 	}
6149 
6150 out:
6151 	/* obj->btf_vmlinux and module BTFs are freed after object load */
6152 	btf__free(obj->btf_vmlinux_override);
6153 	obj->btf_vmlinux_override = NULL;
6154 
6155 	if (!IS_ERR_OR_NULL(cand_cache)) {
6156 		hashmap__for_each_entry(cand_cache, entry, i) {
6157 			bpf_core_free_cands(entry->pvalue);
6158 		}
6159 		hashmap__free(cand_cache);
6160 	}
6161 	return err;
6162 }
6163 
6164 /* base map load ldimm64 special constant, used also for log fixup logic */
6165 #define MAP_LDIMM64_POISON_BASE 2001000000
6166 #define MAP_LDIMM64_POISON_PFX "200100"
6167 
6168 static void poison_map_ldimm64(struct bpf_program *prog, int relo_idx,
6169 			       int insn_idx, struct bpf_insn *insn,
6170 			       int map_idx, const struct bpf_map *map)
6171 {
6172 	int i;
6173 
6174 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that loads map #%d '%s'\n",
6175 		 prog->name, relo_idx, insn_idx, map_idx, map->name);
6176 
6177 	/* we turn single ldimm64 into two identical invalid calls */
6178 	for (i = 0; i < 2; i++) {
6179 		insn->code = BPF_JMP | BPF_CALL;
6180 		insn->dst_reg = 0;
6181 		insn->src_reg = 0;
6182 		insn->off = 0;
6183 		/* if this instruction is reachable (not a dead code),
6184 		 * verifier will complain with something like:
6185 		 * invalid func unknown#2001000123
6186 		 * where lower 123 is map index into obj->maps[] array
6187 		 */
6188 		insn->imm = MAP_LDIMM64_POISON_BASE + map_idx;
6189 
6190 		insn++;
6191 	}
6192 }
6193 
6194 /* Relocate data references within program code:
6195  *  - map references;
6196  *  - global variable references;
6197  *  - extern references.
6198  */
6199 static int
6200 bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
6201 {
6202 	int i;
6203 
6204 	for (i = 0; i < prog->nr_reloc; i++) {
6205 		struct reloc_desc *relo = &prog->reloc_desc[i];
6206 		struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6207 		const struct bpf_map *map;
6208 		struct extern_desc *ext;
6209 
6210 		switch (relo->type) {
6211 		case RELO_LD64:
6212 			map = &obj->maps[relo->map_idx];
6213 			if (obj->gen_loader) {
6214 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
6215 				insn[0].imm = relo->map_idx;
6216 			} else if (map->autocreate) {
6217 				insn[0].src_reg = BPF_PSEUDO_MAP_FD;
6218 				insn[0].imm = map->fd;
6219 			} else {
6220 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6221 						   relo->map_idx, map);
6222 			}
6223 			break;
6224 		case RELO_DATA:
6225 			map = &obj->maps[relo->map_idx];
6226 			insn[1].imm = insn[0].imm + relo->sym_off;
6227 			if (obj->gen_loader) {
6228 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6229 				insn[0].imm = relo->map_idx;
6230 			} else if (map->autocreate) {
6231 				insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6232 				insn[0].imm = map->fd;
6233 			} else {
6234 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6235 						   relo->map_idx, map);
6236 			}
6237 			break;
6238 		case RELO_EXTERN_VAR:
6239 			ext = &obj->externs[relo->sym_off];
6240 			if (ext->type == EXT_KCFG) {
6241 				if (obj->gen_loader) {
6242 					insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6243 					insn[0].imm = obj->kconfig_map_idx;
6244 				} else {
6245 					insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6246 					insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
6247 				}
6248 				insn[1].imm = ext->kcfg.data_off;
6249 			} else /* EXT_KSYM */ {
6250 				if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
6251 					insn[0].src_reg = BPF_PSEUDO_BTF_ID;
6252 					insn[0].imm = ext->ksym.kernel_btf_id;
6253 					insn[1].imm = ext->ksym.kernel_btf_obj_fd;
6254 				} else { /* typeless ksyms or unresolved typed ksyms */
6255 					insn[0].imm = (__u32)ext->ksym.addr;
6256 					insn[1].imm = ext->ksym.addr >> 32;
6257 				}
6258 			}
6259 			break;
6260 		case RELO_EXTERN_FUNC:
6261 			ext = &obj->externs[relo->sym_off];
6262 			insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
6263 			if (ext->is_set) {
6264 				insn[0].imm = ext->ksym.kernel_btf_id;
6265 				insn[0].off = ext->ksym.btf_fd_idx;
6266 			} else { /* unresolved weak kfunc */
6267 				insn[0].imm = 0;
6268 				insn[0].off = 0;
6269 			}
6270 			break;
6271 		case RELO_SUBPROG_ADDR:
6272 			if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
6273 				pr_warn("prog '%s': relo #%d: bad insn\n",
6274 					prog->name, i);
6275 				return -EINVAL;
6276 			}
6277 			/* handled already */
6278 			break;
6279 		case RELO_CALL:
6280 			/* handled already */
6281 			break;
6282 		case RELO_CORE:
6283 			/* will be handled by bpf_program_record_relos() */
6284 			break;
6285 		default:
6286 			pr_warn("prog '%s': relo #%d: bad relo type %d\n",
6287 				prog->name, i, relo->type);
6288 			return -EINVAL;
6289 		}
6290 	}
6291 
6292 	return 0;
6293 }
6294 
6295 static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
6296 				    const struct bpf_program *prog,
6297 				    const struct btf_ext_info *ext_info,
6298 				    void **prog_info, __u32 *prog_rec_cnt,
6299 				    __u32 *prog_rec_sz)
6300 {
6301 	void *copy_start = NULL, *copy_end = NULL;
6302 	void *rec, *rec_end, *new_prog_info;
6303 	const struct btf_ext_info_sec *sec;
6304 	size_t old_sz, new_sz;
6305 	int i, sec_num, sec_idx, off_adj;
6306 
6307 	sec_num = 0;
6308 	for_each_btf_ext_sec(ext_info, sec) {
6309 		sec_idx = ext_info->sec_idxs[sec_num];
6310 		sec_num++;
6311 		if (prog->sec_idx != sec_idx)
6312 			continue;
6313 
6314 		for_each_btf_ext_rec(ext_info, sec, i, rec) {
6315 			__u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
6316 
6317 			if (insn_off < prog->sec_insn_off)
6318 				continue;
6319 			if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
6320 				break;
6321 
6322 			if (!copy_start)
6323 				copy_start = rec;
6324 			copy_end = rec + ext_info->rec_size;
6325 		}
6326 
6327 		if (!copy_start)
6328 			return -ENOENT;
6329 
6330 		/* append func/line info of a given (sub-)program to the main
6331 		 * program func/line info
6332 		 */
6333 		old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
6334 		new_sz = old_sz + (copy_end - copy_start);
6335 		new_prog_info = realloc(*prog_info, new_sz);
6336 		if (!new_prog_info)
6337 			return -ENOMEM;
6338 		*prog_info = new_prog_info;
6339 		*prog_rec_cnt = new_sz / ext_info->rec_size;
6340 		memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
6341 
6342 		/* Kernel instruction offsets are in units of 8-byte
6343 		 * instructions, while .BTF.ext instruction offsets generated
6344 		 * by Clang are in units of bytes. So convert Clang offsets
6345 		 * into kernel offsets and adjust offset according to program
6346 		 * relocated position.
6347 		 */
6348 		off_adj = prog->sub_insn_off - prog->sec_insn_off;
6349 		rec = new_prog_info + old_sz;
6350 		rec_end = new_prog_info + new_sz;
6351 		for (; rec < rec_end; rec += ext_info->rec_size) {
6352 			__u32 *insn_off = rec;
6353 
6354 			*insn_off = *insn_off / BPF_INSN_SZ + off_adj;
6355 		}
6356 		*prog_rec_sz = ext_info->rec_size;
6357 		return 0;
6358 	}
6359 
6360 	return -ENOENT;
6361 }
6362 
6363 static int
6364 reloc_prog_func_and_line_info(const struct bpf_object *obj,
6365 			      struct bpf_program *main_prog,
6366 			      const struct bpf_program *prog)
6367 {
6368 	int err;
6369 
6370 	/* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
6371 	 * supprot func/line info
6372 	 */
6373 	if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
6374 		return 0;
6375 
6376 	/* only attempt func info relocation if main program's func_info
6377 	 * relocation was successful
6378 	 */
6379 	if (main_prog != prog && !main_prog->func_info)
6380 		goto line_info;
6381 
6382 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
6383 				       &main_prog->func_info,
6384 				       &main_prog->func_info_cnt,
6385 				       &main_prog->func_info_rec_size);
6386 	if (err) {
6387 		if (err != -ENOENT) {
6388 			pr_warn("prog '%s': error relocating .BTF.ext function info: %d\n",
6389 				prog->name, err);
6390 			return err;
6391 		}
6392 		if (main_prog->func_info) {
6393 			/*
6394 			 * Some info has already been found but has problem
6395 			 * in the last btf_ext reloc. Must have to error out.
6396 			 */
6397 			pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
6398 			return err;
6399 		}
6400 		/* Have problem loading the very first info. Ignore the rest. */
6401 		pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
6402 			prog->name);
6403 	}
6404 
6405 line_info:
6406 	/* don't relocate line info if main program's relocation failed */
6407 	if (main_prog != prog && !main_prog->line_info)
6408 		return 0;
6409 
6410 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
6411 				       &main_prog->line_info,
6412 				       &main_prog->line_info_cnt,
6413 				       &main_prog->line_info_rec_size);
6414 	if (err) {
6415 		if (err != -ENOENT) {
6416 			pr_warn("prog '%s': error relocating .BTF.ext line info: %d\n",
6417 				prog->name, err);
6418 			return err;
6419 		}
6420 		if (main_prog->line_info) {
6421 			/*
6422 			 * Some info has already been found but has problem
6423 			 * in the last btf_ext reloc. Must have to error out.
6424 			 */
6425 			pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
6426 			return err;
6427 		}
6428 		/* Have problem loading the very first info. Ignore the rest. */
6429 		pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
6430 			prog->name);
6431 	}
6432 	return 0;
6433 }
6434 
6435 static int cmp_relo_by_insn_idx(const void *key, const void *elem)
6436 {
6437 	size_t insn_idx = *(const size_t *)key;
6438 	const struct reloc_desc *relo = elem;
6439 
6440 	if (insn_idx == relo->insn_idx)
6441 		return 0;
6442 	return insn_idx < relo->insn_idx ? -1 : 1;
6443 }
6444 
6445 static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
6446 {
6447 	if (!prog->nr_reloc)
6448 		return NULL;
6449 	return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
6450 		       sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
6451 }
6452 
6453 static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
6454 {
6455 	int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
6456 	struct reloc_desc *relos;
6457 	int i;
6458 
6459 	if (main_prog == subprog)
6460 		return 0;
6461 	relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
6462 	if (!relos)
6463 		return -ENOMEM;
6464 	if (subprog->nr_reloc)
6465 		memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
6466 		       sizeof(*relos) * subprog->nr_reloc);
6467 
6468 	for (i = main_prog->nr_reloc; i < new_cnt; i++)
6469 		relos[i].insn_idx += subprog->sub_insn_off;
6470 	/* After insn_idx adjustment the 'relos' array is still sorted
6471 	 * by insn_idx and doesn't break bsearch.
6472 	 */
6473 	main_prog->reloc_desc = relos;
6474 	main_prog->nr_reloc = new_cnt;
6475 	return 0;
6476 }
6477 
6478 static int
6479 bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
6480 		       struct bpf_program *prog)
6481 {
6482 	size_t sub_insn_idx, insn_idx, new_cnt;
6483 	struct bpf_program *subprog;
6484 	struct bpf_insn *insns, *insn;
6485 	struct reloc_desc *relo;
6486 	int err;
6487 
6488 	err = reloc_prog_func_and_line_info(obj, main_prog, prog);
6489 	if (err)
6490 		return err;
6491 
6492 	for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
6493 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6494 		if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
6495 			continue;
6496 
6497 		relo = find_prog_insn_relo(prog, insn_idx);
6498 		if (relo && relo->type == RELO_EXTERN_FUNC)
6499 			/* kfunc relocations will be handled later
6500 			 * in bpf_object__relocate_data()
6501 			 */
6502 			continue;
6503 		if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
6504 			pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
6505 				prog->name, insn_idx, relo->type);
6506 			return -LIBBPF_ERRNO__RELOC;
6507 		}
6508 		if (relo) {
6509 			/* sub-program instruction index is a combination of
6510 			 * an offset of a symbol pointed to by relocation and
6511 			 * call instruction's imm field; for global functions,
6512 			 * call always has imm = -1, but for static functions
6513 			 * relocation is against STT_SECTION and insn->imm
6514 			 * points to a start of a static function
6515 			 *
6516 			 * for subprog addr relocation, the relo->sym_off + insn->imm is
6517 			 * the byte offset in the corresponding section.
6518 			 */
6519 			if (relo->type == RELO_CALL)
6520 				sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
6521 			else
6522 				sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
6523 		} else if (insn_is_pseudo_func(insn)) {
6524 			/*
6525 			 * RELO_SUBPROG_ADDR relo is always emitted even if both
6526 			 * functions are in the same section, so it shouldn't reach here.
6527 			 */
6528 			pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
6529 				prog->name, insn_idx);
6530 			return -LIBBPF_ERRNO__RELOC;
6531 		} else {
6532 			/* if subprogram call is to a static function within
6533 			 * the same ELF section, there won't be any relocation
6534 			 * emitted, but it also means there is no additional
6535 			 * offset necessary, insns->imm is relative to
6536 			 * instruction's original position within the section
6537 			 */
6538 			sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
6539 		}
6540 
6541 		/* we enforce that sub-programs should be in .text section */
6542 		subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
6543 		if (!subprog) {
6544 			pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
6545 				prog->name);
6546 			return -LIBBPF_ERRNO__RELOC;
6547 		}
6548 
6549 		/* if it's the first call instruction calling into this
6550 		 * subprogram (meaning this subprog hasn't been processed
6551 		 * yet) within the context of current main program:
6552 		 *   - append it at the end of main program's instructions blog;
6553 		 *   - process is recursively, while current program is put on hold;
6554 		 *   - if that subprogram calls some other not yet processes
6555 		 *   subprogram, same thing will happen recursively until
6556 		 *   there are no more unprocesses subprograms left to append
6557 		 *   and relocate.
6558 		 */
6559 		if (subprog->sub_insn_off == 0) {
6560 			subprog->sub_insn_off = main_prog->insns_cnt;
6561 
6562 			new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
6563 			insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
6564 			if (!insns) {
6565 				pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
6566 				return -ENOMEM;
6567 			}
6568 			main_prog->insns = insns;
6569 			main_prog->insns_cnt = new_cnt;
6570 
6571 			memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
6572 			       subprog->insns_cnt * sizeof(*insns));
6573 
6574 			pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
6575 				 main_prog->name, subprog->insns_cnt, subprog->name);
6576 
6577 			/* The subprog insns are now appended. Append its relos too. */
6578 			err = append_subprog_relos(main_prog, subprog);
6579 			if (err)
6580 				return err;
6581 			err = bpf_object__reloc_code(obj, main_prog, subprog);
6582 			if (err)
6583 				return err;
6584 		}
6585 
6586 		/* main_prog->insns memory could have been re-allocated, so
6587 		 * calculate pointer again
6588 		 */
6589 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6590 		/* calculate correct instruction position within current main
6591 		 * prog; each main prog can have a different set of
6592 		 * subprograms appended (potentially in different order as
6593 		 * well), so position of any subprog can be different for
6594 		 * different main programs
6595 		 */
6596 		insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
6597 
6598 		pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
6599 			 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
6600 	}
6601 
6602 	return 0;
6603 }
6604 
6605 /*
6606  * Relocate sub-program calls.
6607  *
6608  * Algorithm operates as follows. Each entry-point BPF program (referred to as
6609  * main prog) is processed separately. For each subprog (non-entry functions,
6610  * that can be called from either entry progs or other subprogs) gets their
6611  * sub_insn_off reset to zero. This serves as indicator that this subprogram
6612  * hasn't been yet appended and relocated within current main prog. Once its
6613  * relocated, sub_insn_off will point at the position within current main prog
6614  * where given subprog was appended. This will further be used to relocate all
6615  * the call instructions jumping into this subprog.
6616  *
6617  * We start with main program and process all call instructions. If the call
6618  * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
6619  * is zero), subprog instructions are appended at the end of main program's
6620  * instruction array. Then main program is "put on hold" while we recursively
6621  * process newly appended subprogram. If that subprogram calls into another
6622  * subprogram that hasn't been appended, new subprogram is appended again to
6623  * the *main* prog's instructions (subprog's instructions are always left
6624  * untouched, as they need to be in unmodified state for subsequent main progs
6625  * and subprog instructions are always sent only as part of a main prog) and
6626  * the process continues recursively. Once all the subprogs called from a main
6627  * prog or any of its subprogs are appended (and relocated), all their
6628  * positions within finalized instructions array are known, so it's easy to
6629  * rewrite call instructions with correct relative offsets, corresponding to
6630  * desired target subprog.
6631  *
6632  * Its important to realize that some subprogs might not be called from some
6633  * main prog and any of its called/used subprogs. Those will keep their
6634  * subprog->sub_insn_off as zero at all times and won't be appended to current
6635  * main prog and won't be relocated within the context of current main prog.
6636  * They might still be used from other main progs later.
6637  *
6638  * Visually this process can be shown as below. Suppose we have two main
6639  * programs mainA and mainB and BPF object contains three subprogs: subA,
6640  * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
6641  * subC both call subB:
6642  *
6643  *        +--------+ +-------+
6644  *        |        v v       |
6645  *     +--+---+ +--+-+-+ +---+--+
6646  *     | subA | | subB | | subC |
6647  *     +--+---+ +------+ +---+--+
6648  *        ^                  ^
6649  *        |                  |
6650  *    +---+-------+   +------+----+
6651  *    |   mainA   |   |   mainB   |
6652  *    +-----------+   +-----------+
6653  *
6654  * We'll start relocating mainA, will find subA, append it and start
6655  * processing sub A recursively:
6656  *
6657  *    +-----------+------+
6658  *    |   mainA   | subA |
6659  *    +-----------+------+
6660  *
6661  * At this point we notice that subB is used from subA, so we append it and
6662  * relocate (there are no further subcalls from subB):
6663  *
6664  *    +-----------+------+------+
6665  *    |   mainA   | subA | subB |
6666  *    +-----------+------+------+
6667  *
6668  * At this point, we relocate subA calls, then go one level up and finish with
6669  * relocatin mainA calls. mainA is done.
6670  *
6671  * For mainB process is similar but results in different order. We start with
6672  * mainB and skip subA and subB, as mainB never calls them (at least
6673  * directly), but we see subC is needed, so we append and start processing it:
6674  *
6675  *    +-----------+------+
6676  *    |   mainB   | subC |
6677  *    +-----------+------+
6678  * Now we see subC needs subB, so we go back to it, append and relocate it:
6679  *
6680  *    +-----------+------+------+
6681  *    |   mainB   | subC | subB |
6682  *    +-----------+------+------+
6683  *
6684  * At this point we unwind recursion, relocate calls in subC, then in mainB.
6685  */
6686 static int
6687 bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
6688 {
6689 	struct bpf_program *subprog;
6690 	int i, err;
6691 
6692 	/* mark all subprogs as not relocated (yet) within the context of
6693 	 * current main program
6694 	 */
6695 	for (i = 0; i < obj->nr_programs; i++) {
6696 		subprog = &obj->programs[i];
6697 		if (!prog_is_subprog(obj, subprog))
6698 			continue;
6699 
6700 		subprog->sub_insn_off = 0;
6701 	}
6702 
6703 	err = bpf_object__reloc_code(obj, prog, prog);
6704 	if (err)
6705 		return err;
6706 
6707 	return 0;
6708 }
6709 
6710 static void
6711 bpf_object__free_relocs(struct bpf_object *obj)
6712 {
6713 	struct bpf_program *prog;
6714 	int i;
6715 
6716 	/* free up relocation descriptors */
6717 	for (i = 0; i < obj->nr_programs; i++) {
6718 		prog = &obj->programs[i];
6719 		zfree(&prog->reloc_desc);
6720 		prog->nr_reloc = 0;
6721 	}
6722 }
6723 
6724 static int cmp_relocs(const void *_a, const void *_b)
6725 {
6726 	const struct reloc_desc *a = _a;
6727 	const struct reloc_desc *b = _b;
6728 
6729 	if (a->insn_idx != b->insn_idx)
6730 		return a->insn_idx < b->insn_idx ? -1 : 1;
6731 
6732 	/* no two relocations should have the same insn_idx, but ... */
6733 	if (a->type != b->type)
6734 		return a->type < b->type ? -1 : 1;
6735 
6736 	return 0;
6737 }
6738 
6739 static void bpf_object__sort_relos(struct bpf_object *obj)
6740 {
6741 	int i;
6742 
6743 	for (i = 0; i < obj->nr_programs; i++) {
6744 		struct bpf_program *p = &obj->programs[i];
6745 
6746 		if (!p->nr_reloc)
6747 			continue;
6748 
6749 		qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
6750 	}
6751 }
6752 
6753 static int
6754 bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
6755 {
6756 	struct bpf_program *prog;
6757 	size_t i, j;
6758 	int err;
6759 
6760 	if (obj->btf_ext) {
6761 		err = bpf_object__relocate_core(obj, targ_btf_path);
6762 		if (err) {
6763 			pr_warn("failed to perform CO-RE relocations: %d\n",
6764 				err);
6765 			return err;
6766 		}
6767 		bpf_object__sort_relos(obj);
6768 	}
6769 
6770 	/* Before relocating calls pre-process relocations and mark
6771 	 * few ld_imm64 instructions that points to subprogs.
6772 	 * Otherwise bpf_object__reloc_code() later would have to consider
6773 	 * all ld_imm64 insns as relocation candidates. That would
6774 	 * reduce relocation speed, since amount of find_prog_insn_relo()
6775 	 * would increase and most of them will fail to find a relo.
6776 	 */
6777 	for (i = 0; i < obj->nr_programs; i++) {
6778 		prog = &obj->programs[i];
6779 		for (j = 0; j < prog->nr_reloc; j++) {
6780 			struct reloc_desc *relo = &prog->reloc_desc[j];
6781 			struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6782 
6783 			/* mark the insn, so it's recognized by insn_is_pseudo_func() */
6784 			if (relo->type == RELO_SUBPROG_ADDR)
6785 				insn[0].src_reg = BPF_PSEUDO_FUNC;
6786 		}
6787 	}
6788 
6789 	/* relocate subprogram calls and append used subprograms to main
6790 	 * programs; each copy of subprogram code needs to be relocated
6791 	 * differently for each main program, because its code location might
6792 	 * have changed.
6793 	 * Append subprog relos to main programs to allow data relos to be
6794 	 * processed after text is completely relocated.
6795 	 */
6796 	for (i = 0; i < obj->nr_programs; i++) {
6797 		prog = &obj->programs[i];
6798 		/* sub-program's sub-calls are relocated within the context of
6799 		 * its main program only
6800 		 */
6801 		if (prog_is_subprog(obj, prog))
6802 			continue;
6803 		if (!prog->autoload)
6804 			continue;
6805 
6806 		err = bpf_object__relocate_calls(obj, prog);
6807 		if (err) {
6808 			pr_warn("prog '%s': failed to relocate calls: %d\n",
6809 				prog->name, err);
6810 			return err;
6811 		}
6812 	}
6813 	/* Process data relos for main programs */
6814 	for (i = 0; i < obj->nr_programs; i++) {
6815 		prog = &obj->programs[i];
6816 		if (prog_is_subprog(obj, prog))
6817 			continue;
6818 		if (!prog->autoload)
6819 			continue;
6820 		err = bpf_object__relocate_data(obj, prog);
6821 		if (err) {
6822 			pr_warn("prog '%s': failed to relocate data references: %d\n",
6823 				prog->name, err);
6824 			return err;
6825 		}
6826 	}
6827 
6828 	return 0;
6829 }
6830 
6831 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
6832 					    Elf64_Shdr *shdr, Elf_Data *data);
6833 
6834 static int bpf_object__collect_map_relos(struct bpf_object *obj,
6835 					 Elf64_Shdr *shdr, Elf_Data *data)
6836 {
6837 	const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
6838 	int i, j, nrels, new_sz;
6839 	const struct btf_var_secinfo *vi = NULL;
6840 	const struct btf_type *sec, *var, *def;
6841 	struct bpf_map *map = NULL, *targ_map = NULL;
6842 	struct bpf_program *targ_prog = NULL;
6843 	bool is_prog_array, is_map_in_map;
6844 	const struct btf_member *member;
6845 	const char *name, *mname, *type;
6846 	unsigned int moff;
6847 	Elf64_Sym *sym;
6848 	Elf64_Rel *rel;
6849 	void *tmp;
6850 
6851 	if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
6852 		return -EINVAL;
6853 	sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
6854 	if (!sec)
6855 		return -EINVAL;
6856 
6857 	nrels = shdr->sh_size / shdr->sh_entsize;
6858 	for (i = 0; i < nrels; i++) {
6859 		rel = elf_rel_by_idx(data, i);
6860 		if (!rel) {
6861 			pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
6862 			return -LIBBPF_ERRNO__FORMAT;
6863 		}
6864 
6865 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
6866 		if (!sym) {
6867 			pr_warn(".maps relo #%d: symbol %zx not found\n",
6868 				i, (size_t)ELF64_R_SYM(rel->r_info));
6869 			return -LIBBPF_ERRNO__FORMAT;
6870 		}
6871 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
6872 
6873 		pr_debug(".maps relo #%d: for %zd value %zd rel->r_offset %zu name %d ('%s')\n",
6874 			 i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
6875 			 (size_t)rel->r_offset, sym->st_name, name);
6876 
6877 		for (j = 0; j < obj->nr_maps; j++) {
6878 			map = &obj->maps[j];
6879 			if (map->sec_idx != obj->efile.btf_maps_shndx)
6880 				continue;
6881 
6882 			vi = btf_var_secinfos(sec) + map->btf_var_idx;
6883 			if (vi->offset <= rel->r_offset &&
6884 			    rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size)
6885 				break;
6886 		}
6887 		if (j == obj->nr_maps) {
6888 			pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
6889 				i, name, (size_t)rel->r_offset);
6890 			return -EINVAL;
6891 		}
6892 
6893 		is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
6894 		is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
6895 		type = is_map_in_map ? "map" : "prog";
6896 		if (is_map_in_map) {
6897 			if (sym->st_shndx != obj->efile.btf_maps_shndx) {
6898 				pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
6899 					i, name);
6900 				return -LIBBPF_ERRNO__RELOC;
6901 			}
6902 			if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
6903 			    map->def.key_size != sizeof(int)) {
6904 				pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
6905 					i, map->name, sizeof(int));
6906 				return -EINVAL;
6907 			}
6908 			targ_map = bpf_object__find_map_by_name(obj, name);
6909 			if (!targ_map) {
6910 				pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
6911 					i, name);
6912 				return -ESRCH;
6913 			}
6914 		} else if (is_prog_array) {
6915 			targ_prog = bpf_object__find_program_by_name(obj, name);
6916 			if (!targ_prog) {
6917 				pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
6918 					i, name);
6919 				return -ESRCH;
6920 			}
6921 			if (targ_prog->sec_idx != sym->st_shndx ||
6922 			    targ_prog->sec_insn_off * 8 != sym->st_value ||
6923 			    prog_is_subprog(obj, targ_prog)) {
6924 				pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
6925 					i, name);
6926 				return -LIBBPF_ERRNO__RELOC;
6927 			}
6928 		} else {
6929 			return -EINVAL;
6930 		}
6931 
6932 		var = btf__type_by_id(obj->btf, vi->type);
6933 		def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
6934 		if (btf_vlen(def) == 0)
6935 			return -EINVAL;
6936 		member = btf_members(def) + btf_vlen(def) - 1;
6937 		mname = btf__name_by_offset(obj->btf, member->name_off);
6938 		if (strcmp(mname, "values"))
6939 			return -EINVAL;
6940 
6941 		moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
6942 		if (rel->r_offset - vi->offset < moff)
6943 			return -EINVAL;
6944 
6945 		moff = rel->r_offset - vi->offset - moff;
6946 		/* here we use BPF pointer size, which is always 64 bit, as we
6947 		 * are parsing ELF that was built for BPF target
6948 		 */
6949 		if (moff % bpf_ptr_sz)
6950 			return -EINVAL;
6951 		moff /= bpf_ptr_sz;
6952 		if (moff >= map->init_slots_sz) {
6953 			new_sz = moff + 1;
6954 			tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
6955 			if (!tmp)
6956 				return -ENOMEM;
6957 			map->init_slots = tmp;
6958 			memset(map->init_slots + map->init_slots_sz, 0,
6959 			       (new_sz - map->init_slots_sz) * host_ptr_sz);
6960 			map->init_slots_sz = new_sz;
6961 		}
6962 		map->init_slots[moff] = is_map_in_map ? (void *)targ_map : (void *)targ_prog;
6963 
6964 		pr_debug(".maps relo #%d: map '%s' slot [%d] points to %s '%s'\n",
6965 			 i, map->name, moff, type, name);
6966 	}
6967 
6968 	return 0;
6969 }
6970 
6971 static int bpf_object__collect_relos(struct bpf_object *obj)
6972 {
6973 	int i, err;
6974 
6975 	for (i = 0; i < obj->efile.sec_cnt; i++) {
6976 		struct elf_sec_desc *sec_desc = &obj->efile.secs[i];
6977 		Elf64_Shdr *shdr;
6978 		Elf_Data *data;
6979 		int idx;
6980 		Elf64_Shdr shdrelf;
6981 
6982 		if (sec_desc->sec_type != SEC_RELO)
6983 			continue;
6984 
6985 #if defined HAVE_LIBELF
6986 		shdr = sec_desc->shdr;
6987 #elif defined HAVE_ELFIO
6988 		shdr = elf_sec_hdr_by_idx(obj, i, &shdrelf);
6989 #endif
6990 		data = sec_desc->data;
6991 		idx = shdr->sh_info;
6992 
6993 		if (shdr->sh_type != SHT_REL) {
6994 			pr_warn("internal error at %d\n", __LINE__);
6995 			return -LIBBPF_ERRNO__INTERNAL;
6996 		}
6997 
6998 		if (idx == obj->efile.st_ops_shndx)
6999 			err = bpf_object__collect_st_ops_relos(obj, shdr, data);
7000 		else if (idx == obj->efile.btf_maps_shndx)
7001 			err = bpf_object__collect_map_relos(obj, shdr, data);
7002 		else
7003 			err = bpf_object__collect_prog_relos(obj, shdr, data);
7004 		if (err)
7005 			return err;
7006 	}
7007 
7008 	bpf_object__sort_relos(obj);
7009 	return 0;
7010 }
7011 
7012 static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
7013 {
7014 	if (BPF_CLASS(insn->code) == BPF_JMP &&
7015 	    BPF_OP(insn->code) == BPF_CALL &&
7016 	    BPF_SRC(insn->code) == BPF_K &&
7017 	    insn->src_reg == 0 &&
7018 	    insn->dst_reg == 0) {
7019 		    *func_id = insn->imm;
7020 		    return true;
7021 	}
7022 	return false;
7023 }
7024 
7025 static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
7026 {
7027 	struct bpf_insn *insn = prog->insns;
7028 	enum bpf_func_id func_id;
7029 	int i;
7030 
7031 	if (obj->gen_loader)
7032 		return 0;
7033 
7034 	for (i = 0; i < prog->insns_cnt; i++, insn++) {
7035 		if (!insn_is_helper_call(insn, &func_id))
7036 			continue;
7037 
7038 		/* on kernels that don't yet support
7039 		 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
7040 		 * to bpf_probe_read() which works well for old kernels
7041 		 */
7042 		switch (func_id) {
7043 		case BPF_FUNC_probe_read_kernel:
7044 		case BPF_FUNC_probe_read_user:
7045 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
7046 				insn->imm = BPF_FUNC_probe_read;
7047 			break;
7048 		case BPF_FUNC_probe_read_kernel_str:
7049 		case BPF_FUNC_probe_read_user_str:
7050 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
7051 				insn->imm = BPF_FUNC_probe_read_str;
7052 			break;
7053 		default:
7054 			break;
7055 		}
7056 	}
7057 	return 0;
7058 }
7059 
7060 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
7061 				     int *btf_obj_fd, int *btf_type_id);
7062 
7063 /* this is called as prog->sec_def->prog_prepare_load_fn for libbpf-supported sec_defs */
7064 static int libbpf_prepare_prog_load(struct bpf_program *prog,
7065 				    struct bpf_prog_load_opts *opts, long cookie)
7066 {
7067 	enum sec_def_flags def = cookie;
7068 
7069 	/* old kernels might not support specifying expected_attach_type */
7070 	if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
7071 		opts->expected_attach_type = 0;
7072 
7073 	if (def & SEC_SLEEPABLE)
7074 		opts->prog_flags |= BPF_F_SLEEPABLE;
7075 
7076 	if (prog->type == BPF_PROG_TYPE_XDP && (def & SEC_XDP_FRAGS))
7077 		opts->prog_flags |= BPF_F_XDP_HAS_FRAGS;
7078 
7079 	if ((def & SEC_ATTACH_BTF) && !prog->attach_btf_id) {
7080 		int btf_obj_fd = 0, btf_type_id = 0, err;
7081 		const char *attach_name;
7082 
7083 		attach_name = strchr(prog->sec_name, '/');
7084 		if (!attach_name) {
7085 			/* if BPF program is annotated with just SEC("fentry")
7086 			 * (or similar) without declaratively specifying
7087 			 * target, then it is expected that target will be
7088 			 * specified with bpf_program__set_attach_target() at
7089 			 * runtime before BPF object load step. If not, then
7090 			 * there is nothing to load into the kernel as BPF
7091 			 * verifier won't be able to validate BPF program
7092 			 * correctness anyways.
7093 			 */
7094 			pr_warn("prog '%s': no BTF-based attach target is specified, use bpf_program__set_attach_target()\n",
7095 				prog->name);
7096 			return -EINVAL;
7097 		}
7098 		attach_name++; /* skip over / */
7099 
7100 		err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
7101 		if (err)
7102 			return err;
7103 
7104 		/* cache resolved BTF FD and BTF type ID in the prog */
7105 		prog->attach_btf_obj_fd = btf_obj_fd;
7106 		prog->attach_btf_id = btf_type_id;
7107 
7108 		/* but by now libbpf common logic is not utilizing
7109 		 * prog->atach_btf_obj_fd/prog->attach_btf_id anymore because
7110 		 * this callback is called after opts were populated by
7111 		 * libbpf, so this callback has to update opts explicitly here
7112 		 */
7113 		opts->attach_btf_obj_fd = btf_obj_fd;
7114 		opts->attach_btf_id = btf_type_id;
7115 	}
7116 	return 0;
7117 }
7118 
7119 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz);
7120 
7121 static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
7122 				struct bpf_insn *insns, int insns_cnt,
7123 				const char *license, __u32 kern_version, int *prog_fd)
7124 {
7125 	LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
7126 	const char *prog_name = NULL;
7127 	char *cp, errmsg[STRERR_BUFSIZE];
7128 	size_t log_buf_size = 0;
7129 	char *log_buf = NULL, *tmp;
7130 	int btf_fd, ret, err;
7131 	bool own_log_buf = true;
7132 	__u32 log_level = prog->log_level;
7133 
7134 	if (prog->type == BPF_PROG_TYPE_UNSPEC) {
7135 		/*
7136 		 * The program type must be set.  Most likely we couldn't find a proper
7137 		 * section definition at load time, and thus we didn't infer the type.
7138 		 */
7139 		pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
7140 			prog->name, prog->sec_name);
7141 		return -EINVAL;
7142 	}
7143 
7144 	if (!insns || !insns_cnt)
7145 		return -EINVAL;
7146 
7147 	load_attr.expected_attach_type = prog->expected_attach_type;
7148 	if (kernel_supports(obj, FEAT_PROG_NAME))
7149 		prog_name = prog->name;
7150 	load_attr.attach_prog_fd = prog->attach_prog_fd;
7151 	load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
7152 	load_attr.attach_btf_id = prog->attach_btf_id;
7153 	load_attr.kern_version = kern_version;
7154 	load_attr.prog_ifindex = prog->prog_ifindex;
7155 
7156 	/* specify func_info/line_info only if kernel supports them */
7157 	btf_fd = bpf_object__btf_fd(obj);
7158 	if (btf_fd >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
7159 		load_attr.prog_btf_fd = btf_fd;
7160 		load_attr.func_info = prog->func_info;
7161 		load_attr.func_info_rec_size = prog->func_info_rec_size;
7162 		load_attr.func_info_cnt = prog->func_info_cnt;
7163 		load_attr.line_info = prog->line_info;
7164 		load_attr.line_info_rec_size = prog->line_info_rec_size;
7165 		load_attr.line_info_cnt = prog->line_info_cnt;
7166 	}
7167 	load_attr.log_level = log_level;
7168 	load_attr.prog_flags = prog->prog_flags;
7169 	load_attr.fd_array = obj->fd_array;
7170 
7171 	/* adjust load_attr if sec_def provides custom preload callback */
7172 	if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
7173 		err = prog->sec_def->prog_prepare_load_fn(prog, &load_attr, prog->sec_def->cookie);
7174 		if (err < 0) {
7175 			pr_warn("prog '%s': failed to prepare load attributes: %d\n",
7176 				prog->name, err);
7177 			return err;
7178 		}
7179 		insns = prog->insns;
7180 		insns_cnt = prog->insns_cnt;
7181 	}
7182 
7183 	if (obj->gen_loader) {
7184 		bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
7185 				   license, insns, insns_cnt, &load_attr,
7186 				   prog - obj->programs);
7187 		*prog_fd = -1;
7188 		return 0;
7189 	}
7190 
7191 retry_load:
7192 	/* if log_level is zero, we don't request logs initially even if
7193 	 * custom log_buf is specified; if the program load fails, then we'll
7194 	 * bump log_level to 1 and use either custom log_buf or we'll allocate
7195 	 * our own and retry the load to get details on what failed
7196 	 */
7197 	if (log_level) {
7198 		if (prog->log_buf) {
7199 			log_buf = prog->log_buf;
7200 			log_buf_size = prog->log_size;
7201 			own_log_buf = false;
7202 		} else if (obj->log_buf) {
7203 			log_buf = obj->log_buf;
7204 			log_buf_size = obj->log_size;
7205 			own_log_buf = false;
7206 		} else {
7207 			log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
7208 			tmp = realloc(log_buf, log_buf_size);
7209 			if (!tmp) {
7210 				ret = -ENOMEM;
7211 				goto out;
7212 			}
7213 			log_buf = tmp;
7214 			log_buf[0] = '\0';
7215 			own_log_buf = true;
7216 		}
7217 	}
7218 
7219 	load_attr.log_buf = log_buf;
7220 	load_attr.log_size = log_buf_size;
7221 	load_attr.log_level = log_level;
7222 
7223 	ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
7224 	if (ret >= 0) {
7225 		if (log_level && own_log_buf) {
7226 			pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
7227 				 prog->name, log_buf);
7228 		}
7229 
7230 		if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
7231 			struct bpf_map *map;
7232 			int i;
7233 
7234 			for (i = 0; i < obj->nr_maps; i++) {
7235 				map = &prog->obj->maps[i];
7236 				if (map->libbpf_type != LIBBPF_MAP_RODATA)
7237 					continue;
7238 
7239 				if (bpf_prog_bind_map(ret, bpf_map__fd(map), NULL)) {
7240 					cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
7241 					pr_warn("prog '%s': failed to bind map '%s': %s\n",
7242 						prog->name, map->real_name, cp);
7243 					/* Don't fail hard if can't bind rodata. */
7244 				}
7245 			}
7246 		}
7247 
7248 		*prog_fd = ret;
7249 		ret = 0;
7250 		goto out;
7251 	}
7252 
7253 	if (log_level == 0) {
7254 		log_level = 1;
7255 		goto retry_load;
7256 	}
7257 	/* On ENOSPC, increase log buffer size and retry, unless custom
7258 	 * log_buf is specified.
7259 	 * Be careful to not overflow u32, though. Kernel's log buf size limit
7260 	 * isn't part of UAPI so it can always be bumped to full 4GB. So don't
7261 	 * multiply by 2 unless we are sure we'll fit within 32 bits.
7262 	 * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
7263 	 */
7264 	if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
7265 		goto retry_load;
7266 
7267 	ret = -errno;
7268 
7269 	/* post-process verifier log to improve error descriptions */
7270 	fixup_verifier_log(prog, log_buf, log_buf_size);
7271 
7272 	cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
7273 	pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, cp);
7274 	pr_perm_msg(ret);
7275 
7276 	if (own_log_buf && log_buf && log_buf[0] != '\0') {
7277 		pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
7278 			prog->name, log_buf);
7279 	}
7280 
7281 out:
7282 	if (own_log_buf)
7283 		free(log_buf);
7284 	return ret;
7285 }
7286 
7287 static char *find_prev_line(char *buf, char *cur)
7288 {
7289 	char *p;
7290 
7291 	if (cur == buf) /* end of a log buf */
7292 		return NULL;
7293 
7294 	p = cur - 1;
7295 	while (p - 1 >= buf && *(p - 1) != '\n')
7296 		p--;
7297 
7298 	return p;
7299 }
7300 
7301 static void patch_log(char *buf, size_t buf_sz, size_t log_sz,
7302 		      char *orig, size_t orig_sz, const char *patch)
7303 {
7304 	/* size of the remaining log content to the right from the to-be-replaced part */
7305 	size_t rem_sz = (buf + log_sz) - (orig + orig_sz);
7306 	size_t patch_sz = strlen(patch);
7307 
7308 	if (patch_sz != orig_sz) {
7309 		/* If patch line(s) are longer than original piece of verifier log,
7310 		 * shift log contents by (patch_sz - orig_sz) bytes to the right
7311 		 * starting from after to-be-replaced part of the log.
7312 		 *
7313 		 * If patch line(s) are shorter than original piece of verifier log,
7314 		 * shift log contents by (orig_sz - patch_sz) bytes to the left
7315 		 * starting from after to-be-replaced part of the log
7316 		 *
7317 		 * We need to be careful about not overflowing available
7318 		 * buf_sz capacity. If that's the case, we'll truncate the end
7319 		 * of the original log, as necessary.
7320 		 */
7321 		if (patch_sz > orig_sz) {
7322 			if (orig + patch_sz >= buf + buf_sz) {
7323 				/* patch is big enough to cover remaining space completely */
7324 				patch_sz -= (orig + patch_sz) - (buf + buf_sz) + 1;
7325 				rem_sz = 0;
7326 			} else if (patch_sz - orig_sz > buf_sz - log_sz) {
7327 				/* patch causes part of remaining log to be truncated */
7328 				rem_sz -= (patch_sz - orig_sz) - (buf_sz - log_sz);
7329 			}
7330 		}
7331 		/* shift remaining log to the right by calculated amount */
7332 		memmove(orig + patch_sz, orig + orig_sz, rem_sz);
7333 	}
7334 
7335 	memcpy(orig, patch, patch_sz);
7336 }
7337 
7338 static void fixup_log_failed_core_relo(struct bpf_program *prog,
7339 				       char *buf, size_t buf_sz, size_t log_sz,
7340 				       char *line1, char *line2, char *line3)
7341 {
7342 	/* Expected log for failed and not properly guarded CO-RE relocation:
7343 	 * line1 -> 123: (85) call unknown#195896080
7344 	 * line2 -> invalid func unknown#195896080
7345 	 * line3 -> <anything else or end of buffer>
7346 	 *
7347 	 * "123" is the index of the instruction that was poisoned. We extract
7348 	 * instruction index to find corresponding CO-RE relocation and
7349 	 * replace this part of the log with more relevant information about
7350 	 * failed CO-RE relocation.
7351 	 */
7352 	const struct bpf_core_relo *relo;
7353 	struct bpf_core_spec spec;
7354 	char patch[512], spec_buf[256];
7355 	int insn_idx, err, spec_len;
7356 
7357 	if (sscanf(line1, "%d: (%*d) call unknown#195896080\n", &insn_idx) != 1)
7358 		return;
7359 
7360 	relo = find_relo_core(prog, insn_idx);
7361 	if (!relo)
7362 		return;
7363 
7364 	err = bpf_core_parse_spec(prog->name, prog->obj->btf, relo, &spec);
7365 	if (err)
7366 		return;
7367 
7368 	spec_len = bpf_core_format_spec(spec_buf, sizeof(spec_buf), &spec);
7369 	snprintf(patch, sizeof(patch),
7370 		 "%d: <invalid CO-RE relocation>\n"
7371 		 "failed to resolve CO-RE relocation %s%s\n",
7372 		 insn_idx, spec_buf, spec_len >= sizeof(spec_buf) ? "..." : "");
7373 
7374 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7375 }
7376 
7377 static void fixup_log_missing_map_load(struct bpf_program *prog,
7378 				       char *buf, size_t buf_sz, size_t log_sz,
7379 				       char *line1, char *line2, char *line3)
7380 {
7381 	/* Expected log for failed and not properly guarded CO-RE relocation:
7382 	 * line1 -> 123: (85) call unknown#2001000345
7383 	 * line2 -> invalid func unknown#2001000345
7384 	 * line3 -> <anything else or end of buffer>
7385 	 *
7386 	 * "123" is the index of the instruction that was poisoned.
7387 	 * "345" in "2001000345" are map index in obj->maps to fetch map name.
7388 	 */
7389 	struct bpf_object *obj = prog->obj;
7390 	const struct bpf_map *map;
7391 	int insn_idx, map_idx;
7392 	char patch[128];
7393 
7394 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &map_idx) != 2)
7395 		return;
7396 
7397 	map_idx -= MAP_LDIMM64_POISON_BASE;
7398 	if (map_idx < 0 || map_idx >= obj->nr_maps)
7399 		return;
7400 	map = &obj->maps[map_idx];
7401 
7402 	snprintf(patch, sizeof(patch),
7403 		 "%d: <invalid BPF map reference>\n"
7404 		 "BPF map '%s' is referenced but wasn't created\n",
7405 		 insn_idx, map->name);
7406 
7407 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7408 }
7409 
7410 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz)
7411 {
7412 	/* look for familiar error patterns in last N lines of the log */
7413 	const size_t max_last_line_cnt = 10;
7414 	char *prev_line, *cur_line, *next_line;
7415 	size_t log_sz;
7416 	int i;
7417 
7418 	if (!buf)
7419 		return;
7420 
7421 	log_sz = strlen(buf) + 1;
7422 	next_line = buf + log_sz - 1;
7423 
7424 	for (i = 0; i < max_last_line_cnt; i++, next_line = cur_line) {
7425 		cur_line = find_prev_line(buf, next_line);
7426 		if (!cur_line)
7427 			return;
7428 
7429 		/* failed CO-RE relocation case */
7430 		if (str_has_pfx(cur_line, "invalid func unknown#195896080\n")) {
7431 			prev_line = find_prev_line(buf, cur_line);
7432 			if (!prev_line)
7433 				continue;
7434 
7435 			fixup_log_failed_core_relo(prog, buf, buf_sz, log_sz,
7436 						   prev_line, cur_line, next_line);
7437 			return;
7438 		} else if (str_has_pfx(cur_line, "invalid func unknown#"MAP_LDIMM64_POISON_PFX)) {
7439 			prev_line = find_prev_line(buf, cur_line);
7440 			if (!prev_line)
7441 				continue;
7442 
7443 			fixup_log_missing_map_load(prog, buf, buf_sz, log_sz,
7444 						   prev_line, cur_line, next_line);
7445 			return;
7446 		}
7447 	}
7448 }
7449 
7450 static int bpf_program_record_relos(struct bpf_program *prog)
7451 {
7452 	struct bpf_object *obj = prog->obj;
7453 	int i;
7454 
7455 	for (i = 0; i < prog->nr_reloc; i++) {
7456 		struct reloc_desc *relo = &prog->reloc_desc[i];
7457 		struct extern_desc *ext = &obj->externs[relo->sym_off];
7458 
7459 		switch (relo->type) {
7460 		case RELO_EXTERN_VAR:
7461 			if (ext->type != EXT_KSYM)
7462 				continue;
7463 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7464 					       ext->is_weak, !ext->ksym.type_id,
7465 					       BTF_KIND_VAR, relo->insn_idx);
7466 			break;
7467 		case RELO_EXTERN_FUNC:
7468 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7469 					       ext->is_weak, false, BTF_KIND_FUNC,
7470 					       relo->insn_idx);
7471 			break;
7472 		case RELO_CORE: {
7473 			struct bpf_core_relo cr = {
7474 				.insn_off = relo->insn_idx * 8,
7475 				.type_id = relo->core_relo->type_id,
7476 				.access_str_off = relo->core_relo->access_str_off,
7477 				.kind = relo->core_relo->kind,
7478 			};
7479 
7480 			bpf_gen__record_relo_core(obj->gen_loader, &cr);
7481 			break;
7482 		}
7483 		default:
7484 			continue;
7485 		}
7486 	}
7487 	return 0;
7488 }
7489 
7490 static int
7491 bpf_object__load_progs(struct bpf_object *obj, int log_level)
7492 {
7493 	struct bpf_program *prog;
7494 	size_t i;
7495 	int err;
7496 
7497 	for (i = 0; i < obj->nr_programs; i++) {
7498 		prog = &obj->programs[i];
7499 		err = bpf_object__sanitize_prog(obj, prog);
7500 		if (err)
7501 			return err;
7502 	}
7503 
7504 	for (i = 0; i < obj->nr_programs; i++) {
7505 		prog = &obj->programs[i];
7506 		if (prog_is_subprog(obj, prog))
7507 			continue;
7508 		if (!prog->autoload) {
7509 			pr_debug("prog '%s': skipped loading\n", prog->name);
7510 			continue;
7511 		}
7512 		prog->log_level |= log_level;
7513 
7514 		if (obj->gen_loader)
7515 			bpf_program_record_relos(prog);
7516 
7517 		err = bpf_object_load_prog(obj, prog, prog->insns, prog->insns_cnt,
7518 					   obj->license, obj->kern_version, &prog->fd);
7519 		if (err) {
7520 			pr_warn("prog '%s': failed to load: %d\n", prog->name, err);
7521 			return err;
7522 		}
7523 	}
7524 
7525 	bpf_object__free_relocs(obj);
7526 	return 0;
7527 }
7528 
7529 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
7530 
7531 static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
7532 {
7533 	struct bpf_program *prog;
7534 	int err;
7535 
7536 	bpf_object__for_each_program(prog, obj) {
7537 		prog->sec_def = find_sec_def(prog->sec_name);
7538 		if (!prog->sec_def) {
7539 			/* couldn't guess, but user might manually specify */
7540 			pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
7541 				prog->name, prog->sec_name);
7542 			continue;
7543 		}
7544 
7545 		prog->type = prog->sec_def->prog_type;
7546 		prog->expected_attach_type = prog->sec_def->expected_attach_type;
7547 
7548 		/* sec_def can have custom callback which should be called
7549 		 * after bpf_program is initialized to adjust its properties
7550 		 */
7551 		if (prog->sec_def->prog_setup_fn) {
7552 			err = prog->sec_def->prog_setup_fn(prog, prog->sec_def->cookie);
7553 			if (err < 0) {
7554 				pr_warn("prog '%s': failed to initialize: %d\n",
7555 					prog->name, err);
7556 				return err;
7557 			}
7558 		}
7559 	}
7560 
7561 	return 0;
7562 }
7563 
7564 static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
7565 					  const struct bpf_object_open_opts *opts)
7566 {
7567 	const char *obj_name, *kconfig, *btf_tmp_path;
7568 	struct bpf_object *obj;
7569 	char tmp_name[64];
7570 	int err;
7571 	char *log_buf;
7572 	size_t log_size;
7573 	__u32 log_level;
7574 
7575 #ifdef HAVE_LIBELF
7576 	if (elf_version(EV_CURRENT) == EV_NONE) {
7577 		pr_warn("failed to init libelf for %s\n",
7578 			path ? : "(mem buf)");
7579 		return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
7580 	}
7581 #endif
7582 
7583 	if (!OPTS_VALID(opts, bpf_object_open_opts))
7584 		return ERR_PTR(-EINVAL);
7585 
7586 	obj_name = OPTS_GET(opts, object_name, NULL);
7587 	if (obj_buf) {
7588 		if (!obj_name) {
7589 			snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
7590 				 (unsigned long)obj_buf,
7591 				 (unsigned long)obj_buf_sz);
7592 			obj_name = tmp_name;
7593 		}
7594 		path = obj_name;
7595 		pr_debug("loading object '%s' from buffer\n", obj_name);
7596 	}
7597 
7598 	log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
7599 	log_size = OPTS_GET(opts, kernel_log_size, 0);
7600 	log_level = OPTS_GET(opts, kernel_log_level, 0);
7601 	if (log_size > UINT_MAX)
7602 		return ERR_PTR(-EINVAL);
7603 	if (log_size && !log_buf)
7604 		return ERR_PTR(-EINVAL);
7605 
7606 	obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
7607 	if (IS_ERR(obj))
7608 		return obj;
7609 
7610 	obj->log_buf = log_buf;
7611 	obj->log_size = log_size;
7612 	obj->log_level = log_level;
7613 
7614 	btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
7615 	if (btf_tmp_path) {
7616 		if (strlen(btf_tmp_path) >= PATH_MAX) {
7617 			err = -ENAMETOOLONG;
7618 			goto out;
7619 		}
7620 		obj->btf_custom_path = strdup(btf_tmp_path);
7621 		if (!obj->btf_custom_path) {
7622 			err = -ENOMEM;
7623 			goto out;
7624 		}
7625 	}
7626 
7627 	kconfig = OPTS_GET(opts, kconfig, NULL);
7628 	if (kconfig) {
7629 		obj->kconfig = strdup(kconfig);
7630 		if (!obj->kconfig) {
7631 			err = -ENOMEM;
7632 			goto out;
7633 		}
7634 	}
7635 
7636 	err = bpf_object__elf_init(obj);
7637 	err = err ? : bpf_object__check_endianness(obj);
7638 	err = err ? : bpf_object__elf_collect(obj);
7639 	err = err ? : bpf_object__collect_externs(obj);
7640 	err = err ? : bpf_object_fixup_btf(obj);
7641 	err = err ? : bpf_object__init_maps(obj, opts);
7642 	err = err ? : bpf_object_init_progs(obj, opts);
7643 	err = err ? : bpf_object__collect_relos(obj);
7644 	if (err)
7645 		goto out;
7646 
7647 	bpf_object__elf_finish(obj);
7648 
7649 	return obj;
7650 out:
7651 	bpf_object__close(obj);
7652 	return ERR_PTR(err);
7653 }
7654 
7655 struct bpf_object *
7656 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
7657 {
7658 	if (!path)
7659 		return libbpf_err_ptr(-EINVAL);
7660 
7661 	pr_debug("loading %s\n", path);
7662 
7663 	return libbpf_ptr(bpf_object_open(path, NULL, 0, opts));
7664 }
7665 
7666 struct bpf_object *bpf_object__open(const char *path)
7667 {
7668 	return bpf_object__open_file(path, NULL);
7669 }
7670 
7671 struct bpf_object *
7672 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
7673 		     const struct bpf_object_open_opts *opts)
7674 {
7675 	if (!obj_buf || obj_buf_sz == 0)
7676 		return libbpf_err_ptr(-EINVAL);
7677 
7678 	return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, opts));
7679 }
7680 
7681 static int bpf_object_unload(struct bpf_object *obj)
7682 {
7683 	size_t i;
7684 
7685 	if (!obj)
7686 		return libbpf_err(-EINVAL);
7687 
7688 	for (i = 0; i < obj->nr_maps; i++) {
7689 		zclose(obj->maps[i].fd);
7690 		if (obj->maps[i].st_ops)
7691 			zfree(&obj->maps[i].st_ops->kern_vdata);
7692 	}
7693 
7694 	for (i = 0; i < obj->nr_programs; i++)
7695 		bpf_program__unload(&obj->programs[i]);
7696 
7697 	return 0;
7698 }
7699 
7700 static int bpf_object__sanitize_maps(struct bpf_object *obj)
7701 {
7702 	struct bpf_map *m;
7703 
7704 	bpf_object__for_each_map(m, obj) {
7705 		if (!bpf_map__is_internal(m))
7706 			continue;
7707 		if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
7708 			m->def.map_flags ^= BPF_F_MMAPABLE;
7709 	}
7710 
7711 	return 0;
7712 }
7713 
7714 int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
7715 {
7716 	char sym_type, sym_name[500];
7717 	unsigned long long sym_addr;
7718 	int ret, err = 0;
7719 	FILE *f;
7720 
7721 	f = fopen("/proc/kallsyms", "r");
7722 	if (!f) {
7723 		err = -errno;
7724 		pr_warn("failed to open /proc/kallsyms: %d\n", err);
7725 		return err;
7726 	}
7727 
7728 	while (true) {
7729 		ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
7730 			     &sym_addr, &sym_type, sym_name);
7731 		if (ret == EOF && feof(f))
7732 			break;
7733 		if (ret != 3) {
7734 			pr_warn("failed to read kallsyms entry: %d\n", ret);
7735 			err = -EINVAL;
7736 			break;
7737 		}
7738 
7739 		err = cb(sym_addr, sym_type, sym_name, ctx);
7740 		if (err)
7741 			break;
7742 	}
7743 
7744 	fclose(f);
7745 	return err;
7746 }
7747 
7748 static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
7749 		       const char *sym_name, void *ctx)
7750 {
7751 	struct bpf_object *obj = ctx;
7752 	const struct btf_type *t;
7753 	struct extern_desc *ext;
7754 
7755 	ext = find_extern_by_name(obj, sym_name);
7756 	if (!ext || ext->type != EXT_KSYM)
7757 		return 0;
7758 
7759 	t = btf__type_by_id(obj->btf, ext->btf_id);
7760 	if (!btf_is_var(t))
7761 		return 0;
7762 
7763 	if (ext->is_set && ext->ksym.addr != sym_addr) {
7764 		pr_warn("extern (ksym) '%s': resolution is ambiguous: 0x%llx or 0x%llx\n",
7765 			sym_name, ext->ksym.addr, sym_addr);
7766 		return -EINVAL;
7767 	}
7768 	if (!ext->is_set) {
7769 		ext->is_set = true;
7770 		ext->ksym.addr = sym_addr;
7771 		pr_debug("extern (ksym) '%s': set to 0x%llx\n", sym_name, sym_addr);
7772 	}
7773 	return 0;
7774 }
7775 
7776 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
7777 {
7778 	return libbpf_kallsyms_parse(kallsyms_cb, obj);
7779 }
7780 
7781 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
7782 			    __u16 kind, struct btf **res_btf,
7783 			    struct module_btf **res_mod_btf)
7784 {
7785 	struct module_btf *mod_btf;
7786 	struct btf *btf;
7787 	int i, id, err;
7788 
7789 	btf = obj->btf_vmlinux;
7790 	mod_btf = NULL;
7791 	id = btf__find_by_name_kind(btf, ksym_name, kind);
7792 
7793 	if (id == -ENOENT) {
7794 		err = load_module_btfs(obj);
7795 		if (err)
7796 			return err;
7797 
7798 		for (i = 0; i < obj->btf_module_cnt; i++) {
7799 			/* we assume module_btf's BTF FD is always >0 */
7800 			mod_btf = &obj->btf_modules[i];
7801 			btf = mod_btf->btf;
7802 			id = btf__find_by_name_kind_own(btf, ksym_name, kind);
7803 			if (id != -ENOENT)
7804 				break;
7805 		}
7806 	}
7807 	if (id <= 0)
7808 		return -ESRCH;
7809 
7810 	*res_btf = btf;
7811 	*res_mod_btf = mod_btf;
7812 	return id;
7813 }
7814 
7815 static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
7816 					       struct extern_desc *ext)
7817 {
7818 	const struct btf_type *targ_var, *targ_type;
7819 	__u32 targ_type_id, local_type_id;
7820 	struct module_btf *mod_btf = NULL;
7821 	const char *targ_var_name;
7822 	struct btf *btf = NULL;
7823 	int id, err;
7824 
7825 	id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
7826 	if (id < 0) {
7827 		if (id == -ESRCH && ext->is_weak)
7828 			return 0;
7829 		pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
7830 			ext->name);
7831 		return id;
7832 	}
7833 
7834 	/* find local type_id */
7835 	local_type_id = ext->ksym.type_id;
7836 
7837 	/* find target type_id */
7838 	targ_var = btf__type_by_id(btf, id);
7839 	targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
7840 	targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
7841 
7842 	err = bpf_core_types_are_compat(obj->btf, local_type_id,
7843 					btf, targ_type_id);
7844 	if (err <= 0) {
7845 		const struct btf_type *local_type;
7846 		const char *targ_name, *local_name;
7847 
7848 		local_type = btf__type_by_id(obj->btf, local_type_id);
7849 		local_name = btf__name_by_offset(obj->btf, local_type->name_off);
7850 		targ_name = btf__name_by_offset(btf, targ_type->name_off);
7851 
7852 		pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
7853 			ext->name, local_type_id,
7854 			btf_kind_str(local_type), local_name, targ_type_id,
7855 			btf_kind_str(targ_type), targ_name);
7856 		return -EINVAL;
7857 	}
7858 
7859 	ext->is_set = true;
7860 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
7861 	ext->ksym.kernel_btf_id = id;
7862 	pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
7863 		 ext->name, id, btf_kind_str(targ_var), targ_var_name);
7864 
7865 	return 0;
7866 }
7867 
7868 static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
7869 						struct extern_desc *ext)
7870 {
7871 	int local_func_proto_id, kfunc_proto_id, kfunc_id;
7872 	struct module_btf *mod_btf = NULL;
7873 	const struct btf_type *kern_func;
7874 	struct btf *kern_btf = NULL;
7875 	int ret;
7876 
7877 	local_func_proto_id = ext->ksym.type_id;
7878 
7879 	kfunc_id = find_ksym_btf_id(obj, ext->name, BTF_KIND_FUNC, &kern_btf, &mod_btf);
7880 	if (kfunc_id < 0) {
7881 		if (kfunc_id == -ESRCH && ext->is_weak)
7882 			return 0;
7883 		pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
7884 			ext->name);
7885 		return kfunc_id;
7886 	}
7887 
7888 	kern_func = btf__type_by_id(kern_btf, kfunc_id);
7889 	kfunc_proto_id = kern_func->type;
7890 
7891 	ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
7892 					kern_btf, kfunc_proto_id);
7893 	if (ret <= 0) {
7894 		pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with kernel [%d]\n",
7895 			ext->name, local_func_proto_id, kfunc_proto_id);
7896 		return -EINVAL;
7897 	}
7898 
7899 	/* set index for module BTF fd in fd_array, if unset */
7900 	if (mod_btf && !mod_btf->fd_array_idx) {
7901 		/* insn->off is s16 */
7902 		if (obj->fd_array_cnt == INT16_MAX) {
7903 			pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
7904 				ext->name, mod_btf->fd_array_idx);
7905 			return -E2BIG;
7906 		}
7907 		/* Cannot use index 0 for module BTF fd */
7908 		if (!obj->fd_array_cnt)
7909 			obj->fd_array_cnt = 1;
7910 
7911 		ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
7912 					obj->fd_array_cnt + 1);
7913 		if (ret)
7914 			return ret;
7915 		mod_btf->fd_array_idx = obj->fd_array_cnt;
7916 		/* we assume module BTF FD is always >0 */
7917 		obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
7918 	}
7919 
7920 	ext->is_set = true;
7921 	ext->ksym.kernel_btf_id = kfunc_id;
7922 	ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
7923 	pr_debug("extern (func ksym) '%s': resolved to kernel [%d]\n",
7924 		 ext->name, kfunc_id);
7925 
7926 	return 0;
7927 }
7928 
7929 static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
7930 {
7931 	const struct btf_type *t;
7932 	struct extern_desc *ext;
7933 	int i, err;
7934 
7935 	for (i = 0; i < obj->nr_extern; i++) {
7936 		ext = &obj->externs[i];
7937 		if (ext->type != EXT_KSYM || !ext->ksym.type_id)
7938 			continue;
7939 
7940 		if (obj->gen_loader) {
7941 			ext->is_set = true;
7942 			ext->ksym.kernel_btf_obj_fd = 0;
7943 			ext->ksym.kernel_btf_id = 0;
7944 			continue;
7945 		}
7946 		t = btf__type_by_id(obj->btf, ext->btf_id);
7947 		if (btf_is_var(t))
7948 			err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
7949 		else
7950 			err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
7951 		if (err)
7952 			return err;
7953 	}
7954 	return 0;
7955 }
7956 
7957 static int bpf_object__resolve_externs(struct bpf_object *obj,
7958 				       const char *extra_kconfig)
7959 {
7960 	bool need_config = false, need_kallsyms = false;
7961 	bool need_vmlinux_btf = false;
7962 	struct extern_desc *ext;
7963 	void *kcfg_data = NULL;
7964 	int err, i;
7965 
7966 	if (obj->nr_extern == 0)
7967 		return 0;
7968 
7969 	if (obj->kconfig_map_idx >= 0)
7970 		kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
7971 
7972 	for (i = 0; i < obj->nr_extern; i++) {
7973 		ext = &obj->externs[i];
7974 
7975 		if (ext->type == EXT_KSYM) {
7976 			if (ext->ksym.type_id)
7977 				need_vmlinux_btf = true;
7978 			else
7979 				need_kallsyms = true;
7980 			continue;
7981 		} else if (ext->type == EXT_KCFG) {
7982 			void *ext_ptr = kcfg_data + ext->kcfg.data_off;
7983 			__u64 value = 0;
7984 
7985 			/* Kconfig externs need actual /proc/config.gz */
7986 			if (str_has_pfx(ext->name, "CONFIG_")) {
7987 				need_config = true;
7988 				continue;
7989 			}
7990 
7991 			/* Virtual kcfg externs are customly handled by libbpf */
7992 			if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
7993 				value = get_kernel_version();
7994 				if (!value) {
7995 					pr_warn("extern (kcfg) '%s': failed to get kernel version\n", ext->name);
7996 					return -EINVAL;
7997 				}
7998 			} else if (strcmp(ext->name, "LINUX_HAS_BPF_COOKIE") == 0) {
7999 				value = kernel_supports(obj, FEAT_BPF_COOKIE);
8000 			} else if (strcmp(ext->name, "LINUX_HAS_SYSCALL_WRAPPER") == 0) {
8001 				value = kernel_supports(obj, FEAT_SYSCALL_WRAPPER);
8002 			} else if (!str_has_pfx(ext->name, "LINUX_") || !ext->is_weak) {
8003 				/* Currently libbpf supports only CONFIG_ and LINUX_ prefixed
8004 				 * __kconfig externs, where LINUX_ ones are virtual and filled out
8005 				 * customly by libbpf (their values don't come from Kconfig).
8006 				 * If LINUX_xxx variable is not recognized by libbpf, but is marked
8007 				 * __weak, it defaults to zero value, just like for CONFIG_xxx
8008 				 * externs.
8009 				 */
8010 				pr_warn("extern (kcfg) '%s': unrecognized virtual extern\n", ext->name);
8011 				return -EINVAL;
8012 			}
8013 
8014 			err = set_kcfg_value_num(ext, ext_ptr, value);
8015 			if (err)
8016 				return err;
8017 			pr_debug("extern (kcfg) '%s': set to 0x%llx\n",
8018 				 ext->name, (long long)value);
8019 		} else {
8020 			pr_warn("extern '%s': unrecognized extern kind\n", ext->name);
8021 			return -EINVAL;
8022 		}
8023 	}
8024 	if (need_config && extra_kconfig) {
8025 		err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
8026 		if (err)
8027 			return -EINVAL;
8028 		need_config = false;
8029 		for (i = 0; i < obj->nr_extern; i++) {
8030 			ext = &obj->externs[i];
8031 			if (ext->type == EXT_KCFG && !ext->is_set) {
8032 				need_config = true;
8033 				break;
8034 			}
8035 		}
8036 	}
8037 	if (need_config) {
8038 		err = bpf_object__read_kconfig_file(obj, kcfg_data);
8039 		if (err)
8040 			return -EINVAL;
8041 	}
8042 	if (need_kallsyms) {
8043 		err = bpf_object__read_kallsyms_file(obj);
8044 		if (err)
8045 			return -EINVAL;
8046 	}
8047 	if (need_vmlinux_btf) {
8048 		err = bpf_object__resolve_ksyms_btf_id(obj);
8049 		if (err)
8050 			return -EINVAL;
8051 	}
8052 	for (i = 0; i < obj->nr_extern; i++) {
8053 		ext = &obj->externs[i];
8054 
8055 		if (!ext->is_set && !ext->is_weak) {
8056 			pr_warn("extern '%s' (strong): not resolved\n", ext->name);
8057 			return -ESRCH;
8058 		} else if (!ext->is_set) {
8059 			pr_debug("extern '%s' (weak): not resolved, defaulting to zero\n",
8060 				 ext->name);
8061 		}
8062 	}
8063 
8064 	return 0;
8065 }
8066 
8067 static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
8068 {
8069 	int err, i;
8070 
8071 	if (!obj)
8072 		return libbpf_err(-EINVAL);
8073 
8074 	if (obj->loaded) {
8075 		pr_warn("object '%s': load can't be attempted twice\n", obj->name);
8076 		return libbpf_err(-EINVAL);
8077 	}
8078 
8079 	if (obj->gen_loader)
8080 		bpf_gen__init(obj->gen_loader, extra_log_level, obj->nr_programs, obj->nr_maps);
8081 
8082 	err = bpf_object__probe_loading(obj);
8083 	err = err ? : bpf_object__load_vmlinux_btf(obj, false);
8084 	err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
8085 	err = err ? : bpf_object__sanitize_and_load_btf(obj);
8086 	err = err ? : bpf_object__sanitize_maps(obj);
8087 	err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
8088 	err = err ? : bpf_object__create_maps(obj);
8089 	err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
8090 	err = err ? : bpf_object__load_progs(obj, extra_log_level);
8091 	err = err ? : bpf_object_init_prog_arrays(obj);
8092 
8093 	if (obj->gen_loader) {
8094 		/* reset FDs */
8095 		if (obj->btf)
8096 			btf__set_fd(obj->btf, -1);
8097 		for (i = 0; i < obj->nr_maps; i++)
8098 			obj->maps[i].fd = -1;
8099 		if (!err)
8100 			err = bpf_gen__finish(obj->gen_loader, obj->nr_programs, obj->nr_maps);
8101 	}
8102 
8103 	/* clean up fd_array */
8104 	zfree(&obj->fd_array);
8105 
8106 	/* clean up module BTFs */
8107 	for (i = 0; i < obj->btf_module_cnt; i++) {
8108 		close(obj->btf_modules[i].fd);
8109 		btf__free(obj->btf_modules[i].btf);
8110 		free(obj->btf_modules[i].name);
8111 	}
8112 	free(obj->btf_modules);
8113 
8114 	/* clean up vmlinux BTF */
8115 	btf__free(obj->btf_vmlinux);
8116 	obj->btf_vmlinux = NULL;
8117 
8118 	obj->loaded = true; /* doesn't matter if successfully or not */
8119 
8120 	if (err)
8121 		goto out;
8122 
8123 	return 0;
8124 out:
8125 	/* unpin any maps that were auto-pinned during load */
8126 	for (i = 0; i < obj->nr_maps; i++)
8127 		if (obj->maps[i].pinned && !obj->maps[i].reused)
8128 			bpf_map__unpin(&obj->maps[i], NULL);
8129 
8130 	bpf_object_unload(obj);
8131 	pr_warn("failed to load object '%s'\n", obj->path);
8132 	return libbpf_err(err);
8133 }
8134 
8135 int bpf_object__load(struct bpf_object *obj)
8136 {
8137 	return bpf_object_load(obj, 0, NULL);
8138 }
8139 
8140 static int make_parent_dir(const char *path)
8141 {
8142 	char *cp, errmsg[STRERR_BUFSIZE];
8143 	char *dname, *dir;
8144 	int err = 0;
8145 
8146 	dname = strdup(path);
8147 	if (dname == NULL)
8148 		return -ENOMEM;
8149 
8150 	dir = dirname(dname);
8151 	if (mkdir(dir, 0700) && errno != EEXIST)
8152 		err = -errno;
8153 
8154 	free(dname);
8155 	if (err) {
8156 		cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
8157 		pr_warn("failed to mkdir %s: %s\n", path, cp);
8158 	}
8159 	return err;
8160 }
8161 
8162 static int check_path(const char *path)
8163 {
8164 	char *cp, errmsg[STRERR_BUFSIZE];
8165 	struct statfs st_fs;
8166 	char *dname, *dir;
8167 	int err = 0;
8168 
8169 	if (path == NULL)
8170 		return -EINVAL;
8171 
8172 	dname = strdup(path);
8173 	if (dname == NULL)
8174 		return -ENOMEM;
8175 
8176 	dir = dirname(dname);
8177 	if (statfs(dir, &st_fs)) {
8178 		cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
8179 		pr_warn("failed to statfs %s: %s\n", dir, cp);
8180 		err = -errno;
8181 	}
8182 	free(dname);
8183 
8184 	if (!err && st_fs.f_type != BPF_FS_MAGIC) {
8185 		pr_warn("specified path %s is not on BPF FS\n", path);
8186 		err = -EINVAL;
8187 	}
8188 
8189 	return err;
8190 }
8191 
8192 int bpf_program__pin(struct bpf_program *prog, const char *path)
8193 {
8194 	char *cp, errmsg[STRERR_BUFSIZE];
8195 	int err;
8196 
8197 	if (prog->fd < 0) {
8198 		pr_warn("prog '%s': can't pin program that wasn't loaded\n", prog->name);
8199 		return libbpf_err(-EINVAL);
8200 	}
8201 
8202 	err = make_parent_dir(path);
8203 	if (err)
8204 		return libbpf_err(err);
8205 
8206 	err = check_path(path);
8207 	if (err)
8208 		return libbpf_err(err);
8209 
8210 	if (bpf_obj_pin(prog->fd, path)) {
8211 		err = -errno;
8212 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
8213 		pr_warn("prog '%s': failed to pin at '%s': %s\n", prog->name, path, cp);
8214 		return libbpf_err(err);
8215 	}
8216 
8217 	pr_debug("prog '%s': pinned at '%s'\n", prog->name, path);
8218 	return 0;
8219 }
8220 
8221 int bpf_program__unpin(struct bpf_program *prog, const char *path)
8222 {
8223 	int err;
8224 
8225 	if (prog->fd < 0) {
8226 		pr_warn("prog '%s': can't unpin program that wasn't loaded\n", prog->name);
8227 		return libbpf_err(-EINVAL);
8228 	}
8229 
8230 	err = check_path(path);
8231 	if (err)
8232 		return libbpf_err(err);
8233 
8234 	err = unlink(path);
8235 	if (err)
8236 		return libbpf_err(-errno);
8237 
8238 	pr_debug("prog '%s': unpinned from '%s'\n", prog->name, path);
8239 	return 0;
8240 }
8241 
8242 int bpf_map__pin(struct bpf_map *map, const char *path)
8243 {
8244 	char *cp, errmsg[STRERR_BUFSIZE];
8245 	int err;
8246 
8247 	if (map == NULL) {
8248 		pr_warn("invalid map pointer\n");
8249 		return libbpf_err(-EINVAL);
8250 	}
8251 
8252 	if (map->pin_path) {
8253 		if (path && strcmp(path, map->pin_path)) {
8254 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8255 				bpf_map__name(map), map->pin_path, path);
8256 			return libbpf_err(-EINVAL);
8257 		} else if (map->pinned) {
8258 			pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
8259 				 bpf_map__name(map), map->pin_path);
8260 			return 0;
8261 		}
8262 	} else {
8263 		if (!path) {
8264 			pr_warn("missing a path to pin map '%s' at\n",
8265 				bpf_map__name(map));
8266 			return libbpf_err(-EINVAL);
8267 		} else if (map->pinned) {
8268 			pr_warn("map '%s' already pinned\n", bpf_map__name(map));
8269 			return libbpf_err(-EEXIST);
8270 		}
8271 
8272 		map->pin_path = strdup(path);
8273 		if (!map->pin_path) {
8274 			err = -errno;
8275 			goto out_err;
8276 		}
8277 	}
8278 
8279 	err = make_parent_dir(map->pin_path);
8280 	if (err)
8281 		return libbpf_err(err);
8282 
8283 	err = check_path(map->pin_path);
8284 	if (err)
8285 		return libbpf_err(err);
8286 
8287 	if (bpf_obj_pin(map->fd, map->pin_path)) {
8288 		err = -errno;
8289 		goto out_err;
8290 	}
8291 
8292 	map->pinned = true;
8293 	pr_debug("pinned map '%s'\n", map->pin_path);
8294 
8295 	return 0;
8296 
8297 out_err:
8298 	cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
8299 	pr_warn("failed to pin map: %s\n", cp);
8300 	return libbpf_err(err);
8301 }
8302 
8303 int bpf_map__unpin(struct bpf_map *map, const char *path)
8304 {
8305 	int err;
8306 
8307 	if (map == NULL) {
8308 		pr_warn("invalid map pointer\n");
8309 		return libbpf_err(-EINVAL);
8310 	}
8311 
8312 	if (map->pin_path) {
8313 		if (path && strcmp(path, map->pin_path)) {
8314 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8315 				bpf_map__name(map), map->pin_path, path);
8316 			return libbpf_err(-EINVAL);
8317 		}
8318 		path = map->pin_path;
8319 	} else if (!path) {
8320 		pr_warn("no path to unpin map '%s' from\n",
8321 			bpf_map__name(map));
8322 		return libbpf_err(-EINVAL);
8323 	}
8324 
8325 	err = check_path(path);
8326 	if (err)
8327 		return libbpf_err(err);
8328 
8329 	err = unlink(path);
8330 	if (err != 0)
8331 		return libbpf_err(-errno);
8332 
8333 	map->pinned = false;
8334 	pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
8335 
8336 	return 0;
8337 }
8338 
8339 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
8340 {
8341 	char *new = NULL;
8342 
8343 	if (path) {
8344 		new = strdup(path);
8345 		if (!new)
8346 			return libbpf_err(-errno);
8347 	}
8348 
8349 	free(map->pin_path);
8350 	map->pin_path = new;
8351 	return 0;
8352 }
8353 
8354 __alias(bpf_map__pin_path)
8355 const char *bpf_map__get_pin_path(const struct bpf_map *map);
8356 
8357 const char *bpf_map__pin_path(const struct bpf_map *map)
8358 {
8359 	return map->pin_path;
8360 }
8361 
8362 bool bpf_map__is_pinned(const struct bpf_map *map)
8363 {
8364 	return map->pinned;
8365 }
8366 
8367 static void sanitize_pin_path(char *s)
8368 {
8369 	/* bpffs disallows periods in path names */
8370 	while (*s) {
8371 		if (*s == '.')
8372 			*s = '_';
8373 		s++;
8374 	}
8375 }
8376 
8377 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
8378 {
8379 	struct bpf_map *map;
8380 	int err;
8381 
8382 	if (!obj)
8383 		return libbpf_err(-ENOENT);
8384 
8385 	if (!obj->loaded) {
8386 		pr_warn("object not yet loaded; load it first\n");
8387 		return libbpf_err(-ENOENT);
8388 	}
8389 
8390 	bpf_object__for_each_map(map, obj) {
8391 		char *pin_path = NULL;
8392 		char buf[PATH_MAX];
8393 
8394 		if (!map->autocreate)
8395 			continue;
8396 
8397 		if (path) {
8398 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8399 			if (err)
8400 				goto err_unpin_maps;
8401 			sanitize_pin_path(buf);
8402 			pin_path = buf;
8403 		} else if (!map->pin_path) {
8404 			continue;
8405 		}
8406 
8407 		err = bpf_map__pin(map, pin_path);
8408 		if (err)
8409 			goto err_unpin_maps;
8410 	}
8411 
8412 	return 0;
8413 
8414 err_unpin_maps:
8415 	while ((map = bpf_object__prev_map(obj, map))) {
8416 		if (!map->pin_path)
8417 			continue;
8418 
8419 		bpf_map__unpin(map, NULL);
8420 	}
8421 
8422 	return libbpf_err(err);
8423 }
8424 
8425 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
8426 {
8427 	struct bpf_map *map;
8428 	int err;
8429 
8430 	if (!obj)
8431 		return libbpf_err(-ENOENT);
8432 
8433 	bpf_object__for_each_map(map, obj) {
8434 		char *pin_path = NULL;
8435 		char buf[PATH_MAX];
8436 
8437 		if (path) {
8438 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8439 			if (err)
8440 				return libbpf_err(err);
8441 			sanitize_pin_path(buf);
8442 			pin_path = buf;
8443 		} else if (!map->pin_path) {
8444 			continue;
8445 		}
8446 
8447 		err = bpf_map__unpin(map, pin_path);
8448 		if (err)
8449 			return libbpf_err(err);
8450 	}
8451 
8452 	return 0;
8453 }
8454 
8455 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
8456 {
8457 	struct bpf_program *prog;
8458 	char buf[PATH_MAX];
8459 	int err;
8460 
8461 	if (!obj)
8462 		return libbpf_err(-ENOENT);
8463 
8464 	if (!obj->loaded) {
8465 		pr_warn("object not yet loaded; load it first\n");
8466 		return libbpf_err(-ENOENT);
8467 	}
8468 
8469 	bpf_object__for_each_program(prog, obj) {
8470 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
8471 		if (err)
8472 			goto err_unpin_programs;
8473 
8474 		err = bpf_program__pin(prog, buf);
8475 		if (err)
8476 			goto err_unpin_programs;
8477 	}
8478 
8479 	return 0;
8480 
8481 err_unpin_programs:
8482 	while ((prog = bpf_object__prev_program(obj, prog))) {
8483 		if (pathname_concat(buf, sizeof(buf), path, prog->name))
8484 			continue;
8485 
8486 		bpf_program__unpin(prog, buf);
8487 	}
8488 
8489 	return libbpf_err(err);
8490 }
8491 
8492 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
8493 {
8494 	struct bpf_program *prog;
8495 	int err;
8496 
8497 	if (!obj)
8498 		return libbpf_err(-ENOENT);
8499 
8500 	bpf_object__for_each_program(prog, obj) {
8501 		char buf[PATH_MAX];
8502 
8503 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
8504 		if (err)
8505 			return libbpf_err(err);
8506 
8507 		err = bpf_program__unpin(prog, buf);
8508 		if (err)
8509 			return libbpf_err(err);
8510 	}
8511 
8512 	return 0;
8513 }
8514 
8515 int bpf_object__pin(struct bpf_object *obj, const char *path)
8516 {
8517 	int err;
8518 
8519 	err = bpf_object__pin_maps(obj, path);
8520 	if (err)
8521 		return libbpf_err(err);
8522 
8523 	err = bpf_object__pin_programs(obj, path);
8524 	if (err) {
8525 		bpf_object__unpin_maps(obj, path);
8526 		return libbpf_err(err);
8527 	}
8528 
8529 	return 0;
8530 }
8531 
8532 static void bpf_map__destroy(struct bpf_map *map)
8533 {
8534 	if (map->inner_map) {
8535 		bpf_map__destroy(map->inner_map);
8536 		zfree(&map->inner_map);
8537 	}
8538 
8539 	zfree(&map->init_slots);
8540 	map->init_slots_sz = 0;
8541 
8542 	if (map->mmaped) {
8543 		munmap(map->mmaped, bpf_map_mmap_sz(map));
8544 		map->mmaped = NULL;
8545 	}
8546 
8547 	if (map->st_ops) {
8548 		zfree(&map->st_ops->data);
8549 		zfree(&map->st_ops->progs);
8550 		zfree(&map->st_ops->kern_func_off);
8551 		zfree(&map->st_ops);
8552 	}
8553 
8554 	zfree(&map->name);
8555 	zfree(&map->real_name);
8556 	zfree(&map->pin_path);
8557 
8558 	if (map->fd >= 0)
8559 		zclose(map->fd);
8560 }
8561 
8562 void bpf_object__close(struct bpf_object *obj)
8563 {
8564 	size_t i;
8565 
8566 	if (IS_ERR_OR_NULL(obj))
8567 		return;
8568 #ifdef  HAVE_LIBELF
8569 	usdt_manager_free(obj->usdt_man);
8570 	obj->usdt_man = NULL;
8571 #endif  //HAVE_LIBELF
8572 	bpf_gen__free(obj->gen_loader);
8573 	bpf_object__elf_finish(obj);
8574 	bpf_object_unload(obj);
8575 	btf__free(obj->btf);
8576 	btf_ext__free(obj->btf_ext);
8577 
8578 	for (i = 0; i < obj->nr_maps; i++)
8579 		bpf_map__destroy(&obj->maps[i]);
8580 
8581 	zfree(&obj->btf_custom_path);
8582 	zfree(&obj->kconfig);
8583 	zfree(&obj->externs);
8584 	obj->nr_extern = 0;
8585 
8586 	zfree(&obj->maps);
8587 	obj->nr_maps = 0;
8588 
8589 	if (obj->programs && obj->nr_programs) {
8590 		for (i = 0; i < obj->nr_programs; i++)
8591 			bpf_program__exit(&obj->programs[i]);
8592 	}
8593 	zfree(&obj->programs);
8594 
8595 	free(obj);
8596 }
8597 
8598 const char *bpf_object__name(const struct bpf_object *obj)
8599 {
8600 	return obj ? obj->name : libbpf_err_ptr(-EINVAL);
8601 }
8602 
8603 unsigned int bpf_object__kversion(const struct bpf_object *obj)
8604 {
8605 	return obj ? obj->kern_version : 0;
8606 }
8607 
8608 struct btf *bpf_object__btf(const struct bpf_object *obj)
8609 {
8610 	return obj ? obj->btf : NULL;
8611 }
8612 
8613 int bpf_object__btf_fd(const struct bpf_object *obj)
8614 {
8615 	return obj->btf ? btf__fd(obj->btf) : -1;
8616 }
8617 
8618 int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
8619 {
8620 	if (obj->loaded)
8621 		return libbpf_err(-EINVAL);
8622 
8623 	obj->kern_version = kern_version;
8624 
8625 	return 0;
8626 }
8627 
8628 int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
8629 {
8630 	struct bpf_gen *gen;
8631 
8632 	if (!opts)
8633 		return -EFAULT;
8634 	if (!OPTS_VALID(opts, gen_loader_opts))
8635 		return -EINVAL;
8636 	gen = calloc(sizeof(*gen), 1);
8637 	if (!gen)
8638 		return -ENOMEM;
8639 	gen->opts = opts;
8640 	obj->gen_loader = gen;
8641 	return 0;
8642 }
8643 
8644 static struct bpf_program *
8645 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
8646 		    bool forward)
8647 {
8648 	size_t nr_programs = obj->nr_programs;
8649 	ssize_t idx;
8650 
8651 	if (!nr_programs)
8652 		return NULL;
8653 
8654 	if (!p)
8655 		/* Iter from the beginning */
8656 		return forward ? &obj->programs[0] :
8657 			&obj->programs[nr_programs - 1];
8658 
8659 	if (p->obj != obj) {
8660 		pr_warn("error: program handler doesn't match object\n");
8661 		return errno = EINVAL, NULL;
8662 	}
8663 
8664 	idx = (p - obj->programs) + (forward ? 1 : -1);
8665 	if (idx >= obj->nr_programs || idx < 0)
8666 		return NULL;
8667 	return &obj->programs[idx];
8668 }
8669 
8670 struct bpf_program *
8671 bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
8672 {
8673 	struct bpf_program *prog = prev;
8674 
8675 	do {
8676 		prog = __bpf_program__iter(prog, obj, true);
8677 	} while (prog && prog_is_subprog(obj, prog));
8678 
8679 	return prog;
8680 }
8681 
8682 struct bpf_program *
8683 bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
8684 {
8685 	struct bpf_program *prog = next;
8686 
8687 	do {
8688 		prog = __bpf_program__iter(prog, obj, false);
8689 	} while (prog && prog_is_subprog(obj, prog));
8690 
8691 	return prog;
8692 }
8693 
8694 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
8695 {
8696 	prog->prog_ifindex = ifindex;
8697 }
8698 
8699 const char *bpf_program__name(const struct bpf_program *prog)
8700 {
8701 	return prog->name;
8702 }
8703 
8704 const char *bpf_program__section_name(const struct bpf_program *prog)
8705 {
8706 	return prog->sec_name;
8707 }
8708 
8709 bool bpf_program__autoload(const struct bpf_program *prog)
8710 {
8711 	return prog->autoload;
8712 }
8713 
8714 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
8715 {
8716 	if (prog->obj->loaded)
8717 		return libbpf_err(-EINVAL);
8718 
8719 	prog->autoload = autoload;
8720 	return 0;
8721 }
8722 
8723 bool bpf_program__autoattach(const struct bpf_program *prog)
8724 {
8725 	return prog->autoattach;
8726 }
8727 
8728 void bpf_program__set_autoattach(struct bpf_program *prog, bool autoattach)
8729 {
8730 	prog->autoattach = autoattach;
8731 }
8732 
8733 const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
8734 {
8735 	return prog->insns;
8736 }
8737 
8738 size_t bpf_program__insn_cnt(const struct bpf_program *prog)
8739 {
8740 	return prog->insns_cnt;
8741 }
8742 
8743 int bpf_program__set_insns(struct bpf_program *prog,
8744 			   struct bpf_insn *new_insns, size_t new_insn_cnt)
8745 {
8746 	struct bpf_insn *insns;
8747 
8748 	if (prog->obj->loaded)
8749 		return -EBUSY;
8750 
8751 	insns = libbpf_reallocarray(prog->insns, new_insn_cnt, sizeof(*insns));
8752 	if (!insns) {
8753 		pr_warn("prog '%s': failed to realloc prog code\n", prog->name);
8754 		return -ENOMEM;
8755 	}
8756 	memcpy(insns, new_insns, new_insn_cnt * sizeof(*insns));
8757 
8758 	prog->insns = insns;
8759 	prog->insns_cnt = new_insn_cnt;
8760 	return 0;
8761 }
8762 
8763 int bpf_program__fd(const struct bpf_program *prog)
8764 {
8765 	if (!prog)
8766 		return libbpf_err(-EINVAL);
8767 
8768 	if (prog->fd < 0)
8769 		return libbpf_err(-ENOENT);
8770 
8771 	return prog->fd;
8772 }
8773 
8774 __alias(bpf_program__type)
8775 enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog);
8776 
8777 enum bpf_prog_type bpf_program__type(const struct bpf_program *prog)
8778 {
8779 	return prog->type;
8780 }
8781 
8782 int bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
8783 {
8784 	if (prog->obj->loaded)
8785 		return libbpf_err(-EBUSY);
8786 
8787 	prog->type = type;
8788 	return 0;
8789 }
8790 
8791 __alias(bpf_program__expected_attach_type)
8792 enum bpf_attach_type bpf_program__get_expected_attach_type(const struct bpf_program *prog);
8793 
8794 enum bpf_attach_type bpf_program__expected_attach_type(const struct bpf_program *prog)
8795 {
8796 	return prog->expected_attach_type;
8797 }
8798 
8799 int bpf_program__set_expected_attach_type(struct bpf_program *prog,
8800 					   enum bpf_attach_type type)
8801 {
8802 	if (prog->obj->loaded)
8803 		return libbpf_err(-EBUSY);
8804 
8805 	prog->expected_attach_type = type;
8806 	return 0;
8807 }
8808 
8809 __u32 bpf_program__flags(const struct bpf_program *prog)
8810 {
8811 	return prog->prog_flags;
8812 }
8813 
8814 int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
8815 {
8816 	if (prog->obj->loaded)
8817 		return libbpf_err(-EBUSY);
8818 
8819 	prog->prog_flags = flags;
8820 	return 0;
8821 }
8822 
8823 __u32 bpf_program__log_level(const struct bpf_program *prog)
8824 {
8825 	return prog->log_level;
8826 }
8827 
8828 int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
8829 {
8830 	if (prog->obj->loaded)
8831 		return libbpf_err(-EBUSY);
8832 
8833 	prog->log_level = log_level;
8834 	return 0;
8835 }
8836 
8837 const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
8838 {
8839 	*log_size = prog->log_size;
8840 	return prog->log_buf;
8841 }
8842 
8843 int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
8844 {
8845 	if (log_size && !log_buf)
8846 		return -EINVAL;
8847 	if (prog->log_size > UINT_MAX)
8848 		return -EINVAL;
8849 	if (prog->obj->loaded)
8850 		return -EBUSY;
8851 
8852 	prog->log_buf = log_buf;
8853 	prog->log_size = log_size;
8854 	return 0;
8855 }
8856 
8857 #define SEC_DEF(sec_pfx, ptype, atype, flags, ...) {			    \
8858 	.sec = (char *)sec_pfx,						    \
8859 	.prog_type = BPF_PROG_TYPE_##ptype,				    \
8860 	.expected_attach_type = atype,					    \
8861 	.cookie = (long)(flags),					    \
8862 	.prog_prepare_load_fn = libbpf_prepare_prog_load,		    \
8863 	__VA_ARGS__							    \
8864 }
8865 
8866 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8867 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8868 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8869 #ifdef  HAVE_LIBELF
8870 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8871 #endif  //HAVE_LIBELF
8872 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8873 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8874 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8875 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8876 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8877 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8878 
8879 static const struct bpf_sec_def section_defs[] = {
8880 	SEC_DEF("socket",		SOCKET_FILTER, 0, SEC_NONE),
8881 	SEC_DEF("sk_reuseport/migrate",	SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE),
8882 	SEC_DEF("sk_reuseport",		SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE),
8883 	SEC_DEF("kprobe+",		KPROBE,	0, SEC_NONE, attach_kprobe),
8884 	SEC_DEF("uprobe+",		KPROBE,	0, SEC_NONE, attach_uprobe),
8885 	SEC_DEF("uprobe.s+",		KPROBE,	0, SEC_SLEEPABLE, attach_uprobe),
8886 	SEC_DEF("kretprobe+",		KPROBE, 0, SEC_NONE, attach_kprobe),
8887 	SEC_DEF("uretprobe+",		KPROBE, 0, SEC_NONE, attach_uprobe),
8888 	SEC_DEF("uretprobe.s+",		KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
8889 	SEC_DEF("kprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
8890 	SEC_DEF("kretprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
8891 	SEC_DEF("ksyscall+",		KPROBE,	0, SEC_NONE, attach_ksyscall),
8892 	SEC_DEF("kretsyscall+",		KPROBE, 0, SEC_NONE, attach_ksyscall),
8893 #ifdef  HAVE_LIBELF
8894 	SEC_DEF("usdt+",		KPROBE,	0, SEC_NONE, attach_usdt),
8895 #endif  //HAVE_LIBELF
8896 	SEC_DEF("tc",			SCHED_CLS, 0, SEC_NONE),
8897 	SEC_DEF("classifier",		SCHED_CLS, 0, SEC_NONE),
8898 	SEC_DEF("action",		SCHED_ACT, 0, SEC_NONE),
8899 	SEC_DEF("tracepoint+",		TRACEPOINT, 0, SEC_NONE, attach_tp),
8900 	SEC_DEF("tp+",			TRACEPOINT, 0, SEC_NONE, attach_tp),
8901 	SEC_DEF("raw_tracepoint+",	RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
8902 	SEC_DEF("raw_tp+",		RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
8903 	SEC_DEF("raw_tracepoint.w+",	RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
8904 	SEC_DEF("raw_tp.w+",		RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
8905 	SEC_DEF("tp_btf+",		TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
8906 	SEC_DEF("fentry+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
8907 	SEC_DEF("fmod_ret+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
8908 	SEC_DEF("fexit+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
8909 	SEC_DEF("fentry.s+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8910 	SEC_DEF("fmod_ret.s+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8911 	SEC_DEF("fexit.s+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8912 	SEC_DEF("freplace+",		EXT, 0, SEC_ATTACH_BTF, attach_trace),
8913 	SEC_DEF("lsm+",			LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
8914 	SEC_DEF("lsm.s+",		LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
8915 	SEC_DEF("lsm_cgroup+",		LSM, BPF_LSM_CGROUP, SEC_ATTACH_BTF),
8916 	SEC_DEF("iter+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
8917 	SEC_DEF("iter.s+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_iter),
8918 	SEC_DEF("syscall",		SYSCALL, 0, SEC_SLEEPABLE),
8919 	SEC_DEF("xdp.frags/devmap",	XDP, BPF_XDP_DEVMAP, SEC_XDP_FRAGS),
8920 	SEC_DEF("xdp/devmap",		XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
8921 	SEC_DEF("xdp.frags/cpumap",	XDP, BPF_XDP_CPUMAP, SEC_XDP_FRAGS),
8922 	SEC_DEF("xdp/cpumap",		XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
8923 	SEC_DEF("xdp.frags",		XDP, BPF_XDP, SEC_XDP_FRAGS),
8924 	SEC_DEF("xdp",			XDP, BPF_XDP, SEC_ATTACHABLE_OPT),
8925 	SEC_DEF("perf_event",		PERF_EVENT, 0, SEC_NONE),
8926 	SEC_DEF("lwt_in",		LWT_IN, 0, SEC_NONE),
8927 	SEC_DEF("lwt_out",		LWT_OUT, 0, SEC_NONE),
8928 	SEC_DEF("lwt_xmit",		LWT_XMIT, 0, SEC_NONE),
8929 	SEC_DEF("lwt_seg6local",	LWT_SEG6LOCAL, 0, SEC_NONE),
8930 	SEC_DEF("sockops",		SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT),
8931 	SEC_DEF("sk_skb/stream_parser",	SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT),
8932 	SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT),
8933 	SEC_DEF("sk_skb",		SK_SKB, 0, SEC_NONE),
8934 	SEC_DEF("sk_msg",		SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT),
8935 	SEC_DEF("lirc_mode2",		LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT),
8936 	SEC_DEF("flow_dissector",	FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT),
8937 	SEC_DEF("cgroup_skb/ingress",	CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT),
8938 	SEC_DEF("cgroup_skb/egress",	CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT),
8939 	SEC_DEF("cgroup/skb",		CGROUP_SKB, 0, SEC_NONE),
8940 	SEC_DEF("cgroup/sock_create",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE),
8941 	SEC_DEF("cgroup/sock_release",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE),
8942 	SEC_DEF("cgroup/sock",		CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT),
8943 	SEC_DEF("cgroup/post_bind4",	CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE),
8944 	SEC_DEF("cgroup/post_bind6",	CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE),
8945 	SEC_DEF("cgroup/bind4",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE),
8946 	SEC_DEF("cgroup/bind6",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE),
8947 	SEC_DEF("cgroup/connect4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE),
8948 	SEC_DEF("cgroup/connect6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE),
8949 	SEC_DEF("cgroup/sendmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE),
8950 	SEC_DEF("cgroup/sendmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE),
8951 	SEC_DEF("cgroup/recvmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE),
8952 	SEC_DEF("cgroup/recvmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE),
8953 	SEC_DEF("cgroup/getpeername4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE),
8954 	SEC_DEF("cgroup/getpeername6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE),
8955 	SEC_DEF("cgroup/getsockname4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE),
8956 	SEC_DEF("cgroup/getsockname6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE),
8957 	SEC_DEF("cgroup/sysctl",	CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE),
8958 	SEC_DEF("cgroup/getsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE),
8959 	SEC_DEF("cgroup/setsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE),
8960 	SEC_DEF("cgroup/dev",		CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT),
8961 	SEC_DEF("struct_ops+",		STRUCT_OPS, 0, SEC_NONE),
8962 	SEC_DEF("sk_lookup",		SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE),
8963 };
8964 
8965 static size_t custom_sec_def_cnt;
8966 static struct bpf_sec_def *custom_sec_defs;
8967 static struct bpf_sec_def custom_fallback_def;
8968 static bool has_custom_fallback_def;
8969 
8970 static int last_custom_sec_def_handler_id;
8971 
8972 int libbpf_register_prog_handler(const char *sec,
8973 				 enum bpf_prog_type prog_type,
8974 				 enum bpf_attach_type exp_attach_type,
8975 				 const struct libbpf_prog_handler_opts *opts)
8976 {
8977 	struct bpf_sec_def *sec_def;
8978 
8979 	if (!OPTS_VALID(opts, libbpf_prog_handler_opts))
8980 		return libbpf_err(-EINVAL);
8981 
8982 	if (last_custom_sec_def_handler_id == INT_MAX) /* prevent overflow */
8983 		return libbpf_err(-E2BIG);
8984 
8985 	if (sec) {
8986 		sec_def = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt + 1,
8987 					      sizeof(*sec_def));
8988 		if (!sec_def)
8989 			return libbpf_err(-ENOMEM);
8990 
8991 		custom_sec_defs = sec_def;
8992 		sec_def = &custom_sec_defs[custom_sec_def_cnt];
8993 	} else {
8994 		if (has_custom_fallback_def)
8995 			return libbpf_err(-EBUSY);
8996 
8997 		sec_def = &custom_fallback_def;
8998 	}
8999 
9000 	sec_def->sec = sec ? strdup(sec) : NULL;
9001 	if (sec && !sec_def->sec)
9002 		return libbpf_err(-ENOMEM);
9003 
9004 	sec_def->prog_type = prog_type;
9005 	sec_def->expected_attach_type = exp_attach_type;
9006 	sec_def->cookie = OPTS_GET(opts, cookie, 0);
9007 
9008 	sec_def->prog_setup_fn = OPTS_GET(opts, prog_setup_fn, NULL);
9009 	sec_def->prog_prepare_load_fn = OPTS_GET(opts, prog_prepare_load_fn, NULL);
9010 	sec_def->prog_attach_fn = OPTS_GET(opts, prog_attach_fn, NULL);
9011 
9012 	sec_def->handler_id = ++last_custom_sec_def_handler_id;
9013 
9014 	if (sec)
9015 		custom_sec_def_cnt++;
9016 	else
9017 		has_custom_fallback_def = true;
9018 
9019 	return sec_def->handler_id;
9020 }
9021 
9022 int libbpf_unregister_prog_handler(int handler_id)
9023 {
9024 	struct bpf_sec_def *sec_defs;
9025 	int i;
9026 
9027 	if (handler_id <= 0)
9028 		return libbpf_err(-EINVAL);
9029 
9030 	if (has_custom_fallback_def && custom_fallback_def.handler_id == handler_id) {
9031 		memset(&custom_fallback_def, 0, sizeof(custom_fallback_def));
9032 		has_custom_fallback_def = false;
9033 		return 0;
9034 	}
9035 
9036 	for (i = 0; i < custom_sec_def_cnt; i++) {
9037 		if (custom_sec_defs[i].handler_id == handler_id)
9038 			break;
9039 	}
9040 
9041 	if (i == custom_sec_def_cnt)
9042 		return libbpf_err(-ENOENT);
9043 
9044 	free(custom_sec_defs[i].sec);
9045 	for (i = i + 1; i < custom_sec_def_cnt; i++)
9046 		custom_sec_defs[i - 1] = custom_sec_defs[i];
9047 	custom_sec_def_cnt--;
9048 
9049 	/* try to shrink the array, but it's ok if we couldn't */
9050 	sec_defs = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt, sizeof(*sec_defs));
9051 	if (sec_defs)
9052 		custom_sec_defs = sec_defs;
9053 
9054 	return 0;
9055 }
9056 
9057 static bool sec_def_matches(const struct bpf_sec_def *sec_def, const char *sec_name)
9058 {
9059 	size_t len = strlen(sec_def->sec);
9060 
9061 	/* "type/" always has to have proper SEC("type/extras") form */
9062 	if (sec_def->sec[len - 1] == '/') {
9063 		if (str_has_pfx(sec_name, sec_def->sec))
9064 			return true;
9065 		return false;
9066 	}
9067 
9068 	/* "type+" means it can be either exact SEC("type") or
9069 	 * well-formed SEC("type/extras") with proper '/' separator
9070 	 */
9071 	if (sec_def->sec[len - 1] == '+') {
9072 		len--;
9073 		/* not even a prefix */
9074 		if (strncmp(sec_name, sec_def->sec, len) != 0)
9075 			return false;
9076 		/* exact match or has '/' separator */
9077 		if (sec_name[len] == '\0' || sec_name[len] == '/')
9078 			return true;
9079 		return false;
9080 	}
9081 
9082 	return strcmp(sec_name, sec_def->sec) == 0;
9083 }
9084 
9085 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
9086 {
9087 	const struct bpf_sec_def *sec_def;
9088 	int i, n;
9089 
9090 	n = custom_sec_def_cnt;
9091 	for (i = 0; i < n; i++) {
9092 		sec_def = &custom_sec_defs[i];
9093 		if (sec_def_matches(sec_def, sec_name))
9094 			return sec_def;
9095 	}
9096 
9097 	n = ARRAY_SIZE(section_defs);
9098 	for (i = 0; i < n; i++) {
9099 		sec_def = &section_defs[i];
9100 		if (sec_def_matches(sec_def, sec_name))
9101 			return sec_def;
9102 	}
9103 
9104 	if (has_custom_fallback_def)
9105 		return &custom_fallback_def;
9106 
9107 	return NULL;
9108 }
9109 
9110 #define MAX_TYPE_NAME_SIZE 32
9111 
9112 static char *libbpf_get_type_names(bool attach_type)
9113 {
9114 	int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
9115 	char *buf;
9116 
9117 	buf = malloc(len);
9118 	if (!buf)
9119 		return NULL;
9120 
9121 	buf[0] = '\0';
9122 	/* Forge string buf with all available names */
9123 	for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
9124 		const struct bpf_sec_def *sec_def = &section_defs[i];
9125 
9126 		if (attach_type) {
9127 			if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
9128 				continue;
9129 
9130 			if (!(sec_def->cookie & SEC_ATTACHABLE))
9131 				continue;
9132 		}
9133 
9134 		if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
9135 			free(buf);
9136 			return NULL;
9137 		}
9138 		strcat(buf, " ");
9139 		strcat(buf, section_defs[i].sec);
9140 	}
9141 
9142 	return buf;
9143 }
9144 
9145 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
9146 			     enum bpf_attach_type *expected_attach_type)
9147 {
9148 	const struct bpf_sec_def *sec_def;
9149 	char *type_names;
9150 
9151 	if (!name)
9152 		return libbpf_err(-EINVAL);
9153 
9154 	sec_def = find_sec_def(name);
9155 	if (sec_def) {
9156 		*prog_type = sec_def->prog_type;
9157 		*expected_attach_type = sec_def->expected_attach_type;
9158 		return 0;
9159 	}
9160 
9161 	pr_debug("failed to guess program type from ELF section '%s'\n", name);
9162 	type_names = libbpf_get_type_names(false);
9163 	if (type_names != NULL) {
9164 		pr_debug("supported section(type) names are:%s\n", type_names);
9165 		free(type_names);
9166 	}
9167 
9168 	return libbpf_err(-ESRCH);
9169 }
9170 
9171 const char *libbpf_bpf_attach_type_str(enum bpf_attach_type t)
9172 {
9173 	if (t < 0 || t >= ARRAY_SIZE(attach_type_name))
9174 		return NULL;
9175 
9176 	return attach_type_name[t];
9177 }
9178 
9179 const char *libbpf_bpf_link_type_str(enum bpf_link_type t)
9180 {
9181 	if (t < 0 || t >= ARRAY_SIZE(link_type_name))
9182 		return NULL;
9183 
9184 	return link_type_name[t];
9185 }
9186 
9187 const char *libbpf_bpf_map_type_str(enum bpf_map_type t)
9188 {
9189 	if (t < 0 || t >= ARRAY_SIZE(map_type_name))
9190 		return NULL;
9191 
9192 	return map_type_name[t];
9193 }
9194 
9195 const char *libbpf_bpf_prog_type_str(enum bpf_prog_type t)
9196 {
9197 	if (t < 0 || t >= ARRAY_SIZE(prog_type_name))
9198 		return NULL;
9199 
9200 	return prog_type_name[t];
9201 }
9202 
9203 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
9204 						     size_t offset)
9205 {
9206 	struct bpf_map *map;
9207 	size_t i;
9208 
9209 	for (i = 0; i < obj->nr_maps; i++) {
9210 		map = &obj->maps[i];
9211 		if (!bpf_map__is_struct_ops(map))
9212 			continue;
9213 		if (map->sec_offset <= offset &&
9214 		    offset - map->sec_offset < map->def.value_size)
9215 			return map;
9216 	}
9217 
9218 	return NULL;
9219 }
9220 
9221 /* Collect the reloc from ELF and populate the st_ops->progs[] */
9222 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
9223 					    Elf64_Shdr *shdr, Elf_Data *data)
9224 {
9225 	const struct btf_member *member;
9226 	struct bpf_struct_ops *st_ops;
9227 	struct bpf_program *prog;
9228 	unsigned int shdr_idx;
9229 	const struct btf *btf;
9230 	struct bpf_map *map;
9231 	unsigned int moff, insn_idx;
9232 	const char *name;
9233 	__u32 member_idx;
9234 	Elf64_Sym *sym;
9235 	Elf64_Rel *rel;
9236 	int i, nrels;
9237 
9238 	btf = obj->btf;
9239 	nrels = shdr->sh_size / shdr->sh_entsize;
9240 	for (i = 0; i < nrels; i++) {
9241 		rel = elf_rel_by_idx(data, i);
9242 		if (!rel) {
9243 			pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
9244 			return -LIBBPF_ERRNO__FORMAT;
9245 		}
9246 
9247 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
9248 		if (!sym) {
9249 			pr_warn("struct_ops reloc: symbol %zx not found\n",
9250 				(size_t)ELF64_R_SYM(rel->r_info));
9251 			return -LIBBPF_ERRNO__FORMAT;
9252 		}
9253 
9254 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
9255 		map = find_struct_ops_map_by_offset(obj, rel->r_offset);
9256 		if (!map) {
9257 			pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
9258 				(size_t)rel->r_offset);
9259 			return -EINVAL;
9260 		}
9261 
9262 		moff = rel->r_offset - map->sec_offset;
9263 		shdr_idx = sym->st_shndx;
9264 		st_ops = map->st_ops;
9265 		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",
9266 			 map->name,
9267 			 (long long)(rel->r_info >> 32),
9268 			 (long long)sym->st_value,
9269 			 shdr_idx, (size_t)rel->r_offset,
9270 			 map->sec_offset, sym->st_name, name);
9271 
9272 		if (shdr_idx >= SHN_LORESERVE) {
9273 			pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
9274 				map->name, (size_t)rel->r_offset, shdr_idx);
9275 			return -LIBBPF_ERRNO__RELOC;
9276 		}
9277 		if (sym->st_value % BPF_INSN_SZ) {
9278 			pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
9279 				map->name, (unsigned long long)sym->st_value);
9280 			return -LIBBPF_ERRNO__FORMAT;
9281 		}
9282 		insn_idx = sym->st_value / BPF_INSN_SZ;
9283 
9284 		member = find_member_by_offset(st_ops->type, moff * 8);
9285 		if (!member) {
9286 			pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
9287 				map->name, moff);
9288 			return -EINVAL;
9289 		}
9290 		member_idx = member - btf_members(st_ops->type);
9291 		name = btf__name_by_offset(btf, member->name_off);
9292 
9293 		if (!resolve_func_ptr(btf, member->type, NULL)) {
9294 			pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
9295 				map->name, name);
9296 			return -EINVAL;
9297 		}
9298 
9299 		prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
9300 		if (!prog) {
9301 			pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
9302 				map->name, shdr_idx, name);
9303 			return -EINVAL;
9304 		}
9305 
9306 		/* prevent the use of BPF prog with invalid type */
9307 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
9308 			pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
9309 				map->name, prog->name);
9310 			return -EINVAL;
9311 		}
9312 
9313 		/* if we haven't yet processed this BPF program, record proper
9314 		 * attach_btf_id and member_idx
9315 		 */
9316 		if (!prog->attach_btf_id) {
9317 			prog->attach_btf_id = st_ops->type_id;
9318 			prog->expected_attach_type = member_idx;
9319 		}
9320 
9321 		/* struct_ops BPF prog can be re-used between multiple
9322 		 * .struct_ops as long as it's the same struct_ops struct
9323 		 * definition and the same function pointer field
9324 		 */
9325 		if (prog->attach_btf_id != st_ops->type_id ||
9326 		    prog->expected_attach_type != member_idx) {
9327 			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",
9328 				map->name, prog->name, prog->sec_name, prog->type,
9329 				prog->attach_btf_id, prog->expected_attach_type, name);
9330 			return -EINVAL;
9331 		}
9332 
9333 		st_ops->progs[member_idx] = prog;
9334 	}
9335 
9336 	return 0;
9337 }
9338 
9339 #define BTF_TRACE_PREFIX "btf_trace_"
9340 #define BTF_LSM_PREFIX "bpf_lsm_"
9341 #define BTF_ITER_PREFIX "bpf_iter_"
9342 #define BTF_MAX_NAME_SIZE 128
9343 
9344 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
9345 				const char **prefix, int *kind)
9346 {
9347 	switch (attach_type) {
9348 	case BPF_TRACE_RAW_TP:
9349 		*prefix = BTF_TRACE_PREFIX;
9350 		*kind = BTF_KIND_TYPEDEF;
9351 		break;
9352 	case BPF_LSM_MAC:
9353 	case BPF_LSM_CGROUP:
9354 		*prefix = BTF_LSM_PREFIX;
9355 		*kind = BTF_KIND_FUNC;
9356 		break;
9357 	case BPF_TRACE_ITER:
9358 		*prefix = BTF_ITER_PREFIX;
9359 		*kind = BTF_KIND_FUNC;
9360 		break;
9361 	default:
9362 		*prefix = "";
9363 		*kind = BTF_KIND_FUNC;
9364 	}
9365 }
9366 
9367 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
9368 				   const char *name, __u32 kind)
9369 {
9370 	char btf_type_name[BTF_MAX_NAME_SIZE];
9371 	int ret;
9372 
9373 	ret = snprintf(btf_type_name, sizeof(btf_type_name),
9374 		       "%s%s", prefix, name);
9375 	/* snprintf returns the number of characters written excluding the
9376 	 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
9377 	 * indicates truncation.
9378 	 */
9379 	if (ret < 0 || ret >= sizeof(btf_type_name))
9380 		return -ENAMETOOLONG;
9381 	return btf__find_by_name_kind(btf, btf_type_name, kind);
9382 }
9383 
9384 static inline int find_attach_btf_id(struct btf *btf, const char *name,
9385 				     enum bpf_attach_type attach_type)
9386 {
9387 	const char *prefix;
9388 	int kind;
9389 
9390 	btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
9391 	return find_btf_by_prefix_kind(btf, prefix, name, kind);
9392 }
9393 
9394 int libbpf_find_vmlinux_btf_id(const char *name,
9395 			       enum bpf_attach_type attach_type)
9396 {
9397 	struct btf *btf;
9398 	int err;
9399 
9400 	btf = btf__load_vmlinux_btf();
9401 	err = libbpf_get_error(btf);
9402 	if (err) {
9403 		pr_warn("vmlinux BTF is not found\n");
9404 		return libbpf_err(err);
9405 	}
9406 
9407 	err = find_attach_btf_id(btf, name, attach_type);
9408 	if (err <= 0)
9409 		pr_warn("%s is not found in vmlinux BTF\n", name);
9410 
9411 	btf__free(btf);
9412 	return libbpf_err(err);
9413 }
9414 
9415 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
9416 {
9417 	struct bpf_prog_info info;
9418 	__u32 info_len = sizeof(info);
9419 	struct btf *btf;
9420 	int err;
9421 
9422 	memset(&info, 0, info_len);
9423 	err = bpf_obj_get_info_by_fd(attach_prog_fd, &info, &info_len);
9424 	if (err) {
9425 		pr_warn("failed bpf_obj_get_info_by_fd for FD %d: %d\n",
9426 			attach_prog_fd, err);
9427 		return err;
9428 	}
9429 
9430 	err = -EINVAL;
9431 	if (!info.btf_id) {
9432 		pr_warn("The target program doesn't have BTF\n");
9433 		goto out;
9434 	}
9435 	btf = btf__load_from_kernel_by_id(info.btf_id);
9436 	err = libbpf_get_error(btf);
9437 	if (err) {
9438 		pr_warn("Failed to get BTF %d of the program: %d\n", info.btf_id, err);
9439 		goto out;
9440 	}
9441 	err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
9442 	btf__free(btf);
9443 	if (err <= 0) {
9444 		pr_warn("%s is not found in prog's BTF\n", name);
9445 		goto out;
9446 	}
9447 out:
9448 	return err;
9449 }
9450 
9451 static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
9452 			      enum bpf_attach_type attach_type,
9453 			      int *btf_obj_fd, int *btf_type_id)
9454 {
9455 	int ret, i;
9456 
9457 	ret = find_attach_btf_id(obj->btf_vmlinux, attach_name, attach_type);
9458 	if (ret > 0) {
9459 		*btf_obj_fd = 0; /* vmlinux BTF */
9460 		*btf_type_id = ret;
9461 		return 0;
9462 	}
9463 	if (ret != -ENOENT)
9464 		return ret;
9465 
9466 	ret = load_module_btfs(obj);
9467 	if (ret)
9468 		return ret;
9469 
9470 	for (i = 0; i < obj->btf_module_cnt; i++) {
9471 		const struct module_btf *mod = &obj->btf_modules[i];
9472 
9473 		ret = find_attach_btf_id(mod->btf, attach_name, attach_type);
9474 		if (ret > 0) {
9475 			*btf_obj_fd = mod->fd;
9476 			*btf_type_id = ret;
9477 			return 0;
9478 		}
9479 		if (ret == -ENOENT)
9480 			continue;
9481 
9482 		return ret;
9483 	}
9484 
9485 	return -ESRCH;
9486 }
9487 
9488 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
9489 				     int *btf_obj_fd, int *btf_type_id)
9490 {
9491 	enum bpf_attach_type attach_type = prog->expected_attach_type;
9492 	__u32 attach_prog_fd = prog->attach_prog_fd;
9493 	int err = 0;
9494 
9495 	/* BPF program's BTF ID */
9496 	if (prog->type == BPF_PROG_TYPE_EXT || attach_prog_fd) {
9497 		if (!attach_prog_fd) {
9498 			pr_warn("prog '%s': attach program FD is not set\n", prog->name);
9499 			return -EINVAL;
9500 		}
9501 		err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd);
9502 		if (err < 0) {
9503 			pr_warn("prog '%s': failed to find BPF program (FD %d) BTF ID for '%s': %d\n",
9504 				 prog->name, attach_prog_fd, attach_name, err);
9505 			return err;
9506 		}
9507 		*btf_obj_fd = 0;
9508 		*btf_type_id = err;
9509 		return 0;
9510 	}
9511 
9512 	/* kernel/module BTF ID */
9513 	if (prog->obj->gen_loader) {
9514 		bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
9515 		*btf_obj_fd = 0;
9516 		*btf_type_id = 1;
9517 	} else {
9518 		err = find_kernel_btf_id(prog->obj, attach_name, attach_type, btf_obj_fd, btf_type_id);
9519 	}
9520 	if (err) {
9521 		pr_warn("prog '%s': failed to find kernel BTF type ID of '%s': %d\n",
9522 			prog->name, attach_name, err);
9523 		return err;
9524 	}
9525 	return 0;
9526 }
9527 
9528 int libbpf_attach_type_by_name(const char *name,
9529 			       enum bpf_attach_type *attach_type)
9530 {
9531 	char *type_names;
9532 	const struct bpf_sec_def *sec_def;
9533 
9534 	if (!name)
9535 		return libbpf_err(-EINVAL);
9536 
9537 	sec_def = find_sec_def(name);
9538 	if (!sec_def) {
9539 		pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
9540 		type_names = libbpf_get_type_names(true);
9541 		if (type_names != NULL) {
9542 			pr_debug("attachable section(type) names are:%s\n", type_names);
9543 			free(type_names);
9544 		}
9545 
9546 		return libbpf_err(-EINVAL);
9547 	}
9548 
9549 	if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
9550 		return libbpf_err(-EINVAL);
9551 	if (!(sec_def->cookie & SEC_ATTACHABLE))
9552 		return libbpf_err(-EINVAL);
9553 
9554 	*attach_type = sec_def->expected_attach_type;
9555 	return 0;
9556 }
9557 
9558 int bpf_map__fd(const struct bpf_map *map)
9559 {
9560 	return map ? map->fd : libbpf_err(-EINVAL);
9561 }
9562 
9563 static bool map_uses_real_name(const struct bpf_map *map)
9564 {
9565 	/* Since libbpf started to support custom .data.* and .rodata.* maps,
9566 	 * their user-visible name differs from kernel-visible name. Users see
9567 	 * such map's corresponding ELF section name as a map name.
9568 	 * This check distinguishes .data/.rodata from .data.* and .rodata.*
9569 	 * maps to know which name has to be returned to the user.
9570 	 */
9571 	if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
9572 		return true;
9573 	if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
9574 		return true;
9575 	return false;
9576 }
9577 
9578 const char *bpf_map__name(const struct bpf_map *map)
9579 {
9580 	if (!map)
9581 		return NULL;
9582 
9583 	if (map_uses_real_name(map))
9584 		return map->real_name;
9585 
9586 	return map->name;
9587 }
9588 
9589 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
9590 {
9591 	return map->def.type;
9592 }
9593 
9594 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
9595 {
9596 	if (map->fd >= 0)
9597 		return libbpf_err(-EBUSY);
9598 	map->def.type = type;
9599 	return 0;
9600 }
9601 
9602 __u32 bpf_map__map_flags(const struct bpf_map *map)
9603 {
9604 	return map->def.map_flags;
9605 }
9606 
9607 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
9608 {
9609 	if (map->fd >= 0)
9610 		return libbpf_err(-EBUSY);
9611 	map->def.map_flags = flags;
9612 	return 0;
9613 }
9614 
9615 __u64 bpf_map__map_extra(const struct bpf_map *map)
9616 {
9617 	return map->map_extra;
9618 }
9619 
9620 int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
9621 {
9622 	if (map->fd >= 0)
9623 		return libbpf_err(-EBUSY);
9624 	map->map_extra = map_extra;
9625 	return 0;
9626 }
9627 
9628 __u32 bpf_map__numa_node(const struct bpf_map *map)
9629 {
9630 	return map->numa_node;
9631 }
9632 
9633 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
9634 {
9635 	if (map->fd >= 0)
9636 		return libbpf_err(-EBUSY);
9637 	map->numa_node = numa_node;
9638 	return 0;
9639 }
9640 
9641 __u32 bpf_map__key_size(const struct bpf_map *map)
9642 {
9643 	return map->def.key_size;
9644 }
9645 
9646 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
9647 {
9648 	if (map->fd >= 0)
9649 		return libbpf_err(-EBUSY);
9650 	map->def.key_size = size;
9651 	return 0;
9652 }
9653 
9654 __u32 bpf_map__value_size(const struct bpf_map *map)
9655 {
9656 	return map->def.value_size;
9657 }
9658 
9659 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
9660 {
9661 	if (map->fd >= 0)
9662 		return libbpf_err(-EBUSY);
9663 	map->def.value_size = size;
9664 	return 0;
9665 }
9666 
9667 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
9668 {
9669 	return map ? map->btf_key_type_id : 0;
9670 }
9671 
9672 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
9673 {
9674 	return map ? map->btf_value_type_id : 0;
9675 }
9676 
9677 int bpf_map__set_initial_value(struct bpf_map *map,
9678 			       const void *data, size_t size)
9679 {
9680 	if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG ||
9681 	    size != map->def.value_size || map->fd >= 0)
9682 		return libbpf_err(-EINVAL);
9683 
9684 	memcpy(map->mmaped, data, size);
9685 	return 0;
9686 }
9687 
9688 const void *bpf_map__initial_value(struct bpf_map *map, size_t *psize)
9689 {
9690 	if (!map->mmaped)
9691 		return NULL;
9692 	*psize = map->def.value_size;
9693 	return map->mmaped;
9694 }
9695 
9696 bool bpf_map__is_internal(const struct bpf_map *map)
9697 {
9698 	return map->libbpf_type != LIBBPF_MAP_UNSPEC;
9699 }
9700 
9701 __u32 bpf_map__ifindex(const struct bpf_map *map)
9702 {
9703 	return map->map_ifindex;
9704 }
9705 
9706 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
9707 {
9708 	if (map->fd >= 0)
9709 		return libbpf_err(-EBUSY);
9710 	map->map_ifindex = ifindex;
9711 	return 0;
9712 }
9713 
9714 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
9715 {
9716 	if (!bpf_map_type__is_map_in_map(map->def.type)) {
9717 		pr_warn("error: unsupported map type\n");
9718 		return libbpf_err(-EINVAL);
9719 	}
9720 	if (map->inner_map_fd != -1) {
9721 		pr_warn("error: inner_map_fd already specified\n");
9722 		return libbpf_err(-EINVAL);
9723 	}
9724 	if (map->inner_map) {
9725 		bpf_map__destroy(map->inner_map);
9726 		zfree(&map->inner_map);
9727 	}
9728 	map->inner_map_fd = fd;
9729 	return 0;
9730 }
9731 
9732 static struct bpf_map *
9733 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
9734 {
9735 	ssize_t idx;
9736 	struct bpf_map *s, *e;
9737 
9738 	if (!obj || !obj->maps)
9739 		return errno = EINVAL, NULL;
9740 
9741 	s = obj->maps;
9742 	e = obj->maps + obj->nr_maps;
9743 
9744 	if ((m < s) || (m >= e)) {
9745 		pr_warn("error in %s: map handler doesn't belong to object\n",
9746 			 __func__);
9747 		return errno = EINVAL, NULL;
9748 	}
9749 
9750 	idx = (m - obj->maps) + i;
9751 	if (idx >= obj->nr_maps || idx < 0)
9752 		return NULL;
9753 	return &obj->maps[idx];
9754 }
9755 
9756 struct bpf_map *
9757 bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
9758 {
9759 	if (prev == NULL)
9760 		return obj->maps;
9761 
9762 	return __bpf_map__iter(prev, obj, 1);
9763 }
9764 
9765 struct bpf_map *
9766 bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
9767 {
9768 	if (next == NULL) {
9769 		if (!obj->nr_maps)
9770 			return NULL;
9771 		return obj->maps + obj->nr_maps - 1;
9772 	}
9773 
9774 	return __bpf_map__iter(next, obj, -1);
9775 }
9776 
9777 struct bpf_map *
9778 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
9779 {
9780 	struct bpf_map *pos;
9781 
9782 	bpf_object__for_each_map(pos, obj) {
9783 		/* if it's a special internal map name (which always starts
9784 		 * with dot) then check if that special name matches the
9785 		 * real map name (ELF section name)
9786 		 */
9787 		if (name[0] == '.') {
9788 			if (pos->real_name && strcmp(pos->real_name, name) == 0)
9789 				return pos;
9790 			continue;
9791 		}
9792 		/* otherwise map name has to be an exact match */
9793 		if (map_uses_real_name(pos)) {
9794 			if (strcmp(pos->real_name, name) == 0)
9795 				return pos;
9796 			continue;
9797 		}
9798 		if (strcmp(pos->name, name) == 0)
9799 			return pos;
9800 	}
9801 	return errno = ENOENT, NULL;
9802 }
9803 
9804 int
9805 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
9806 {
9807 	return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
9808 }
9809 
9810 static int validate_map_op(const struct bpf_map *map, size_t key_sz,
9811 			   size_t value_sz, bool check_value_sz)
9812 {
9813 	if (map->fd <= 0)
9814 		return -ENOENT;
9815 
9816 	if (map->def.key_size != key_sz) {
9817 		pr_warn("map '%s': unexpected key size %zu provided, expected %u\n",
9818 			map->name, key_sz, map->def.key_size);
9819 		return -EINVAL;
9820 	}
9821 
9822 	if (!check_value_sz)
9823 		return 0;
9824 
9825 	switch (map->def.type) {
9826 	case BPF_MAP_TYPE_PERCPU_ARRAY:
9827 	case BPF_MAP_TYPE_PERCPU_HASH:
9828 	case BPF_MAP_TYPE_LRU_PERCPU_HASH:
9829 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: {
9830 		int num_cpu = libbpf_num_possible_cpus();
9831 		size_t elem_sz = roundup(map->def.value_size, 8);
9832 
9833 		if (value_sz != num_cpu * elem_sz) {
9834 			pr_warn("map '%s': unexpected value size %zu provided for per-CPU map, expected %d * %zu = %zd\n",
9835 				map->name, value_sz, num_cpu, elem_sz, num_cpu * elem_sz);
9836 			return -EINVAL;
9837 		}
9838 		break;
9839 	}
9840 	default:
9841 		if (map->def.value_size != value_sz) {
9842 			pr_warn("map '%s': unexpected value size %zu provided, expected %u\n",
9843 				map->name, value_sz, map->def.value_size);
9844 			return -EINVAL;
9845 		}
9846 		break;
9847 	}
9848 	return 0;
9849 }
9850 
9851 int bpf_map__lookup_elem(const struct bpf_map *map,
9852 			 const void *key, size_t key_sz,
9853 			 void *value, size_t value_sz, __u64 flags)
9854 {
9855 	int err;
9856 
9857 	err = validate_map_op(map, key_sz, value_sz, true);
9858 	if (err)
9859 		return libbpf_err(err);
9860 
9861 	return bpf_map_lookup_elem_flags(map->fd, key, value, flags);
9862 }
9863 
9864 int bpf_map__update_elem(const struct bpf_map *map,
9865 			 const void *key, size_t key_sz,
9866 			 const void *value, size_t value_sz, __u64 flags)
9867 {
9868 	int err;
9869 
9870 	err = validate_map_op(map, key_sz, value_sz, true);
9871 	if (err)
9872 		return libbpf_err(err);
9873 
9874 	return bpf_map_update_elem(map->fd, key, value, flags);
9875 }
9876 
9877 int bpf_map__delete_elem(const struct bpf_map *map,
9878 			 const void *key, size_t key_sz, __u64 flags)
9879 {
9880 	int err;
9881 
9882 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
9883 	if (err)
9884 		return libbpf_err(err);
9885 
9886 	return bpf_map_delete_elem_flags(map->fd, key, flags);
9887 }
9888 
9889 int bpf_map__lookup_and_delete_elem(const struct bpf_map *map,
9890 				    const void *key, size_t key_sz,
9891 				    void *value, size_t value_sz, __u64 flags)
9892 {
9893 	int err;
9894 
9895 	err = validate_map_op(map, key_sz, value_sz, true);
9896 	if (err)
9897 		return libbpf_err(err);
9898 
9899 	return bpf_map_lookup_and_delete_elem_flags(map->fd, key, value, flags);
9900 }
9901 
9902 int bpf_map__get_next_key(const struct bpf_map *map,
9903 			  const void *cur_key, void *next_key, size_t key_sz)
9904 {
9905 	int err;
9906 
9907 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
9908 	if (err)
9909 		return libbpf_err(err);
9910 
9911 	return bpf_map_get_next_key(map->fd, cur_key, next_key);
9912 }
9913 
9914 long libbpf_get_error(const void *ptr)
9915 {
9916 	if (!IS_ERR_OR_NULL(ptr))
9917 		return 0;
9918 
9919 	if (IS_ERR(ptr))
9920 		errno = -PTR_ERR(ptr);
9921 
9922 	/* If ptr == NULL, then errno should be already set by the failing
9923 	 * API, because libbpf never returns NULL on success and it now always
9924 	 * sets errno on error. So no extra errno handling for ptr == NULL
9925 	 * case.
9926 	 */
9927 	return -errno;
9928 }
9929 
9930 /* Replace link's underlying BPF program with the new one */
9931 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
9932 {
9933 	int ret;
9934 
9935 	ret = bpf_link_update(bpf_link__fd(link), bpf_program__fd(prog), NULL);
9936 	return libbpf_err_errno(ret);
9937 }
9938 
9939 /* Release "ownership" of underlying BPF resource (typically, BPF program
9940  * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
9941  * link, when destructed through bpf_link__destroy() call won't attempt to
9942  * detach/unregisted that BPF resource. This is useful in situations where,
9943  * say, attached BPF program has to outlive userspace program that attached it
9944  * in the system. Depending on type of BPF program, though, there might be
9945  * additional steps (like pinning BPF program in BPF FS) necessary to ensure
9946  * exit of userspace program doesn't trigger automatic detachment and clean up
9947  * inside the kernel.
9948  */
9949 void bpf_link__disconnect(struct bpf_link *link)
9950 {
9951 	link->disconnected = true;
9952 }
9953 
9954 int bpf_link__destroy(struct bpf_link *link)
9955 {
9956 	int err = 0;
9957 
9958 	if (IS_ERR_OR_NULL(link))
9959 		return 0;
9960 
9961 	if (!link->disconnected && link->detach)
9962 		err = link->detach(link);
9963 	if (link->pin_path)
9964 		free(link->pin_path);
9965 	if (link->dealloc)
9966 		link->dealloc(link);
9967 	else
9968 		free(link);
9969 
9970 	return libbpf_err(err);
9971 }
9972 
9973 int bpf_link__fd(const struct bpf_link *link)
9974 {
9975 	return link->fd;
9976 }
9977 
9978 const char *bpf_link__pin_path(const struct bpf_link *link)
9979 {
9980 	return link->pin_path;
9981 }
9982 
9983 static int bpf_link__detach_fd(struct bpf_link *link)
9984 {
9985 	return libbpf_err_errno(close(link->fd));
9986 }
9987 
9988 struct bpf_link *bpf_link__open(const char *path)
9989 {
9990 	struct bpf_link *link;
9991 	int fd;
9992 
9993 	fd = bpf_obj_get(path);
9994 	if (fd < 0) {
9995 		fd = -errno;
9996 		pr_warn("failed to open link at %s: %d\n", path, fd);
9997 		return libbpf_err_ptr(fd);
9998 	}
9999 
10000 	link = calloc(1, sizeof(*link));
10001 	if (!link) {
10002 		close(fd);
10003 		return libbpf_err_ptr(-ENOMEM);
10004 	}
10005 	link->detach = &bpf_link__detach_fd;
10006 	link->fd = fd;
10007 
10008 	link->pin_path = strdup(path);
10009 	if (!link->pin_path) {
10010 		bpf_link__destroy(link);
10011 		return libbpf_err_ptr(-ENOMEM);
10012 	}
10013 
10014 	return link;
10015 }
10016 
10017 int bpf_link__detach(struct bpf_link *link)
10018 {
10019 	return bpf_link_detach(link->fd) ? -errno : 0;
10020 }
10021 
10022 int bpf_link__pin(struct bpf_link *link, const char *path)
10023 {
10024 	int err;
10025 
10026 	if (link->pin_path)
10027 		return libbpf_err(-EBUSY);
10028 	err = make_parent_dir(path);
10029 	if (err)
10030 		return libbpf_err(err);
10031 	err = check_path(path);
10032 	if (err)
10033 		return libbpf_err(err);
10034 
10035 	link->pin_path = strdup(path);
10036 	if (!link->pin_path)
10037 		return libbpf_err(-ENOMEM);
10038 
10039 	if (bpf_obj_pin(link->fd, link->pin_path)) {
10040 		err = -errno;
10041 		zfree(&link->pin_path);
10042 		return libbpf_err(err);
10043 	}
10044 
10045 	pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
10046 	return 0;
10047 }
10048 
10049 int bpf_link__unpin(struct bpf_link *link)
10050 {
10051 	int err;
10052 
10053 	if (!link->pin_path)
10054 		return libbpf_err(-EINVAL);
10055 
10056 	err = unlink(link->pin_path);
10057 	if (err != 0)
10058 		return -errno;
10059 
10060 	pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
10061 	zfree(&link->pin_path);
10062 	return 0;
10063 }
10064 
10065 struct bpf_link_perf {
10066 	struct bpf_link link;
10067 	int perf_event_fd;
10068 	/* legacy kprobe support: keep track of probe identifier and type */
10069 	char *legacy_probe_name;
10070 	bool legacy_is_kprobe;
10071 	bool legacy_is_retprobe;
10072 };
10073 
10074 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
10075 static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
10076 
10077 static int bpf_link_perf_detach(struct bpf_link *link)
10078 {
10079 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10080 	int err = 0;
10081 
10082 	if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
10083 		err = -errno;
10084 
10085 	if (perf_link->perf_event_fd != link->fd)
10086 		close(perf_link->perf_event_fd);
10087 	close(link->fd);
10088 
10089 	/* legacy uprobe/kprobe needs to be removed after perf event fd closure */
10090 	if (perf_link->legacy_probe_name) {
10091 		if (perf_link->legacy_is_kprobe) {
10092 			err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
10093 							 perf_link->legacy_is_retprobe);
10094 		} else {
10095 			err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
10096 							 perf_link->legacy_is_retprobe);
10097 		}
10098 	}
10099 
10100 	return err;
10101 }
10102 
10103 static void bpf_link_perf_dealloc(struct bpf_link *link)
10104 {
10105 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10106 
10107 	free(perf_link->legacy_probe_name);
10108 	free(perf_link);
10109 }
10110 
10111 struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
10112 						     const struct bpf_perf_event_opts *opts)
10113 {
10114 	char errmsg[STRERR_BUFSIZE];
10115 	struct bpf_link_perf *link;
10116 	int prog_fd, link_fd = -1, err;
10117 
10118 	if (!OPTS_VALID(opts, bpf_perf_event_opts))
10119 		return libbpf_err_ptr(-EINVAL);
10120 
10121 	if (pfd < 0) {
10122 		pr_warn("prog '%s': invalid perf event FD %d\n",
10123 			prog->name, pfd);
10124 		return libbpf_err_ptr(-EINVAL);
10125 	}
10126 	prog_fd = bpf_program__fd(prog);
10127 	if (prog_fd < 0) {
10128 		pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
10129 			prog->name);
10130 		return libbpf_err_ptr(-EINVAL);
10131 	}
10132 
10133 	link = calloc(1, sizeof(*link));
10134 	if (!link)
10135 		return libbpf_err_ptr(-ENOMEM);
10136 	link->link.detach = &bpf_link_perf_detach;
10137 	link->link.dealloc = &bpf_link_perf_dealloc;
10138 	link->perf_event_fd = pfd;
10139 
10140 	if (kernel_supports(prog->obj, FEAT_PERF_LINK)) {
10141 		DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
10142 			.perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
10143 
10144 		link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
10145 		if (link_fd < 0) {
10146 			err = -errno;
10147 			pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %d (%s)\n",
10148 				prog->name, pfd,
10149 				err, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10150 			goto err_out;
10151 		}
10152 		link->link.fd = link_fd;
10153 	} else {
10154 		if (OPTS_GET(opts, bpf_cookie, 0)) {
10155 			pr_warn("prog '%s': user context value is not supported\n", prog->name);
10156 			err = -EOPNOTSUPP;
10157 			goto err_out;
10158 		}
10159 
10160 		if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
10161 			err = -errno;
10162 			pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
10163 				prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10164 			if (err == -EPROTO)
10165 				pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
10166 					prog->name, pfd);
10167 			goto err_out;
10168 		}
10169 		link->link.fd = pfd;
10170 	}
10171 	if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
10172 		err = -errno;
10173 		pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
10174 			prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10175 		goto err_out;
10176 	}
10177 
10178 	return &link->link;
10179 err_out:
10180 	if (link_fd >= 0)
10181 		close(link_fd);
10182 	free(link);
10183 	return libbpf_err_ptr(err);
10184 }
10185 
10186 struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
10187 {
10188 	return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
10189 }
10190 
10191 /*
10192  * this function is expected to parse integer in the range of [0, 2^31-1] from
10193  * given file using scanf format string fmt. If actual parsed value is
10194  * negative, the result might be indistinguishable from error
10195  */
10196 static int parse_uint_from_file(const char *file, const char *fmt)
10197 {
10198 	char buf[STRERR_BUFSIZE];
10199 	int err, ret;
10200 	FILE *f;
10201 
10202 	f = fopen(file, "r");
10203 	if (!f) {
10204 		err = -errno;
10205 		pr_debug("failed to open '%s': %s\n", file,
10206 			 libbpf_strerror_r(err, buf, sizeof(buf)));
10207 		return err;
10208 	}
10209 	err = fscanf(f, fmt, &ret);
10210 	if (err != 1) {
10211 		err = err == EOF ? -EIO : -errno;
10212 		pr_debug("failed to parse '%s': %s\n", file,
10213 			libbpf_strerror_r(err, buf, sizeof(buf)));
10214 		fclose(f);
10215 		return err;
10216 	}
10217 	fclose(f);
10218 	return ret;
10219 }
10220 
10221 static int determine_kprobe_perf_type(void)
10222 {
10223 	const char *file = "/sys/bus/event_source/devices/kprobe/type";
10224 
10225 	return parse_uint_from_file(file, "%d\n");
10226 }
10227 
10228 static int determine_uprobe_perf_type(void)
10229 {
10230 	const char *file = "/sys/bus/event_source/devices/uprobe/type";
10231 
10232 	return parse_uint_from_file(file, "%d\n");
10233 }
10234 
10235 static int determine_kprobe_retprobe_bit(void)
10236 {
10237 	const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
10238 
10239 	return parse_uint_from_file(file, "config:%d\n");
10240 }
10241 
10242 static int determine_uprobe_retprobe_bit(void)
10243 {
10244 	const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
10245 
10246 	return parse_uint_from_file(file, "config:%d\n");
10247 }
10248 
10249 #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
10250 #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
10251 
10252 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
10253 				 uint64_t offset, int pid, size_t ref_ctr_off)
10254 {
10255 	const size_t attr_sz = sizeof(struct perf_event_attr);
10256 	struct perf_event_attr attr;
10257 	char errmsg[STRERR_BUFSIZE];
10258 	int type, pfd;
10259 
10260 	if ((__u64)ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
10261 		return -EINVAL;
10262 
10263 	memset(&attr, 0, attr_sz);
10264 
10265 	type = uprobe ? determine_uprobe_perf_type()
10266 		      : determine_kprobe_perf_type();
10267 	if (type < 0) {
10268 		pr_warn("failed to determine %s perf type: %s\n",
10269 			uprobe ? "uprobe" : "kprobe",
10270 			libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
10271 		return type;
10272 	}
10273 	if (retprobe) {
10274 		int bit = uprobe ? determine_uprobe_retprobe_bit()
10275 				 : determine_kprobe_retprobe_bit();
10276 
10277 		if (bit < 0) {
10278 			pr_warn("failed to determine %s retprobe bit: %s\n",
10279 				uprobe ? "uprobe" : "kprobe",
10280 				libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
10281 			return bit;
10282 		}
10283 		attr.config |= 1 << bit;
10284 	}
10285 	attr.size = attr_sz;
10286 	attr.type = type;
10287 	attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
10288 	attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
10289 	attr.config2 = offset;		 /* kprobe_addr or probe_offset */
10290 
10291 	/* pid filter is meaningful only for uprobes */
10292 	pfd = syscall(__NR_perf_event_open, &attr,
10293 		      pid < 0 ? -1 : pid /* pid */,
10294 		      pid == -1 ? 0 : -1 /* cpu */,
10295 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
10296 	return pfd >= 0 ? pfd : -errno;
10297 }
10298 
10299 static int append_to_file(const char *file, const char *fmt, ...)
10300 {
10301 	int fd, n, err = 0;
10302 	va_list ap;
10303 
10304 	fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
10305 	if (fd < 0)
10306 		return -errno;
10307 
10308 	va_start(ap, fmt);
10309 	n = vdprintf(fd, fmt, ap);
10310 	va_end(ap);
10311 
10312 	if (n < 0)
10313 		err = -errno;
10314 
10315 	close(fd);
10316 	return err;
10317 }
10318 
10319 #define DEBUGFS "/sys/kernel/debug/tracing"
10320 #define TRACEFS "/sys/kernel/tracing"
10321 
10322 static bool use_debugfs(void)
10323 {
10324 	static int has_debugfs = -1;
10325 
10326 	if (has_debugfs < 0)
10327 		has_debugfs = faccessat(AT_FDCWD, DEBUGFS, F_OK, AT_EACCESS) == 0;
10328 
10329 	return has_debugfs == 1;
10330 }
10331 
10332 static const char *tracefs_path(void)
10333 {
10334 	return use_debugfs() ? DEBUGFS : TRACEFS;
10335 }
10336 
10337 static const char *tracefs_kprobe_events(void)
10338 {
10339 	return use_debugfs() ? DEBUGFS"/kprobe_events" : TRACEFS"/kprobe_events";
10340 }
10341 
10342 static const char *tracefs_uprobe_events(void)
10343 {
10344 	return use_debugfs() ? DEBUGFS"/uprobe_events" : TRACEFS"/uprobe_events";
10345 }
10346 
10347 static void gen_kprobe_legacy_event_name(char *buf, size_t buf_sz,
10348 					 const char *kfunc_name, size_t offset)
10349 {
10350 	static int index = 0;
10351 
10352 	snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx_%d", getpid(), kfunc_name, offset,
10353 		 __sync_fetch_and_add(&index, 1));
10354 }
10355 
10356 static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
10357 				   const char *kfunc_name, size_t offset)
10358 {
10359 	return append_to_file(tracefs_kprobe_events(), "%c:%s/%s %s+0x%zx",
10360 			      retprobe ? 'r' : 'p',
10361 			      retprobe ? "kretprobes" : "kprobes",
10362 			      probe_name, kfunc_name, offset);
10363 }
10364 
10365 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
10366 {
10367 	return append_to_file(tracefs_kprobe_events(), "-:%s/%s",
10368 			      retprobe ? "kretprobes" : "kprobes", probe_name);
10369 }
10370 
10371 static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
10372 {
10373 	char file[256];
10374 
10375 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
10376 		 tracefs_path(), retprobe ? "kretprobes" : "kprobes", probe_name);
10377 
10378 	return parse_uint_from_file(file, "%d\n");
10379 }
10380 
10381 static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
10382 					 const char *kfunc_name, size_t offset, int pid)
10383 {
10384 	const size_t attr_sz = sizeof(struct perf_event_attr);
10385 	struct perf_event_attr attr;
10386 	char errmsg[STRERR_BUFSIZE];
10387 	int type, pfd, err;
10388 
10389 	err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
10390 	if (err < 0) {
10391 		pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
10392 			kfunc_name, offset,
10393 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10394 		return err;
10395 	}
10396 	type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
10397 	if (type < 0) {
10398 		err = type;
10399 		pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
10400 			kfunc_name, offset,
10401 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10402 		goto err_clean_legacy;
10403 	}
10404 
10405 	memset(&attr, 0, attr_sz);
10406 	attr.size = attr_sz;
10407 	attr.config = type;
10408 	attr.type = PERF_TYPE_TRACEPOINT;
10409 
10410 	pfd = syscall(__NR_perf_event_open, &attr,
10411 		      pid < 0 ? -1 : pid, /* pid */
10412 		      pid == -1 ? 0 : -1, /* cpu */
10413 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
10414 	if (pfd < 0) {
10415 		err = -errno;
10416 		pr_warn("legacy kprobe perf_event_open() failed: %s\n",
10417 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10418 		goto err_clean_legacy;
10419 	}
10420 	return pfd;
10421 
10422 err_clean_legacy:
10423 	/* Clear the newly added legacy kprobe_event */
10424 	remove_kprobe_event_legacy(probe_name, retprobe);
10425 	return err;
10426 }
10427 
10428 static const char *arch_specific_syscall_pfx(void)
10429 {
10430 #if defined(__x86_64__)
10431 	return "x64";
10432 #elif defined(__i386__)
10433 	return "ia32";
10434 #elif defined(__s390x__)
10435 	return "s390x";
10436 #elif defined(__s390__)
10437 	return "s390";
10438 #elif defined(__arm__)
10439 	return "arm";
10440 #elif defined(__aarch64__)
10441 	return "arm64";
10442 #elif defined(__mips__)
10443 	return "mips";
10444 #elif defined(__riscv)
10445 	return "riscv";
10446 #elif defined(__powerpc__)
10447 	return "powerpc";
10448 #elif defined(__powerpc64__)
10449 	return "powerpc64";
10450 #else
10451 	return NULL;
10452 #endif
10453 }
10454 
10455 static int probe_kern_syscall_wrapper(void)
10456 {
10457 	char syscall_name[64];
10458 	const char *ksys_pfx;
10459 
10460 	ksys_pfx = arch_specific_syscall_pfx();
10461 	if (!ksys_pfx)
10462 		return 0;
10463 
10464 	snprintf(syscall_name, sizeof(syscall_name), "__%s_sys_bpf", ksys_pfx);
10465 
10466 	if (determine_kprobe_perf_type() >= 0) {
10467 		int pfd;
10468 
10469 		pfd = perf_event_open_probe(false, false, syscall_name, 0, getpid(), 0);
10470 		if (pfd >= 0)
10471 			close(pfd);
10472 
10473 		return pfd >= 0 ? 1 : 0;
10474 	} else { /* legacy mode */
10475 		char probe_name[128];
10476 
10477 		gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name), syscall_name, 0);
10478 		if (add_kprobe_event_legacy(probe_name, false, syscall_name, 0) < 0)
10479 			return 0;
10480 
10481 		(void)remove_kprobe_event_legacy(probe_name, false);
10482 		return 1;
10483 	}
10484 }
10485 
10486 struct bpf_link *
10487 bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
10488 				const char *func_name,
10489 				const struct bpf_kprobe_opts *opts)
10490 {
10491 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
10492 	char errmsg[STRERR_BUFSIZE];
10493 	char *legacy_probe = NULL;
10494 	struct bpf_link *link;
10495 	size_t offset;
10496 	bool retprobe, legacy;
10497 	int pfd, err;
10498 
10499 	if (!OPTS_VALID(opts, bpf_kprobe_opts))
10500 		return libbpf_err_ptr(-EINVAL);
10501 
10502 	retprobe = OPTS_GET(opts, retprobe, false);
10503 	offset = OPTS_GET(opts, offset, 0);
10504 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10505 
10506 	legacy = determine_kprobe_perf_type() < 0;
10507 	if (!legacy) {
10508 		pfd = perf_event_open_probe(false /* uprobe */, retprobe,
10509 					    func_name, offset,
10510 					    -1 /* pid */, 0 /* ref_ctr_off */);
10511 	} else {
10512 		char probe_name[256];
10513 
10514 		gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name),
10515 					     func_name, offset);
10516 
10517 		legacy_probe = strdup(probe_name);
10518 		if (!legacy_probe)
10519 			return libbpf_err_ptr(-ENOMEM);
10520 
10521 		pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
10522 						    offset, -1 /* pid */);
10523 	}
10524 	if (pfd < 0) {
10525 		err = -errno;
10526 		pr_warn("prog '%s': failed to create %s '%s+0x%zx' perf event: %s\n",
10527 			prog->name, retprobe ? "kretprobe" : "kprobe",
10528 			func_name, offset,
10529 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10530 		goto err_out;
10531 	}
10532 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
10533 	err = libbpf_get_error(link);
10534 	if (err) {
10535 		close(pfd);
10536 		pr_warn("prog '%s': failed to attach to %s '%s+0x%zx': %s\n",
10537 			prog->name, retprobe ? "kretprobe" : "kprobe",
10538 			func_name, offset,
10539 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10540 		goto err_clean_legacy;
10541 	}
10542 	if (legacy) {
10543 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10544 
10545 		perf_link->legacy_probe_name = legacy_probe;
10546 		perf_link->legacy_is_kprobe = true;
10547 		perf_link->legacy_is_retprobe = retprobe;
10548 	}
10549 
10550 	return link;
10551 
10552 err_clean_legacy:
10553 	if (legacy)
10554 		remove_kprobe_event_legacy(legacy_probe, retprobe);
10555 err_out:
10556 	free(legacy_probe);
10557 	return libbpf_err_ptr(err);
10558 }
10559 
10560 struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
10561 					    bool retprobe,
10562 					    const char *func_name)
10563 {
10564 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
10565 		.retprobe = retprobe,
10566 	);
10567 
10568 	return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
10569 }
10570 
10571 struct bpf_link *bpf_program__attach_ksyscall(const struct bpf_program *prog,
10572 					      const char *syscall_name,
10573 					      const struct bpf_ksyscall_opts *opts)
10574 {
10575 	LIBBPF_OPTS(bpf_kprobe_opts, kprobe_opts);
10576 	char func_name[128];
10577 
10578 	if (!OPTS_VALID(opts, bpf_ksyscall_opts))
10579 		return libbpf_err_ptr(-EINVAL);
10580 
10581 	if (kernel_supports(prog->obj, FEAT_SYSCALL_WRAPPER)) {
10582 		/* arch_specific_syscall_pfx() should never return NULL here
10583 		 * because it is guarded by kernel_supports(). However, since
10584 		 * compiler does not know that we have an explicit conditional
10585 		 * as well.
10586 		 */
10587 		snprintf(func_name, sizeof(func_name), "__%s_sys_%s",
10588 			 arch_specific_syscall_pfx() ? : "", syscall_name);
10589 	} else {
10590 		snprintf(func_name, sizeof(func_name), "__se_sys_%s", syscall_name);
10591 	}
10592 
10593 	kprobe_opts.retprobe = OPTS_GET(opts, retprobe, false);
10594 	kprobe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10595 
10596 	return bpf_program__attach_kprobe_opts(prog, func_name, &kprobe_opts);
10597 }
10598 
10599 /* Adapted from perf/util/string.c */
10600 static bool glob_match(const char *str, const char *pat)
10601 {
10602 	while (*str && *pat && *pat != '*') {
10603 		if (*pat == '?') {      /* Matches any single character */
10604 			str++;
10605 			pat++;
10606 			continue;
10607 		}
10608 		if (*str != *pat)
10609 			return false;
10610 		str++;
10611 		pat++;
10612 	}
10613 	/* Check wild card */
10614 	if (*pat == '*') {
10615 		while (*pat == '*')
10616 			pat++;
10617 		if (!*pat) /* Tail wild card matches all */
10618 			return true;
10619 		while (*str)
10620 			if (glob_match(str++, pat))
10621 				return true;
10622 	}
10623 	return !*str && !*pat;
10624 }
10625 
10626 struct kprobe_multi_resolve {
10627 	const char *pattern;
10628 	unsigned long *addrs;
10629 	size_t cap;
10630 	size_t cnt;
10631 };
10632 
10633 static int
10634 resolve_kprobe_multi_cb(unsigned long long sym_addr, char sym_type,
10635 			const char *sym_name, void *ctx)
10636 {
10637 	struct kprobe_multi_resolve *res = ctx;
10638 	int err;
10639 
10640 	if (!glob_match(sym_name, res->pattern))
10641 		return 0;
10642 
10643 	err = libbpf_ensure_mem((void **) &res->addrs, &res->cap, sizeof(unsigned long),
10644 				res->cnt + 1);
10645 	if (err)
10646 		return err;
10647 
10648 	res->addrs[res->cnt++] = (unsigned long) sym_addr;
10649 	return 0;
10650 }
10651 
10652 struct bpf_link *
10653 bpf_program__attach_kprobe_multi_opts(const struct bpf_program *prog,
10654 				      const char *pattern,
10655 				      const struct bpf_kprobe_multi_opts *opts)
10656 {
10657 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
10658 	struct kprobe_multi_resolve res = {
10659 		.pattern = pattern,
10660 	};
10661 	struct bpf_link *link = NULL;
10662 	char errmsg[STRERR_BUFSIZE];
10663 	const unsigned long *addrs;
10664 	int err, link_fd, prog_fd;
10665 	const __u64 *cookies;
10666 	const char **syms;
10667 	bool retprobe;
10668 	size_t cnt;
10669 
10670 	if (!OPTS_VALID(opts, bpf_kprobe_multi_opts))
10671 		return libbpf_err_ptr(-EINVAL);
10672 
10673 	syms    = OPTS_GET(opts, syms, false);
10674 	addrs   = OPTS_GET(opts, addrs, false);
10675 	cnt     = OPTS_GET(opts, cnt, false);
10676 	cookies = OPTS_GET(opts, cookies, false);
10677 
10678 	if (!pattern && !addrs && !syms)
10679 		return libbpf_err_ptr(-EINVAL);
10680 	if (pattern && (addrs || syms || cookies || cnt))
10681 		return libbpf_err_ptr(-EINVAL);
10682 	if (!pattern && !cnt)
10683 		return libbpf_err_ptr(-EINVAL);
10684 	if (addrs && syms)
10685 		return libbpf_err_ptr(-EINVAL);
10686 
10687 	if (pattern) {
10688 		err = libbpf_kallsyms_parse(resolve_kprobe_multi_cb, &res);
10689 		if (err)
10690 			goto error;
10691 		if (!res.cnt) {
10692 			err = -ENOENT;
10693 			goto error;
10694 		}
10695 		addrs = res.addrs;
10696 		cnt = res.cnt;
10697 	}
10698 
10699 	retprobe = OPTS_GET(opts, retprobe, false);
10700 
10701 	lopts.kprobe_multi.syms = syms;
10702 	lopts.kprobe_multi.addrs = addrs;
10703 	lopts.kprobe_multi.cookies = cookies;
10704 	lopts.kprobe_multi.cnt = cnt;
10705 	lopts.kprobe_multi.flags = retprobe ? BPF_F_KPROBE_MULTI_RETURN : 0;
10706 
10707 	link = calloc(1, sizeof(*link));
10708 	if (!link) {
10709 		err = -ENOMEM;
10710 		goto error;
10711 	}
10712 	link->detach = &bpf_link__detach_fd;
10713 
10714 	prog_fd = bpf_program__fd(prog);
10715 	link_fd = bpf_link_create(prog_fd, 0, BPF_TRACE_KPROBE_MULTI, &lopts);
10716 	if (link_fd < 0) {
10717 		err = -errno;
10718 		pr_warn("prog '%s': failed to attach: %s\n",
10719 			prog->name, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10720 		goto error;
10721 	}
10722 	link->fd = link_fd;
10723 	free(res.addrs);
10724 	return link;
10725 
10726 error:
10727 	free(link);
10728 	free(res.addrs);
10729 	return libbpf_err_ptr(err);
10730 }
10731 
10732 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10733 {
10734 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
10735 	unsigned long offset = 0;
10736 	const char *func_name;
10737 	char *func;
10738 	int n;
10739 
10740 	*link = NULL;
10741 
10742 	/* no auto-attach for SEC("kprobe") and SEC("kretprobe") */
10743 	if (strcmp(prog->sec_name, "kprobe") == 0 || strcmp(prog->sec_name, "kretprobe") == 0)
10744 		return 0;
10745 
10746 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
10747 	if (opts.retprobe)
10748 		func_name = prog->sec_name + sizeof("kretprobe/") - 1;
10749 	else
10750 		func_name = prog->sec_name + sizeof("kprobe/") - 1;
10751 
10752 	n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
10753 	if (n < 1) {
10754 		pr_warn("kprobe name is invalid: %s\n", func_name);
10755 		return -EINVAL;
10756 	}
10757 	if (opts.retprobe && offset != 0) {
10758 		free(func);
10759 		pr_warn("kretprobes do not support offset specification\n");
10760 		return -EINVAL;
10761 	}
10762 
10763 	opts.offset = offset;
10764 	*link = bpf_program__attach_kprobe_opts(prog, func, &opts);
10765 	free(func);
10766 	return libbpf_get_error(*link);
10767 }
10768 
10769 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10770 {
10771 	LIBBPF_OPTS(bpf_ksyscall_opts, opts);
10772 	const char *syscall_name;
10773 
10774 	*link = NULL;
10775 
10776 	/* no auto-attach for SEC("ksyscall") and SEC("kretsyscall") */
10777 	if (strcmp(prog->sec_name, "ksyscall") == 0 || strcmp(prog->sec_name, "kretsyscall") == 0)
10778 		return 0;
10779 
10780 	opts.retprobe = str_has_pfx(prog->sec_name, "kretsyscall/");
10781 	if (opts.retprobe)
10782 		syscall_name = prog->sec_name + sizeof("kretsyscall/") - 1;
10783 	else
10784 		syscall_name = prog->sec_name + sizeof("ksyscall/") - 1;
10785 
10786 	*link = bpf_program__attach_ksyscall(prog, syscall_name, &opts);
10787 	return *link ? 0 : -errno;
10788 }
10789 
10790 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10791 {
10792 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts);
10793 	const char *spec;
10794 	char *pattern;
10795 	int n;
10796 
10797 	*link = NULL;
10798 
10799 	/* no auto-attach for SEC("kprobe.multi") and SEC("kretprobe.multi") */
10800 	if (strcmp(prog->sec_name, "kprobe.multi") == 0 ||
10801 	    strcmp(prog->sec_name, "kretprobe.multi") == 0)
10802 		return 0;
10803 
10804 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe.multi/");
10805 	if (opts.retprobe)
10806 		spec = prog->sec_name + sizeof("kretprobe.multi/") - 1;
10807 	else
10808 		spec = prog->sec_name + sizeof("kprobe.multi/") - 1;
10809 
10810 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
10811 	if (n < 1) {
10812 		pr_warn("kprobe multi pattern is invalid: %s\n", pattern);
10813 		return -EINVAL;
10814 	}
10815 
10816 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
10817 	free(pattern);
10818 	return libbpf_get_error(*link);
10819 }
10820 
10821 static void gen_uprobe_legacy_event_name(char *buf, size_t buf_sz,
10822 					 const char *binary_path, uint64_t offset)
10823 {
10824 	int i;
10825 
10826 	snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx", getpid(), binary_path, (size_t)offset);
10827 
10828 	/* sanitize binary_path in the probe name */
10829 	for (i = 0; buf[i]; i++) {
10830 		if (!isalnum(buf[i]))
10831 			buf[i] = '_';
10832 	}
10833 }
10834 
10835 static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
10836 					  const char *binary_path, size_t offset)
10837 {
10838 	return append_to_file(tracefs_uprobe_events(), "%c:%s/%s %s:0x%zx",
10839 			      retprobe ? 'r' : 'p',
10840 			      retprobe ? "uretprobes" : "uprobes",
10841 			      probe_name, binary_path, offset);
10842 }
10843 
10844 static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
10845 {
10846 	return append_to_file(tracefs_uprobe_events(), "-:%s/%s",
10847 			      retprobe ? "uretprobes" : "uprobes", probe_name);
10848 }
10849 
10850 static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
10851 {
10852 	char file[512];
10853 
10854 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
10855 		 tracefs_path(), retprobe ? "uretprobes" : "uprobes", probe_name);
10856 
10857 	return parse_uint_from_file(file, "%d\n");
10858 }
10859 
10860 static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
10861 					 const char *binary_path, size_t offset, int pid)
10862 {
10863 	const size_t attr_sz = sizeof(struct perf_event_attr);
10864 	struct perf_event_attr attr;
10865 	int type, pfd, err;
10866 
10867 	err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
10868 	if (err < 0) {
10869 		pr_warn("failed to add legacy uprobe event for %s:0x%zx: %d\n",
10870 			binary_path, (size_t)offset, err);
10871 		return err;
10872 	}
10873 	type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
10874 	if (type < 0) {
10875 		err = type;
10876 		pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %d\n",
10877 			binary_path, offset, err);
10878 		goto err_clean_legacy;
10879 	}
10880 
10881 	memset(&attr, 0, attr_sz);
10882 	attr.size = attr_sz;
10883 	attr.config = type;
10884 	attr.type = PERF_TYPE_TRACEPOINT;
10885 
10886 	pfd = syscall(__NR_perf_event_open, &attr,
10887 		      pid < 0 ? -1 : pid, /* pid */
10888 		      pid == -1 ? 0 : -1, /* cpu */
10889 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
10890 	if (pfd < 0) {
10891 		err = -errno;
10892 		pr_warn("legacy uprobe perf_event_open() failed: %d\n", err);
10893 		goto err_clean_legacy;
10894 	}
10895 	return pfd;
10896 
10897 err_clean_legacy:
10898 	/* Clear the newly added legacy uprobe_event */
10899 	remove_uprobe_event_legacy(probe_name, retprobe);
10900 	return err;
10901 }
10902 
10903 /* Return next ELF section of sh_type after scn, or first of that type if scn is NULL. */
10904 #ifdef  HAVE_LIBELF
10905 static Elf_Scn *elf_find_next_scn_by_type(Elf *elf, int sh_type, Elf_Scn *scn)
10906 {
10907 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
10908 		GElf_Shdr sh;
10909 
10910 		if (!gelf_getshdr(scn, &sh))
10911 			continue;
10912 		if (sh.sh_type == sh_type)
10913 			return scn;
10914 	}
10915 	return NULL;
10916 }
10917 #elif HAVE_ELFIO
10918 static psection_t elf_find_next_scn_by_type(pelfio_t pelfio, int sh_type, psection_t pscn)
10919 {
10920     int secno = elfio_get_sections_num(pelfio);
10921     int j = 0;
10922     if (pscn != NULL) {
10923         for (int i = 0; i < secno; i++) {
10924             psection_t psection = elfio_get_section_by_index(pelfio, i);
10925             if (psection == pscn) {
10926                 j = i;
10927             }
10928         }
10929     }
10930     for (; j < secno; j++) {
10931         psection_t psection = elfio_get_section_by_index(pelfio, j);
10932         Elf_Word sec_type = elfio_section_get_type(psection);
10933         if (sec_type == sh_type) {
10934             return psection;
10935         }
10936     }
10937     return NULL;
10938 }
10939 #endif
10940 
10941 /* Find offset of function name in object specified by path.  "name" matches
10942  * symbol name or name@@LIB for library functions.
10943  */
10944 static long elf_find_func_offset(const char *binary_path, const char *name)
10945 {
10946 	int fd, i, sh_types[2] = { SHT_DYNSYM, SHT_SYMTAB };
10947 	bool is_shared_lib, is_name_qualified;
10948 	char errmsg[STRERR_BUFSIZE];
10949 	long ret = -ENOENT;
10950 	size_t name_len;
10951 #ifdef  HAVE_LIBELF
10952 	GElf_Ehdr ehdr;
10953 	Elf *elf;
10954 #elif HAVE_ELFIO
10955 	pelfio_t pelfio = elfio_new();
10956 	bool is_load = elfio_load(pelfio, binary_path);
10957 #endif  //
10958 #ifdef  HAVE_LIBELF
10959 	fd = open(binary_path, O_RDONLY | O_CLOEXEC);
10960 	if (fd < 0) {
10961 #elif HAVE_ELFIO
10962 	if (!is_load) {
10963 #endif  //
10964 		ret = -errno;
10965 		pr_warn("failed to open %s: %s\n", binary_path,
10966 			libbpf_strerror_r(ret, errmsg, sizeof(errmsg)));
10967 		return ret;
10968 	}
10969 #ifdef  HAVE_LIBELF
10970 	elf = elf_begin(fd, ELF_C_READ_MMAP, NULL);
10971 	if (!elf) {
10972 		pr_warn("elf: could not read elf from %s: %s\n", binary_path, elf_errmsg(-1));
10973 		close(fd);
10974 		return -LIBBPF_ERRNO__FORMAT;
10975 	}
10976 	if (!gelf_getehdr(elf, &ehdr)) {
10977 		pr_warn("elf: failed to get ehdr from %s: %s\n", binary_path, elf_errmsg(-1));
10978 		ret = -LIBBPF_ERRNO__FORMAT;
10979 		goto out;
10980 	}
10981 	/* for shared lib case, we do not need to calculate relative offset */
10982 	is_shared_lib = ehdr.e_type == ET_DYN;
10983 #elif HAVA_ELFIO
10984 	is_shared_lib = (ET_DYN == elfio_get_type(pelfio));
10985 #endif  //HAVE_LIBELF
10986 
10987 	name_len = strlen(name);
10988 	/* Does name specify "@@LIB"? */
10989 	is_name_qualified = strstr(name, "@@") != NULL;
10990 
10991 	/* Search SHT_DYNSYM, SHT_SYMTAB for symbol.  This search order is used because if
10992 	 * a binary is stripped, it may only have SHT_DYNSYM, and a fully-statically
10993 	 * linked binary may not have SHT_DYMSYM, so absence of a section should not be
10994 	 * reported as a warning/error.
10995 	 */
10996 	for (i = 0; i < ARRAY_SIZE(sh_types); i++) {
10997 		size_t nr_syms, strtabidx, idx;
10998 #ifdef  HAVE_LIBELF
10999 		Elf_Data *symbols = NULL;
11000 		Elf_Scn *scn = NULL;
11001 		GElf_Shdr sh;
11002 #elif HAVE_ELFIO
11003 		Elf_Data realData = {};
11004 		psection_t pSec = NULL;
11005 #endif  //HAVE_LIBELF
11006 		int last_bind = -1;
11007 		const char *sname;
11008 #ifdef  HAVE_LIBELF
11009 		scn = elf_find_next_scn_by_type(elf, sh_types[i], NULL);
11010 #elif HAVE_ELFIO
11011 		pSec = elf_find_next_scn_by_type(pelfio, sh_types[i], NULL);
11012 #endif  //HAVE_LIBELF
11013 #ifdef  HAVE_LIBELF
11014 		if (!scn) {
11015 #elif HAVE_ELFIO
11016 		if (!pSec) {
11017 #endif  //HAVE_LIBELF
11018 			pr_debug("elf: failed to find symbol table ELF sections in '%s'\n",
11019 				 binary_path);
11020 			continue;
11021 		}
11022 #ifdef  HAVE_LIBELF
11023 		if (!gelf_getshdr(scn, &sh))
11024 			continue;
11025 		strtabidx = sh.sh_link;
11026 #elif HAVE_ELFIO
11027 		strtabidx = elfio_section_get_link(pSec);
11028 #endif  //
11029 #ifdef  HAVE_LIBELF
11030 		symbols = elf_getdata(scn, 0);
11031 		if (!symbols) {
11032 			pr_warn("elf: failed to get symbols for symtab section in '%s': %s\n",
11033 				binary_path, elf_errmsg(-1));
11034 			ret = -LIBBPF_ERRNO__FORMAT;
11035 			goto out;
11036 		}
11037 		nr_syms = symbols->d_size / sh.sh_entsize;
11038 #elif HAVE_ELFIO
11039 		realData.d_buf = (void*)elfio_section_get_data(pSec);
11040 		realData.d_size = elfio_section_get_size(pSec);
11041 		if (!realData.d_buf) {
11042 			pr_warn("elf: failed to get symbols for symtab section in '%s': %s\n",
11043 				binary_path, elf_errmsg(-1));
11044 			ret = -LIBBPF_ERRNO__FORMAT;
11045 			goto out;
11046 		}
11047 		nr_syms = realData.d_size / elfio_section_get_entry_size(pSec);
11048 		psymbol_t  psymbols;
11049 		psymbols = elfio_symbol_section_accessor_new(pelfio, pSec);
11050 		if (!psymbols) {
11051 			pr_warn("elf: failed to get symbols in '%s': %s\n",
11052 				binary_path, elf_errmsg(-1));
11053 			ret = -LIBBPF_ERRNO__FORMAT;
11054 			goto out;
11055 		}
11056 #endif  //HAVE_LIBELF
11057 		for (idx = 0; idx < nr_syms; idx++) {
11058 			int curr_bind;
11059 #ifdef  HAVE_LIBELF
11060 			GElf_Sym sym;
11061 			Elf_Scn *sym_scn;
11062 			GElf_Shdr sym_sh;
11063 
11064 			if (!gelf_getsym(symbols, idx, &sym))
11065 				continue;
11066 
11067 			if (GELF_ST_TYPE(sym.st_info) != STT_FUNC)
11068 				continue;
11069 
11070 			sname = elf_strptr(elf, strtabidx, sym.st_name);
11071 			if (!sname)
11072 				continue;
11073 
11074 			curr_bind = GELF_ST_BIND(sym.st_info);
11075 #elif HAVE_ELFIO
11076 			char          sname[128] = {0};
11077         	Elf64_Addr    st_value;
11078         	Elf_Xword     size;
11079         	unsigned char bind;
11080         	unsigned char type;
11081         	Elf_Half      section_index;
11082         	unsigned char other;
11083         	elfio_symbol_get_symbol( psymbols, idx, sname, 128, &st_value, &size, &bind,
11084                                  &type, &section_index, &other );
11085 			if (type == STT_FUNC)
11086 				continue;
11087 			if (sname[0] == '\0')
11088 				continue;
11089 			curr_bind = bind;
11090 #endif  //HAVE_LIBELF
11091 
11092 
11093 			/* User can specify func, func@@LIB or func@@LIB_VERSION. */
11094 			if (strncmp(sname, name, name_len) != 0)
11095 				continue;
11096 			/* ...but we don't want a search for "foo" to match 'foo2" also, so any
11097 			 * additional characters in sname should be of the form "@@LIB".
11098 			 */
11099 			if (!is_name_qualified && sname[name_len] != '\0' && sname[name_len] != '@')
11100 				continue;
11101 
11102 			if (ret >= 0) {
11103 				/* handle multiple matches */
11104 				if (last_bind != STB_WEAK && curr_bind != STB_WEAK) {
11105 					/* Only accept one non-weak bind. */
11106 					pr_warn("elf: ambiguous match for '%s', '%s' in '%s'\n",
11107 						sname, name, binary_path);
11108 					ret = -LIBBPF_ERRNO__FORMAT;
11109 					goto out;
11110 				} else if (curr_bind == STB_WEAK) {
11111 					/* already have a non-weak bind, and
11112 					 * this is a weak bind, so ignore.
11113 					 */
11114 					continue;
11115 				}
11116 			}
11117 
11118 			/* Transform symbol's virtual address (absolute for
11119 			 * binaries and relative for shared libs) into file
11120 			 * offset, which is what kernel is expecting for
11121 			 * uprobe/uretprobe attachment.
11122 			 * See Documentation/trace/uprobetracer.rst for more
11123 			 * details.
11124 			 * This is done by looking up symbol's containing
11125 			 * section's header and using it's virtual address
11126 			 * (sh_addr) and corresponding file offset (sh_offset)
11127 			 * to transform sym.st_value (virtual address) into
11128 			 * desired final file offset.
11129 			 */
11130 #ifdef  HAVE_LIBELF
11131 			sym_scn = elf_getscn(elf, sym.st_shndx);
11132 			if (!sym_scn)
11133 				continue;
11134 			if (!gelf_getshdr(sym_scn, &sym_sh))
11135 				continue;
11136 			ret = sym.st_value - sym_sh.sh_addr + sym_sh.sh_offset;
11137 #elif HAVE_ELFIO
11138 			psection_t pSymSection= NULL;
11139 			pSymSection = elfio_get_section_by_index(pelfio,section_index);
11140 			if (!pSymSection)
11141 				continue;
11142 			Elf64_Addr sh_addr = elfio_section_get_address(pSymSection);
11143 			Elf64_Off sh_offset = elfio_section_get_offset(pSymSection);
11144 			ret = st_value - sh_addr + sh_offset;
11145 #endif  //HAVE_LIBELF
11146 			last_bind = curr_bind;
11147 		}
11148 #ifdef  HAVE_ELFIO
11149 		elfio_symbol_section_accessor_delete(psymbols);
11150 #endif  //HAVE_ELFIO
11151 		if (ret > 0)
11152 			break;
11153 	}
11154 
11155 	if (ret > 0) {
11156 		pr_debug("elf: symbol address match for '%s' in '%s': 0x%lx\n", name, binary_path,
11157 			 ret);
11158 	} else {
11159 		if (ret == 0) {
11160 			pr_warn("elf: '%s' is 0 in symtab for '%s': %s\n", name, binary_path,
11161 				is_shared_lib ? "should not be 0 in a shared library" :
11162 						"try using shared library path instead");
11163 			ret = -ENOENT;
11164 		} else {
11165 			pr_warn("elf: failed to find symbol '%s' in '%s'\n", name, binary_path);
11166 		}
11167 	}
11168 out:
11169 #ifdef  HAVE_LIBELF
11170 	elf_end(elf);
11171 	close(fd);
11172 #elif HAVE_ELFIO
11173 	elfio_delete(pelfio);
11174 #endif  //HAVE_LIBELF
11175 	return ret;
11176 }
11177 
11178 
11179 
11180 static const char *arch_specific_lib_paths(void)
11181 {
11182 	/*
11183 	 * Based on https://packages.debian.org/sid/libc6.
11184 	 *
11185 	 * Assume that the traced program is built for the same architecture
11186 	 * as libbpf, which should cover the vast majority of cases.
11187 	 */
11188 #if defined(__x86_64__)
11189 	return "/lib/x86_64-linux-gnu";
11190 #elif defined(__i386__)
11191 	return "/lib/i386-linux-gnu";
11192 #elif defined(__s390x__)
11193 	return "/lib/s390x-linux-gnu";
11194 #elif defined(__s390__)
11195 	return "/lib/s390-linux-gnu";
11196 #elif defined(__arm__) && defined(__SOFTFP__)
11197 	return "/lib/arm-linux-gnueabi";
11198 #elif defined(__arm__) && !defined(__SOFTFP__)
11199 	return "/lib/arm-linux-gnueabihf";
11200 #elif defined(__aarch64__)
11201 	return "/lib/aarch64-linux-gnu";
11202 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 64
11203 	return "/lib/mips64el-linux-gnuabi64";
11204 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 32
11205 	return "/lib/mipsel-linux-gnu";
11206 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
11207 	return "/lib/powerpc64le-linux-gnu";
11208 #elif defined(__sparc__) && defined(__arch64__)
11209 	return "/lib/sparc64-linux-gnu";
11210 #elif defined(__riscv) && __riscv_xlen == 64
11211 	return "/lib/riscv64-linux-gnu";
11212 #else
11213 	return NULL;
11214 #endif
11215 }
11216 
11217 /* Get full path to program/shared library. */
11218 static int resolve_full_path(const char *file, char *result, size_t result_sz)
11219 {
11220 	const char *search_paths[3] = {};
11221 	int i, perm;
11222 
11223 	if (str_has_sfx(file, ".so") || strstr(file, ".so.")) {
11224 		search_paths[0] = getenv("LD_LIBRARY_PATH");
11225 		search_paths[1] = "/usr/lib64:/usr/lib";
11226 		search_paths[2] = arch_specific_lib_paths();
11227 		perm = R_OK;
11228 	} else {
11229 		search_paths[0] = getenv("PATH");
11230 		search_paths[1] = "/usr/bin:/usr/sbin";
11231 		perm = R_OK | X_OK;
11232 	}
11233 
11234 	for (i = 0; i < ARRAY_SIZE(search_paths); i++) {
11235 		const char *s;
11236 
11237 		if (!search_paths[i])
11238 			continue;
11239 		for (s = search_paths[i]; s != NULL; s = strchr(s, ':')) {
11240 			char *next_path;
11241 			int seg_len;
11242 
11243 			if (s[0] == ':')
11244 				s++;
11245 			next_path = strchr(s, ':');
11246 			seg_len = next_path ? next_path - s : strlen(s);
11247 			if (!seg_len)
11248 				continue;
11249 			snprintf(result, result_sz, "%.*s/%s", seg_len, s, file);
11250 			/* ensure it has required permissions */
11251 			if (faccessat(AT_FDCWD, result, perm, AT_EACCESS) < 0)
11252 				continue;
11253 			pr_debug("resolved '%s' to '%s'\n", file, result);
11254 			return 0;
11255 		}
11256 	}
11257 	return -ENOENT;
11258 }
11259 
11260 LIBBPF_API struct bpf_link *
11261 bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
11262 				const char *binary_path, size_t func_offset,
11263 				const struct bpf_uprobe_opts *opts)
11264 {
11265 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11266 	char errmsg[STRERR_BUFSIZE], *legacy_probe = NULL;
11267 	char full_binary_path[PATH_MAX];
11268 	struct bpf_link *link;
11269 	size_t ref_ctr_off;
11270 	int pfd, err;
11271 	bool retprobe, legacy;
11272 	const char *func_name;
11273 
11274 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
11275 		return libbpf_err_ptr(-EINVAL);
11276 
11277 	retprobe = OPTS_GET(opts, retprobe, false);
11278 	ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
11279 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11280 
11281 	if (!binary_path)
11282 		return libbpf_err_ptr(-EINVAL);
11283 
11284 	if (!strchr(binary_path, '/')) {
11285 		err = resolve_full_path(binary_path, full_binary_path,
11286 					sizeof(full_binary_path));
11287 		if (err) {
11288 			pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11289 				prog->name, binary_path, err);
11290 			return libbpf_err_ptr(err);
11291 		}
11292 		binary_path = full_binary_path;
11293 	}
11294 	func_name = OPTS_GET(opts, func_name, NULL);
11295 	if (func_name) {
11296 		long sym_off;
11297 
11298 		sym_off = elf_find_func_offset(binary_path, func_name);
11299 		if (sym_off < 0)
11300 			return libbpf_err_ptr(sym_off);
11301 		func_offset += sym_off;
11302 	}
11303 
11304 	legacy = determine_uprobe_perf_type() < 0;
11305 	if (!legacy) {
11306 		pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
11307 					    func_offset, pid, ref_ctr_off);
11308 	} else {
11309 		char probe_name[PATH_MAX + 64];
11310 
11311 		if (ref_ctr_off)
11312 			return libbpf_err_ptr(-EINVAL);
11313 
11314 		gen_uprobe_legacy_event_name(probe_name, sizeof(probe_name),
11315 					     binary_path, func_offset);
11316 
11317 		legacy_probe = strdup(probe_name);
11318 		if (!legacy_probe)
11319 			return libbpf_err_ptr(-ENOMEM);
11320 
11321 		pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
11322 						    binary_path, func_offset, pid);
11323 	}
11324 	if (pfd < 0) {
11325 		err = -errno;
11326 		pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
11327 			prog->name, retprobe ? "uretprobe" : "uprobe",
11328 			binary_path, func_offset,
11329 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11330 		goto err_out;
11331 	}
11332 
11333 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11334 	err = libbpf_get_error(link);
11335 	if (err) {
11336 		close(pfd);
11337 		pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
11338 			prog->name, retprobe ? "uretprobe" : "uprobe",
11339 			binary_path, func_offset,
11340 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11341 		goto err_clean_legacy;
11342 	}
11343 	if (legacy) {
11344 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
11345 
11346 		perf_link->legacy_probe_name = legacy_probe;
11347 		perf_link->legacy_is_kprobe = false;
11348 		perf_link->legacy_is_retprobe = retprobe;
11349 	}
11350 	return link;
11351 
11352 err_clean_legacy:
11353 	if (legacy)
11354 		remove_uprobe_event_legacy(legacy_probe, retprobe);
11355 err_out:
11356 	free(legacy_probe);
11357 	return libbpf_err_ptr(err);
11358 }
11359 
11360 /* Format of u[ret]probe section definition supporting auto-attach:
11361  * u[ret]probe/binary:function[+offset]
11362  *
11363  * binary can be an absolute/relative path or a filename; the latter is resolved to a
11364  * full binary path via bpf_program__attach_uprobe_opts.
11365  *
11366  * Specifying uprobe+ ensures we carry out strict matching; either "uprobe" must be
11367  * specified (and auto-attach is not possible) or the above format is specified for
11368  * auto-attach.
11369  */
11370 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11371 {
11372 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts);
11373 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
11374 	int n, ret = -EINVAL;
11375 	long offset = 0;
11376 
11377 	*link = NULL;
11378 
11379 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[a-zA-Z0-9_.]+%li",
11380 		   &probe_type, &binary_path, &func_name, &offset);
11381 	switch (n) {
11382 	case 1:
11383 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
11384 		ret = 0;
11385 		break;
11386 	case 2:
11387 		pr_warn("prog '%s': section '%s' missing ':function[+offset]' specification\n",
11388 			prog->name, prog->sec_name);
11389 		break;
11390 	case 3:
11391 	case 4:
11392 		opts.retprobe = strcmp(probe_type, "uretprobe") == 0 ||
11393 				strcmp(probe_type, "uretprobe.s") == 0;
11394 		if (opts.retprobe && offset != 0) {
11395 			pr_warn("prog '%s': uretprobes do not support offset specification\n",
11396 				prog->name);
11397 			break;
11398 		}
11399 		opts.func_name = func_name;
11400 		*link = bpf_program__attach_uprobe_opts(prog, -1, binary_path, offset, &opts);
11401 		ret = libbpf_get_error(*link);
11402 		break;
11403 	default:
11404 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
11405 			prog->sec_name);
11406 		break;
11407 	}
11408 	free(probe_type);
11409 	free(binary_path);
11410 	free(func_name);
11411 
11412 	return ret;
11413 }
11414 
11415 struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
11416 					    bool retprobe, pid_t pid,
11417 					    const char *binary_path,
11418 					    size_t func_offset)
11419 {
11420 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
11421 
11422 	return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
11423 }
11424 
11425 #ifdef  HAVE_LIBELF
11426 struct bpf_link *bpf_program__attach_usdt(const struct bpf_program *prog,
11427 					  pid_t pid, const char *binary_path,
11428 					  const char *usdt_provider, const char *usdt_name,
11429 					  const struct bpf_usdt_opts *opts)
11430 {
11431 	char resolved_path[512];
11432 	struct bpf_object *obj = prog->obj;
11433 	struct bpf_link *link;
11434 	__u64 usdt_cookie;
11435 	int err;
11436 
11437 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
11438 		return libbpf_err_ptr(-EINVAL);
11439 
11440 	if (bpf_program__fd(prog) < 0) {
11441 		pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
11442 			prog->name);
11443 		return libbpf_err_ptr(-EINVAL);
11444 	}
11445 
11446 	if (!binary_path)
11447 		return libbpf_err_ptr(-EINVAL);
11448 
11449 	if (!strchr(binary_path, '/')) {
11450 		err = resolve_full_path(binary_path, resolved_path, sizeof(resolved_path));
11451 		if (err) {
11452 			pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11453 				prog->name, binary_path, err);
11454 			return libbpf_err_ptr(err);
11455 		}
11456 		binary_path = resolved_path;
11457 	}
11458 
11459 	/* USDT manager is instantiated lazily on first USDT attach. It will
11460 	 * be destroyed together with BPF object in bpf_object__close().
11461 	 */
11462 	if (IS_ERR(obj->usdt_man))
11463 		return libbpf_ptr(obj->usdt_man);
11464 	if (!obj->usdt_man) {
11465 		obj->usdt_man = usdt_manager_new(obj);
11466 		if (IS_ERR(obj->usdt_man))
11467 			return libbpf_ptr(obj->usdt_man);
11468 	}
11469 
11470 	usdt_cookie = OPTS_GET(opts, usdt_cookie, 0);
11471 	link = usdt_manager_attach_usdt(obj->usdt_man, prog, pid, binary_path,
11472 					usdt_provider, usdt_name, usdt_cookie);
11473 	err = libbpf_get_error(link);
11474 	if (err)
11475 		return libbpf_err_ptr(err);
11476 	return link;
11477 }
11478 #endif  //HAVE_LIBELF
11479 
11480 #ifdef  HAVE_LIBELF
11481 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11482 {
11483 	char *path = NULL, *provider = NULL, *name = NULL;
11484 	const char *sec_name;
11485 	int n, err;
11486 
11487 	sec_name = bpf_program__section_name(prog);
11488 	if (strcmp(sec_name, "usdt") == 0) {
11489 		/* no auto-attach for just SEC("usdt") */
11490 		*link = NULL;
11491 		return 0;
11492 	}
11493 
11494 	n = sscanf(sec_name, "usdt/%m[^:]:%m[^:]:%m[^:]", &path, &provider, &name);
11495 	if (n != 3) {
11496 		pr_warn("invalid section '%s', expected SEC(\"usdt/<path>:<provider>:<name>\")\n",
11497 			sec_name);
11498 		err = -EINVAL;
11499 	} else {
11500 		*link = bpf_program__attach_usdt(prog, -1 /* any process */, path,
11501 						 provider, name, NULL);
11502 		err = libbpf_get_error(*link);
11503 	}
11504 	free(path);
11505 	free(provider);
11506 	free(name);
11507 	return err;
11508 }
11509 #endif  //HAVE_LIBELF
11510 
11511 static int determine_tracepoint_id(const char *tp_category,
11512 				   const char *tp_name)
11513 {
11514 	char file[PATH_MAX];
11515 	int ret;
11516 
11517 	ret = snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11518 		       tracefs_path(), tp_category, tp_name);
11519 	if (ret < 0)
11520 		return -errno;
11521 	if (ret >= sizeof(file)) {
11522 		pr_debug("tracepoint %s/%s path is too long\n",
11523 			 tp_category, tp_name);
11524 		return -E2BIG;
11525 	}
11526 	return parse_uint_from_file(file, "%d\n");
11527 }
11528 
11529 static int perf_event_open_tracepoint(const char *tp_category,
11530 				      const char *tp_name)
11531 {
11532 	const size_t attr_sz = sizeof(struct perf_event_attr);
11533 	struct perf_event_attr attr;
11534 	char errmsg[STRERR_BUFSIZE];
11535 	int tp_id, pfd, err;
11536 
11537 	tp_id = determine_tracepoint_id(tp_category, tp_name);
11538 	if (tp_id < 0) {
11539 		pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
11540 			tp_category, tp_name,
11541 			libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
11542 		return tp_id;
11543 	}
11544 
11545 	memset(&attr, 0, attr_sz);
11546 	attr.type = PERF_TYPE_TRACEPOINT;
11547 	attr.size = attr_sz;
11548 	attr.config = tp_id;
11549 
11550 	pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
11551 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
11552 	if (pfd < 0) {
11553 		err = -errno;
11554 		pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
11555 			tp_category, tp_name,
11556 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11557 		return err;
11558 	}
11559 	return pfd;
11560 }
11561 
11562 struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
11563 						     const char *tp_category,
11564 						     const char *tp_name,
11565 						     const struct bpf_tracepoint_opts *opts)
11566 {
11567 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11568 	char errmsg[STRERR_BUFSIZE];
11569 	struct bpf_link *link;
11570 	int pfd, err;
11571 
11572 	if (!OPTS_VALID(opts, bpf_tracepoint_opts))
11573 		return libbpf_err_ptr(-EINVAL);
11574 
11575 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11576 
11577 	pfd = perf_event_open_tracepoint(tp_category, tp_name);
11578 	if (pfd < 0) {
11579 		pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
11580 			prog->name, tp_category, tp_name,
11581 			libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11582 		return libbpf_err_ptr(pfd);
11583 	}
11584 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11585 	err = libbpf_get_error(link);
11586 	if (err) {
11587 		close(pfd);
11588 		pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
11589 			prog->name, tp_category, tp_name,
11590 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11591 		return libbpf_err_ptr(err);
11592 	}
11593 	return link;
11594 }
11595 
11596 struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
11597 						const char *tp_category,
11598 						const char *tp_name)
11599 {
11600 	return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
11601 }
11602 
11603 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11604 {
11605 	char *sec_name, *tp_cat, *tp_name;
11606 
11607 	*link = NULL;
11608 
11609 	/* no auto-attach for SEC("tp") or SEC("tracepoint") */
11610 	if (strcmp(prog->sec_name, "tp") == 0 || strcmp(prog->sec_name, "tracepoint") == 0)
11611 		return 0;
11612 
11613 	sec_name = strdup(prog->sec_name);
11614 	if (!sec_name)
11615 		return -ENOMEM;
11616 
11617 	/* extract "tp/<category>/<name>" or "tracepoint/<category>/<name>" */
11618 	if (str_has_pfx(prog->sec_name, "tp/"))
11619 		tp_cat = sec_name + sizeof("tp/") - 1;
11620 	else
11621 		tp_cat = sec_name + sizeof("tracepoint/") - 1;
11622 	tp_name = strchr(tp_cat, '/');
11623 	if (!tp_name) {
11624 		free(sec_name);
11625 		return -EINVAL;
11626 	}
11627 	*tp_name = '\0';
11628 	tp_name++;
11629 
11630 	*link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
11631 	free(sec_name);
11632 	return libbpf_get_error(*link);
11633 }
11634 
11635 struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
11636 						    const char *tp_name)
11637 {
11638 	char errmsg[STRERR_BUFSIZE];
11639 	struct bpf_link *link;
11640 	int prog_fd, pfd;
11641 
11642 	prog_fd = bpf_program__fd(prog);
11643 	if (prog_fd < 0) {
11644 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11645 		return libbpf_err_ptr(-EINVAL);
11646 	}
11647 
11648 	link = calloc(1, sizeof(*link));
11649 	if (!link)
11650 		return libbpf_err_ptr(-ENOMEM);
11651 	link->detach = &bpf_link__detach_fd;
11652 
11653 	pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
11654 	if (pfd < 0) {
11655 		pfd = -errno;
11656 		free(link);
11657 		pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
11658 			prog->name, tp_name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11659 		return libbpf_err_ptr(pfd);
11660 	}
11661 	link->fd = pfd;
11662 	return link;
11663 }
11664 
11665 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11666 {
11667 	static const char *const prefixes[] = {
11668 		"raw_tp",
11669 		"raw_tracepoint",
11670 		"raw_tp.w",
11671 		"raw_tracepoint.w",
11672 	};
11673 	size_t i;
11674 	const char *tp_name = NULL;
11675 
11676 	*link = NULL;
11677 
11678 	for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
11679 		size_t pfx_len;
11680 
11681 		if (!str_has_pfx(prog->sec_name, prefixes[i]))
11682 			continue;
11683 
11684 		pfx_len = strlen(prefixes[i]);
11685 		/* no auto-attach case of, e.g., SEC("raw_tp") */
11686 		if (prog->sec_name[pfx_len] == '\0')
11687 			return 0;
11688 
11689 		if (prog->sec_name[pfx_len] != '/')
11690 			continue;
11691 
11692 		tp_name = prog->sec_name + pfx_len + 1;
11693 		break;
11694 	}
11695 
11696 	if (!tp_name) {
11697 		pr_warn("prog '%s': invalid section name '%s'\n",
11698 			prog->name, prog->sec_name);
11699 		return -EINVAL;
11700 	}
11701 
11702 	*link = bpf_program__attach_raw_tracepoint(prog, tp_name);
11703 	return libbpf_get_error(*link);
11704 }
11705 
11706 /* Common logic for all BPF program types that attach to a btf_id */
11707 static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog,
11708 						   const struct bpf_trace_opts *opts)
11709 {
11710 	LIBBPF_OPTS(bpf_link_create_opts, link_opts);
11711 	char errmsg[STRERR_BUFSIZE];
11712 	struct bpf_link *link;
11713 	int prog_fd, pfd;
11714 
11715 	if (!OPTS_VALID(opts, bpf_trace_opts))
11716 		return libbpf_err_ptr(-EINVAL);
11717 
11718 	prog_fd = bpf_program__fd(prog);
11719 	if (prog_fd < 0) {
11720 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11721 		return libbpf_err_ptr(-EINVAL);
11722 	}
11723 
11724 	link = calloc(1, sizeof(*link));
11725 	if (!link)
11726 		return libbpf_err_ptr(-ENOMEM);
11727 	link->detach = &bpf_link__detach_fd;
11728 
11729 	/* libbpf is smart enough to redirect to BPF_RAW_TRACEPOINT_OPEN on old kernels */
11730 	link_opts.tracing.cookie = OPTS_GET(opts, cookie, 0);
11731 	pfd = bpf_link_create(prog_fd, 0, bpf_program__expected_attach_type(prog), &link_opts);
11732 	if (pfd < 0) {
11733 		pfd = -errno;
11734 		free(link);
11735 		pr_warn("prog '%s': failed to attach: %s\n",
11736 			prog->name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11737 		return libbpf_err_ptr(pfd);
11738 	}
11739 	link->fd = pfd;
11740 	return link;
11741 }
11742 
11743 struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
11744 {
11745 	return bpf_program__attach_btf_id(prog, NULL);
11746 }
11747 
11748 struct bpf_link *bpf_program__attach_trace_opts(const struct bpf_program *prog,
11749 						const struct bpf_trace_opts *opts)
11750 {
11751 	return bpf_program__attach_btf_id(prog, opts);
11752 }
11753 
11754 struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
11755 {
11756 	return bpf_program__attach_btf_id(prog, NULL);
11757 }
11758 
11759 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11760 {
11761 	*link = bpf_program__attach_trace(prog);
11762 	return libbpf_get_error(*link);
11763 }
11764 
11765 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11766 {
11767 	*link = bpf_program__attach_lsm(prog);
11768 	return libbpf_get_error(*link);
11769 }
11770 
11771 static struct bpf_link *
11772 bpf_program__attach_fd(const struct bpf_program *prog, int target_fd, int btf_id,
11773 		       const char *target_name)
11774 {
11775 	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, opts,
11776 			    .target_btf_id = btf_id);
11777 	enum bpf_attach_type attach_type;
11778 	char errmsg[STRERR_BUFSIZE];
11779 	struct bpf_link *link;
11780 	int prog_fd, link_fd;
11781 
11782 	prog_fd = bpf_program__fd(prog);
11783 	if (prog_fd < 0) {
11784 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11785 		return libbpf_err_ptr(-EINVAL);
11786 	}
11787 
11788 	link = calloc(1, sizeof(*link));
11789 	if (!link)
11790 		return libbpf_err_ptr(-ENOMEM);
11791 	link->detach = &bpf_link__detach_fd;
11792 
11793 	attach_type = bpf_program__expected_attach_type(prog);
11794 	link_fd = bpf_link_create(prog_fd, target_fd, attach_type, &opts);
11795 	if (link_fd < 0) {
11796 		link_fd = -errno;
11797 		free(link);
11798 		pr_warn("prog '%s': failed to attach to %s: %s\n",
11799 			prog->name, target_name,
11800 			libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
11801 		return libbpf_err_ptr(link_fd);
11802 	}
11803 	link->fd = link_fd;
11804 	return link;
11805 }
11806 
11807 struct bpf_link *
11808 bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
11809 {
11810 	return bpf_program__attach_fd(prog, cgroup_fd, 0, "cgroup");
11811 }
11812 
11813 struct bpf_link *
11814 bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
11815 {
11816 	return bpf_program__attach_fd(prog, netns_fd, 0, "netns");
11817 }
11818 
11819 struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
11820 {
11821 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
11822 	return bpf_program__attach_fd(prog, ifindex, 0, "xdp");
11823 }
11824 
11825 struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
11826 					      int target_fd,
11827 					      const char *attach_func_name)
11828 {
11829 	int btf_id;
11830 
11831 	if (!!target_fd != !!attach_func_name) {
11832 		pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
11833 			prog->name);
11834 		return libbpf_err_ptr(-EINVAL);
11835 	}
11836 
11837 	if (prog->type != BPF_PROG_TYPE_EXT) {
11838 		pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace",
11839 			prog->name);
11840 		return libbpf_err_ptr(-EINVAL);
11841 	}
11842 
11843 	if (target_fd) {
11844 		btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd);
11845 		if (btf_id < 0)
11846 			return libbpf_err_ptr(btf_id);
11847 
11848 		return bpf_program__attach_fd(prog, target_fd, btf_id, "freplace");
11849 	} else {
11850 		/* no target, so use raw_tracepoint_open for compatibility
11851 		 * with old kernels
11852 		 */
11853 		return bpf_program__attach_trace(prog);
11854 	}
11855 }
11856 
11857 struct bpf_link *
11858 bpf_program__attach_iter(const struct bpf_program *prog,
11859 			 const struct bpf_iter_attach_opts *opts)
11860 {
11861 	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
11862 	char errmsg[STRERR_BUFSIZE];
11863 	struct bpf_link *link;
11864 	int prog_fd, link_fd;
11865 	__u32 target_fd = 0;
11866 
11867 	if (!OPTS_VALID(opts, bpf_iter_attach_opts))
11868 		return libbpf_err_ptr(-EINVAL);
11869 
11870 	link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
11871 	link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
11872 
11873 	prog_fd = bpf_program__fd(prog);
11874 	if (prog_fd < 0) {
11875 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11876 		return libbpf_err_ptr(-EINVAL);
11877 	}
11878 
11879 	link = calloc(1, sizeof(*link));
11880 	if (!link)
11881 		return libbpf_err_ptr(-ENOMEM);
11882 	link->detach = &bpf_link__detach_fd;
11883 
11884 	link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
11885 				  &link_create_opts);
11886 	if (link_fd < 0) {
11887 		link_fd = -errno;
11888 		free(link);
11889 		pr_warn("prog '%s': failed to attach to iterator: %s\n",
11890 			prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
11891 		return libbpf_err_ptr(link_fd);
11892 	}
11893 	link->fd = link_fd;
11894 	return link;
11895 }
11896 
11897 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11898 {
11899 	*link = bpf_program__attach_iter(prog, NULL);
11900 	return libbpf_get_error(*link);
11901 }
11902 
11903 struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
11904 {
11905 	struct bpf_link *link = NULL;
11906 	int err;
11907 
11908 	if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
11909 		return libbpf_err_ptr(-EOPNOTSUPP);
11910 
11911 	err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, &link);
11912 	if (err)
11913 		return libbpf_err_ptr(err);
11914 
11915 	/* When calling bpf_program__attach() explicitly, auto-attach support
11916 	 * is expected to work, so NULL returned link is considered an error.
11917 	 * This is different for skeleton's attach, see comment in
11918 	 * bpf_object__attach_skeleton().
11919 	 */
11920 	if (!link)
11921 		return libbpf_err_ptr(-EOPNOTSUPP);
11922 
11923 	return link;
11924 }
11925 
11926 static int bpf_link__detach_struct_ops(struct bpf_link *link)
11927 {
11928 	__u32 zero = 0;
11929 
11930 	if (bpf_map_delete_elem(link->fd, &zero))
11931 		return -errno;
11932 
11933 	return 0;
11934 }
11935 
11936 struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
11937 {
11938 	struct bpf_struct_ops *st_ops;
11939 	struct bpf_link *link;
11940 	__u32 i, zero = 0;
11941 	int err;
11942 
11943 	if (!bpf_map__is_struct_ops(map) || map->fd == -1)
11944 		return libbpf_err_ptr(-EINVAL);
11945 
11946 	link = calloc(1, sizeof(*link));
11947 	if (!link)
11948 		return libbpf_err_ptr(-EINVAL);
11949 
11950 	st_ops = map->st_ops;
11951 	for (i = 0; i < btf_vlen(st_ops->type); i++) {
11952 		struct bpf_program *prog = st_ops->progs[i];
11953 		void *kern_data;
11954 		int prog_fd;
11955 
11956 		if (!prog)
11957 			continue;
11958 
11959 		prog_fd = bpf_program__fd(prog);
11960 		kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
11961 		*(unsigned long *)kern_data = prog_fd;
11962 	}
11963 
11964 	err = bpf_map_update_elem(map->fd, &zero, st_ops->kern_vdata, 0);
11965 	if (err) {
11966 		err = -errno;
11967 		free(link);
11968 		return libbpf_err_ptr(err);
11969 	}
11970 
11971 	link->detach = bpf_link__detach_struct_ops;
11972 	link->fd = map->fd;
11973 
11974 	return link;
11975 }
11976 
11977 typedef enum bpf_perf_event_ret (*bpf_perf_event_print_t)(struct perf_event_header *hdr,
11978 							  void *private_data);
11979 
11980 static enum bpf_perf_event_ret
11981 perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
11982 		       void **copy_mem, size_t *copy_size,
11983 		       bpf_perf_event_print_t fn, void *private_data)
11984 {
11985 	struct perf_event_mmap_page *header = mmap_mem;
11986 	__u64 data_head = ring_buffer_read_head(header);
11987 	__u64 data_tail = header->data_tail;
11988 	void *base = ((__u8 *)header) + page_size;
11989 	int ret = LIBBPF_PERF_EVENT_CONT;
11990 	struct perf_event_header *ehdr;
11991 	size_t ehdr_size;
11992 
11993 	while (data_head != data_tail) {
11994 		ehdr = base + (data_tail & (mmap_size - 1));
11995 		ehdr_size = ehdr->size;
11996 
11997 		if (((void *)ehdr) + ehdr_size > base + mmap_size) {
11998 			void *copy_start = ehdr;
11999 			size_t len_first = base + mmap_size - copy_start;
12000 			size_t len_secnd = ehdr_size - len_first;
12001 
12002 			if (*copy_size < ehdr_size) {
12003 				free(*copy_mem);
12004 				*copy_mem = malloc(ehdr_size);
12005 				if (!*copy_mem) {
12006 					*copy_size = 0;
12007 					ret = LIBBPF_PERF_EVENT_ERROR;
12008 					break;
12009 				}
12010 				*copy_size = ehdr_size;
12011 			}
12012 
12013 			memcpy(*copy_mem, copy_start, len_first);
12014 			memcpy(*copy_mem + len_first, base, len_secnd);
12015 			ehdr = *copy_mem;
12016 		}
12017 
12018 		ret = fn(ehdr, private_data);
12019 		data_tail += ehdr_size;
12020 		if (ret != LIBBPF_PERF_EVENT_CONT)
12021 			break;
12022 	}
12023 
12024 	ring_buffer_write_tail(header, data_tail);
12025 	return libbpf_err(ret);
12026 }
12027 
12028 struct perf_buffer;
12029 
12030 struct perf_buffer_params {
12031 	struct perf_event_attr *attr;
12032 	/* if event_cb is specified, it takes precendence */
12033 	perf_buffer_event_fn event_cb;
12034 	/* sample_cb and lost_cb are higher-level common-case callbacks */
12035 	perf_buffer_sample_fn sample_cb;
12036 	perf_buffer_lost_fn lost_cb;
12037 	void *ctx;
12038 	int cpu_cnt;
12039 	int *cpus;
12040 	int *map_keys;
12041 };
12042 
12043 struct perf_cpu_buf {
12044 	struct perf_buffer *pb;
12045 	void *base; /* mmap()'ed memory */
12046 	void *buf; /* for reconstructing segmented data */
12047 	size_t buf_size;
12048 	int fd;
12049 	int cpu;
12050 	int map_key;
12051 };
12052 
12053 struct perf_buffer {
12054 	perf_buffer_event_fn event_cb;
12055 	perf_buffer_sample_fn sample_cb;
12056 	perf_buffer_lost_fn lost_cb;
12057 	void *ctx; /* passed into callbacks */
12058 
12059 	size_t page_size;
12060 	size_t mmap_size;
12061 	struct perf_cpu_buf **cpu_bufs;
12062 	struct epoll_event *events;
12063 	int cpu_cnt; /* number of allocated CPU buffers */
12064 	int epoll_fd; /* perf event FD */
12065 	int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
12066 };
12067 
12068 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
12069 				      struct perf_cpu_buf *cpu_buf)
12070 {
12071 	if (!cpu_buf)
12072 		return;
12073 	if (cpu_buf->base &&
12074 	    munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
12075 		pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
12076 	if (cpu_buf->fd >= 0) {
12077 		ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
12078 		close(cpu_buf->fd);
12079 	}
12080 	free(cpu_buf->buf);
12081 	free(cpu_buf);
12082 }
12083 
12084 void perf_buffer__free(struct perf_buffer *pb)
12085 {
12086 	int i;
12087 
12088 	if (IS_ERR_OR_NULL(pb))
12089 		return;
12090 	if (pb->cpu_bufs) {
12091 		for (i = 0; i < pb->cpu_cnt; i++) {
12092 			struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
12093 
12094 			if (!cpu_buf)
12095 				continue;
12096 
12097 			bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
12098 			perf_buffer__free_cpu_buf(pb, cpu_buf);
12099 		}
12100 		free(pb->cpu_bufs);
12101 	}
12102 	if (pb->epoll_fd >= 0)
12103 		close(pb->epoll_fd);
12104 	free(pb->events);
12105 	free(pb);
12106 }
12107 
12108 static struct perf_cpu_buf *
12109 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
12110 			  int cpu, int map_key)
12111 {
12112 	struct perf_cpu_buf *cpu_buf;
12113 	char msg[STRERR_BUFSIZE];
12114 	int err;
12115 
12116 	cpu_buf = calloc(1, sizeof(*cpu_buf));
12117 	if (!cpu_buf)
12118 		return ERR_PTR(-ENOMEM);
12119 
12120 	cpu_buf->pb = pb;
12121 	cpu_buf->cpu = cpu;
12122 	cpu_buf->map_key = map_key;
12123 
12124 	cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
12125 			      -1, PERF_FLAG_FD_CLOEXEC);
12126 	if (cpu_buf->fd < 0) {
12127 		err = -errno;
12128 		pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
12129 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
12130 		goto error;
12131 	}
12132 
12133 	cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
12134 			     PROT_READ | PROT_WRITE, MAP_SHARED,
12135 			     cpu_buf->fd, 0);
12136 	if (cpu_buf->base == MAP_FAILED) {
12137 		cpu_buf->base = NULL;
12138 		err = -errno;
12139 		pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
12140 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
12141 		goto error;
12142 	}
12143 
12144 	if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
12145 		err = -errno;
12146 		pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
12147 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
12148 		goto error;
12149 	}
12150 
12151 	return cpu_buf;
12152 
12153 error:
12154 	perf_buffer__free_cpu_buf(pb, cpu_buf);
12155 	return (struct perf_cpu_buf *)ERR_PTR(err);
12156 }
12157 
12158 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
12159 					      struct perf_buffer_params *p);
12160 
12161 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
12162 				     perf_buffer_sample_fn sample_cb,
12163 				     perf_buffer_lost_fn lost_cb,
12164 				     void *ctx,
12165 				     const struct perf_buffer_opts *opts)
12166 {
12167 	const size_t attr_sz = sizeof(struct perf_event_attr);
12168 	struct perf_buffer_params p = {};
12169 	struct perf_event_attr attr;
12170 
12171 	if (!OPTS_VALID(opts, perf_buffer_opts))
12172 		return libbpf_err_ptr(-EINVAL);
12173 
12174 	memset(&attr, 0, attr_sz);
12175 	attr.size = attr_sz;
12176 	attr.config = PERF_COUNT_SW_BPF_OUTPUT;
12177 	attr.type = PERF_TYPE_SOFTWARE;
12178 	attr.sample_type = PERF_SAMPLE_RAW;
12179 	attr.sample_period = 1;
12180 	attr.wakeup_events = 1;
12181 
12182 	p.attr = &attr;
12183 	p.sample_cb = sample_cb;
12184 	p.lost_cb = lost_cb;
12185 	p.ctx = ctx;
12186 
12187 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
12188 }
12189 
12190 struct perf_buffer *perf_buffer__new_raw(int map_fd, size_t page_cnt,
12191 					 struct perf_event_attr *attr,
12192 					 perf_buffer_event_fn event_cb, void *ctx,
12193 					 const struct perf_buffer_raw_opts *opts)
12194 {
12195 	struct perf_buffer_params p = {};
12196 
12197 	if (!attr)
12198 		return libbpf_err_ptr(-EINVAL);
12199 
12200 	if (!OPTS_VALID(opts, perf_buffer_raw_opts))
12201 		return libbpf_err_ptr(-EINVAL);
12202 
12203 	p.attr = attr;
12204 	p.event_cb = event_cb;
12205 	p.ctx = ctx;
12206 	p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
12207 	p.cpus = OPTS_GET(opts, cpus, NULL);
12208 	p.map_keys = OPTS_GET(opts, map_keys, NULL);
12209 
12210 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
12211 }
12212 
12213 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
12214 					      struct perf_buffer_params *p)
12215 {
12216 	const char *online_cpus_file = "/sys/devices/system/cpu/online";
12217 	struct bpf_map_info map;
12218 	char msg[STRERR_BUFSIZE];
12219 	struct perf_buffer *pb;
12220 	bool *online = NULL;
12221 	__u32 map_info_len;
12222 	int err, i, j, n;
12223 
12224 	if (page_cnt == 0 || (page_cnt & (page_cnt - 1))) {
12225 		pr_warn("page count should be power of two, but is %zu\n",
12226 			page_cnt);
12227 		return ERR_PTR(-EINVAL);
12228 	}
12229 
12230 	/* best-effort sanity checks */
12231 	memset(&map, 0, sizeof(map));
12232 	map_info_len = sizeof(map);
12233 	err = bpf_obj_get_info_by_fd(map_fd, &map, &map_info_len);
12234 	if (err) {
12235 		err = -errno;
12236 		/* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
12237 		 * -EBADFD, -EFAULT, or -E2BIG on real error
12238 		 */
12239 		if (err != -EINVAL) {
12240 			pr_warn("failed to get map info for map FD %d: %s\n",
12241 				map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
12242 			return ERR_PTR(err);
12243 		}
12244 		pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
12245 			 map_fd);
12246 	} else {
12247 		if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
12248 			pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
12249 				map.name);
12250 			return ERR_PTR(-EINVAL);
12251 		}
12252 	}
12253 
12254 	pb = calloc(1, sizeof(*pb));
12255 	if (!pb)
12256 		return ERR_PTR(-ENOMEM);
12257 
12258 	pb->event_cb = p->event_cb;
12259 	pb->sample_cb = p->sample_cb;
12260 	pb->lost_cb = p->lost_cb;
12261 	pb->ctx = p->ctx;
12262 
12263 	pb->page_size = getpagesize();
12264 	pb->mmap_size = pb->page_size * page_cnt;
12265 	pb->map_fd = map_fd;
12266 
12267 	pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
12268 	if (pb->epoll_fd < 0) {
12269 		err = -errno;
12270 		pr_warn("failed to create epoll instance: %s\n",
12271 			libbpf_strerror_r(err, msg, sizeof(msg)));
12272 		goto error;
12273 	}
12274 
12275 	if (p->cpu_cnt > 0) {
12276 		pb->cpu_cnt = p->cpu_cnt;
12277 	} else {
12278 		pb->cpu_cnt = libbpf_num_possible_cpus();
12279 		if (pb->cpu_cnt < 0) {
12280 			err = pb->cpu_cnt;
12281 			goto error;
12282 		}
12283 		if (map.max_entries && map.max_entries < pb->cpu_cnt)
12284 			pb->cpu_cnt = map.max_entries;
12285 	}
12286 
12287 	pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
12288 	if (!pb->events) {
12289 		err = -ENOMEM;
12290 		pr_warn("failed to allocate events: out of memory\n");
12291 		goto error;
12292 	}
12293 	pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
12294 	if (!pb->cpu_bufs) {
12295 		err = -ENOMEM;
12296 		pr_warn("failed to allocate buffers: out of memory\n");
12297 		goto error;
12298 	}
12299 
12300 	err = parse_cpu_mask_file(online_cpus_file, &online, &n);
12301 	if (err) {
12302 		pr_warn("failed to get online CPU mask: %d\n", err);
12303 		goto error;
12304 	}
12305 
12306 	for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
12307 		struct perf_cpu_buf *cpu_buf;
12308 		int cpu, map_key;
12309 
12310 		cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
12311 		map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
12312 
12313 		/* in case user didn't explicitly requested particular CPUs to
12314 		 * be attached to, skip offline/not present CPUs
12315 		 */
12316 		if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
12317 			continue;
12318 
12319 		cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
12320 		if (IS_ERR(cpu_buf)) {
12321 			err = PTR_ERR(cpu_buf);
12322 			goto error;
12323 		}
12324 
12325 		pb->cpu_bufs[j] = cpu_buf;
12326 
12327 		err = bpf_map_update_elem(pb->map_fd, &map_key,
12328 					  &cpu_buf->fd, 0);
12329 		if (err) {
12330 			err = -errno;
12331 			pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
12332 				cpu, map_key, cpu_buf->fd,
12333 				libbpf_strerror_r(err, msg, sizeof(msg)));
12334 			goto error;
12335 		}
12336 
12337 		pb->events[j].events = EPOLLIN;
12338 		pb->events[j].data.ptr = cpu_buf;
12339 		if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
12340 			      &pb->events[j]) < 0) {
12341 			err = -errno;
12342 			pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
12343 				cpu, cpu_buf->fd,
12344 				libbpf_strerror_r(err, msg, sizeof(msg)));
12345 			goto error;
12346 		}
12347 		j++;
12348 	}
12349 	pb->cpu_cnt = j;
12350 	free(online);
12351 
12352 	return pb;
12353 
12354 error:
12355 	free(online);
12356 	if (pb)
12357 		perf_buffer__free(pb);
12358 	return ERR_PTR(err);
12359 }
12360 
12361 struct perf_sample_raw {
12362 	struct perf_event_header header;
12363 	uint32_t size;
12364 	char data[];
12365 };
12366 
12367 struct perf_sample_lost {
12368 	struct perf_event_header header;
12369 	uint64_t id;
12370 	uint64_t lost;
12371 	uint64_t sample_id;
12372 };
12373 
12374 static enum bpf_perf_event_ret
12375 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
12376 {
12377 	struct perf_cpu_buf *cpu_buf = ctx;
12378 	struct perf_buffer *pb = cpu_buf->pb;
12379 	void *data = e;
12380 
12381 	/* user wants full control over parsing perf event */
12382 	if (pb->event_cb)
12383 		return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
12384 
12385 	switch (e->type) {
12386 	case PERF_RECORD_SAMPLE: {
12387 		struct perf_sample_raw *s = data;
12388 
12389 		if (pb->sample_cb)
12390 			pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
12391 		break;
12392 	}
12393 	case PERF_RECORD_LOST: {
12394 		struct perf_sample_lost *s = data;
12395 
12396 		if (pb->lost_cb)
12397 			pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
12398 		break;
12399 	}
12400 	default:
12401 		pr_warn("unknown perf sample type %d\n", e->type);
12402 		return LIBBPF_PERF_EVENT_ERROR;
12403 	}
12404 	return LIBBPF_PERF_EVENT_CONT;
12405 }
12406 
12407 static int perf_buffer__process_records(struct perf_buffer *pb,
12408 					struct perf_cpu_buf *cpu_buf)
12409 {
12410 	enum bpf_perf_event_ret ret;
12411 
12412 	ret = perf_event_read_simple(cpu_buf->base, pb->mmap_size,
12413 				     pb->page_size, &cpu_buf->buf,
12414 				     &cpu_buf->buf_size,
12415 				     perf_buffer__process_record, cpu_buf);
12416 	if (ret != LIBBPF_PERF_EVENT_CONT)
12417 		return ret;
12418 	return 0;
12419 }
12420 
12421 int perf_buffer__epoll_fd(const struct perf_buffer *pb)
12422 {
12423 	return pb->epoll_fd;
12424 }
12425 
12426 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
12427 {
12428 	int i, cnt, err;
12429 
12430 	cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
12431 	if (cnt < 0)
12432 		return -errno;
12433 
12434 	for (i = 0; i < cnt; i++) {
12435 		struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
12436 
12437 		err = perf_buffer__process_records(pb, cpu_buf);
12438 		if (err) {
12439 			pr_warn("error while processing records: %d\n", err);
12440 			return libbpf_err(err);
12441 		}
12442 	}
12443 	return cnt;
12444 }
12445 
12446 /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
12447  * manager.
12448  */
12449 size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
12450 {
12451 	return pb->cpu_cnt;
12452 }
12453 
12454 /*
12455  * Return perf_event FD of a ring buffer in *buf_idx* slot of
12456  * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
12457  * select()/poll()/epoll() Linux syscalls.
12458  */
12459 int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
12460 {
12461 	struct perf_cpu_buf *cpu_buf;
12462 
12463 	if (buf_idx >= pb->cpu_cnt)
12464 		return libbpf_err(-EINVAL);
12465 
12466 	cpu_buf = pb->cpu_bufs[buf_idx];
12467 	if (!cpu_buf)
12468 		return libbpf_err(-ENOENT);
12469 
12470 	return cpu_buf->fd;
12471 }
12472 
12473 int perf_buffer__buffer(struct perf_buffer *pb, int buf_idx, void **buf, size_t *buf_size)
12474 {
12475 	struct perf_cpu_buf *cpu_buf;
12476 
12477 	if (buf_idx >= pb->cpu_cnt)
12478 		return libbpf_err(-EINVAL);
12479 
12480 	cpu_buf = pb->cpu_bufs[buf_idx];
12481 	if (!cpu_buf)
12482 		return libbpf_err(-ENOENT);
12483 
12484 	*buf = cpu_buf->base;
12485 	*buf_size = pb->mmap_size;
12486 	return 0;
12487 }
12488 
12489 /*
12490  * Consume data from perf ring buffer corresponding to slot *buf_idx* in
12491  * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
12492  * consume, do nothing and return success.
12493  * Returns:
12494  *   - 0 on success;
12495  *   - <0 on failure.
12496  */
12497 int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
12498 {
12499 	struct perf_cpu_buf *cpu_buf;
12500 
12501 	if (buf_idx >= pb->cpu_cnt)
12502 		return libbpf_err(-EINVAL);
12503 
12504 	cpu_buf = pb->cpu_bufs[buf_idx];
12505 	if (!cpu_buf)
12506 		return libbpf_err(-ENOENT);
12507 
12508 	return perf_buffer__process_records(pb, cpu_buf);
12509 }
12510 
12511 int perf_buffer__consume(struct perf_buffer *pb)
12512 {
12513 	int i, err;
12514 
12515 	for (i = 0; i < pb->cpu_cnt; i++) {
12516 		struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
12517 
12518 		if (!cpu_buf)
12519 			continue;
12520 
12521 		err = perf_buffer__process_records(pb, cpu_buf);
12522 		if (err) {
12523 			pr_warn("perf_buffer: failed to process records in buffer #%d: %d\n", i, err);
12524 			return libbpf_err(err);
12525 		}
12526 	}
12527 	return 0;
12528 }
12529 
12530 int bpf_program__set_attach_target(struct bpf_program *prog,
12531 				   int attach_prog_fd,
12532 				   const char *attach_func_name)
12533 {
12534 	int btf_obj_fd = 0, btf_id = 0, err;
12535 
12536 	if (!prog || attach_prog_fd < 0)
12537 		return libbpf_err(-EINVAL);
12538 
12539 	if (prog->obj->loaded)
12540 		return libbpf_err(-EINVAL);
12541 
12542 	if (attach_prog_fd && !attach_func_name) {
12543 		/* remember attach_prog_fd and let bpf_program__load() find
12544 		 * BTF ID during the program load
12545 		 */
12546 		prog->attach_prog_fd = attach_prog_fd;
12547 		return 0;
12548 	}
12549 
12550 	if (attach_prog_fd) {
12551 		btf_id = libbpf_find_prog_btf_id(attach_func_name,
12552 						 attach_prog_fd);
12553 		if (btf_id < 0)
12554 			return libbpf_err(btf_id);
12555 	} else {
12556 		if (!attach_func_name)
12557 			return libbpf_err(-EINVAL);
12558 
12559 		/* load btf_vmlinux, if not yet */
12560 		err = bpf_object__load_vmlinux_btf(prog->obj, true);
12561 		if (err)
12562 			return libbpf_err(err);
12563 		err = find_kernel_btf_id(prog->obj, attach_func_name,
12564 					 prog->expected_attach_type,
12565 					 &btf_obj_fd, &btf_id);
12566 		if (err)
12567 			return libbpf_err(err);
12568 	}
12569 
12570 	prog->attach_btf_id = btf_id;
12571 	prog->attach_btf_obj_fd = btf_obj_fd;
12572 	prog->attach_prog_fd = attach_prog_fd;
12573 	return 0;
12574 }
12575 
12576 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
12577 {
12578 	int err = 0, n, len, start, end = -1;
12579 	bool *tmp;
12580 
12581 	*mask = NULL;
12582 	*mask_sz = 0;
12583 
12584 	/* Each sub string separated by ',' has format \d+-\d+ or \d+ */
12585 	while (*s) {
12586 		if (*s == ',' || *s == '\n') {
12587 			s++;
12588 			continue;
12589 		}
12590 		n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
12591 		if (n <= 0 || n > 2) {
12592 			pr_warn("Failed to get CPU range %s: %d\n", s, n);
12593 			err = -EINVAL;
12594 			goto cleanup;
12595 		} else if (n == 1) {
12596 			end = start;
12597 		}
12598 		if (start < 0 || start > end) {
12599 			pr_warn("Invalid CPU range [%d,%d] in %s\n",
12600 				start, end, s);
12601 			err = -EINVAL;
12602 			goto cleanup;
12603 		}
12604 		tmp = realloc(*mask, end + 1);
12605 		if (!tmp) {
12606 			err = -ENOMEM;
12607 			goto cleanup;
12608 		}
12609 		*mask = tmp;
12610 		memset(tmp + *mask_sz, 0, start - *mask_sz);
12611 		memset(tmp + start, 1, end - start + 1);
12612 		*mask_sz = end + 1;
12613 		s += len;
12614 	}
12615 	if (!*mask_sz) {
12616 		pr_warn("Empty CPU range\n");
12617 		return -EINVAL;
12618 	}
12619 	return 0;
12620 cleanup:
12621 	free(*mask);
12622 	*mask = NULL;
12623 	return err;
12624 }
12625 
12626 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
12627 {
12628 	int fd, err = 0, len;
12629 	char buf[128];
12630 
12631 	fd = open(fcpu, O_RDONLY | O_CLOEXEC);
12632 	if (fd < 0) {
12633 		err = -errno;
12634 		pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
12635 		return err;
12636 	}
12637 	len = read(fd, buf, sizeof(buf));
12638 	close(fd);
12639 	if (len <= 0) {
12640 		err = len ? -errno : -EINVAL;
12641 		pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
12642 		return err;
12643 	}
12644 	if (len >= sizeof(buf)) {
12645 		pr_warn("CPU mask is too big in file %s\n", fcpu);
12646 		return -E2BIG;
12647 	}
12648 	buf[len] = '\0';
12649 
12650 	return parse_cpu_mask_str(buf, mask, mask_sz);
12651 }
12652 
12653 int libbpf_num_possible_cpus(void)
12654 {
12655 	static const char *fcpu = "/sys/devices/system/cpu/possible";
12656 	static int cpus;
12657 	int err, n, i, tmp_cpus;
12658 	bool *mask;
12659 
12660 	tmp_cpus = READ_ONCE(cpus);
12661 	if (tmp_cpus > 0)
12662 		return tmp_cpus;
12663 
12664 	err = parse_cpu_mask_file(fcpu, &mask, &n);
12665 	if (err)
12666 		return libbpf_err(err);
12667 
12668 	tmp_cpus = 0;
12669 	for (i = 0; i < n; i++) {
12670 		if (mask[i])
12671 			tmp_cpus++;
12672 	}
12673 	free(mask);
12674 
12675 	WRITE_ONCE(cpus, tmp_cpus);
12676 	return tmp_cpus;
12677 }
12678 
12679 static int populate_skeleton_maps(const struct bpf_object *obj,
12680 				  struct bpf_map_skeleton *maps,
12681 				  size_t map_cnt)
12682 {
12683 	int i;
12684 
12685 	for (i = 0; i < map_cnt; i++) {
12686 		struct bpf_map **map = maps[i].map;
12687 		const char *name = maps[i].name;
12688 		void **mmaped = maps[i].mmaped;
12689 
12690 		*map = bpf_object__find_map_by_name(obj, name);
12691 		if (!*map) {
12692 			pr_warn("failed to find skeleton map '%s'\n", name);
12693 			return -ESRCH;
12694 		}
12695 
12696 		/* externs shouldn't be pre-setup from user code */
12697 		if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
12698 			*mmaped = (*map)->mmaped;
12699 	}
12700 	return 0;
12701 }
12702 
12703 static int populate_skeleton_progs(const struct bpf_object *obj,
12704 				   struct bpf_prog_skeleton *progs,
12705 				   size_t prog_cnt)
12706 {
12707 	int i;
12708 
12709 	for (i = 0; i < prog_cnt; i++) {
12710 		struct bpf_program **prog = progs[i].prog;
12711 		const char *name = progs[i].name;
12712 
12713 		*prog = bpf_object__find_program_by_name(obj, name);
12714 		if (!*prog) {
12715 			pr_warn("failed to find skeleton program '%s'\n", name);
12716 			return -ESRCH;
12717 		}
12718 	}
12719 	return 0;
12720 }
12721 
12722 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
12723 			      const struct bpf_object_open_opts *opts)
12724 {
12725 	DECLARE_LIBBPF_OPTS(bpf_object_open_opts, skel_opts,
12726 		.object_name = s->name,
12727 	);
12728 	struct bpf_object *obj;
12729 	int err;
12730 
12731 	/* Attempt to preserve opts->object_name, unless overriden by user
12732 	 * explicitly. Overwriting object name for skeletons is discouraged,
12733 	 * as it breaks global data maps, because they contain object name
12734 	 * prefix as their own map name prefix. When skeleton is generated,
12735 	 * bpftool is making an assumption that this name will stay the same.
12736 	 */
12737 	if (opts) {
12738 		memcpy(&skel_opts, opts, sizeof(*opts));
12739 		if (!opts->object_name)
12740 			skel_opts.object_name = s->name;
12741 	}
12742 
12743 	obj = bpf_object__open_mem(s->data, s->data_sz, &skel_opts);
12744 	err = libbpf_get_error(obj);
12745 	if (err) {
12746 		pr_warn("failed to initialize skeleton BPF object '%s': %d\n",
12747 			s->name, err);
12748 		return libbpf_err(err);
12749 	}
12750 
12751 	*s->obj = obj;
12752 	err = populate_skeleton_maps(obj, s->maps, s->map_cnt);
12753 	if (err) {
12754 		pr_warn("failed to populate skeleton maps for '%s': %d\n", s->name, err);
12755 		return libbpf_err(err);
12756 	}
12757 
12758 	err = populate_skeleton_progs(obj, s->progs, s->prog_cnt);
12759 	if (err) {
12760 		pr_warn("failed to populate skeleton progs for '%s': %d\n", s->name, err);
12761 		return libbpf_err(err);
12762 	}
12763 
12764 	return 0;
12765 }
12766 
12767 int bpf_object__open_subskeleton(struct bpf_object_subskeleton *s)
12768 {
12769 	int err, len, var_idx, i;
12770 	const char *var_name;
12771 	const struct bpf_map *map;
12772 	struct btf *btf;
12773 	__u32 map_type_id;
12774 	const struct btf_type *map_type, *var_type;
12775 	const struct bpf_var_skeleton *var_skel;
12776 	struct btf_var_secinfo *var;
12777 
12778 	if (!s->obj)
12779 		return libbpf_err(-EINVAL);
12780 
12781 	btf = bpf_object__btf(s->obj);
12782 	if (!btf) {
12783 		pr_warn("subskeletons require BTF at runtime (object %s)\n",
12784 			bpf_object__name(s->obj));
12785 		return libbpf_err(-errno);
12786 	}
12787 
12788 	err = populate_skeleton_maps(s->obj, s->maps, s->map_cnt);
12789 	if (err) {
12790 		pr_warn("failed to populate subskeleton maps: %d\n", err);
12791 		return libbpf_err(err);
12792 	}
12793 
12794 	err = populate_skeleton_progs(s->obj, s->progs, s->prog_cnt);
12795 	if (err) {
12796 		pr_warn("failed to populate subskeleton maps: %d\n", err);
12797 		return libbpf_err(err);
12798 	}
12799 
12800 	for (var_idx = 0; var_idx < s->var_cnt; var_idx++) {
12801 		var_skel = &s->vars[var_idx];
12802 		map = *var_skel->map;
12803 		map_type_id = bpf_map__btf_value_type_id(map);
12804 		map_type = btf__type_by_id(btf, map_type_id);
12805 
12806 		if (!btf_is_datasec(map_type)) {
12807 			pr_warn("type for map '%1$s' is not a datasec: %2$s",
12808 				bpf_map__name(map),
12809 				__btf_kind_str(btf_kind(map_type)));
12810 			return libbpf_err(-EINVAL);
12811 		}
12812 
12813 		len = btf_vlen(map_type);
12814 		var = btf_var_secinfos(map_type);
12815 		for (i = 0; i < len; i++, var++) {
12816 			var_type = btf__type_by_id(btf, var->type);
12817 			var_name = btf__name_by_offset(btf, var_type->name_off);
12818 			if (strcmp(var_name, var_skel->name) == 0) {
12819 				*var_skel->addr = map->mmaped + var->offset;
12820 				break;
12821 			}
12822 		}
12823 	}
12824 	return 0;
12825 }
12826 
12827 void bpf_object__destroy_subskeleton(struct bpf_object_subskeleton *s)
12828 {
12829 	if (!s)
12830 		return;
12831 	free(s->maps);
12832 	free(s->progs);
12833 	free(s->vars);
12834 	free(s);
12835 }
12836 
12837 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
12838 {
12839 	int i, err;
12840 
12841 	err = bpf_object__load(*s->obj);
12842 	if (err) {
12843 		pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
12844 		return libbpf_err(err);
12845 	}
12846 
12847 	for (i = 0; i < s->map_cnt; i++) {
12848 		struct bpf_map *map = *s->maps[i].map;
12849 		size_t mmap_sz = bpf_map_mmap_sz(map);
12850 		int prot, map_fd = bpf_map__fd(map);
12851 		void **mmaped = s->maps[i].mmaped;
12852 
12853 		if (!mmaped)
12854 			continue;
12855 
12856 		if (!(map->def.map_flags & BPF_F_MMAPABLE)) {
12857 			*mmaped = NULL;
12858 			continue;
12859 		}
12860 
12861 		if (map->def.map_flags & BPF_F_RDONLY_PROG)
12862 			prot = PROT_READ;
12863 		else
12864 			prot = PROT_READ | PROT_WRITE;
12865 
12866 		/* Remap anonymous mmap()-ed "map initialization image" as
12867 		 * a BPF map-backed mmap()-ed memory, but preserving the same
12868 		 * memory address. This will cause kernel to change process'
12869 		 * page table to point to a different piece of kernel memory,
12870 		 * but from userspace point of view memory address (and its
12871 		 * contents, being identical at this point) will stay the
12872 		 * same. This mapping will be released by bpf_object__close()
12873 		 * as per normal clean up procedure, so we don't need to worry
12874 		 * about it from skeleton's clean up perspective.
12875 		 */
12876 		*mmaped = mmap(map->mmaped, mmap_sz, prot,
12877 				MAP_SHARED | MAP_FIXED, map_fd, 0);
12878 		if (*mmaped == MAP_FAILED) {
12879 			err = -errno;
12880 			*mmaped = NULL;
12881 			pr_warn("failed to re-mmap() map '%s': %d\n",
12882 				 bpf_map__name(map), err);
12883 			return libbpf_err(err);
12884 		}
12885 	}
12886 
12887 	return 0;
12888 }
12889 
12890 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
12891 {
12892 	int i, err;
12893 
12894 	for (i = 0; i < s->prog_cnt; i++) {
12895 		struct bpf_program *prog = *s->progs[i].prog;
12896 		struct bpf_link **link = s->progs[i].link;
12897 
12898 		if (!prog->autoload || !prog->autoattach)
12899 			continue;
12900 
12901 		/* auto-attaching not supported for this program */
12902 		if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
12903 			continue;
12904 
12905 		/* if user already set the link manually, don't attempt auto-attach */
12906 		if (*link)
12907 			continue;
12908 
12909 		err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, link);
12910 		if (err) {
12911 			pr_warn("prog '%s': failed to auto-attach: %d\n",
12912 				bpf_program__name(prog), err);
12913 			return libbpf_err(err);
12914 		}
12915 
12916 		/* It's possible that for some SEC() definitions auto-attach
12917 		 * is supported in some cases (e.g., if definition completely
12918 		 * specifies target information), but is not in other cases.
12919 		 * SEC("uprobe") is one such case. If user specified target
12920 		 * binary and function name, such BPF program can be
12921 		 * auto-attached. But if not, it shouldn't trigger skeleton's
12922 		 * attach to fail. It should just be skipped.
12923 		 * attach_fn signals such case with returning 0 (no error) and
12924 		 * setting link to NULL.
12925 		 */
12926 	}
12927 
12928 	return 0;
12929 }
12930 
12931 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
12932 {
12933 	int i;
12934 
12935 	for (i = 0; i < s->prog_cnt; i++) {
12936 		struct bpf_link **link = s->progs[i].link;
12937 
12938 		bpf_link__destroy(*link);
12939 		*link = NULL;
12940 	}
12941 }
12942 
12943 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
12944 {
12945 	if (!s)
12946 		return;
12947 
12948 	if (s->progs)
12949 		bpf_object__detach_skeleton(s);
12950 	if (s->obj)
12951 		bpf_object__close(*s->obj);
12952 	free(s->maps);
12953 	free(s->progs);
12954 	free(s);
12955 }
12956