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