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