xref: /linux/tools/lib/bpf/libbpf.c (revision 1ba5ad36e00f46e3f7676f5de6b87f5a2f57f1f1)
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/list.h>
35 #include <linux/limits.h>
36 #include <linux/perf_event.h>
37 #include <linux/ring_buffer.h>
38 #include <linux/version.h>
39 #include <sys/epoll.h>
40 #include <sys/ioctl.h>
41 #include <sys/mman.h>
42 #include <sys/stat.h>
43 #include <sys/types.h>
44 #include <sys/vfs.h>
45 #include <sys/utsname.h>
46 #include <sys/resource.h>
47 #include <libelf.h>
48 #include <gelf.h>
49 #include <zlib.h>
50 
51 #include "libbpf.h"
52 #include "bpf.h"
53 #include "btf.h"
54 #include "str_error.h"
55 #include "libbpf_internal.h"
56 #include "hashmap.h"
57 #include "bpf_gen_internal.h"
58 
59 #ifndef BPF_FS_MAGIC
60 #define BPF_FS_MAGIC		0xcafe4a11
61 #endif
62 
63 #define BPF_INSN_SZ (sizeof(struct bpf_insn))
64 
65 /* vsprintf() in __base_pr() uses nonliteral format string. It may break
66  * compilation if user enables corresponding warning. Disable it explicitly.
67  */
68 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
69 
70 #define __printf(a, b)	__attribute__((format(printf, a, b)))
71 
72 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj);
73 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog);
74 
75 static const char * const attach_type_name[] = {
76 	[BPF_CGROUP_INET_INGRESS]	= "cgroup_inet_ingress",
77 	[BPF_CGROUP_INET_EGRESS]	= "cgroup_inet_egress",
78 	[BPF_CGROUP_INET_SOCK_CREATE]	= "cgroup_inet_sock_create",
79 	[BPF_CGROUP_INET_SOCK_RELEASE]	= "cgroup_inet_sock_release",
80 	[BPF_CGROUP_SOCK_OPS]		= "cgroup_sock_ops",
81 	[BPF_CGROUP_DEVICE]		= "cgroup_device",
82 	[BPF_CGROUP_INET4_BIND]		= "cgroup_inet4_bind",
83 	[BPF_CGROUP_INET6_BIND]		= "cgroup_inet6_bind",
84 	[BPF_CGROUP_INET4_CONNECT]	= "cgroup_inet4_connect",
85 	[BPF_CGROUP_INET6_CONNECT]	= "cgroup_inet6_connect",
86 	[BPF_CGROUP_INET4_POST_BIND]	= "cgroup_inet4_post_bind",
87 	[BPF_CGROUP_INET6_POST_BIND]	= "cgroup_inet6_post_bind",
88 	[BPF_CGROUP_INET4_GETPEERNAME]	= "cgroup_inet4_getpeername",
89 	[BPF_CGROUP_INET6_GETPEERNAME]	= "cgroup_inet6_getpeername",
90 	[BPF_CGROUP_INET4_GETSOCKNAME]	= "cgroup_inet4_getsockname",
91 	[BPF_CGROUP_INET6_GETSOCKNAME]	= "cgroup_inet6_getsockname",
92 	[BPF_CGROUP_UDP4_SENDMSG]	= "cgroup_udp4_sendmsg",
93 	[BPF_CGROUP_UDP6_SENDMSG]	= "cgroup_udp6_sendmsg",
94 	[BPF_CGROUP_SYSCTL]		= "cgroup_sysctl",
95 	[BPF_CGROUP_UDP4_RECVMSG]	= "cgroup_udp4_recvmsg",
96 	[BPF_CGROUP_UDP6_RECVMSG]	= "cgroup_udp6_recvmsg",
97 	[BPF_CGROUP_GETSOCKOPT]		= "cgroup_getsockopt",
98 	[BPF_CGROUP_SETSOCKOPT]		= "cgroup_setsockopt",
99 	[BPF_SK_SKB_STREAM_PARSER]	= "sk_skb_stream_parser",
100 	[BPF_SK_SKB_STREAM_VERDICT]	= "sk_skb_stream_verdict",
101 	[BPF_SK_SKB_VERDICT]		= "sk_skb_verdict",
102 	[BPF_SK_MSG_VERDICT]		= "sk_msg_verdict",
103 	[BPF_LIRC_MODE2]		= "lirc_mode2",
104 	[BPF_FLOW_DISSECTOR]		= "flow_dissector",
105 	[BPF_TRACE_RAW_TP]		= "trace_raw_tp",
106 	[BPF_TRACE_FENTRY]		= "trace_fentry",
107 	[BPF_TRACE_FEXIT]		= "trace_fexit",
108 	[BPF_MODIFY_RETURN]		= "modify_return",
109 	[BPF_LSM_MAC]			= "lsm_mac",
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 map_type_name[] = {
122 	[BPF_MAP_TYPE_UNSPEC]			= "unspec",
123 	[BPF_MAP_TYPE_HASH]			= "hash",
124 	[BPF_MAP_TYPE_ARRAY]			= "array",
125 	[BPF_MAP_TYPE_PROG_ARRAY]		= "prog_array",
126 	[BPF_MAP_TYPE_PERF_EVENT_ARRAY]		= "perf_event_array",
127 	[BPF_MAP_TYPE_PERCPU_HASH]		= "percpu_hash",
128 	[BPF_MAP_TYPE_PERCPU_ARRAY]		= "percpu_array",
129 	[BPF_MAP_TYPE_STACK_TRACE]		= "stack_trace",
130 	[BPF_MAP_TYPE_CGROUP_ARRAY]		= "cgroup_array",
131 	[BPF_MAP_TYPE_LRU_HASH]			= "lru_hash",
132 	[BPF_MAP_TYPE_LRU_PERCPU_HASH]		= "lru_percpu_hash",
133 	[BPF_MAP_TYPE_LPM_TRIE]			= "lpm_trie",
134 	[BPF_MAP_TYPE_ARRAY_OF_MAPS]		= "array_of_maps",
135 	[BPF_MAP_TYPE_HASH_OF_MAPS]		= "hash_of_maps",
136 	[BPF_MAP_TYPE_DEVMAP]			= "devmap",
137 	[BPF_MAP_TYPE_DEVMAP_HASH]		= "devmap_hash",
138 	[BPF_MAP_TYPE_SOCKMAP]			= "sockmap",
139 	[BPF_MAP_TYPE_CPUMAP]			= "cpumap",
140 	[BPF_MAP_TYPE_XSKMAP]			= "xskmap",
141 	[BPF_MAP_TYPE_SOCKHASH]			= "sockhash",
142 	[BPF_MAP_TYPE_CGROUP_STORAGE]		= "cgroup_storage",
143 	[BPF_MAP_TYPE_REUSEPORT_SOCKARRAY]	= "reuseport_sockarray",
144 	[BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE]	= "percpu_cgroup_storage",
145 	[BPF_MAP_TYPE_QUEUE]			= "queue",
146 	[BPF_MAP_TYPE_STACK]			= "stack",
147 	[BPF_MAP_TYPE_SK_STORAGE]		= "sk_storage",
148 	[BPF_MAP_TYPE_STRUCT_OPS]		= "struct_ops",
149 	[BPF_MAP_TYPE_RINGBUF]			= "ringbuf",
150 	[BPF_MAP_TYPE_INODE_STORAGE]		= "inode_storage",
151 	[BPF_MAP_TYPE_TASK_STORAGE]		= "task_storage",
152 	[BPF_MAP_TYPE_BLOOM_FILTER]		= "bloom_filter",
153 };
154 
155 static const char * const prog_type_name[] = {
156 	[BPF_PROG_TYPE_UNSPEC]			= "unspec",
157 	[BPF_PROG_TYPE_SOCKET_FILTER]		= "socket_filter",
158 	[BPF_PROG_TYPE_KPROBE]			= "kprobe",
159 	[BPF_PROG_TYPE_SCHED_CLS]		= "sched_cls",
160 	[BPF_PROG_TYPE_SCHED_ACT]		= "sched_act",
161 	[BPF_PROG_TYPE_TRACEPOINT]		= "tracepoint",
162 	[BPF_PROG_TYPE_XDP]			= "xdp",
163 	[BPF_PROG_TYPE_PERF_EVENT]		= "perf_event",
164 	[BPF_PROG_TYPE_CGROUP_SKB]		= "cgroup_skb",
165 	[BPF_PROG_TYPE_CGROUP_SOCK]		= "cgroup_sock",
166 	[BPF_PROG_TYPE_LWT_IN]			= "lwt_in",
167 	[BPF_PROG_TYPE_LWT_OUT]			= "lwt_out",
168 	[BPF_PROG_TYPE_LWT_XMIT]		= "lwt_xmit",
169 	[BPF_PROG_TYPE_SOCK_OPS]		= "sock_ops",
170 	[BPF_PROG_TYPE_SK_SKB]			= "sk_skb",
171 	[BPF_PROG_TYPE_CGROUP_DEVICE]		= "cgroup_device",
172 	[BPF_PROG_TYPE_SK_MSG]			= "sk_msg",
173 	[BPF_PROG_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
174 	[BPF_PROG_TYPE_CGROUP_SOCK_ADDR]	= "cgroup_sock_addr",
175 	[BPF_PROG_TYPE_LWT_SEG6LOCAL]		= "lwt_seg6local",
176 	[BPF_PROG_TYPE_LIRC_MODE2]		= "lirc_mode2",
177 	[BPF_PROG_TYPE_SK_REUSEPORT]		= "sk_reuseport",
178 	[BPF_PROG_TYPE_FLOW_DISSECTOR]		= "flow_dissector",
179 	[BPF_PROG_TYPE_CGROUP_SYSCTL]		= "cgroup_sysctl",
180 	[BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE]	= "raw_tracepoint_writable",
181 	[BPF_PROG_TYPE_CGROUP_SOCKOPT]		= "cgroup_sockopt",
182 	[BPF_PROG_TYPE_TRACING]			= "tracing",
183 	[BPF_PROG_TYPE_STRUCT_OPS]		= "struct_ops",
184 	[BPF_PROG_TYPE_EXT]			= "ext",
185 	[BPF_PROG_TYPE_LSM]			= "lsm",
186 	[BPF_PROG_TYPE_SK_LOOKUP]		= "sk_lookup",
187 	[BPF_PROG_TYPE_SYSCALL]			= "syscall",
188 };
189 
190 static int __base_pr(enum libbpf_print_level level, const char *format,
191 		     va_list args)
192 {
193 	if (level == LIBBPF_DEBUG)
194 		return 0;
195 
196 	return vfprintf(stderr, format, args);
197 }
198 
199 static libbpf_print_fn_t __libbpf_pr = __base_pr;
200 
201 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
202 {
203 	libbpf_print_fn_t old_print_fn = __libbpf_pr;
204 
205 	__libbpf_pr = fn;
206 	return old_print_fn;
207 }
208 
209 __printf(2, 3)
210 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
211 {
212 	va_list args;
213 
214 	if (!__libbpf_pr)
215 		return;
216 
217 	va_start(args, format);
218 	__libbpf_pr(level, format, args);
219 	va_end(args);
220 }
221 
222 static void pr_perm_msg(int err)
223 {
224 	struct rlimit limit;
225 	char buf[100];
226 
227 	if (err != -EPERM || geteuid() != 0)
228 		return;
229 
230 	err = getrlimit(RLIMIT_MEMLOCK, &limit);
231 	if (err)
232 		return;
233 
234 	if (limit.rlim_cur == RLIM_INFINITY)
235 		return;
236 
237 	if (limit.rlim_cur < 1024)
238 		snprintf(buf, sizeof(buf), "%zu bytes", (size_t)limit.rlim_cur);
239 	else if (limit.rlim_cur < 1024*1024)
240 		snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
241 	else
242 		snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
243 
244 	pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
245 		buf);
246 }
247 
248 #define STRERR_BUFSIZE  128
249 
250 /* Copied from tools/perf/util/util.h */
251 #ifndef zfree
252 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
253 #endif
254 
255 #ifndef zclose
256 # define zclose(fd) ({			\
257 	int ___err = 0;			\
258 	if ((fd) >= 0)			\
259 		___err = close((fd));	\
260 	fd = -1;			\
261 	___err; })
262 #endif
263 
264 static inline __u64 ptr_to_u64(const void *ptr)
265 {
266 	return (__u64) (unsigned long) ptr;
267 }
268 
269 /* this goes away in libbpf 1.0 */
270 enum libbpf_strict_mode libbpf_mode = LIBBPF_STRICT_NONE;
271 
272 int libbpf_set_strict_mode(enum libbpf_strict_mode mode)
273 {
274 	libbpf_mode = mode;
275 	return 0;
276 }
277 
278 __u32 libbpf_major_version(void)
279 {
280 	return LIBBPF_MAJOR_VERSION;
281 }
282 
283 __u32 libbpf_minor_version(void)
284 {
285 	return LIBBPF_MINOR_VERSION;
286 }
287 
288 const char *libbpf_version_string(void)
289 {
290 #define __S(X) #X
291 #define _S(X) __S(X)
292 	return  "v" _S(LIBBPF_MAJOR_VERSION) "." _S(LIBBPF_MINOR_VERSION);
293 #undef _S
294 #undef __S
295 }
296 
297 enum reloc_type {
298 	RELO_LD64,
299 	RELO_CALL,
300 	RELO_DATA,
301 	RELO_EXTERN_VAR,
302 	RELO_EXTERN_FUNC,
303 	RELO_SUBPROG_ADDR,
304 	RELO_CORE,
305 };
306 
307 struct reloc_desc {
308 	enum reloc_type type;
309 	int insn_idx;
310 	union {
311 		const struct bpf_core_relo *core_relo; /* used when type == RELO_CORE */
312 		struct {
313 			int map_idx;
314 			int sym_off;
315 		};
316 	};
317 };
318 
319 /* stored as sec_def->cookie for all libbpf-supported SEC()s */
320 enum sec_def_flags {
321 	SEC_NONE = 0,
322 	/* expected_attach_type is optional, if kernel doesn't support that */
323 	SEC_EXP_ATTACH_OPT = 1,
324 	/* legacy, only used by libbpf_get_type_names() and
325 	 * libbpf_attach_type_by_name(), not used by libbpf itself at all.
326 	 * This used to be associated with cgroup (and few other) BPF programs
327 	 * that were attachable through BPF_PROG_ATTACH command. Pretty
328 	 * meaningless nowadays, though.
329 	 */
330 	SEC_ATTACHABLE = 2,
331 	SEC_ATTACHABLE_OPT = SEC_ATTACHABLE | SEC_EXP_ATTACH_OPT,
332 	/* attachment target is specified through BTF ID in either kernel or
333 	 * other BPF program's BTF object */
334 	SEC_ATTACH_BTF = 4,
335 	/* BPF program type allows sleeping/blocking in kernel */
336 	SEC_SLEEPABLE = 8,
337 	/* allow non-strict prefix matching */
338 	SEC_SLOPPY_PFX = 16,
339 	/* BPF program support non-linear XDP buffer */
340 	SEC_XDP_FRAGS = 32,
341 	/* deprecated sec definitions not supposed to be used */
342 	SEC_DEPRECATED = 64,
343 };
344 
345 struct bpf_sec_def {
346 	char *sec;
347 	enum bpf_prog_type prog_type;
348 	enum bpf_attach_type expected_attach_type;
349 	long cookie;
350 	int handler_id;
351 
352 	libbpf_prog_setup_fn_t prog_setup_fn;
353 	libbpf_prog_prepare_load_fn_t prog_prepare_load_fn;
354 	libbpf_prog_attach_fn_t prog_attach_fn;
355 };
356 
357 /*
358  * bpf_prog should be a better name but it has been used in
359  * linux/filter.h.
360  */
361 struct bpf_program {
362 	const struct bpf_sec_def *sec_def;
363 	char *sec_name;
364 	size_t sec_idx;
365 	/* this program's instruction offset (in number of instructions)
366 	 * within its containing ELF section
367 	 */
368 	size_t sec_insn_off;
369 	/* number of original instructions in ELF section belonging to this
370 	 * program, not taking into account subprogram instructions possible
371 	 * appended later during relocation
372 	 */
373 	size_t sec_insn_cnt;
374 	/* Offset (in number of instructions) of the start of instruction
375 	 * belonging to this BPF program  within its containing main BPF
376 	 * program. For the entry-point (main) BPF program, this is always
377 	 * zero. For a sub-program, this gets reset before each of main BPF
378 	 * programs are processed and relocated and is used to determined
379 	 * whether sub-program was already appended to the main program, and
380 	 * if yes, at which instruction offset.
381 	 */
382 	size_t sub_insn_off;
383 
384 	char *name;
385 	/* name with / replaced by _; makes recursive pinning
386 	 * in bpf_object__pin_programs easier
387 	 */
388 	char *pin_name;
389 
390 	/* instructions that belong to BPF program; insns[0] is located at
391 	 * sec_insn_off instruction within its ELF section in ELF file, so
392 	 * when mapping ELF file instruction index to the local instruction,
393 	 * one needs to subtract sec_insn_off; and vice versa.
394 	 */
395 	struct bpf_insn *insns;
396 	/* actual number of instruction in this BPF program's image; for
397 	 * entry-point BPF programs this includes the size of main program
398 	 * itself plus all the used sub-programs, appended at the end
399 	 */
400 	size_t insns_cnt;
401 
402 	struct reloc_desc *reloc_desc;
403 	int nr_reloc;
404 
405 	/* BPF verifier log settings */
406 	char *log_buf;
407 	size_t log_size;
408 	__u32 log_level;
409 
410 	struct {
411 		int nr;
412 		int *fds;
413 	} instances;
414 	bpf_program_prep_t preprocessor;
415 
416 	struct bpf_object *obj;
417 	void *priv;
418 	bpf_program_clear_priv_t clear_priv;
419 
420 	bool autoload;
421 	bool mark_btf_static;
422 	enum bpf_prog_type type;
423 	enum bpf_attach_type expected_attach_type;
424 	int prog_ifindex;
425 	__u32 attach_btf_obj_fd;
426 	__u32 attach_btf_id;
427 	__u32 attach_prog_fd;
428 	void *func_info;
429 	__u32 func_info_rec_size;
430 	__u32 func_info_cnt;
431 
432 	void *line_info;
433 	__u32 line_info_rec_size;
434 	__u32 line_info_cnt;
435 	__u32 prog_flags;
436 };
437 
438 struct bpf_struct_ops {
439 	const char *tname;
440 	const struct btf_type *type;
441 	struct bpf_program **progs;
442 	__u32 *kern_func_off;
443 	/* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
444 	void *data;
445 	/* e.g. struct bpf_struct_ops_tcp_congestion_ops in
446 	 *      btf_vmlinux's format.
447 	 * struct bpf_struct_ops_tcp_congestion_ops {
448 	 *	[... some other kernel fields ...]
449 	 *	struct tcp_congestion_ops data;
450 	 * }
451 	 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
452 	 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
453 	 * from "data".
454 	 */
455 	void *kern_vdata;
456 	__u32 type_id;
457 };
458 
459 #define DATA_SEC ".data"
460 #define BSS_SEC ".bss"
461 #define RODATA_SEC ".rodata"
462 #define KCONFIG_SEC ".kconfig"
463 #define KSYMS_SEC ".ksyms"
464 #define STRUCT_OPS_SEC ".struct_ops"
465 
466 enum libbpf_map_type {
467 	LIBBPF_MAP_UNSPEC,
468 	LIBBPF_MAP_DATA,
469 	LIBBPF_MAP_BSS,
470 	LIBBPF_MAP_RODATA,
471 	LIBBPF_MAP_KCONFIG,
472 };
473 
474 struct bpf_map {
475 	struct bpf_object *obj;
476 	char *name;
477 	/* real_name is defined for special internal maps (.rodata*,
478 	 * .data*, .bss, .kconfig) and preserves their original ELF section
479 	 * name. This is important to be be able to find corresponding BTF
480 	 * DATASEC information.
481 	 */
482 	char *real_name;
483 	int fd;
484 	int sec_idx;
485 	size_t sec_offset;
486 	int map_ifindex;
487 	int inner_map_fd;
488 	struct bpf_map_def def;
489 	__u32 numa_node;
490 	__u32 btf_var_idx;
491 	__u32 btf_key_type_id;
492 	__u32 btf_value_type_id;
493 	__u32 btf_vmlinux_value_type_id;
494 	void *priv;
495 	bpf_map_clear_priv_t clear_priv;
496 	enum libbpf_map_type libbpf_type;
497 	void *mmaped;
498 	struct bpf_struct_ops *st_ops;
499 	struct bpf_map *inner_map;
500 	void **init_slots;
501 	int init_slots_sz;
502 	char *pin_path;
503 	bool pinned;
504 	bool reused;
505 	bool autocreate;
506 	__u64 map_extra;
507 };
508 
509 enum extern_type {
510 	EXT_UNKNOWN,
511 	EXT_KCFG,
512 	EXT_KSYM,
513 };
514 
515 enum kcfg_type {
516 	KCFG_UNKNOWN,
517 	KCFG_CHAR,
518 	KCFG_BOOL,
519 	KCFG_INT,
520 	KCFG_TRISTATE,
521 	KCFG_CHAR_ARR,
522 };
523 
524 struct extern_desc {
525 	enum extern_type type;
526 	int sym_idx;
527 	int btf_id;
528 	int sec_btf_id;
529 	const char *name;
530 	bool is_set;
531 	bool is_weak;
532 	union {
533 		struct {
534 			enum kcfg_type type;
535 			int sz;
536 			int align;
537 			int data_off;
538 			bool is_signed;
539 		} kcfg;
540 		struct {
541 			unsigned long long addr;
542 
543 			/* target btf_id of the corresponding kernel var. */
544 			int kernel_btf_obj_fd;
545 			int kernel_btf_id;
546 
547 			/* local btf_id of the ksym extern's type. */
548 			__u32 type_id;
549 			/* BTF fd index to be patched in for insn->off, this is
550 			 * 0 for vmlinux BTF, index in obj->fd_array for module
551 			 * BTF
552 			 */
553 			__s16 btf_fd_idx;
554 		} ksym;
555 	};
556 };
557 
558 static LIST_HEAD(bpf_objects_list);
559 
560 struct module_btf {
561 	struct btf *btf;
562 	char *name;
563 	__u32 id;
564 	int fd;
565 	int fd_array_idx;
566 };
567 
568 enum sec_type {
569 	SEC_UNUSED = 0,
570 	SEC_RELO,
571 	SEC_BSS,
572 	SEC_DATA,
573 	SEC_RODATA,
574 };
575 
576 struct elf_sec_desc {
577 	enum sec_type sec_type;
578 	Elf64_Shdr *shdr;
579 	Elf_Data *data;
580 };
581 
582 struct elf_state {
583 	int fd;
584 	const void *obj_buf;
585 	size_t obj_buf_sz;
586 	Elf *elf;
587 	Elf64_Ehdr *ehdr;
588 	Elf_Data *symbols;
589 	Elf_Data *st_ops_data;
590 	size_t shstrndx; /* section index for section name strings */
591 	size_t strtabidx;
592 	struct elf_sec_desc *secs;
593 	int sec_cnt;
594 	int maps_shndx;
595 	int btf_maps_shndx;
596 	__u32 btf_maps_sec_btf_id;
597 	int text_shndx;
598 	int symbols_shndx;
599 	int st_ops_shndx;
600 };
601 
602 struct usdt_manager;
603 
604 struct bpf_object {
605 	char name[BPF_OBJ_NAME_LEN];
606 	char license[64];
607 	__u32 kern_version;
608 
609 	struct bpf_program *programs;
610 	size_t nr_programs;
611 	struct bpf_map *maps;
612 	size_t nr_maps;
613 	size_t maps_cap;
614 
615 	char *kconfig;
616 	struct extern_desc *externs;
617 	int nr_extern;
618 	int kconfig_map_idx;
619 
620 	bool loaded;
621 	bool has_subcalls;
622 	bool has_rodata;
623 
624 	struct bpf_gen *gen_loader;
625 
626 	/* Information when doing ELF related work. Only valid if efile.elf is not NULL */
627 	struct elf_state efile;
628 	/*
629 	 * All loaded bpf_object are linked in a list, which is
630 	 * hidden to caller. bpf_objects__<func> handlers deal with
631 	 * all objects.
632 	 */
633 	struct list_head list;
634 
635 	struct btf *btf;
636 	struct btf_ext *btf_ext;
637 
638 	/* Parse and load BTF vmlinux if any of the programs in the object need
639 	 * it at load time.
640 	 */
641 	struct btf *btf_vmlinux;
642 	/* Path to the custom BTF to be used for BPF CO-RE relocations as an
643 	 * override for vmlinux BTF.
644 	 */
645 	char *btf_custom_path;
646 	/* vmlinux BTF override for CO-RE relocations */
647 	struct btf *btf_vmlinux_override;
648 	/* Lazily initialized kernel module BTFs */
649 	struct module_btf *btf_modules;
650 	bool btf_modules_loaded;
651 	size_t btf_module_cnt;
652 	size_t btf_module_cap;
653 
654 	/* optional log settings passed to BPF_BTF_LOAD and BPF_PROG_LOAD commands */
655 	char *log_buf;
656 	size_t log_size;
657 	__u32 log_level;
658 
659 	void *priv;
660 	bpf_object_clear_priv_t clear_priv;
661 
662 	int *fd_array;
663 	size_t fd_array_cap;
664 	size_t fd_array_cnt;
665 
666 	struct usdt_manager *usdt_man;
667 
668 	char path[];
669 };
670 
671 static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
672 static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
673 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
674 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
675 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn);
676 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
677 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
678 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx);
679 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx);
680 
681 void bpf_program__unload(struct bpf_program *prog)
682 {
683 	int i;
684 
685 	if (!prog)
686 		return;
687 
688 	/*
689 	 * If the object is opened but the program was never loaded,
690 	 * it is possible that prog->instances.nr == -1.
691 	 */
692 	if (prog->instances.nr > 0) {
693 		for (i = 0; i < prog->instances.nr; i++)
694 			zclose(prog->instances.fds[i]);
695 	} else if (prog->instances.nr != -1) {
696 		pr_warn("Internal error: instances.nr is %d\n",
697 			prog->instances.nr);
698 	}
699 
700 	prog->instances.nr = -1;
701 	zfree(&prog->instances.fds);
702 
703 	zfree(&prog->func_info);
704 	zfree(&prog->line_info);
705 }
706 
707 static void bpf_program__exit(struct bpf_program *prog)
708 {
709 	if (!prog)
710 		return;
711 
712 	if (prog->clear_priv)
713 		prog->clear_priv(prog, prog->priv);
714 
715 	prog->priv = NULL;
716 	prog->clear_priv = NULL;
717 
718 	bpf_program__unload(prog);
719 	zfree(&prog->name);
720 	zfree(&prog->sec_name);
721 	zfree(&prog->pin_name);
722 	zfree(&prog->insns);
723 	zfree(&prog->reloc_desc);
724 
725 	prog->nr_reloc = 0;
726 	prog->insns_cnt = 0;
727 	prog->sec_idx = -1;
728 }
729 
730 static char *__bpf_program__pin_name(struct bpf_program *prog)
731 {
732 	char *name, *p;
733 
734 	if (libbpf_mode & LIBBPF_STRICT_SEC_NAME)
735 		name = strdup(prog->name);
736 	else
737 		name = strdup(prog->sec_name);
738 
739 	if (!name)
740 		return NULL;
741 
742 	p = name;
743 
744 	while ((p = strchr(p, '/')))
745 		*p = '_';
746 
747 	return name;
748 }
749 
750 static bool insn_is_subprog_call(const struct bpf_insn *insn)
751 {
752 	return BPF_CLASS(insn->code) == BPF_JMP &&
753 	       BPF_OP(insn->code) == BPF_CALL &&
754 	       BPF_SRC(insn->code) == BPF_K &&
755 	       insn->src_reg == BPF_PSEUDO_CALL &&
756 	       insn->dst_reg == 0 &&
757 	       insn->off == 0;
758 }
759 
760 static bool is_call_insn(const struct bpf_insn *insn)
761 {
762 	return insn->code == (BPF_JMP | BPF_CALL);
763 }
764 
765 static bool insn_is_pseudo_func(struct bpf_insn *insn)
766 {
767 	return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
768 }
769 
770 static int
771 bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
772 		      const char *name, size_t sec_idx, const char *sec_name,
773 		      size_t sec_off, void *insn_data, size_t insn_data_sz)
774 {
775 	if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
776 		pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
777 			sec_name, name, sec_off, insn_data_sz);
778 		return -EINVAL;
779 	}
780 
781 	memset(prog, 0, sizeof(*prog));
782 	prog->obj = obj;
783 
784 	prog->sec_idx = sec_idx;
785 	prog->sec_insn_off = sec_off / BPF_INSN_SZ;
786 	prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
787 	/* insns_cnt can later be increased by appending used subprograms */
788 	prog->insns_cnt = prog->sec_insn_cnt;
789 
790 	prog->type = BPF_PROG_TYPE_UNSPEC;
791 
792 	/* libbpf's convention for SEC("?abc...") is that it's just like
793 	 * SEC("abc...") but the corresponding bpf_program starts out with
794 	 * autoload set to false.
795 	 */
796 	if (sec_name[0] == '?') {
797 		prog->autoload = false;
798 		/* from now on forget there was ? in section name */
799 		sec_name++;
800 	} else {
801 		prog->autoload = true;
802 	}
803 
804 	prog->instances.fds = NULL;
805 	prog->instances.nr = -1;
806 
807 	/* inherit object's log_level */
808 	prog->log_level = obj->log_level;
809 
810 	prog->sec_name = strdup(sec_name);
811 	if (!prog->sec_name)
812 		goto errout;
813 
814 	prog->name = strdup(name);
815 	if (!prog->name)
816 		goto errout;
817 
818 	prog->pin_name = __bpf_program__pin_name(prog);
819 	if (!prog->pin_name)
820 		goto errout;
821 
822 	prog->insns = malloc(insn_data_sz);
823 	if (!prog->insns)
824 		goto errout;
825 	memcpy(prog->insns, insn_data, insn_data_sz);
826 
827 	return 0;
828 errout:
829 	pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
830 	bpf_program__exit(prog);
831 	return -ENOMEM;
832 }
833 
834 static int
835 bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
836 			 const char *sec_name, int sec_idx)
837 {
838 	Elf_Data *symbols = obj->efile.symbols;
839 	struct bpf_program *prog, *progs;
840 	void *data = sec_data->d_buf;
841 	size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
842 	int nr_progs, err, i;
843 	const char *name;
844 	Elf64_Sym *sym;
845 
846 	progs = obj->programs;
847 	nr_progs = obj->nr_programs;
848 	nr_syms = symbols->d_size / sizeof(Elf64_Sym);
849 	sec_off = 0;
850 
851 	for (i = 0; i < nr_syms; i++) {
852 		sym = elf_sym_by_idx(obj, i);
853 
854 		if (sym->st_shndx != sec_idx)
855 			continue;
856 		if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC)
857 			continue;
858 
859 		prog_sz = sym->st_size;
860 		sec_off = sym->st_value;
861 
862 		name = elf_sym_str(obj, sym->st_name);
863 		if (!name) {
864 			pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
865 				sec_name, sec_off);
866 			return -LIBBPF_ERRNO__FORMAT;
867 		}
868 
869 		if (sec_off + prog_sz > sec_sz) {
870 			pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
871 				sec_name, sec_off);
872 			return -LIBBPF_ERRNO__FORMAT;
873 		}
874 
875 		if (sec_idx != obj->efile.text_shndx && ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
876 			pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
877 			return -ENOTSUP;
878 		}
879 
880 		pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
881 			 sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
882 
883 		progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
884 		if (!progs) {
885 			/*
886 			 * In this case the original obj->programs
887 			 * is still valid, so don't need special treat for
888 			 * bpf_close_object().
889 			 */
890 			pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
891 				sec_name, name);
892 			return -ENOMEM;
893 		}
894 		obj->programs = progs;
895 
896 		prog = &progs[nr_progs];
897 
898 		err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
899 					    sec_off, data + sec_off, prog_sz);
900 		if (err)
901 			return err;
902 
903 		/* if function is a global/weak symbol, but has restricted
904 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
905 		 * as static to enable more permissive BPF verification mode
906 		 * with more outside context available to BPF verifier
907 		 */
908 		if (ELF64_ST_BIND(sym->st_info) != STB_LOCAL
909 		    && (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
910 			|| ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL))
911 			prog->mark_btf_static = true;
912 
913 		nr_progs++;
914 		obj->nr_programs = nr_progs;
915 	}
916 
917 	return 0;
918 }
919 
920 __u32 get_kernel_version(void)
921 {
922 	/* On Ubuntu LINUX_VERSION_CODE doesn't correspond to info.release,
923 	 * but Ubuntu provides /proc/version_signature file, as described at
924 	 * https://ubuntu.com/kernel, with an example contents below, which we
925 	 * can use to get a proper LINUX_VERSION_CODE.
926 	 *
927 	 *   Ubuntu 5.4.0-12.15-generic 5.4.8
928 	 *
929 	 * In the above, 5.4.8 is what kernel is actually expecting, while
930 	 * uname() call will return 5.4.0 in info.release.
931 	 */
932 	const char *ubuntu_kver_file = "/proc/version_signature";
933 	__u32 major, minor, patch;
934 	struct utsname info;
935 
936 	if (access(ubuntu_kver_file, R_OK) == 0) {
937 		FILE *f;
938 
939 		f = fopen(ubuntu_kver_file, "r");
940 		if (f) {
941 			if (fscanf(f, "%*s %*s %d.%d.%d\n", &major, &minor, &patch) == 3) {
942 				fclose(f);
943 				return KERNEL_VERSION(major, minor, patch);
944 			}
945 			fclose(f);
946 		}
947 		/* something went wrong, fall back to uname() approach */
948 	}
949 
950 	uname(&info);
951 	if (sscanf(info.release, "%u.%u.%u", &major, &minor, &patch) != 3)
952 		return 0;
953 	return KERNEL_VERSION(major, minor, patch);
954 }
955 
956 static const struct btf_member *
957 find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
958 {
959 	struct btf_member *m;
960 	int i;
961 
962 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
963 		if (btf_member_bit_offset(t, i) == bit_offset)
964 			return m;
965 	}
966 
967 	return NULL;
968 }
969 
970 static const struct btf_member *
971 find_member_by_name(const struct btf *btf, const struct btf_type *t,
972 		    const char *name)
973 {
974 	struct btf_member *m;
975 	int i;
976 
977 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
978 		if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
979 			return m;
980 	}
981 
982 	return NULL;
983 }
984 
985 #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
986 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
987 				   const char *name, __u32 kind);
988 
989 static int
990 find_struct_ops_kern_types(const struct btf *btf, const char *tname,
991 			   const struct btf_type **type, __u32 *type_id,
992 			   const struct btf_type **vtype, __u32 *vtype_id,
993 			   const struct btf_member **data_member)
994 {
995 	const struct btf_type *kern_type, *kern_vtype;
996 	const struct btf_member *kern_data_member;
997 	__s32 kern_vtype_id, kern_type_id;
998 	__u32 i;
999 
1000 	kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
1001 	if (kern_type_id < 0) {
1002 		pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n",
1003 			tname);
1004 		return kern_type_id;
1005 	}
1006 	kern_type = btf__type_by_id(btf, kern_type_id);
1007 
1008 	/* Find the corresponding "map_value" type that will be used
1009 	 * in map_update(BPF_MAP_TYPE_STRUCT_OPS).  For example,
1010 	 * find "struct bpf_struct_ops_tcp_congestion_ops" from the
1011 	 * btf_vmlinux.
1012 	 */
1013 	kern_vtype_id = find_btf_by_prefix_kind(btf, STRUCT_OPS_VALUE_PREFIX,
1014 						tname, BTF_KIND_STRUCT);
1015 	if (kern_vtype_id < 0) {
1016 		pr_warn("struct_ops init_kern: struct %s%s is not found in kernel BTF\n",
1017 			STRUCT_OPS_VALUE_PREFIX, tname);
1018 		return kern_vtype_id;
1019 	}
1020 	kern_vtype = btf__type_by_id(btf, kern_vtype_id);
1021 
1022 	/* Find "struct tcp_congestion_ops" from
1023 	 * struct bpf_struct_ops_tcp_congestion_ops {
1024 	 *	[ ... ]
1025 	 *	struct tcp_congestion_ops data;
1026 	 * }
1027 	 */
1028 	kern_data_member = btf_members(kern_vtype);
1029 	for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
1030 		if (kern_data_member->type == kern_type_id)
1031 			break;
1032 	}
1033 	if (i == btf_vlen(kern_vtype)) {
1034 		pr_warn("struct_ops init_kern: struct %s data is not found in struct %s%s\n",
1035 			tname, STRUCT_OPS_VALUE_PREFIX, tname);
1036 		return -EINVAL;
1037 	}
1038 
1039 	*type = kern_type;
1040 	*type_id = kern_type_id;
1041 	*vtype = kern_vtype;
1042 	*vtype_id = kern_vtype_id;
1043 	*data_member = kern_data_member;
1044 
1045 	return 0;
1046 }
1047 
1048 static bool bpf_map__is_struct_ops(const struct bpf_map *map)
1049 {
1050 	return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
1051 }
1052 
1053 /* Init the map's fields that depend on kern_btf */
1054 static int bpf_map__init_kern_struct_ops(struct bpf_map *map,
1055 					 const struct btf *btf,
1056 					 const struct btf *kern_btf)
1057 {
1058 	const struct btf_member *member, *kern_member, *kern_data_member;
1059 	const struct btf_type *type, *kern_type, *kern_vtype;
1060 	__u32 i, kern_type_id, kern_vtype_id, kern_data_off;
1061 	struct bpf_struct_ops *st_ops;
1062 	void *data, *kern_data;
1063 	const char *tname;
1064 	int err;
1065 
1066 	st_ops = map->st_ops;
1067 	type = st_ops->type;
1068 	tname = st_ops->tname;
1069 	err = find_struct_ops_kern_types(kern_btf, tname,
1070 					 &kern_type, &kern_type_id,
1071 					 &kern_vtype, &kern_vtype_id,
1072 					 &kern_data_member);
1073 	if (err)
1074 		return err;
1075 
1076 	pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
1077 		 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
1078 
1079 	map->def.value_size = kern_vtype->size;
1080 	map->btf_vmlinux_value_type_id = kern_vtype_id;
1081 
1082 	st_ops->kern_vdata = calloc(1, kern_vtype->size);
1083 	if (!st_ops->kern_vdata)
1084 		return -ENOMEM;
1085 
1086 	data = st_ops->data;
1087 	kern_data_off = kern_data_member->offset / 8;
1088 	kern_data = st_ops->kern_vdata + kern_data_off;
1089 
1090 	member = btf_members(type);
1091 	for (i = 0; i < btf_vlen(type); i++, member++) {
1092 		const struct btf_type *mtype, *kern_mtype;
1093 		__u32 mtype_id, kern_mtype_id;
1094 		void *mdata, *kern_mdata;
1095 		__s64 msize, kern_msize;
1096 		__u32 moff, kern_moff;
1097 		__u32 kern_member_idx;
1098 		const char *mname;
1099 
1100 		mname = btf__name_by_offset(btf, member->name_off);
1101 		kern_member = find_member_by_name(kern_btf, kern_type, mname);
1102 		if (!kern_member) {
1103 			pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
1104 				map->name, mname);
1105 			return -ENOTSUP;
1106 		}
1107 
1108 		kern_member_idx = kern_member - btf_members(kern_type);
1109 		if (btf_member_bitfield_size(type, i) ||
1110 		    btf_member_bitfield_size(kern_type, kern_member_idx)) {
1111 			pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
1112 				map->name, mname);
1113 			return -ENOTSUP;
1114 		}
1115 
1116 		moff = member->offset / 8;
1117 		kern_moff = kern_member->offset / 8;
1118 
1119 		mdata = data + moff;
1120 		kern_mdata = kern_data + kern_moff;
1121 
1122 		mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
1123 		kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
1124 						    &kern_mtype_id);
1125 		if (BTF_INFO_KIND(mtype->info) !=
1126 		    BTF_INFO_KIND(kern_mtype->info)) {
1127 			pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
1128 				map->name, mname, BTF_INFO_KIND(mtype->info),
1129 				BTF_INFO_KIND(kern_mtype->info));
1130 			return -ENOTSUP;
1131 		}
1132 
1133 		if (btf_is_ptr(mtype)) {
1134 			struct bpf_program *prog;
1135 
1136 			prog = st_ops->progs[i];
1137 			if (!prog)
1138 				continue;
1139 
1140 			kern_mtype = skip_mods_and_typedefs(kern_btf,
1141 							    kern_mtype->type,
1142 							    &kern_mtype_id);
1143 
1144 			/* mtype->type must be a func_proto which was
1145 			 * guaranteed in bpf_object__collect_st_ops_relos(),
1146 			 * so only check kern_mtype for func_proto here.
1147 			 */
1148 			if (!btf_is_func_proto(kern_mtype)) {
1149 				pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
1150 					map->name, mname);
1151 				return -ENOTSUP;
1152 			}
1153 
1154 			prog->attach_btf_id = kern_type_id;
1155 			prog->expected_attach_type = kern_member_idx;
1156 
1157 			st_ops->kern_func_off[i] = kern_data_off + kern_moff;
1158 
1159 			pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
1160 				 map->name, mname, prog->name, moff,
1161 				 kern_moff);
1162 
1163 			continue;
1164 		}
1165 
1166 		msize = btf__resolve_size(btf, mtype_id);
1167 		kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
1168 		if (msize < 0 || kern_msize < 0 || msize != kern_msize) {
1169 			pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
1170 				map->name, mname, (ssize_t)msize,
1171 				(ssize_t)kern_msize);
1172 			return -ENOTSUP;
1173 		}
1174 
1175 		pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
1176 			 map->name, mname, (unsigned int)msize,
1177 			 moff, kern_moff);
1178 		memcpy(kern_mdata, mdata, msize);
1179 	}
1180 
1181 	return 0;
1182 }
1183 
1184 static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
1185 {
1186 	struct bpf_map *map;
1187 	size_t i;
1188 	int err;
1189 
1190 	for (i = 0; i < obj->nr_maps; i++) {
1191 		map = &obj->maps[i];
1192 
1193 		if (!bpf_map__is_struct_ops(map))
1194 			continue;
1195 
1196 		err = bpf_map__init_kern_struct_ops(map, obj->btf,
1197 						    obj->btf_vmlinux);
1198 		if (err)
1199 			return err;
1200 	}
1201 
1202 	return 0;
1203 }
1204 
1205 static int bpf_object__init_struct_ops_maps(struct bpf_object *obj)
1206 {
1207 	const struct btf_type *type, *datasec;
1208 	const struct btf_var_secinfo *vsi;
1209 	struct bpf_struct_ops *st_ops;
1210 	const char *tname, *var_name;
1211 	__s32 type_id, datasec_id;
1212 	const struct btf *btf;
1213 	struct bpf_map *map;
1214 	__u32 i;
1215 
1216 	if (obj->efile.st_ops_shndx == -1)
1217 		return 0;
1218 
1219 	btf = obj->btf;
1220 	datasec_id = btf__find_by_name_kind(btf, STRUCT_OPS_SEC,
1221 					    BTF_KIND_DATASEC);
1222 	if (datasec_id < 0) {
1223 		pr_warn("struct_ops init: DATASEC %s not found\n",
1224 			STRUCT_OPS_SEC);
1225 		return -EINVAL;
1226 	}
1227 
1228 	datasec = btf__type_by_id(btf, datasec_id);
1229 	vsi = btf_var_secinfos(datasec);
1230 	for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
1231 		type = btf__type_by_id(obj->btf, vsi->type);
1232 		var_name = btf__name_by_offset(obj->btf, type->name_off);
1233 
1234 		type_id = btf__resolve_type(obj->btf, vsi->type);
1235 		if (type_id < 0) {
1236 			pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
1237 				vsi->type, STRUCT_OPS_SEC);
1238 			return -EINVAL;
1239 		}
1240 
1241 		type = btf__type_by_id(obj->btf, type_id);
1242 		tname = btf__name_by_offset(obj->btf, type->name_off);
1243 		if (!tname[0]) {
1244 			pr_warn("struct_ops init: anonymous type is not supported\n");
1245 			return -ENOTSUP;
1246 		}
1247 		if (!btf_is_struct(type)) {
1248 			pr_warn("struct_ops init: %s is not a struct\n", tname);
1249 			return -EINVAL;
1250 		}
1251 
1252 		map = bpf_object__add_map(obj);
1253 		if (IS_ERR(map))
1254 			return PTR_ERR(map);
1255 
1256 		map->sec_idx = obj->efile.st_ops_shndx;
1257 		map->sec_offset = vsi->offset;
1258 		map->name = strdup(var_name);
1259 		if (!map->name)
1260 			return -ENOMEM;
1261 
1262 		map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
1263 		map->def.key_size = sizeof(int);
1264 		map->def.value_size = type->size;
1265 		map->def.max_entries = 1;
1266 
1267 		map->st_ops = calloc(1, sizeof(*map->st_ops));
1268 		if (!map->st_ops)
1269 			return -ENOMEM;
1270 		st_ops = map->st_ops;
1271 		st_ops->data = malloc(type->size);
1272 		st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1273 		st_ops->kern_func_off = malloc(btf_vlen(type) *
1274 					       sizeof(*st_ops->kern_func_off));
1275 		if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1276 			return -ENOMEM;
1277 
1278 		if (vsi->offset + type->size > obj->efile.st_ops_data->d_size) {
1279 			pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1280 				var_name, STRUCT_OPS_SEC);
1281 			return -EINVAL;
1282 		}
1283 
1284 		memcpy(st_ops->data,
1285 		       obj->efile.st_ops_data->d_buf + vsi->offset,
1286 		       type->size);
1287 		st_ops->tname = tname;
1288 		st_ops->type = type;
1289 		st_ops->type_id = type_id;
1290 
1291 		pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
1292 			 tname, type_id, var_name, vsi->offset);
1293 	}
1294 
1295 	return 0;
1296 }
1297 
1298 static struct bpf_object *bpf_object__new(const char *path,
1299 					  const void *obj_buf,
1300 					  size_t obj_buf_sz,
1301 					  const char *obj_name)
1302 {
1303 	bool strict = (libbpf_mode & LIBBPF_STRICT_NO_OBJECT_LIST);
1304 	struct bpf_object *obj;
1305 	char *end;
1306 
1307 	obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1308 	if (!obj) {
1309 		pr_warn("alloc memory failed for %s\n", path);
1310 		return ERR_PTR(-ENOMEM);
1311 	}
1312 
1313 	strcpy(obj->path, path);
1314 	if (obj_name) {
1315 		libbpf_strlcpy(obj->name, obj_name, sizeof(obj->name));
1316 	} else {
1317 		/* Using basename() GNU version which doesn't modify arg. */
1318 		libbpf_strlcpy(obj->name, basename((void *)path), sizeof(obj->name));
1319 		end = strchr(obj->name, '.');
1320 		if (end)
1321 			*end = 0;
1322 	}
1323 
1324 	obj->efile.fd = -1;
1325 	/*
1326 	 * Caller of this function should also call
1327 	 * bpf_object__elf_finish() after data collection to return
1328 	 * obj_buf to user. If not, we should duplicate the buffer to
1329 	 * avoid user freeing them before elf finish.
1330 	 */
1331 	obj->efile.obj_buf = obj_buf;
1332 	obj->efile.obj_buf_sz = obj_buf_sz;
1333 	obj->efile.maps_shndx = -1;
1334 	obj->efile.btf_maps_shndx = -1;
1335 	obj->efile.st_ops_shndx = -1;
1336 	obj->kconfig_map_idx = -1;
1337 
1338 	obj->kern_version = get_kernel_version();
1339 	obj->loaded = false;
1340 
1341 	INIT_LIST_HEAD(&obj->list);
1342 	if (!strict)
1343 		list_add(&obj->list, &bpf_objects_list);
1344 	return obj;
1345 }
1346 
1347 static void bpf_object__elf_finish(struct bpf_object *obj)
1348 {
1349 	if (!obj->efile.elf)
1350 		return;
1351 
1352 	elf_end(obj->efile.elf);
1353 	obj->efile.elf = NULL;
1354 	obj->efile.symbols = NULL;
1355 	obj->efile.st_ops_data = NULL;
1356 
1357 	zfree(&obj->efile.secs);
1358 	obj->efile.sec_cnt = 0;
1359 	zclose(obj->efile.fd);
1360 	obj->efile.obj_buf = NULL;
1361 	obj->efile.obj_buf_sz = 0;
1362 }
1363 
1364 static int bpf_object__elf_init(struct bpf_object *obj)
1365 {
1366 	Elf64_Ehdr *ehdr;
1367 	int err = 0;
1368 	Elf *elf;
1369 
1370 	if (obj->efile.elf) {
1371 		pr_warn("elf: init internal error\n");
1372 		return -LIBBPF_ERRNO__LIBELF;
1373 	}
1374 
1375 	if (obj->efile.obj_buf_sz > 0) {
1376 		/*
1377 		 * obj_buf should have been validated by
1378 		 * bpf_object__open_buffer().
1379 		 */
1380 		elf = elf_memory((char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
1381 	} else {
1382 		obj->efile.fd = open(obj->path, O_RDONLY | O_CLOEXEC);
1383 		if (obj->efile.fd < 0) {
1384 			char errmsg[STRERR_BUFSIZE], *cp;
1385 
1386 			err = -errno;
1387 			cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
1388 			pr_warn("elf: failed to open %s: %s\n", obj->path, cp);
1389 			return err;
1390 		}
1391 
1392 		elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1393 	}
1394 
1395 	if (!elf) {
1396 		pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
1397 		err = -LIBBPF_ERRNO__LIBELF;
1398 		goto errout;
1399 	}
1400 
1401 	obj->efile.elf = elf;
1402 
1403 	if (elf_kind(elf) != ELF_K_ELF) {
1404 		err = -LIBBPF_ERRNO__FORMAT;
1405 		pr_warn("elf: '%s' is not a proper ELF object\n", obj->path);
1406 		goto errout;
1407 	}
1408 
1409 	if (gelf_getclass(elf) != ELFCLASS64) {
1410 		err = -LIBBPF_ERRNO__FORMAT;
1411 		pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path);
1412 		goto errout;
1413 	}
1414 
1415 	obj->efile.ehdr = ehdr = elf64_getehdr(elf);
1416 	if (!obj->efile.ehdr) {
1417 		pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
1418 		err = -LIBBPF_ERRNO__FORMAT;
1419 		goto errout;
1420 	}
1421 
1422 	if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
1423 		pr_warn("elf: failed to get section names section index for %s: %s\n",
1424 			obj->path, elf_errmsg(-1));
1425 		err = -LIBBPF_ERRNO__FORMAT;
1426 		goto errout;
1427 	}
1428 
1429 	/* Elf is corrupted/truncated, avoid calling elf_strptr. */
1430 	if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
1431 		pr_warn("elf: failed to get section names strings from %s: %s\n",
1432 			obj->path, elf_errmsg(-1));
1433 		err = -LIBBPF_ERRNO__FORMAT;
1434 		goto errout;
1435 	}
1436 
1437 	/* Old LLVM set e_machine to EM_NONE */
1438 	if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
1439 		pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
1440 		err = -LIBBPF_ERRNO__FORMAT;
1441 		goto errout;
1442 	}
1443 
1444 	return 0;
1445 errout:
1446 	bpf_object__elf_finish(obj);
1447 	return err;
1448 }
1449 
1450 static int bpf_object__check_endianness(struct bpf_object *obj)
1451 {
1452 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1453 	if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2LSB)
1454 		return 0;
1455 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1456 	if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2MSB)
1457 		return 0;
1458 #else
1459 # error "Unrecognized __BYTE_ORDER__"
1460 #endif
1461 	pr_warn("elf: endianness mismatch in %s.\n", obj->path);
1462 	return -LIBBPF_ERRNO__ENDIAN;
1463 }
1464 
1465 static int
1466 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1467 {
1468 	/* libbpf_strlcpy() only copies first N - 1 bytes, so size + 1 won't
1469 	 * go over allowed ELF data section buffer
1470 	 */
1471 	libbpf_strlcpy(obj->license, data, min(size + 1, sizeof(obj->license)));
1472 	pr_debug("license of %s is %s\n", obj->path, obj->license);
1473 	return 0;
1474 }
1475 
1476 static int
1477 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1478 {
1479 	__u32 kver;
1480 
1481 	if (size != sizeof(kver)) {
1482 		pr_warn("invalid kver section in %s\n", obj->path);
1483 		return -LIBBPF_ERRNO__FORMAT;
1484 	}
1485 	memcpy(&kver, data, sizeof(kver));
1486 	obj->kern_version = kver;
1487 	pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1488 	return 0;
1489 }
1490 
1491 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1492 {
1493 	if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1494 	    type == BPF_MAP_TYPE_HASH_OF_MAPS)
1495 		return true;
1496 	return false;
1497 }
1498 
1499 static int find_elf_sec_sz(const struct bpf_object *obj, const char *name, __u32 *size)
1500 {
1501 	Elf_Data *data;
1502 	Elf_Scn *scn;
1503 
1504 	if (!name)
1505 		return -EINVAL;
1506 
1507 	scn = elf_sec_by_name(obj, name);
1508 	data = elf_sec_data(obj, scn);
1509 	if (data) {
1510 		*size = data->d_size;
1511 		return 0; /* found it */
1512 	}
1513 
1514 	return -ENOENT;
1515 }
1516 
1517 static int find_elf_var_offset(const struct bpf_object *obj, const char *name, __u32 *off)
1518 {
1519 	Elf_Data *symbols = obj->efile.symbols;
1520 	const char *sname;
1521 	size_t si;
1522 
1523 	if (!name || !off)
1524 		return -EINVAL;
1525 
1526 	for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
1527 		Elf64_Sym *sym = elf_sym_by_idx(obj, si);
1528 
1529 		if (ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)
1530 			continue;
1531 
1532 		if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL &&
1533 		    ELF64_ST_BIND(sym->st_info) != STB_WEAK)
1534 			continue;
1535 
1536 		sname = elf_sym_str(obj, sym->st_name);
1537 		if (!sname) {
1538 			pr_warn("failed to get sym name string for var %s\n", name);
1539 			return -EIO;
1540 		}
1541 		if (strcmp(name, sname) == 0) {
1542 			*off = sym->st_value;
1543 			return 0;
1544 		}
1545 	}
1546 
1547 	return -ENOENT;
1548 }
1549 
1550 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1551 {
1552 	struct bpf_map *map;
1553 	int err;
1554 
1555 	err = libbpf_ensure_mem((void **)&obj->maps, &obj->maps_cap,
1556 				sizeof(*obj->maps), obj->nr_maps + 1);
1557 	if (err)
1558 		return ERR_PTR(err);
1559 
1560 	map = &obj->maps[obj->nr_maps++];
1561 	map->obj = obj;
1562 	map->fd = -1;
1563 	map->inner_map_fd = -1;
1564 	map->autocreate = true;
1565 
1566 	return map;
1567 }
1568 
1569 static size_t bpf_map_mmap_sz(const struct bpf_map *map)
1570 {
1571 	long page_sz = sysconf(_SC_PAGE_SIZE);
1572 	size_t map_sz;
1573 
1574 	map_sz = (size_t)roundup(map->def.value_size, 8) * map->def.max_entries;
1575 	map_sz = roundup(map_sz, page_sz);
1576 	return map_sz;
1577 }
1578 
1579 static char *internal_map_name(struct bpf_object *obj, const char *real_name)
1580 {
1581 	char map_name[BPF_OBJ_NAME_LEN], *p;
1582 	int pfx_len, sfx_len = max((size_t)7, strlen(real_name));
1583 
1584 	/* This is one of the more confusing parts of libbpf for various
1585 	 * reasons, some of which are historical. The original idea for naming
1586 	 * internal names was to include as much of BPF object name prefix as
1587 	 * possible, so that it can be distinguished from similar internal
1588 	 * maps of a different BPF object.
1589 	 * As an example, let's say we have bpf_object named 'my_object_name'
1590 	 * and internal map corresponding to '.rodata' ELF section. The final
1591 	 * map name advertised to user and to the kernel will be
1592 	 * 'my_objec.rodata', taking first 8 characters of object name and
1593 	 * entire 7 characters of '.rodata'.
1594 	 * Somewhat confusingly, if internal map ELF section name is shorter
1595 	 * than 7 characters, e.g., '.bss', we still reserve 7 characters
1596 	 * for the suffix, even though we only have 4 actual characters, and
1597 	 * resulting map will be called 'my_objec.bss', not even using all 15
1598 	 * characters allowed by the kernel. Oh well, at least the truncated
1599 	 * object name is somewhat consistent in this case. But if the map
1600 	 * name is '.kconfig', we'll still have entirety of '.kconfig' added
1601 	 * (8 chars) and thus will be left with only first 7 characters of the
1602 	 * object name ('my_obje'). Happy guessing, user, that the final map
1603 	 * name will be "my_obje.kconfig".
1604 	 * Now, with libbpf starting to support arbitrarily named .rodata.*
1605 	 * and .data.* data sections, it's possible that ELF section name is
1606 	 * longer than allowed 15 chars, so we now need to be careful to take
1607 	 * only up to 15 first characters of ELF name, taking no BPF object
1608 	 * name characters at all. So '.rodata.abracadabra' will result in
1609 	 * '.rodata.abracad' kernel and user-visible name.
1610 	 * We need to keep this convoluted logic intact for .data, .bss and
1611 	 * .rodata maps, but for new custom .data.custom and .rodata.custom
1612 	 * maps we use their ELF names as is, not prepending bpf_object name
1613 	 * in front. We still need to truncate them to 15 characters for the
1614 	 * kernel. Full name can be recovered for such maps by using DATASEC
1615 	 * BTF type associated with such map's value type, though.
1616 	 */
1617 	if (sfx_len >= BPF_OBJ_NAME_LEN)
1618 		sfx_len = BPF_OBJ_NAME_LEN - 1;
1619 
1620 	/* if there are two or more dots in map name, it's a custom dot map */
1621 	if (strchr(real_name + 1, '.') != NULL)
1622 		pfx_len = 0;
1623 	else
1624 		pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
1625 
1626 	snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1627 		 sfx_len, real_name);
1628 
1629 	/* sanitise map name to characters allowed by kernel */
1630 	for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1631 		if (!isalnum(*p) && *p != '_' && *p != '.')
1632 			*p = '_';
1633 
1634 	return strdup(map_name);
1635 }
1636 
1637 static int
1638 bpf_map_find_btf_info(struct bpf_object *obj, struct bpf_map *map);
1639 
1640 static int
1641 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
1642 			      const char *real_name, int sec_idx, void *data, size_t data_sz)
1643 {
1644 	struct bpf_map_def *def;
1645 	struct bpf_map *map;
1646 	int err;
1647 
1648 	map = bpf_object__add_map(obj);
1649 	if (IS_ERR(map))
1650 		return PTR_ERR(map);
1651 
1652 	map->libbpf_type = type;
1653 	map->sec_idx = sec_idx;
1654 	map->sec_offset = 0;
1655 	map->real_name = strdup(real_name);
1656 	map->name = internal_map_name(obj, real_name);
1657 	if (!map->real_name || !map->name) {
1658 		zfree(&map->real_name);
1659 		zfree(&map->name);
1660 		return -ENOMEM;
1661 	}
1662 
1663 	def = &map->def;
1664 	def->type = BPF_MAP_TYPE_ARRAY;
1665 	def->key_size = sizeof(int);
1666 	def->value_size = data_sz;
1667 	def->max_entries = 1;
1668 	def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
1669 			 ? BPF_F_RDONLY_PROG : 0;
1670 	def->map_flags |= BPF_F_MMAPABLE;
1671 
1672 	pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
1673 		 map->name, map->sec_idx, map->sec_offset, def->map_flags);
1674 
1675 	map->mmaped = mmap(NULL, bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
1676 			   MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1677 	if (map->mmaped == MAP_FAILED) {
1678 		err = -errno;
1679 		map->mmaped = NULL;
1680 		pr_warn("failed to alloc map '%s' content buffer: %d\n",
1681 			map->name, err);
1682 		zfree(&map->real_name);
1683 		zfree(&map->name);
1684 		return err;
1685 	}
1686 
1687 	/* failures are fine because of maps like .rodata.str1.1 */
1688 	(void) bpf_map_find_btf_info(obj, map);
1689 
1690 	if (data)
1691 		memcpy(map->mmaped, data, data_sz);
1692 
1693 	pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
1694 	return 0;
1695 }
1696 
1697 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
1698 {
1699 	struct elf_sec_desc *sec_desc;
1700 	const char *sec_name;
1701 	int err = 0, sec_idx;
1702 
1703 	/*
1704 	 * Populate obj->maps with libbpf internal maps.
1705 	 */
1706 	for (sec_idx = 1; sec_idx < obj->efile.sec_cnt; sec_idx++) {
1707 		sec_desc = &obj->efile.secs[sec_idx];
1708 
1709 		switch (sec_desc->sec_type) {
1710 		case SEC_DATA:
1711 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1712 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
1713 							    sec_name, sec_idx,
1714 							    sec_desc->data->d_buf,
1715 							    sec_desc->data->d_size);
1716 			break;
1717 		case SEC_RODATA:
1718 			obj->has_rodata = true;
1719 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1720 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
1721 							    sec_name, sec_idx,
1722 							    sec_desc->data->d_buf,
1723 							    sec_desc->data->d_size);
1724 			break;
1725 		case SEC_BSS:
1726 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1727 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
1728 							    sec_name, sec_idx,
1729 							    NULL,
1730 							    sec_desc->data->d_size);
1731 			break;
1732 		default:
1733 			/* skip */
1734 			break;
1735 		}
1736 		if (err)
1737 			return err;
1738 	}
1739 	return 0;
1740 }
1741 
1742 
1743 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
1744 					       const void *name)
1745 {
1746 	int i;
1747 
1748 	for (i = 0; i < obj->nr_extern; i++) {
1749 		if (strcmp(obj->externs[i].name, name) == 0)
1750 			return &obj->externs[i];
1751 	}
1752 	return NULL;
1753 }
1754 
1755 static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
1756 			      char value)
1757 {
1758 	switch (ext->kcfg.type) {
1759 	case KCFG_BOOL:
1760 		if (value == 'm') {
1761 			pr_warn("extern (kcfg) %s=%c should be tristate or char\n",
1762 				ext->name, value);
1763 			return -EINVAL;
1764 		}
1765 		*(bool *)ext_val = value == 'y' ? true : false;
1766 		break;
1767 	case KCFG_TRISTATE:
1768 		if (value == 'y')
1769 			*(enum libbpf_tristate *)ext_val = TRI_YES;
1770 		else if (value == 'm')
1771 			*(enum libbpf_tristate *)ext_val = TRI_MODULE;
1772 		else /* value == 'n' */
1773 			*(enum libbpf_tristate *)ext_val = TRI_NO;
1774 		break;
1775 	case KCFG_CHAR:
1776 		*(char *)ext_val = value;
1777 		break;
1778 	case KCFG_UNKNOWN:
1779 	case KCFG_INT:
1780 	case KCFG_CHAR_ARR:
1781 	default:
1782 		pr_warn("extern (kcfg) %s=%c should be bool, tristate, or char\n",
1783 			ext->name, value);
1784 		return -EINVAL;
1785 	}
1786 	ext->is_set = true;
1787 	return 0;
1788 }
1789 
1790 static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
1791 			      const char *value)
1792 {
1793 	size_t len;
1794 
1795 	if (ext->kcfg.type != KCFG_CHAR_ARR) {
1796 		pr_warn("extern (kcfg) %s=%s should be char array\n", ext->name, value);
1797 		return -EINVAL;
1798 	}
1799 
1800 	len = strlen(value);
1801 	if (value[len - 1] != '"') {
1802 		pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
1803 			ext->name, value);
1804 		return -EINVAL;
1805 	}
1806 
1807 	/* strip quotes */
1808 	len -= 2;
1809 	if (len >= ext->kcfg.sz) {
1810 		pr_warn("extern (kcfg) '%s': long string config %s of (%zu bytes) truncated to %d bytes\n",
1811 			ext->name, value, len, ext->kcfg.sz - 1);
1812 		len = ext->kcfg.sz - 1;
1813 	}
1814 	memcpy(ext_val, value + 1, len);
1815 	ext_val[len] = '\0';
1816 	ext->is_set = true;
1817 	return 0;
1818 }
1819 
1820 static int parse_u64(const char *value, __u64 *res)
1821 {
1822 	char *value_end;
1823 	int err;
1824 
1825 	errno = 0;
1826 	*res = strtoull(value, &value_end, 0);
1827 	if (errno) {
1828 		err = -errno;
1829 		pr_warn("failed to parse '%s' as integer: %d\n", value, err);
1830 		return err;
1831 	}
1832 	if (*value_end) {
1833 		pr_warn("failed to parse '%s' as integer completely\n", value);
1834 		return -EINVAL;
1835 	}
1836 	return 0;
1837 }
1838 
1839 static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
1840 {
1841 	int bit_sz = ext->kcfg.sz * 8;
1842 
1843 	if (ext->kcfg.sz == 8)
1844 		return true;
1845 
1846 	/* Validate that value stored in u64 fits in integer of `ext->sz`
1847 	 * bytes size without any loss of information. If the target integer
1848 	 * is signed, we rely on the following limits of integer type of
1849 	 * Y bits and subsequent transformation:
1850 	 *
1851 	 *     -2^(Y-1) <= X           <= 2^(Y-1) - 1
1852 	 *            0 <= X + 2^(Y-1) <= 2^Y - 1
1853 	 *            0 <= X + 2^(Y-1) <  2^Y
1854 	 *
1855 	 *  For unsigned target integer, check that all the (64 - Y) bits are
1856 	 *  zero.
1857 	 */
1858 	if (ext->kcfg.is_signed)
1859 		return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
1860 	else
1861 		return (v >> bit_sz) == 0;
1862 }
1863 
1864 static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
1865 			      __u64 value)
1866 {
1867 	if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
1868 		pr_warn("extern (kcfg) %s=%llu should be integer\n",
1869 			ext->name, (unsigned long long)value);
1870 		return -EINVAL;
1871 	}
1872 	if (!is_kcfg_value_in_range(ext, value)) {
1873 		pr_warn("extern (kcfg) %s=%llu value doesn't fit in %d bytes\n",
1874 			ext->name, (unsigned long long)value, ext->kcfg.sz);
1875 		return -ERANGE;
1876 	}
1877 	switch (ext->kcfg.sz) {
1878 		case 1: *(__u8 *)ext_val = value; break;
1879 		case 2: *(__u16 *)ext_val = value; break;
1880 		case 4: *(__u32 *)ext_val = value; break;
1881 		case 8: *(__u64 *)ext_val = value; break;
1882 		default:
1883 			return -EINVAL;
1884 	}
1885 	ext->is_set = true;
1886 	return 0;
1887 }
1888 
1889 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
1890 					    char *buf, void *data)
1891 {
1892 	struct extern_desc *ext;
1893 	char *sep, *value;
1894 	int len, err = 0;
1895 	void *ext_val;
1896 	__u64 num;
1897 
1898 	if (!str_has_pfx(buf, "CONFIG_"))
1899 		return 0;
1900 
1901 	sep = strchr(buf, '=');
1902 	if (!sep) {
1903 		pr_warn("failed to parse '%s': no separator\n", buf);
1904 		return -EINVAL;
1905 	}
1906 
1907 	/* Trim ending '\n' */
1908 	len = strlen(buf);
1909 	if (buf[len - 1] == '\n')
1910 		buf[len - 1] = '\0';
1911 	/* Split on '=' and ensure that a value is present. */
1912 	*sep = '\0';
1913 	if (!sep[1]) {
1914 		*sep = '=';
1915 		pr_warn("failed to parse '%s': no value\n", buf);
1916 		return -EINVAL;
1917 	}
1918 
1919 	ext = find_extern_by_name(obj, buf);
1920 	if (!ext || ext->is_set)
1921 		return 0;
1922 
1923 	ext_val = data + ext->kcfg.data_off;
1924 	value = sep + 1;
1925 
1926 	switch (*value) {
1927 	case 'y': case 'n': case 'm':
1928 		err = set_kcfg_value_tri(ext, ext_val, *value);
1929 		break;
1930 	case '"':
1931 		err = set_kcfg_value_str(ext, ext_val, value);
1932 		break;
1933 	default:
1934 		/* assume integer */
1935 		err = parse_u64(value, &num);
1936 		if (err) {
1937 			pr_warn("extern (kcfg) %s=%s should be integer\n",
1938 				ext->name, value);
1939 			return err;
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=%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 static int bpf_object__init_user_maps(struct bpf_object *obj, bool strict)
2043 {
2044 	Elf_Data *symbols = obj->efile.symbols;
2045 	int i, map_def_sz = 0, nr_maps = 0, nr_syms;
2046 	Elf_Data *data = NULL;
2047 	Elf_Scn *scn;
2048 
2049 	if (obj->efile.maps_shndx < 0)
2050 		return 0;
2051 
2052 	if (libbpf_mode & LIBBPF_STRICT_MAP_DEFINITIONS) {
2053 		pr_warn("legacy map definitions in SEC(\"maps\") are not supported\n");
2054 		return -EOPNOTSUPP;
2055 	}
2056 
2057 	if (!symbols)
2058 		return -EINVAL;
2059 
2060 	scn = elf_sec_by_idx(obj, obj->efile.maps_shndx);
2061 	data = elf_sec_data(obj, scn);
2062 	if (!scn || !data) {
2063 		pr_warn("elf: failed to get legacy map definitions for %s\n",
2064 			obj->path);
2065 		return -EINVAL;
2066 	}
2067 
2068 	/*
2069 	 * Count number of maps. Each map has a name.
2070 	 * Array of maps is not supported: only the first element is
2071 	 * considered.
2072 	 *
2073 	 * TODO: Detect array of map and report error.
2074 	 */
2075 	nr_syms = symbols->d_size / sizeof(Elf64_Sym);
2076 	for (i = 0; i < nr_syms; i++) {
2077 		Elf64_Sym *sym = elf_sym_by_idx(obj, i);
2078 
2079 		if (sym->st_shndx != obj->efile.maps_shndx)
2080 			continue;
2081 		if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION)
2082 			continue;
2083 		nr_maps++;
2084 	}
2085 	/* Assume equally sized map definitions */
2086 	pr_debug("elf: found %d legacy map definitions (%zd bytes) in %s\n",
2087 		 nr_maps, data->d_size, obj->path);
2088 
2089 	if (!data->d_size || nr_maps == 0 || (data->d_size % nr_maps) != 0) {
2090 		pr_warn("elf: unable to determine legacy map definition size in %s\n",
2091 			obj->path);
2092 		return -EINVAL;
2093 	}
2094 	map_def_sz = data->d_size / nr_maps;
2095 
2096 	/* Fill obj->maps using data in "maps" section.  */
2097 	for (i = 0; i < nr_syms; i++) {
2098 		Elf64_Sym *sym = elf_sym_by_idx(obj, i);
2099 		const char *map_name;
2100 		struct bpf_map_def *def;
2101 		struct bpf_map *map;
2102 
2103 		if (sym->st_shndx != obj->efile.maps_shndx)
2104 			continue;
2105 		if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION)
2106 			continue;
2107 
2108 		map = bpf_object__add_map(obj);
2109 		if (IS_ERR(map))
2110 			return PTR_ERR(map);
2111 
2112 		map_name = elf_sym_str(obj, sym->st_name);
2113 		if (!map_name) {
2114 			pr_warn("failed to get map #%d name sym string for obj %s\n",
2115 				i, obj->path);
2116 			return -LIBBPF_ERRNO__FORMAT;
2117 		}
2118 
2119 		pr_warn("map '%s' (legacy): legacy map definitions are deprecated, use BTF-defined maps instead\n", map_name);
2120 
2121 		if (ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
2122 			pr_warn("map '%s' (legacy): static maps are not supported\n", map_name);
2123 			return -ENOTSUP;
2124 		}
2125 
2126 		map->libbpf_type = LIBBPF_MAP_UNSPEC;
2127 		map->sec_idx = sym->st_shndx;
2128 		map->sec_offset = sym->st_value;
2129 		pr_debug("map '%s' (legacy): at sec_idx %d, offset %zu.\n",
2130 			 map_name, map->sec_idx, map->sec_offset);
2131 		if (sym->st_value + map_def_sz > data->d_size) {
2132 			pr_warn("corrupted maps section in %s: last map \"%s\" too small\n",
2133 				obj->path, map_name);
2134 			return -EINVAL;
2135 		}
2136 
2137 		map->name = strdup(map_name);
2138 		if (!map->name) {
2139 			pr_warn("map '%s': failed to alloc map name\n", map_name);
2140 			return -ENOMEM;
2141 		}
2142 		pr_debug("map %d is \"%s\"\n", i, map->name);
2143 		def = (struct bpf_map_def *)(data->d_buf + sym->st_value);
2144 		/*
2145 		 * If the definition of the map in the object file fits in
2146 		 * bpf_map_def, copy it.  Any extra fields in our version
2147 		 * of bpf_map_def will default to zero as a result of the
2148 		 * calloc above.
2149 		 */
2150 		if (map_def_sz <= sizeof(struct bpf_map_def)) {
2151 			memcpy(&map->def, def, map_def_sz);
2152 		} else {
2153 			/*
2154 			 * Here the map structure being read is bigger than what
2155 			 * we expect, truncate if the excess bits are all zero.
2156 			 * If they are not zero, reject this map as
2157 			 * incompatible.
2158 			 */
2159 			char *b;
2160 
2161 			for (b = ((char *)def) + sizeof(struct bpf_map_def);
2162 			     b < ((char *)def) + map_def_sz; b++) {
2163 				if (*b != 0) {
2164 					pr_warn("maps section in %s: \"%s\" has unrecognized, non-zero options\n",
2165 						obj->path, map_name);
2166 					if (strict)
2167 						return -EINVAL;
2168 				}
2169 			}
2170 			memcpy(&map->def, def, sizeof(struct bpf_map_def));
2171 		}
2172 
2173 		/* btf info may not exist but fill it in if it does exist */
2174 		(void) bpf_map_find_btf_info(obj, map);
2175 	}
2176 	return 0;
2177 }
2178 
2179 const struct btf_type *
2180 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
2181 {
2182 	const struct btf_type *t = btf__type_by_id(btf, id);
2183 
2184 	if (res_id)
2185 		*res_id = id;
2186 
2187 	while (btf_is_mod(t) || btf_is_typedef(t)) {
2188 		if (res_id)
2189 			*res_id = t->type;
2190 		t = btf__type_by_id(btf, t->type);
2191 	}
2192 
2193 	return t;
2194 }
2195 
2196 static const struct btf_type *
2197 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
2198 {
2199 	const struct btf_type *t;
2200 
2201 	t = skip_mods_and_typedefs(btf, id, NULL);
2202 	if (!btf_is_ptr(t))
2203 		return NULL;
2204 
2205 	t = skip_mods_and_typedefs(btf, t->type, res_id);
2206 
2207 	return btf_is_func_proto(t) ? t : NULL;
2208 }
2209 
2210 static const char *__btf_kind_str(__u16 kind)
2211 {
2212 	switch (kind) {
2213 	case BTF_KIND_UNKN: return "void";
2214 	case BTF_KIND_INT: return "int";
2215 	case BTF_KIND_PTR: return "ptr";
2216 	case BTF_KIND_ARRAY: return "array";
2217 	case BTF_KIND_STRUCT: return "struct";
2218 	case BTF_KIND_UNION: return "union";
2219 	case BTF_KIND_ENUM: return "enum";
2220 	case BTF_KIND_FWD: return "fwd";
2221 	case BTF_KIND_TYPEDEF: return "typedef";
2222 	case BTF_KIND_VOLATILE: return "volatile";
2223 	case BTF_KIND_CONST: return "const";
2224 	case BTF_KIND_RESTRICT: return "restrict";
2225 	case BTF_KIND_FUNC: return "func";
2226 	case BTF_KIND_FUNC_PROTO: return "func_proto";
2227 	case BTF_KIND_VAR: return "var";
2228 	case BTF_KIND_DATASEC: return "datasec";
2229 	case BTF_KIND_FLOAT: return "float";
2230 	case BTF_KIND_DECL_TAG: return "decl_tag";
2231 	case BTF_KIND_TYPE_TAG: return "type_tag";
2232 	default: return "unknown";
2233 	}
2234 }
2235 
2236 const char *btf_kind_str(const struct btf_type *t)
2237 {
2238 	return __btf_kind_str(btf_kind(t));
2239 }
2240 
2241 /*
2242  * Fetch integer attribute of BTF map definition. Such attributes are
2243  * represented using a pointer to an array, in which dimensionality of array
2244  * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2245  * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2246  * type definition, while using only sizeof(void *) space in ELF data section.
2247  */
2248 static bool get_map_field_int(const char *map_name, const struct btf *btf,
2249 			      const struct btf_member *m, __u32 *res)
2250 {
2251 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2252 	const char *name = btf__name_by_offset(btf, m->name_off);
2253 	const struct btf_array *arr_info;
2254 	const struct btf_type *arr_t;
2255 
2256 	if (!btf_is_ptr(t)) {
2257 		pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2258 			map_name, name, btf_kind_str(t));
2259 		return false;
2260 	}
2261 
2262 	arr_t = btf__type_by_id(btf, t->type);
2263 	if (!arr_t) {
2264 		pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2265 			map_name, name, t->type);
2266 		return false;
2267 	}
2268 	if (!btf_is_array(arr_t)) {
2269 		pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2270 			map_name, name, btf_kind_str(arr_t));
2271 		return false;
2272 	}
2273 	arr_info = btf_array(arr_t);
2274 	*res = arr_info->nelems;
2275 	return true;
2276 }
2277 
2278 static int build_map_pin_path(struct bpf_map *map, const char *path)
2279 {
2280 	char buf[PATH_MAX];
2281 	int len;
2282 
2283 	if (!path)
2284 		path = "/sys/fs/bpf";
2285 
2286 	len = snprintf(buf, PATH_MAX, "%s/%s", path, bpf_map__name(map));
2287 	if (len < 0)
2288 		return -EINVAL;
2289 	else if (len >= PATH_MAX)
2290 		return -ENAMETOOLONG;
2291 
2292 	return bpf_map__set_pin_path(map, buf);
2293 }
2294 
2295 int parse_btf_map_def(const char *map_name, struct btf *btf,
2296 		      const struct btf_type *def_t, bool strict,
2297 		      struct btf_map_def *map_def, struct btf_map_def *inner_def)
2298 {
2299 	const struct btf_type *t;
2300 	const struct btf_member *m;
2301 	bool is_inner = inner_def == NULL;
2302 	int vlen, i;
2303 
2304 	vlen = btf_vlen(def_t);
2305 	m = btf_members(def_t);
2306 	for (i = 0; i < vlen; i++, m++) {
2307 		const char *name = btf__name_by_offset(btf, m->name_off);
2308 
2309 		if (!name) {
2310 			pr_warn("map '%s': invalid field #%d.\n", map_name, i);
2311 			return -EINVAL;
2312 		}
2313 		if (strcmp(name, "type") == 0) {
2314 			if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
2315 				return -EINVAL;
2316 			map_def->parts |= MAP_DEF_MAP_TYPE;
2317 		} else if (strcmp(name, "max_entries") == 0) {
2318 			if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
2319 				return -EINVAL;
2320 			map_def->parts |= MAP_DEF_MAX_ENTRIES;
2321 		} else if (strcmp(name, "map_flags") == 0) {
2322 			if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
2323 				return -EINVAL;
2324 			map_def->parts |= MAP_DEF_MAP_FLAGS;
2325 		} else if (strcmp(name, "numa_node") == 0) {
2326 			if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
2327 				return -EINVAL;
2328 			map_def->parts |= MAP_DEF_NUMA_NODE;
2329 		} else if (strcmp(name, "key_size") == 0) {
2330 			__u32 sz;
2331 
2332 			if (!get_map_field_int(map_name, btf, m, &sz))
2333 				return -EINVAL;
2334 			if (map_def->key_size && map_def->key_size != sz) {
2335 				pr_warn("map '%s': conflicting key size %u != %u.\n",
2336 					map_name, map_def->key_size, sz);
2337 				return -EINVAL;
2338 			}
2339 			map_def->key_size = sz;
2340 			map_def->parts |= MAP_DEF_KEY_SIZE;
2341 		} else if (strcmp(name, "key") == 0) {
2342 			__s64 sz;
2343 
2344 			t = btf__type_by_id(btf, m->type);
2345 			if (!t) {
2346 				pr_warn("map '%s': key type [%d] not found.\n",
2347 					map_name, m->type);
2348 				return -EINVAL;
2349 			}
2350 			if (!btf_is_ptr(t)) {
2351 				pr_warn("map '%s': key spec is not PTR: %s.\n",
2352 					map_name, btf_kind_str(t));
2353 				return -EINVAL;
2354 			}
2355 			sz = btf__resolve_size(btf, t->type);
2356 			if (sz < 0) {
2357 				pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2358 					map_name, t->type, (ssize_t)sz);
2359 				return sz;
2360 			}
2361 			if (map_def->key_size && map_def->key_size != sz) {
2362 				pr_warn("map '%s': conflicting key size %u != %zd.\n",
2363 					map_name, map_def->key_size, (ssize_t)sz);
2364 				return -EINVAL;
2365 			}
2366 			map_def->key_size = sz;
2367 			map_def->key_type_id = t->type;
2368 			map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
2369 		} else if (strcmp(name, "value_size") == 0) {
2370 			__u32 sz;
2371 
2372 			if (!get_map_field_int(map_name, btf, m, &sz))
2373 				return -EINVAL;
2374 			if (map_def->value_size && map_def->value_size != sz) {
2375 				pr_warn("map '%s': conflicting value size %u != %u.\n",
2376 					map_name, map_def->value_size, sz);
2377 				return -EINVAL;
2378 			}
2379 			map_def->value_size = sz;
2380 			map_def->parts |= MAP_DEF_VALUE_SIZE;
2381 		} else if (strcmp(name, "value") == 0) {
2382 			__s64 sz;
2383 
2384 			t = btf__type_by_id(btf, m->type);
2385 			if (!t) {
2386 				pr_warn("map '%s': value type [%d] not found.\n",
2387 					map_name, m->type);
2388 				return -EINVAL;
2389 			}
2390 			if (!btf_is_ptr(t)) {
2391 				pr_warn("map '%s': value spec is not PTR: %s.\n",
2392 					map_name, btf_kind_str(t));
2393 				return -EINVAL;
2394 			}
2395 			sz = btf__resolve_size(btf, t->type);
2396 			if (sz < 0) {
2397 				pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2398 					map_name, t->type, (ssize_t)sz);
2399 				return sz;
2400 			}
2401 			if (map_def->value_size && map_def->value_size != sz) {
2402 				pr_warn("map '%s': conflicting value size %u != %zd.\n",
2403 					map_name, map_def->value_size, (ssize_t)sz);
2404 				return -EINVAL;
2405 			}
2406 			map_def->value_size = sz;
2407 			map_def->value_type_id = t->type;
2408 			map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
2409 		}
2410 		else if (strcmp(name, "values") == 0) {
2411 			bool is_map_in_map = bpf_map_type__is_map_in_map(map_def->map_type);
2412 			bool is_prog_array = map_def->map_type == BPF_MAP_TYPE_PROG_ARRAY;
2413 			const char *desc = is_map_in_map ? "map-in-map inner" : "prog-array value";
2414 			char inner_map_name[128];
2415 			int err;
2416 
2417 			if (is_inner) {
2418 				pr_warn("map '%s': multi-level inner maps not supported.\n",
2419 					map_name);
2420 				return -ENOTSUP;
2421 			}
2422 			if (i != vlen - 1) {
2423 				pr_warn("map '%s': '%s' member should be last.\n",
2424 					map_name, name);
2425 				return -EINVAL;
2426 			}
2427 			if (!is_map_in_map && !is_prog_array) {
2428 				pr_warn("map '%s': should be map-in-map or prog-array.\n",
2429 					map_name);
2430 				return -ENOTSUP;
2431 			}
2432 			if (map_def->value_size && map_def->value_size != 4) {
2433 				pr_warn("map '%s': conflicting value size %u != 4.\n",
2434 					map_name, map_def->value_size);
2435 				return -EINVAL;
2436 			}
2437 			map_def->value_size = 4;
2438 			t = btf__type_by_id(btf, m->type);
2439 			if (!t) {
2440 				pr_warn("map '%s': %s type [%d] not found.\n",
2441 					map_name, desc, m->type);
2442 				return -EINVAL;
2443 			}
2444 			if (!btf_is_array(t) || btf_array(t)->nelems) {
2445 				pr_warn("map '%s': %s spec is not a zero-sized array.\n",
2446 					map_name, desc);
2447 				return -EINVAL;
2448 			}
2449 			t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
2450 			if (!btf_is_ptr(t)) {
2451 				pr_warn("map '%s': %s def is of unexpected kind %s.\n",
2452 					map_name, desc, btf_kind_str(t));
2453 				return -EINVAL;
2454 			}
2455 			t = skip_mods_and_typedefs(btf, t->type, NULL);
2456 			if (is_prog_array) {
2457 				if (!btf_is_func_proto(t)) {
2458 					pr_warn("map '%s': prog-array value def is of unexpected kind %s.\n",
2459 						map_name, btf_kind_str(t));
2460 					return -EINVAL;
2461 				}
2462 				continue;
2463 			}
2464 			if (!btf_is_struct(t)) {
2465 				pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2466 					map_name, btf_kind_str(t));
2467 				return -EINVAL;
2468 			}
2469 
2470 			snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2471 			err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
2472 			if (err)
2473 				return err;
2474 
2475 			map_def->parts |= MAP_DEF_INNER_MAP;
2476 		} else if (strcmp(name, "pinning") == 0) {
2477 			__u32 val;
2478 
2479 			if (is_inner) {
2480 				pr_warn("map '%s': inner def can't be pinned.\n", map_name);
2481 				return -EINVAL;
2482 			}
2483 			if (!get_map_field_int(map_name, btf, m, &val))
2484 				return -EINVAL;
2485 			if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
2486 				pr_warn("map '%s': invalid pinning value %u.\n",
2487 					map_name, val);
2488 				return -EINVAL;
2489 			}
2490 			map_def->pinning = val;
2491 			map_def->parts |= MAP_DEF_PINNING;
2492 		} else if (strcmp(name, "map_extra") == 0) {
2493 			__u32 map_extra;
2494 
2495 			if (!get_map_field_int(map_name, btf, m, &map_extra))
2496 				return -EINVAL;
2497 			map_def->map_extra = map_extra;
2498 			map_def->parts |= MAP_DEF_MAP_EXTRA;
2499 		} else {
2500 			if (strict) {
2501 				pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
2502 				return -ENOTSUP;
2503 			}
2504 			pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
2505 		}
2506 	}
2507 
2508 	if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2509 		pr_warn("map '%s': map type isn't specified.\n", map_name);
2510 		return -EINVAL;
2511 	}
2512 
2513 	return 0;
2514 }
2515 
2516 static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2517 {
2518 	map->def.type = def->map_type;
2519 	map->def.key_size = def->key_size;
2520 	map->def.value_size = def->value_size;
2521 	map->def.max_entries = def->max_entries;
2522 	map->def.map_flags = def->map_flags;
2523 	map->map_extra = def->map_extra;
2524 
2525 	map->numa_node = def->numa_node;
2526 	map->btf_key_type_id = def->key_type_id;
2527 	map->btf_value_type_id = def->value_type_id;
2528 
2529 	if (def->parts & MAP_DEF_MAP_TYPE)
2530 		pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2531 
2532 	if (def->parts & MAP_DEF_KEY_TYPE)
2533 		pr_debug("map '%s': found key [%u], sz = %u.\n",
2534 			 map->name, def->key_type_id, def->key_size);
2535 	else if (def->parts & MAP_DEF_KEY_SIZE)
2536 		pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2537 
2538 	if (def->parts & MAP_DEF_VALUE_TYPE)
2539 		pr_debug("map '%s': found value [%u], sz = %u.\n",
2540 			 map->name, def->value_type_id, def->value_size);
2541 	else if (def->parts & MAP_DEF_VALUE_SIZE)
2542 		pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2543 
2544 	if (def->parts & MAP_DEF_MAX_ENTRIES)
2545 		pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2546 	if (def->parts & MAP_DEF_MAP_FLAGS)
2547 		pr_debug("map '%s': found map_flags = 0x%x.\n", map->name, def->map_flags);
2548 	if (def->parts & MAP_DEF_MAP_EXTRA)
2549 		pr_debug("map '%s': found map_extra = 0x%llx.\n", map->name,
2550 			 (unsigned long long)def->map_extra);
2551 	if (def->parts & MAP_DEF_PINNING)
2552 		pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2553 	if (def->parts & MAP_DEF_NUMA_NODE)
2554 		pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2555 
2556 	if (def->parts & MAP_DEF_INNER_MAP)
2557 		pr_debug("map '%s': found inner map definition.\n", map->name);
2558 }
2559 
2560 static const char *btf_var_linkage_str(__u32 linkage)
2561 {
2562 	switch (linkage) {
2563 	case BTF_VAR_STATIC: return "static";
2564 	case BTF_VAR_GLOBAL_ALLOCATED: return "global";
2565 	case BTF_VAR_GLOBAL_EXTERN: return "extern";
2566 	default: return "unknown";
2567 	}
2568 }
2569 
2570 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2571 					 const struct btf_type *sec,
2572 					 int var_idx, int sec_idx,
2573 					 const Elf_Data *data, bool strict,
2574 					 const char *pin_root_path)
2575 {
2576 	struct btf_map_def map_def = {}, inner_def = {};
2577 	const struct btf_type *var, *def;
2578 	const struct btf_var_secinfo *vi;
2579 	const struct btf_var *var_extra;
2580 	const char *map_name;
2581 	struct bpf_map *map;
2582 	int err;
2583 
2584 	vi = btf_var_secinfos(sec) + var_idx;
2585 	var = btf__type_by_id(obj->btf, vi->type);
2586 	var_extra = btf_var(var);
2587 	map_name = btf__name_by_offset(obj->btf, var->name_off);
2588 
2589 	if (map_name == NULL || map_name[0] == '\0') {
2590 		pr_warn("map #%d: empty name.\n", var_idx);
2591 		return -EINVAL;
2592 	}
2593 	if ((__u64)vi->offset + vi->size > data->d_size) {
2594 		pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2595 		return -EINVAL;
2596 	}
2597 	if (!btf_is_var(var)) {
2598 		pr_warn("map '%s': unexpected var kind %s.\n",
2599 			map_name, btf_kind_str(var));
2600 		return -EINVAL;
2601 	}
2602 	if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
2603 		pr_warn("map '%s': unsupported map linkage %s.\n",
2604 			map_name, btf_var_linkage_str(var_extra->linkage));
2605 		return -EOPNOTSUPP;
2606 	}
2607 
2608 	def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2609 	if (!btf_is_struct(def)) {
2610 		pr_warn("map '%s': unexpected def kind %s.\n",
2611 			map_name, btf_kind_str(var));
2612 		return -EINVAL;
2613 	}
2614 	if (def->size > vi->size) {
2615 		pr_warn("map '%s': invalid def size.\n", map_name);
2616 		return -EINVAL;
2617 	}
2618 
2619 	map = bpf_object__add_map(obj);
2620 	if (IS_ERR(map))
2621 		return PTR_ERR(map);
2622 	map->name = strdup(map_name);
2623 	if (!map->name) {
2624 		pr_warn("map '%s': failed to alloc map name.\n", map_name);
2625 		return -ENOMEM;
2626 	}
2627 	map->libbpf_type = LIBBPF_MAP_UNSPEC;
2628 	map->def.type = BPF_MAP_TYPE_UNSPEC;
2629 	map->sec_idx = sec_idx;
2630 	map->sec_offset = vi->offset;
2631 	map->btf_var_idx = var_idx;
2632 	pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2633 		 map_name, map->sec_idx, map->sec_offset);
2634 
2635 	err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
2636 	if (err)
2637 		return err;
2638 
2639 	fill_map_from_def(map, &map_def);
2640 
2641 	if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
2642 		err = build_map_pin_path(map, pin_root_path);
2643 		if (err) {
2644 			pr_warn("map '%s': couldn't build pin path.\n", map->name);
2645 			return err;
2646 		}
2647 	}
2648 
2649 	if (map_def.parts & MAP_DEF_INNER_MAP) {
2650 		map->inner_map = calloc(1, sizeof(*map->inner_map));
2651 		if (!map->inner_map)
2652 			return -ENOMEM;
2653 		map->inner_map->fd = -1;
2654 		map->inner_map->sec_idx = sec_idx;
2655 		map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
2656 		if (!map->inner_map->name)
2657 			return -ENOMEM;
2658 		sprintf(map->inner_map->name, "%s.inner", map_name);
2659 
2660 		fill_map_from_def(map->inner_map, &inner_def);
2661 	}
2662 
2663 	err = bpf_map_find_btf_info(obj, map);
2664 	if (err)
2665 		return err;
2666 
2667 	return 0;
2668 }
2669 
2670 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
2671 					  const char *pin_root_path)
2672 {
2673 	const struct btf_type *sec = NULL;
2674 	int nr_types, i, vlen, err;
2675 	const struct btf_type *t;
2676 	const char *name;
2677 	Elf_Data *data;
2678 	Elf_Scn *scn;
2679 
2680 	if (obj->efile.btf_maps_shndx < 0)
2681 		return 0;
2682 
2683 	scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
2684 	data = elf_sec_data(obj, scn);
2685 	if (!scn || !data) {
2686 		pr_warn("elf: failed to get %s map definitions for %s\n",
2687 			MAPS_ELF_SEC, obj->path);
2688 		return -EINVAL;
2689 	}
2690 
2691 	nr_types = btf__type_cnt(obj->btf);
2692 	for (i = 1; i < nr_types; i++) {
2693 		t = btf__type_by_id(obj->btf, i);
2694 		if (!btf_is_datasec(t))
2695 			continue;
2696 		name = btf__name_by_offset(obj->btf, t->name_off);
2697 		if (strcmp(name, MAPS_ELF_SEC) == 0) {
2698 			sec = t;
2699 			obj->efile.btf_maps_sec_btf_id = i;
2700 			break;
2701 		}
2702 	}
2703 
2704 	if (!sec) {
2705 		pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
2706 		return -ENOENT;
2707 	}
2708 
2709 	vlen = btf_vlen(sec);
2710 	for (i = 0; i < vlen; i++) {
2711 		err = bpf_object__init_user_btf_map(obj, sec, i,
2712 						    obj->efile.btf_maps_shndx,
2713 						    data, strict,
2714 						    pin_root_path);
2715 		if (err)
2716 			return err;
2717 	}
2718 
2719 	return 0;
2720 }
2721 
2722 static int bpf_object__init_maps(struct bpf_object *obj,
2723 				 const struct bpf_object_open_opts *opts)
2724 {
2725 	const char *pin_root_path;
2726 	bool strict;
2727 	int err;
2728 
2729 	strict = !OPTS_GET(opts, relaxed_maps, false);
2730 	pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
2731 
2732 	err = bpf_object__init_user_maps(obj, strict);
2733 	err = err ?: bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
2734 	err = err ?: bpf_object__init_global_data_maps(obj);
2735 	err = err ?: bpf_object__init_kconfig_map(obj);
2736 	err = err ?: bpf_object__init_struct_ops_maps(obj);
2737 
2738 	return err;
2739 }
2740 
2741 static bool section_have_execinstr(struct bpf_object *obj, int idx)
2742 {
2743 	Elf64_Shdr *sh;
2744 
2745 	sh = elf_sec_hdr(obj, elf_sec_by_idx(obj, idx));
2746 	if (!sh)
2747 		return false;
2748 
2749 	return sh->sh_flags & SHF_EXECINSTR;
2750 }
2751 
2752 static bool btf_needs_sanitization(struct bpf_object *obj)
2753 {
2754 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2755 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2756 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2757 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2758 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2759 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2760 
2761 	return !has_func || !has_datasec || !has_func_global || !has_float ||
2762 	       !has_decl_tag || !has_type_tag;
2763 }
2764 
2765 static void bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *btf)
2766 {
2767 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2768 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2769 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2770 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2771 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2772 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2773 	struct btf_type *t;
2774 	int i, j, vlen;
2775 
2776 	for (i = 1; i < btf__type_cnt(btf); i++) {
2777 		t = (struct btf_type *)btf__type_by_id(btf, i);
2778 
2779 		if ((!has_datasec && btf_is_var(t)) || (!has_decl_tag && btf_is_decl_tag(t))) {
2780 			/* replace VAR/DECL_TAG with INT */
2781 			t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
2782 			/*
2783 			 * using size = 1 is the safest choice, 4 will be too
2784 			 * big and cause kernel BTF validation failure if
2785 			 * original variable took less than 4 bytes
2786 			 */
2787 			t->size = 1;
2788 			*(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
2789 		} else if (!has_datasec && btf_is_datasec(t)) {
2790 			/* replace DATASEC with STRUCT */
2791 			const struct btf_var_secinfo *v = btf_var_secinfos(t);
2792 			struct btf_member *m = btf_members(t);
2793 			struct btf_type *vt;
2794 			char *name;
2795 
2796 			name = (char *)btf__name_by_offset(btf, t->name_off);
2797 			while (*name) {
2798 				if (*name == '.')
2799 					*name = '_';
2800 				name++;
2801 			}
2802 
2803 			vlen = btf_vlen(t);
2804 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
2805 			for (j = 0; j < vlen; j++, v++, m++) {
2806 				/* order of field assignments is important */
2807 				m->offset = v->offset * 8;
2808 				m->type = v->type;
2809 				/* preserve variable name as member name */
2810 				vt = (void *)btf__type_by_id(btf, v->type);
2811 				m->name_off = vt->name_off;
2812 			}
2813 		} else if (!has_func && btf_is_func_proto(t)) {
2814 			/* replace FUNC_PROTO with ENUM */
2815 			vlen = btf_vlen(t);
2816 			t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
2817 			t->size = sizeof(__u32); /* kernel enforced */
2818 		} else if (!has_func && btf_is_func(t)) {
2819 			/* replace FUNC with TYPEDEF */
2820 			t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
2821 		} else if (!has_func_global && btf_is_func(t)) {
2822 			/* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
2823 			t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
2824 		} else if (!has_float && btf_is_float(t)) {
2825 			/* replace FLOAT with an equally-sized empty STRUCT;
2826 			 * since C compilers do not accept e.g. "float" as a
2827 			 * valid struct name, make it anonymous
2828 			 */
2829 			t->name_off = 0;
2830 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
2831 		} else if (!has_type_tag && btf_is_type_tag(t)) {
2832 			/* replace TYPE_TAG with a CONST */
2833 			t->name_off = 0;
2834 			t->info = BTF_INFO_ENC(BTF_KIND_CONST, 0, 0);
2835 		}
2836 	}
2837 }
2838 
2839 static bool libbpf_needs_btf(const struct bpf_object *obj)
2840 {
2841 	return obj->efile.btf_maps_shndx >= 0 ||
2842 	       obj->efile.st_ops_shndx >= 0 ||
2843 	       obj->nr_extern > 0;
2844 }
2845 
2846 static bool kernel_needs_btf(const struct bpf_object *obj)
2847 {
2848 	return obj->efile.st_ops_shndx >= 0;
2849 }
2850 
2851 static int bpf_object__init_btf(struct bpf_object *obj,
2852 				Elf_Data *btf_data,
2853 				Elf_Data *btf_ext_data)
2854 {
2855 	int err = -ENOENT;
2856 
2857 	if (btf_data) {
2858 		obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
2859 		err = libbpf_get_error(obj->btf);
2860 		if (err) {
2861 			obj->btf = NULL;
2862 			pr_warn("Error loading ELF section %s: %d.\n", BTF_ELF_SEC, err);
2863 			goto out;
2864 		}
2865 		/* enforce 8-byte pointers for BPF-targeted BTFs */
2866 		btf__set_pointer_size(obj->btf, 8);
2867 	}
2868 	if (btf_ext_data) {
2869 		struct btf_ext_info *ext_segs[3];
2870 		int seg_num, sec_num;
2871 
2872 		if (!obj->btf) {
2873 			pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
2874 				 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
2875 			goto out;
2876 		}
2877 		obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
2878 		err = libbpf_get_error(obj->btf_ext);
2879 		if (err) {
2880 			pr_warn("Error loading ELF section %s: %d. Ignored and continue.\n",
2881 				BTF_EXT_ELF_SEC, err);
2882 			obj->btf_ext = NULL;
2883 			goto out;
2884 		}
2885 
2886 		/* setup .BTF.ext to ELF section mapping */
2887 		ext_segs[0] = &obj->btf_ext->func_info;
2888 		ext_segs[1] = &obj->btf_ext->line_info;
2889 		ext_segs[2] = &obj->btf_ext->core_relo_info;
2890 		for (seg_num = 0; seg_num < ARRAY_SIZE(ext_segs); seg_num++) {
2891 			struct btf_ext_info *seg = ext_segs[seg_num];
2892 			const struct btf_ext_info_sec *sec;
2893 			const char *sec_name;
2894 			Elf_Scn *scn;
2895 
2896 			if (seg->sec_cnt == 0)
2897 				continue;
2898 
2899 			seg->sec_idxs = calloc(seg->sec_cnt, sizeof(*seg->sec_idxs));
2900 			if (!seg->sec_idxs) {
2901 				err = -ENOMEM;
2902 				goto out;
2903 			}
2904 
2905 			sec_num = 0;
2906 			for_each_btf_ext_sec(seg, sec) {
2907 				/* preventively increment index to avoid doing
2908 				 * this before every continue below
2909 				 */
2910 				sec_num++;
2911 
2912 				sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
2913 				if (str_is_empty(sec_name))
2914 					continue;
2915 				scn = elf_sec_by_name(obj, sec_name);
2916 				if (!scn)
2917 					continue;
2918 
2919 				seg->sec_idxs[sec_num - 1] = elf_ndxscn(scn);
2920 			}
2921 		}
2922 	}
2923 out:
2924 	if (err && libbpf_needs_btf(obj)) {
2925 		pr_warn("BTF is required, but is missing or corrupted.\n");
2926 		return err;
2927 	}
2928 	return 0;
2929 }
2930 
2931 static int compare_vsi_off(const void *_a, const void *_b)
2932 {
2933 	const struct btf_var_secinfo *a = _a;
2934 	const struct btf_var_secinfo *b = _b;
2935 
2936 	return a->offset - b->offset;
2937 }
2938 
2939 static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
2940 			     struct btf_type *t)
2941 {
2942 	__u32 size = 0, off = 0, i, vars = btf_vlen(t);
2943 	const char *name = btf__name_by_offset(btf, t->name_off);
2944 	const struct btf_type *t_var;
2945 	struct btf_var_secinfo *vsi;
2946 	const struct btf_var *var;
2947 	int ret;
2948 
2949 	if (!name) {
2950 		pr_debug("No name found in string section for DATASEC kind.\n");
2951 		return -ENOENT;
2952 	}
2953 
2954 	/* .extern datasec size and var offsets were set correctly during
2955 	 * extern collection step, so just skip straight to sorting variables
2956 	 */
2957 	if (t->size)
2958 		goto sort_vars;
2959 
2960 	ret = find_elf_sec_sz(obj, name, &size);
2961 	if (ret || !size) {
2962 		pr_debug("Invalid size for section %s: %u bytes\n", name, size);
2963 		return -ENOENT;
2964 	}
2965 
2966 	t->size = size;
2967 
2968 	for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
2969 		t_var = btf__type_by_id(btf, vsi->type);
2970 		if (!t_var || !btf_is_var(t_var)) {
2971 			pr_debug("Non-VAR type seen in section %s\n", name);
2972 			return -EINVAL;
2973 		}
2974 
2975 		var = btf_var(t_var);
2976 		if (var->linkage == BTF_VAR_STATIC)
2977 			continue;
2978 
2979 		name = btf__name_by_offset(btf, t_var->name_off);
2980 		if (!name) {
2981 			pr_debug("No name found in string section for VAR kind\n");
2982 			return -ENOENT;
2983 		}
2984 
2985 		ret = find_elf_var_offset(obj, name, &off);
2986 		if (ret) {
2987 			pr_debug("No offset found in symbol table for VAR %s\n",
2988 				 name);
2989 			return -ENOENT;
2990 		}
2991 
2992 		vsi->offset = off;
2993 	}
2994 
2995 sort_vars:
2996 	qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
2997 	return 0;
2998 }
2999 
3000 static int btf_finalize_data(struct bpf_object *obj, struct btf *btf)
3001 {
3002 	int err = 0;
3003 	__u32 i, n = btf__type_cnt(btf);
3004 
3005 	for (i = 1; i < n; i++) {
3006 		struct btf_type *t = btf_type_by_id(btf, i);
3007 
3008 		/* Loader needs to fix up some of the things compiler
3009 		 * couldn't get its hands on while emitting BTF. This
3010 		 * is section size and global variable offset. We use
3011 		 * the info from the ELF itself for this purpose.
3012 		 */
3013 		if (btf_is_datasec(t)) {
3014 			err = btf_fixup_datasec(obj, btf, t);
3015 			if (err)
3016 				break;
3017 		}
3018 	}
3019 
3020 	return libbpf_err(err);
3021 }
3022 
3023 int btf__finalize_data(struct bpf_object *obj, struct btf *btf)
3024 {
3025 	return btf_finalize_data(obj, btf);
3026 }
3027 
3028 static int bpf_object__finalize_btf(struct bpf_object *obj)
3029 {
3030 	int err;
3031 
3032 	if (!obj->btf)
3033 		return 0;
3034 
3035 	err = btf_finalize_data(obj, obj->btf);
3036 	if (err) {
3037 		pr_warn("Error finalizing %s: %d.\n", BTF_ELF_SEC, err);
3038 		return err;
3039 	}
3040 
3041 	return 0;
3042 }
3043 
3044 static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
3045 {
3046 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
3047 	    prog->type == BPF_PROG_TYPE_LSM)
3048 		return true;
3049 
3050 	/* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
3051 	 * also need vmlinux BTF
3052 	 */
3053 	if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
3054 		return true;
3055 
3056 	return false;
3057 }
3058 
3059 static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
3060 {
3061 	struct bpf_program *prog;
3062 	int i;
3063 
3064 	/* CO-RE relocations need kernel BTF, only when btf_custom_path
3065 	 * is not specified
3066 	 */
3067 	if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
3068 		return true;
3069 
3070 	/* Support for typed ksyms needs kernel BTF */
3071 	for (i = 0; i < obj->nr_extern; i++) {
3072 		const struct extern_desc *ext;
3073 
3074 		ext = &obj->externs[i];
3075 		if (ext->type == EXT_KSYM && ext->ksym.type_id)
3076 			return true;
3077 	}
3078 
3079 	bpf_object__for_each_program(prog, obj) {
3080 		if (!prog->autoload)
3081 			continue;
3082 		if (prog_needs_vmlinux_btf(prog))
3083 			return true;
3084 	}
3085 
3086 	return false;
3087 }
3088 
3089 static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
3090 {
3091 	int err;
3092 
3093 	/* btf_vmlinux could be loaded earlier */
3094 	if (obj->btf_vmlinux || obj->gen_loader)
3095 		return 0;
3096 
3097 	if (!force && !obj_needs_vmlinux_btf(obj))
3098 		return 0;
3099 
3100 	obj->btf_vmlinux = btf__load_vmlinux_btf();
3101 	err = libbpf_get_error(obj->btf_vmlinux);
3102 	if (err) {
3103 		pr_warn("Error loading vmlinux BTF: %d\n", err);
3104 		obj->btf_vmlinux = NULL;
3105 		return err;
3106 	}
3107 	return 0;
3108 }
3109 
3110 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
3111 {
3112 	struct btf *kern_btf = obj->btf;
3113 	bool btf_mandatory, sanitize;
3114 	int i, err = 0;
3115 
3116 	if (!obj->btf)
3117 		return 0;
3118 
3119 	if (!kernel_supports(obj, FEAT_BTF)) {
3120 		if (kernel_needs_btf(obj)) {
3121 			err = -EOPNOTSUPP;
3122 			goto report;
3123 		}
3124 		pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
3125 		return 0;
3126 	}
3127 
3128 	/* Even though some subprogs are global/weak, user might prefer more
3129 	 * permissive BPF verification process that BPF verifier performs for
3130 	 * static functions, taking into account more context from the caller
3131 	 * functions. In such case, they need to mark such subprogs with
3132 	 * __attribute__((visibility("hidden"))) and libbpf will adjust
3133 	 * corresponding FUNC BTF type to be marked as static and trigger more
3134 	 * involved BPF verification process.
3135 	 */
3136 	for (i = 0; i < obj->nr_programs; i++) {
3137 		struct bpf_program *prog = &obj->programs[i];
3138 		struct btf_type *t;
3139 		const char *name;
3140 		int j, n;
3141 
3142 		if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
3143 			continue;
3144 
3145 		n = btf__type_cnt(obj->btf);
3146 		for (j = 1; j < n; j++) {
3147 			t = btf_type_by_id(obj->btf, j);
3148 			if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
3149 				continue;
3150 
3151 			name = btf__str_by_offset(obj->btf, t->name_off);
3152 			if (strcmp(name, prog->name) != 0)
3153 				continue;
3154 
3155 			t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
3156 			break;
3157 		}
3158 	}
3159 
3160 	sanitize = btf_needs_sanitization(obj);
3161 	if (sanitize) {
3162 		const void *raw_data;
3163 		__u32 sz;
3164 
3165 		/* clone BTF to sanitize a copy and leave the original intact */
3166 		raw_data = btf__raw_data(obj->btf, &sz);
3167 		kern_btf = btf__new(raw_data, sz);
3168 		err = libbpf_get_error(kern_btf);
3169 		if (err)
3170 			return err;
3171 
3172 		/* enforce 8-byte pointers for BPF-targeted BTFs */
3173 		btf__set_pointer_size(obj->btf, 8);
3174 		bpf_object__sanitize_btf(obj, kern_btf);
3175 	}
3176 
3177 	if (obj->gen_loader) {
3178 		__u32 raw_size = 0;
3179 		const void *raw_data = btf__raw_data(kern_btf, &raw_size);
3180 
3181 		if (!raw_data)
3182 			return -ENOMEM;
3183 		bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
3184 		/* Pretend to have valid FD to pass various fd >= 0 checks.
3185 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
3186 		 */
3187 		btf__set_fd(kern_btf, 0);
3188 	} else {
3189 		/* currently BPF_BTF_LOAD only supports log_level 1 */
3190 		err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
3191 					   obj->log_level ? 1 : 0);
3192 	}
3193 	if (sanitize) {
3194 		if (!err) {
3195 			/* move fd to libbpf's BTF */
3196 			btf__set_fd(obj->btf, btf__fd(kern_btf));
3197 			btf__set_fd(kern_btf, -1);
3198 		}
3199 		btf__free(kern_btf);
3200 	}
3201 report:
3202 	if (err) {
3203 		btf_mandatory = kernel_needs_btf(obj);
3204 		pr_warn("Error loading .BTF into kernel: %d. %s\n", err,
3205 			btf_mandatory ? "BTF is mandatory, can't proceed."
3206 				      : "BTF is optional, ignoring.");
3207 		if (!btf_mandatory)
3208 			err = 0;
3209 	}
3210 	return err;
3211 }
3212 
3213 static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
3214 {
3215 	const char *name;
3216 
3217 	name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
3218 	if (!name) {
3219 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3220 			off, obj->path, elf_errmsg(-1));
3221 		return NULL;
3222 	}
3223 
3224 	return name;
3225 }
3226 
3227 static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
3228 {
3229 	const char *name;
3230 
3231 	name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
3232 	if (!name) {
3233 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3234 			off, obj->path, elf_errmsg(-1));
3235 		return NULL;
3236 	}
3237 
3238 	return name;
3239 }
3240 
3241 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
3242 {
3243 	Elf_Scn *scn;
3244 
3245 	scn = elf_getscn(obj->efile.elf, idx);
3246 	if (!scn) {
3247 		pr_warn("elf: failed to get section(%zu) from %s: %s\n",
3248 			idx, obj->path, elf_errmsg(-1));
3249 		return NULL;
3250 	}
3251 	return scn;
3252 }
3253 
3254 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
3255 {
3256 	Elf_Scn *scn = NULL;
3257 	Elf *elf = obj->efile.elf;
3258 	const char *sec_name;
3259 
3260 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3261 		sec_name = elf_sec_name(obj, scn);
3262 		if (!sec_name)
3263 			return NULL;
3264 
3265 		if (strcmp(sec_name, name) != 0)
3266 			continue;
3267 
3268 		return scn;
3269 	}
3270 	return NULL;
3271 }
3272 
3273 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn)
3274 {
3275 	Elf64_Shdr *shdr;
3276 
3277 	if (!scn)
3278 		return NULL;
3279 
3280 	shdr = elf64_getshdr(scn);
3281 	if (!shdr) {
3282 		pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
3283 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3284 		return NULL;
3285 	}
3286 
3287 	return shdr;
3288 }
3289 
3290 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
3291 {
3292 	const char *name;
3293 	Elf64_Shdr *sh;
3294 
3295 	if (!scn)
3296 		return NULL;
3297 
3298 	sh = elf_sec_hdr(obj, scn);
3299 	if (!sh)
3300 		return NULL;
3301 
3302 	name = elf_sec_str(obj, sh->sh_name);
3303 	if (!name) {
3304 		pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
3305 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3306 		return NULL;
3307 	}
3308 
3309 	return name;
3310 }
3311 
3312 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
3313 {
3314 	Elf_Data *data;
3315 
3316 	if (!scn)
3317 		return NULL;
3318 
3319 	data = elf_getdata(scn, 0);
3320 	if (!data) {
3321 		pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
3322 			elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
3323 			obj->path, elf_errmsg(-1));
3324 		return NULL;
3325 	}
3326 
3327 	return data;
3328 }
3329 
3330 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx)
3331 {
3332 	if (idx >= obj->efile.symbols->d_size / sizeof(Elf64_Sym))
3333 		return NULL;
3334 
3335 	return (Elf64_Sym *)obj->efile.symbols->d_buf + idx;
3336 }
3337 
3338 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx)
3339 {
3340 	if (idx >= data->d_size / sizeof(Elf64_Rel))
3341 		return NULL;
3342 
3343 	return (Elf64_Rel *)data->d_buf + idx;
3344 }
3345 
3346 static bool is_sec_name_dwarf(const char *name)
3347 {
3348 	/* approximation, but the actual list is too long */
3349 	return str_has_pfx(name, ".debug_");
3350 }
3351 
3352 static bool ignore_elf_section(Elf64_Shdr *hdr, const char *name)
3353 {
3354 	/* no special handling of .strtab */
3355 	if (hdr->sh_type == SHT_STRTAB)
3356 		return true;
3357 
3358 	/* ignore .llvm_addrsig section as well */
3359 	if (hdr->sh_type == SHT_LLVM_ADDRSIG)
3360 		return true;
3361 
3362 	/* no subprograms will lead to an empty .text section, ignore it */
3363 	if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
3364 	    strcmp(name, ".text") == 0)
3365 		return true;
3366 
3367 	/* DWARF sections */
3368 	if (is_sec_name_dwarf(name))
3369 		return true;
3370 
3371 	if (str_has_pfx(name, ".rel")) {
3372 		name += sizeof(".rel") - 1;
3373 		/* DWARF section relocations */
3374 		if (is_sec_name_dwarf(name))
3375 			return true;
3376 
3377 		/* .BTF and .BTF.ext don't need relocations */
3378 		if (strcmp(name, BTF_ELF_SEC) == 0 ||
3379 		    strcmp(name, BTF_EXT_ELF_SEC) == 0)
3380 			return true;
3381 	}
3382 
3383 	return false;
3384 }
3385 
3386 static int cmp_progs(const void *_a, const void *_b)
3387 {
3388 	const struct bpf_program *a = _a;
3389 	const struct bpf_program *b = _b;
3390 
3391 	if (a->sec_idx != b->sec_idx)
3392 		return a->sec_idx < b->sec_idx ? -1 : 1;
3393 
3394 	/* sec_insn_off can't be the same within the section */
3395 	return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
3396 }
3397 
3398 static int bpf_object__elf_collect(struct bpf_object *obj)
3399 {
3400 	struct elf_sec_desc *sec_desc;
3401 	Elf *elf = obj->efile.elf;
3402 	Elf_Data *btf_ext_data = NULL;
3403 	Elf_Data *btf_data = NULL;
3404 	int idx = 0, err = 0;
3405 	const char *name;
3406 	Elf_Data *data;
3407 	Elf_Scn *scn;
3408 	Elf64_Shdr *sh;
3409 
3410 	/* ELF section indices are 0-based, but sec #0 is special "invalid"
3411 	 * section. e_shnum does include sec #0, so e_shnum is the necessary
3412 	 * size of an array to keep all the sections.
3413 	 */
3414 	obj->efile.sec_cnt = obj->efile.ehdr->e_shnum;
3415 	obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs));
3416 	if (!obj->efile.secs)
3417 		return -ENOMEM;
3418 
3419 	/* a bunch of ELF parsing functionality depends on processing symbols,
3420 	 * so do the first pass and find the symbol table
3421 	 */
3422 	scn = NULL;
3423 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3424 		sh = elf_sec_hdr(obj, scn);
3425 		if (!sh)
3426 			return -LIBBPF_ERRNO__FORMAT;
3427 
3428 		if (sh->sh_type == SHT_SYMTAB) {
3429 			if (obj->efile.symbols) {
3430 				pr_warn("elf: multiple symbol tables in %s\n", obj->path);
3431 				return -LIBBPF_ERRNO__FORMAT;
3432 			}
3433 
3434 			data = elf_sec_data(obj, scn);
3435 			if (!data)
3436 				return -LIBBPF_ERRNO__FORMAT;
3437 
3438 			idx = elf_ndxscn(scn);
3439 
3440 			obj->efile.symbols = data;
3441 			obj->efile.symbols_shndx = idx;
3442 			obj->efile.strtabidx = sh->sh_link;
3443 		}
3444 	}
3445 
3446 	if (!obj->efile.symbols) {
3447 		pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
3448 			obj->path);
3449 		return -ENOENT;
3450 	}
3451 
3452 	scn = NULL;
3453 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3454 		idx = elf_ndxscn(scn);
3455 		sec_desc = &obj->efile.secs[idx];
3456 
3457 		sh = elf_sec_hdr(obj, scn);
3458 		if (!sh)
3459 			return -LIBBPF_ERRNO__FORMAT;
3460 
3461 		name = elf_sec_str(obj, sh->sh_name);
3462 		if (!name)
3463 			return -LIBBPF_ERRNO__FORMAT;
3464 
3465 		if (ignore_elf_section(sh, name))
3466 			continue;
3467 
3468 		data = elf_sec_data(obj, scn);
3469 		if (!data)
3470 			return -LIBBPF_ERRNO__FORMAT;
3471 
3472 		pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
3473 			 idx, name, (unsigned long)data->d_size,
3474 			 (int)sh->sh_link, (unsigned long)sh->sh_flags,
3475 			 (int)sh->sh_type);
3476 
3477 		if (strcmp(name, "license") == 0) {
3478 			err = bpf_object__init_license(obj, data->d_buf, data->d_size);
3479 			if (err)
3480 				return err;
3481 		} else if (strcmp(name, "version") == 0) {
3482 			err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
3483 			if (err)
3484 				return err;
3485 		} else if (strcmp(name, "maps") == 0) {
3486 			obj->efile.maps_shndx = idx;
3487 		} else if (strcmp(name, MAPS_ELF_SEC) == 0) {
3488 			obj->efile.btf_maps_shndx = idx;
3489 		} else if (strcmp(name, BTF_ELF_SEC) == 0) {
3490 			if (sh->sh_type != SHT_PROGBITS)
3491 				return -LIBBPF_ERRNO__FORMAT;
3492 			btf_data = data;
3493 		} else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
3494 			if (sh->sh_type != SHT_PROGBITS)
3495 				return -LIBBPF_ERRNO__FORMAT;
3496 			btf_ext_data = data;
3497 		} else if (sh->sh_type == SHT_SYMTAB) {
3498 			/* already processed during the first pass above */
3499 		} else if (sh->sh_type == SHT_PROGBITS && data->d_size > 0) {
3500 			if (sh->sh_flags & SHF_EXECINSTR) {
3501 				if (strcmp(name, ".text") == 0)
3502 					obj->efile.text_shndx = idx;
3503 				err = bpf_object__add_programs(obj, data, name, idx);
3504 				if (err)
3505 					return err;
3506 			} else if (strcmp(name, DATA_SEC) == 0 ||
3507 				   str_has_pfx(name, DATA_SEC ".")) {
3508 				sec_desc->sec_type = SEC_DATA;
3509 				sec_desc->shdr = sh;
3510 				sec_desc->data = data;
3511 			} else if (strcmp(name, RODATA_SEC) == 0 ||
3512 				   str_has_pfx(name, RODATA_SEC ".")) {
3513 				sec_desc->sec_type = SEC_RODATA;
3514 				sec_desc->shdr = sh;
3515 				sec_desc->data = data;
3516 			} else if (strcmp(name, STRUCT_OPS_SEC) == 0) {
3517 				obj->efile.st_ops_data = data;
3518 				obj->efile.st_ops_shndx = idx;
3519 			} else {
3520 				pr_info("elf: skipping unrecognized data section(%d) %s\n",
3521 					idx, name);
3522 			}
3523 		} else if (sh->sh_type == SHT_REL) {
3524 			int targ_sec_idx = sh->sh_info; /* points to other section */
3525 
3526 			if (sh->sh_entsize != sizeof(Elf64_Rel) ||
3527 			    targ_sec_idx >= obj->efile.sec_cnt)
3528 				return -LIBBPF_ERRNO__FORMAT;
3529 
3530 			/* Only do relo for section with exec instructions */
3531 			if (!section_have_execinstr(obj, targ_sec_idx) &&
3532 			    strcmp(name, ".rel" STRUCT_OPS_SEC) &&
3533 			    strcmp(name, ".rel" MAPS_ELF_SEC)) {
3534 				pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
3535 					idx, name, targ_sec_idx,
3536 					elf_sec_name(obj, elf_sec_by_idx(obj, targ_sec_idx)) ?: "<?>");
3537 				continue;
3538 			}
3539 
3540 			sec_desc->sec_type = SEC_RELO;
3541 			sec_desc->shdr = sh;
3542 			sec_desc->data = data;
3543 		} else if (sh->sh_type == SHT_NOBITS && strcmp(name, BSS_SEC) == 0) {
3544 			sec_desc->sec_type = SEC_BSS;
3545 			sec_desc->shdr = sh;
3546 			sec_desc->data = data;
3547 		} else {
3548 			pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
3549 				(size_t)sh->sh_size);
3550 		}
3551 	}
3552 
3553 	if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
3554 		pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
3555 		return -LIBBPF_ERRNO__FORMAT;
3556 	}
3557 
3558 	/* sort BPF programs by section name and in-section instruction offset
3559 	 * for faster search */
3560 	if (obj->nr_programs)
3561 		qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
3562 
3563 	return bpf_object__init_btf(obj, btf_data, btf_ext_data);
3564 }
3565 
3566 static bool sym_is_extern(const Elf64_Sym *sym)
3567 {
3568 	int bind = ELF64_ST_BIND(sym->st_info);
3569 	/* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
3570 	return sym->st_shndx == SHN_UNDEF &&
3571 	       (bind == STB_GLOBAL || bind == STB_WEAK) &&
3572 	       ELF64_ST_TYPE(sym->st_info) == STT_NOTYPE;
3573 }
3574 
3575 static bool sym_is_subprog(const Elf64_Sym *sym, int text_shndx)
3576 {
3577 	int bind = ELF64_ST_BIND(sym->st_info);
3578 	int type = ELF64_ST_TYPE(sym->st_info);
3579 
3580 	/* in .text section */
3581 	if (sym->st_shndx != text_shndx)
3582 		return false;
3583 
3584 	/* local function */
3585 	if (bind == STB_LOCAL && type == STT_SECTION)
3586 		return true;
3587 
3588 	/* global function */
3589 	return bind == STB_GLOBAL && type == STT_FUNC;
3590 }
3591 
3592 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
3593 {
3594 	const struct btf_type *t;
3595 	const char *tname;
3596 	int i, n;
3597 
3598 	if (!btf)
3599 		return -ESRCH;
3600 
3601 	n = btf__type_cnt(btf);
3602 	for (i = 1; i < n; i++) {
3603 		t = btf__type_by_id(btf, i);
3604 
3605 		if (!btf_is_var(t) && !btf_is_func(t))
3606 			continue;
3607 
3608 		tname = btf__name_by_offset(btf, t->name_off);
3609 		if (strcmp(tname, ext_name))
3610 			continue;
3611 
3612 		if (btf_is_var(t) &&
3613 		    btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
3614 			return -EINVAL;
3615 
3616 		if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
3617 			return -EINVAL;
3618 
3619 		return i;
3620 	}
3621 
3622 	return -ENOENT;
3623 }
3624 
3625 static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
3626 	const struct btf_var_secinfo *vs;
3627 	const struct btf_type *t;
3628 	int i, j, n;
3629 
3630 	if (!btf)
3631 		return -ESRCH;
3632 
3633 	n = btf__type_cnt(btf);
3634 	for (i = 1; i < n; i++) {
3635 		t = btf__type_by_id(btf, i);
3636 
3637 		if (!btf_is_datasec(t))
3638 			continue;
3639 
3640 		vs = btf_var_secinfos(t);
3641 		for (j = 0; j < btf_vlen(t); j++, vs++) {
3642 			if (vs->type == ext_btf_id)
3643 				return i;
3644 		}
3645 	}
3646 
3647 	return -ENOENT;
3648 }
3649 
3650 static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
3651 				     bool *is_signed)
3652 {
3653 	const struct btf_type *t;
3654 	const char *name;
3655 
3656 	t = skip_mods_and_typedefs(btf, id, NULL);
3657 	name = btf__name_by_offset(btf, t->name_off);
3658 
3659 	if (is_signed)
3660 		*is_signed = false;
3661 	switch (btf_kind(t)) {
3662 	case BTF_KIND_INT: {
3663 		int enc = btf_int_encoding(t);
3664 
3665 		if (enc & BTF_INT_BOOL)
3666 			return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
3667 		if (is_signed)
3668 			*is_signed = enc & BTF_INT_SIGNED;
3669 		if (t->size == 1)
3670 			return KCFG_CHAR;
3671 		if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
3672 			return KCFG_UNKNOWN;
3673 		return KCFG_INT;
3674 	}
3675 	case BTF_KIND_ENUM:
3676 		if (t->size != 4)
3677 			return KCFG_UNKNOWN;
3678 		if (strcmp(name, "libbpf_tristate"))
3679 			return KCFG_UNKNOWN;
3680 		return KCFG_TRISTATE;
3681 	case BTF_KIND_ARRAY:
3682 		if (btf_array(t)->nelems == 0)
3683 			return KCFG_UNKNOWN;
3684 		if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
3685 			return KCFG_UNKNOWN;
3686 		return KCFG_CHAR_ARR;
3687 	default:
3688 		return KCFG_UNKNOWN;
3689 	}
3690 }
3691 
3692 static int cmp_externs(const void *_a, const void *_b)
3693 {
3694 	const struct extern_desc *a = _a;
3695 	const struct extern_desc *b = _b;
3696 
3697 	if (a->type != b->type)
3698 		return a->type < b->type ? -1 : 1;
3699 
3700 	if (a->type == EXT_KCFG) {
3701 		/* descending order by alignment requirements */
3702 		if (a->kcfg.align != b->kcfg.align)
3703 			return a->kcfg.align > b->kcfg.align ? -1 : 1;
3704 		/* ascending order by size, within same alignment class */
3705 		if (a->kcfg.sz != b->kcfg.sz)
3706 			return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
3707 	}
3708 
3709 	/* resolve ties by name */
3710 	return strcmp(a->name, b->name);
3711 }
3712 
3713 static int find_int_btf_id(const struct btf *btf)
3714 {
3715 	const struct btf_type *t;
3716 	int i, n;
3717 
3718 	n = btf__type_cnt(btf);
3719 	for (i = 1; i < n; i++) {
3720 		t = btf__type_by_id(btf, i);
3721 
3722 		if (btf_is_int(t) && btf_int_bits(t) == 32)
3723 			return i;
3724 	}
3725 
3726 	return 0;
3727 }
3728 
3729 static int add_dummy_ksym_var(struct btf *btf)
3730 {
3731 	int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
3732 	const struct btf_var_secinfo *vs;
3733 	const struct btf_type *sec;
3734 
3735 	if (!btf)
3736 		return 0;
3737 
3738 	sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
3739 					    BTF_KIND_DATASEC);
3740 	if (sec_btf_id < 0)
3741 		return 0;
3742 
3743 	sec = btf__type_by_id(btf, sec_btf_id);
3744 	vs = btf_var_secinfos(sec);
3745 	for (i = 0; i < btf_vlen(sec); i++, vs++) {
3746 		const struct btf_type *vt;
3747 
3748 		vt = btf__type_by_id(btf, vs->type);
3749 		if (btf_is_func(vt))
3750 			break;
3751 	}
3752 
3753 	/* No func in ksyms sec.  No need to add dummy var. */
3754 	if (i == btf_vlen(sec))
3755 		return 0;
3756 
3757 	int_btf_id = find_int_btf_id(btf);
3758 	dummy_var_btf_id = btf__add_var(btf,
3759 					"dummy_ksym",
3760 					BTF_VAR_GLOBAL_ALLOCATED,
3761 					int_btf_id);
3762 	if (dummy_var_btf_id < 0)
3763 		pr_warn("cannot create a dummy_ksym var\n");
3764 
3765 	return dummy_var_btf_id;
3766 }
3767 
3768 static int bpf_object__collect_externs(struct bpf_object *obj)
3769 {
3770 	struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
3771 	const struct btf_type *t;
3772 	struct extern_desc *ext;
3773 	int i, n, off, dummy_var_btf_id;
3774 	const char *ext_name, *sec_name;
3775 	Elf_Scn *scn;
3776 	Elf64_Shdr *sh;
3777 
3778 	if (!obj->efile.symbols)
3779 		return 0;
3780 
3781 	scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
3782 	sh = elf_sec_hdr(obj, scn);
3783 	if (!sh || sh->sh_entsize != sizeof(Elf64_Sym))
3784 		return -LIBBPF_ERRNO__FORMAT;
3785 
3786 	dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
3787 	if (dummy_var_btf_id < 0)
3788 		return dummy_var_btf_id;
3789 
3790 	n = sh->sh_size / sh->sh_entsize;
3791 	pr_debug("looking for externs among %d symbols...\n", n);
3792 
3793 	for (i = 0; i < n; i++) {
3794 		Elf64_Sym *sym = elf_sym_by_idx(obj, i);
3795 
3796 		if (!sym)
3797 			return -LIBBPF_ERRNO__FORMAT;
3798 		if (!sym_is_extern(sym))
3799 			continue;
3800 		ext_name = elf_sym_str(obj, sym->st_name);
3801 		if (!ext_name || !ext_name[0])
3802 			continue;
3803 
3804 		ext = obj->externs;
3805 		ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
3806 		if (!ext)
3807 			return -ENOMEM;
3808 		obj->externs = ext;
3809 		ext = &ext[obj->nr_extern];
3810 		memset(ext, 0, sizeof(*ext));
3811 		obj->nr_extern++;
3812 
3813 		ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
3814 		if (ext->btf_id <= 0) {
3815 			pr_warn("failed to find BTF for extern '%s': %d\n",
3816 				ext_name, ext->btf_id);
3817 			return ext->btf_id;
3818 		}
3819 		t = btf__type_by_id(obj->btf, ext->btf_id);
3820 		ext->name = btf__name_by_offset(obj->btf, t->name_off);
3821 		ext->sym_idx = i;
3822 		ext->is_weak = ELF64_ST_BIND(sym->st_info) == STB_WEAK;
3823 
3824 		ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
3825 		if (ext->sec_btf_id <= 0) {
3826 			pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
3827 				ext_name, ext->btf_id, ext->sec_btf_id);
3828 			return ext->sec_btf_id;
3829 		}
3830 		sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
3831 		sec_name = btf__name_by_offset(obj->btf, sec->name_off);
3832 
3833 		if (strcmp(sec_name, KCONFIG_SEC) == 0) {
3834 			if (btf_is_func(t)) {
3835 				pr_warn("extern function %s is unsupported under %s section\n",
3836 					ext->name, KCONFIG_SEC);
3837 				return -ENOTSUP;
3838 			}
3839 			kcfg_sec = sec;
3840 			ext->type = EXT_KCFG;
3841 			ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
3842 			if (ext->kcfg.sz <= 0) {
3843 				pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
3844 					ext_name, ext->kcfg.sz);
3845 				return ext->kcfg.sz;
3846 			}
3847 			ext->kcfg.align = btf__align_of(obj->btf, t->type);
3848 			if (ext->kcfg.align <= 0) {
3849 				pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
3850 					ext_name, ext->kcfg.align);
3851 				return -EINVAL;
3852 			}
3853 			ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
3854 						        &ext->kcfg.is_signed);
3855 			if (ext->kcfg.type == KCFG_UNKNOWN) {
3856 				pr_warn("extern (kcfg) '%s' type is unsupported\n", ext_name);
3857 				return -ENOTSUP;
3858 			}
3859 		} else if (strcmp(sec_name, KSYMS_SEC) == 0) {
3860 			ksym_sec = sec;
3861 			ext->type = EXT_KSYM;
3862 			skip_mods_and_typedefs(obj->btf, t->type,
3863 					       &ext->ksym.type_id);
3864 		} else {
3865 			pr_warn("unrecognized extern section '%s'\n", sec_name);
3866 			return -ENOTSUP;
3867 		}
3868 	}
3869 	pr_debug("collected %d externs total\n", obj->nr_extern);
3870 
3871 	if (!obj->nr_extern)
3872 		return 0;
3873 
3874 	/* sort externs by type, for kcfg ones also by (align, size, name) */
3875 	qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
3876 
3877 	/* for .ksyms section, we need to turn all externs into allocated
3878 	 * variables in BTF to pass kernel verification; we do this by
3879 	 * pretending that each extern is a 8-byte variable
3880 	 */
3881 	if (ksym_sec) {
3882 		/* find existing 4-byte integer type in BTF to use for fake
3883 		 * extern variables in DATASEC
3884 		 */
3885 		int int_btf_id = find_int_btf_id(obj->btf);
3886 		/* For extern function, a dummy_var added earlier
3887 		 * will be used to replace the vs->type and
3888 		 * its name string will be used to refill
3889 		 * the missing param's name.
3890 		 */
3891 		const struct btf_type *dummy_var;
3892 
3893 		dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
3894 		for (i = 0; i < obj->nr_extern; i++) {
3895 			ext = &obj->externs[i];
3896 			if (ext->type != EXT_KSYM)
3897 				continue;
3898 			pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
3899 				 i, ext->sym_idx, ext->name);
3900 		}
3901 
3902 		sec = ksym_sec;
3903 		n = btf_vlen(sec);
3904 		for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
3905 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3906 			struct btf_type *vt;
3907 
3908 			vt = (void *)btf__type_by_id(obj->btf, vs->type);
3909 			ext_name = btf__name_by_offset(obj->btf, vt->name_off);
3910 			ext = find_extern_by_name(obj, ext_name);
3911 			if (!ext) {
3912 				pr_warn("failed to find extern definition for BTF %s '%s'\n",
3913 					btf_kind_str(vt), ext_name);
3914 				return -ESRCH;
3915 			}
3916 			if (btf_is_func(vt)) {
3917 				const struct btf_type *func_proto;
3918 				struct btf_param *param;
3919 				int j;
3920 
3921 				func_proto = btf__type_by_id(obj->btf,
3922 							     vt->type);
3923 				param = btf_params(func_proto);
3924 				/* Reuse the dummy_var string if the
3925 				 * func proto does not have param name.
3926 				 */
3927 				for (j = 0; j < btf_vlen(func_proto); j++)
3928 					if (param[j].type && !param[j].name_off)
3929 						param[j].name_off =
3930 							dummy_var->name_off;
3931 				vs->type = dummy_var_btf_id;
3932 				vt->info &= ~0xffff;
3933 				vt->info |= BTF_FUNC_GLOBAL;
3934 			} else {
3935 				btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3936 				vt->type = int_btf_id;
3937 			}
3938 			vs->offset = off;
3939 			vs->size = sizeof(int);
3940 		}
3941 		sec->size = off;
3942 	}
3943 
3944 	if (kcfg_sec) {
3945 		sec = kcfg_sec;
3946 		/* for kcfg externs calculate their offsets within a .kconfig map */
3947 		off = 0;
3948 		for (i = 0; i < obj->nr_extern; i++) {
3949 			ext = &obj->externs[i];
3950 			if (ext->type != EXT_KCFG)
3951 				continue;
3952 
3953 			ext->kcfg.data_off = roundup(off, ext->kcfg.align);
3954 			off = ext->kcfg.data_off + ext->kcfg.sz;
3955 			pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
3956 				 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
3957 		}
3958 		sec->size = off;
3959 		n = btf_vlen(sec);
3960 		for (i = 0; i < n; i++) {
3961 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3962 
3963 			t = btf__type_by_id(obj->btf, vs->type);
3964 			ext_name = btf__name_by_offset(obj->btf, t->name_off);
3965 			ext = find_extern_by_name(obj, ext_name);
3966 			if (!ext) {
3967 				pr_warn("failed to find extern definition for BTF var '%s'\n",
3968 					ext_name);
3969 				return -ESRCH;
3970 			}
3971 			btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3972 			vs->offset = ext->kcfg.data_off;
3973 		}
3974 	}
3975 	return 0;
3976 }
3977 
3978 struct bpf_program *
3979 bpf_object__find_program_by_title(const struct bpf_object *obj,
3980 				  const char *title)
3981 {
3982 	struct bpf_program *pos;
3983 
3984 	bpf_object__for_each_program(pos, obj) {
3985 		if (pos->sec_name && !strcmp(pos->sec_name, title))
3986 			return pos;
3987 	}
3988 	return errno = ENOENT, NULL;
3989 }
3990 
3991 static bool prog_is_subprog(const struct bpf_object *obj,
3992 			    const struct bpf_program *prog)
3993 {
3994 	/* For legacy reasons, libbpf supports an entry-point BPF programs
3995 	 * without SEC() attribute, i.e., those in the .text section. But if
3996 	 * there are 2 or more such programs in the .text section, they all
3997 	 * must be subprograms called from entry-point BPF programs in
3998 	 * designated SEC()'tions, otherwise there is no way to distinguish
3999 	 * which of those programs should be loaded vs which are a subprogram.
4000 	 * Similarly, if there is a function/program in .text and at least one
4001 	 * other BPF program with custom SEC() attribute, then we just assume
4002 	 * .text programs are subprograms (even if they are not called from
4003 	 * other programs), because libbpf never explicitly supported mixing
4004 	 * SEC()-designated BPF programs and .text entry-point BPF programs.
4005 	 *
4006 	 * In libbpf 1.0 strict mode, we always consider .text
4007 	 * programs to be subprograms.
4008 	 */
4009 
4010 	if (libbpf_mode & LIBBPF_STRICT_SEC_NAME)
4011 		return prog->sec_idx == obj->efile.text_shndx;
4012 
4013 	return prog->sec_idx == obj->efile.text_shndx && obj->nr_programs > 1;
4014 }
4015 
4016 struct bpf_program *
4017 bpf_object__find_program_by_name(const struct bpf_object *obj,
4018 				 const char *name)
4019 {
4020 	struct bpf_program *prog;
4021 
4022 	bpf_object__for_each_program(prog, obj) {
4023 		if (prog_is_subprog(obj, prog))
4024 			continue;
4025 		if (!strcmp(prog->name, name))
4026 			return prog;
4027 	}
4028 	return errno = ENOENT, NULL;
4029 }
4030 
4031 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
4032 				      int shndx)
4033 {
4034 	switch (obj->efile.secs[shndx].sec_type) {
4035 	case SEC_BSS:
4036 	case SEC_DATA:
4037 	case SEC_RODATA:
4038 		return true;
4039 	default:
4040 		return false;
4041 	}
4042 }
4043 
4044 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
4045 				      int shndx)
4046 {
4047 	return shndx == obj->efile.maps_shndx ||
4048 	       shndx == obj->efile.btf_maps_shndx;
4049 }
4050 
4051 static enum libbpf_map_type
4052 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
4053 {
4054 	if (shndx == obj->efile.symbols_shndx)
4055 		return LIBBPF_MAP_KCONFIG;
4056 
4057 	switch (obj->efile.secs[shndx].sec_type) {
4058 	case SEC_BSS:
4059 		return LIBBPF_MAP_BSS;
4060 	case SEC_DATA:
4061 		return LIBBPF_MAP_DATA;
4062 	case SEC_RODATA:
4063 		return LIBBPF_MAP_RODATA;
4064 	default:
4065 		return LIBBPF_MAP_UNSPEC;
4066 	}
4067 }
4068 
4069 static int bpf_program__record_reloc(struct bpf_program *prog,
4070 				     struct reloc_desc *reloc_desc,
4071 				     __u32 insn_idx, const char *sym_name,
4072 				     const Elf64_Sym *sym, const Elf64_Rel *rel)
4073 {
4074 	struct bpf_insn *insn = &prog->insns[insn_idx];
4075 	size_t map_idx, nr_maps = prog->obj->nr_maps;
4076 	struct bpf_object *obj = prog->obj;
4077 	__u32 shdr_idx = sym->st_shndx;
4078 	enum libbpf_map_type type;
4079 	const char *sym_sec_name;
4080 	struct bpf_map *map;
4081 
4082 	if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
4083 		pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n",
4084 			prog->name, sym_name, insn_idx, insn->code);
4085 		return -LIBBPF_ERRNO__RELOC;
4086 	}
4087 
4088 	if (sym_is_extern(sym)) {
4089 		int sym_idx = ELF64_R_SYM(rel->r_info);
4090 		int i, n = obj->nr_extern;
4091 		struct extern_desc *ext;
4092 
4093 		for (i = 0; i < n; i++) {
4094 			ext = &obj->externs[i];
4095 			if (ext->sym_idx == sym_idx)
4096 				break;
4097 		}
4098 		if (i >= n) {
4099 			pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
4100 				prog->name, sym_name, sym_idx);
4101 			return -LIBBPF_ERRNO__RELOC;
4102 		}
4103 		pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
4104 			 prog->name, i, ext->name, ext->sym_idx, insn_idx);
4105 		if (insn->code == (BPF_JMP | BPF_CALL))
4106 			reloc_desc->type = RELO_EXTERN_FUNC;
4107 		else
4108 			reloc_desc->type = RELO_EXTERN_VAR;
4109 		reloc_desc->insn_idx = insn_idx;
4110 		reloc_desc->sym_off = i; /* sym_off stores extern index */
4111 		return 0;
4112 	}
4113 
4114 	/* sub-program call relocation */
4115 	if (is_call_insn(insn)) {
4116 		if (insn->src_reg != BPF_PSEUDO_CALL) {
4117 			pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
4118 			return -LIBBPF_ERRNO__RELOC;
4119 		}
4120 		/* text_shndx can be 0, if no default "main" program exists */
4121 		if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
4122 			sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4123 			pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
4124 				prog->name, sym_name, sym_sec_name);
4125 			return -LIBBPF_ERRNO__RELOC;
4126 		}
4127 		if (sym->st_value % BPF_INSN_SZ) {
4128 			pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
4129 				prog->name, sym_name, (size_t)sym->st_value);
4130 			return -LIBBPF_ERRNO__RELOC;
4131 		}
4132 		reloc_desc->type = RELO_CALL;
4133 		reloc_desc->insn_idx = insn_idx;
4134 		reloc_desc->sym_off = sym->st_value;
4135 		return 0;
4136 	}
4137 
4138 	if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
4139 		pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
4140 			prog->name, sym_name, shdr_idx);
4141 		return -LIBBPF_ERRNO__RELOC;
4142 	}
4143 
4144 	/* loading subprog addresses */
4145 	if (sym_is_subprog(sym, obj->efile.text_shndx)) {
4146 		/* global_func: sym->st_value = offset in the section, insn->imm = 0.
4147 		 * local_func: sym->st_value = 0, insn->imm = offset in the section.
4148 		 */
4149 		if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
4150 			pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
4151 				prog->name, sym_name, (size_t)sym->st_value, insn->imm);
4152 			return -LIBBPF_ERRNO__RELOC;
4153 		}
4154 
4155 		reloc_desc->type = RELO_SUBPROG_ADDR;
4156 		reloc_desc->insn_idx = insn_idx;
4157 		reloc_desc->sym_off = sym->st_value;
4158 		return 0;
4159 	}
4160 
4161 	type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
4162 	sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4163 
4164 	/* generic map reference relocation */
4165 	if (type == LIBBPF_MAP_UNSPEC) {
4166 		if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
4167 			pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
4168 				prog->name, sym_name, sym_sec_name);
4169 			return -LIBBPF_ERRNO__RELOC;
4170 		}
4171 		for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4172 			map = &obj->maps[map_idx];
4173 			if (map->libbpf_type != type ||
4174 			    map->sec_idx != sym->st_shndx ||
4175 			    map->sec_offset != sym->st_value)
4176 				continue;
4177 			pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n",
4178 				 prog->name, map_idx, map->name, map->sec_idx,
4179 				 map->sec_offset, insn_idx);
4180 			break;
4181 		}
4182 		if (map_idx >= nr_maps) {
4183 			pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
4184 				prog->name, sym_sec_name, (size_t)sym->st_value);
4185 			return -LIBBPF_ERRNO__RELOC;
4186 		}
4187 		reloc_desc->type = RELO_LD64;
4188 		reloc_desc->insn_idx = insn_idx;
4189 		reloc_desc->map_idx = map_idx;
4190 		reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
4191 		return 0;
4192 	}
4193 
4194 	/* global data map relocation */
4195 	if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
4196 		pr_warn("prog '%s': bad data relo against section '%s'\n",
4197 			prog->name, sym_sec_name);
4198 		return -LIBBPF_ERRNO__RELOC;
4199 	}
4200 	for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4201 		map = &obj->maps[map_idx];
4202 		if (map->libbpf_type != type || map->sec_idx != sym->st_shndx)
4203 			continue;
4204 		pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n",
4205 			 prog->name, map_idx, map->name, map->sec_idx,
4206 			 map->sec_offset, insn_idx);
4207 		break;
4208 	}
4209 	if (map_idx >= nr_maps) {
4210 		pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
4211 			prog->name, sym_sec_name);
4212 		return -LIBBPF_ERRNO__RELOC;
4213 	}
4214 
4215 	reloc_desc->type = RELO_DATA;
4216 	reloc_desc->insn_idx = insn_idx;
4217 	reloc_desc->map_idx = map_idx;
4218 	reloc_desc->sym_off = sym->st_value;
4219 	return 0;
4220 }
4221 
4222 static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
4223 {
4224 	return insn_idx >= prog->sec_insn_off &&
4225 	       insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
4226 }
4227 
4228 static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
4229 						 size_t sec_idx, size_t insn_idx)
4230 {
4231 	int l = 0, r = obj->nr_programs - 1, m;
4232 	struct bpf_program *prog;
4233 
4234 	while (l < r) {
4235 		m = l + (r - l + 1) / 2;
4236 		prog = &obj->programs[m];
4237 
4238 		if (prog->sec_idx < sec_idx ||
4239 		    (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
4240 			l = m;
4241 		else
4242 			r = m - 1;
4243 	}
4244 	/* matching program could be at index l, but it still might be the
4245 	 * wrong one, so we need to double check conditions for the last time
4246 	 */
4247 	prog = &obj->programs[l];
4248 	if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
4249 		return prog;
4250 	return NULL;
4251 }
4252 
4253 static int
4254 bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
4255 {
4256 	const char *relo_sec_name, *sec_name;
4257 	size_t sec_idx = shdr->sh_info, sym_idx;
4258 	struct bpf_program *prog;
4259 	struct reloc_desc *relos;
4260 	int err, i, nrels;
4261 	const char *sym_name;
4262 	__u32 insn_idx;
4263 	Elf_Scn *scn;
4264 	Elf_Data *scn_data;
4265 	Elf64_Sym *sym;
4266 	Elf64_Rel *rel;
4267 
4268 	if (sec_idx >= obj->efile.sec_cnt)
4269 		return -EINVAL;
4270 
4271 	scn = elf_sec_by_idx(obj, sec_idx);
4272 	scn_data = elf_sec_data(obj, scn);
4273 
4274 	relo_sec_name = elf_sec_str(obj, shdr->sh_name);
4275 	sec_name = elf_sec_name(obj, scn);
4276 	if (!relo_sec_name || !sec_name)
4277 		return -EINVAL;
4278 
4279 	pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
4280 		 relo_sec_name, sec_idx, sec_name);
4281 	nrels = shdr->sh_size / shdr->sh_entsize;
4282 
4283 	for (i = 0; i < nrels; i++) {
4284 		rel = elf_rel_by_idx(data, i);
4285 		if (!rel) {
4286 			pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
4287 			return -LIBBPF_ERRNO__FORMAT;
4288 		}
4289 
4290 		sym_idx = ELF64_R_SYM(rel->r_info);
4291 		sym = elf_sym_by_idx(obj, sym_idx);
4292 		if (!sym) {
4293 			pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
4294 				relo_sec_name, sym_idx, i);
4295 			return -LIBBPF_ERRNO__FORMAT;
4296 		}
4297 
4298 		if (sym->st_shndx >= obj->efile.sec_cnt) {
4299 			pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
4300 				relo_sec_name, sym_idx, (size_t)sym->st_shndx, i);
4301 			return -LIBBPF_ERRNO__FORMAT;
4302 		}
4303 
4304 		if (rel->r_offset % BPF_INSN_SZ || rel->r_offset >= scn_data->d_size) {
4305 			pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
4306 				relo_sec_name, (size_t)rel->r_offset, i);
4307 			return -LIBBPF_ERRNO__FORMAT;
4308 		}
4309 
4310 		insn_idx = rel->r_offset / BPF_INSN_SZ;
4311 		/* relocations against static functions are recorded as
4312 		 * relocations against the section that contains a function;
4313 		 * in such case, symbol will be STT_SECTION and sym.st_name
4314 		 * will point to empty string (0), so fetch section name
4315 		 * instead
4316 		 */
4317 		if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
4318 			sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx));
4319 		else
4320 			sym_name = elf_sym_str(obj, sym->st_name);
4321 		sym_name = sym_name ?: "<?";
4322 
4323 		pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
4324 			 relo_sec_name, i, insn_idx, sym_name);
4325 
4326 		prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
4327 		if (!prog) {
4328 			pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
4329 				relo_sec_name, i, sec_name, insn_idx);
4330 			continue;
4331 		}
4332 
4333 		relos = libbpf_reallocarray(prog->reloc_desc,
4334 					    prog->nr_reloc + 1, sizeof(*relos));
4335 		if (!relos)
4336 			return -ENOMEM;
4337 		prog->reloc_desc = relos;
4338 
4339 		/* adjust insn_idx to local BPF program frame of reference */
4340 		insn_idx -= prog->sec_insn_off;
4341 		err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
4342 						insn_idx, sym_name, sym, rel);
4343 		if (err)
4344 			return err;
4345 
4346 		prog->nr_reloc++;
4347 	}
4348 	return 0;
4349 }
4350 
4351 static int bpf_map_find_btf_info(struct bpf_object *obj, struct bpf_map *map)
4352 {
4353 	struct bpf_map_def *def = &map->def;
4354 	__u32 key_type_id = 0, value_type_id = 0;
4355 	int ret;
4356 
4357 	if (!obj->btf)
4358 		return -ENOENT;
4359 
4360 	/* if it's BTF-defined map, we don't need to search for type IDs.
4361 	 * For struct_ops map, it does not need btf_key_type_id and
4362 	 * btf_value_type_id.
4363 	 */
4364 	if (map->sec_idx == obj->efile.btf_maps_shndx ||
4365 	    bpf_map__is_struct_ops(map))
4366 		return 0;
4367 
4368 	if (!bpf_map__is_internal(map)) {
4369 		pr_warn("Use of BPF_ANNOTATE_KV_PAIR is deprecated, use BTF-defined maps in .maps section instead\n");
4370 #pragma GCC diagnostic push
4371 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
4372 		ret = btf__get_map_kv_tids(obj->btf, map->name, def->key_size,
4373 					   def->value_size, &key_type_id,
4374 					   &value_type_id);
4375 #pragma GCC diagnostic pop
4376 	} else {
4377 		/*
4378 		 * LLVM annotates global data differently in BTF, that is,
4379 		 * only as '.data', '.bss' or '.rodata'.
4380 		 */
4381 		ret = btf__find_by_name(obj->btf, map->real_name);
4382 	}
4383 	if (ret < 0)
4384 		return ret;
4385 
4386 	map->btf_key_type_id = key_type_id;
4387 	map->btf_value_type_id = bpf_map__is_internal(map) ?
4388 				 ret : value_type_id;
4389 	return 0;
4390 }
4391 
4392 static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
4393 {
4394 	char file[PATH_MAX], buff[4096];
4395 	FILE *fp;
4396 	__u32 val;
4397 	int err;
4398 
4399 	snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
4400 	memset(info, 0, sizeof(*info));
4401 
4402 	fp = fopen(file, "r");
4403 	if (!fp) {
4404 		err = -errno;
4405 		pr_warn("failed to open %s: %d. No procfs support?\n", file,
4406 			err);
4407 		return err;
4408 	}
4409 
4410 	while (fgets(buff, sizeof(buff), fp)) {
4411 		if (sscanf(buff, "map_type:\t%u", &val) == 1)
4412 			info->type = val;
4413 		else if (sscanf(buff, "key_size:\t%u", &val) == 1)
4414 			info->key_size = val;
4415 		else if (sscanf(buff, "value_size:\t%u", &val) == 1)
4416 			info->value_size = val;
4417 		else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
4418 			info->max_entries = val;
4419 		else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
4420 			info->map_flags = val;
4421 	}
4422 
4423 	fclose(fp);
4424 
4425 	return 0;
4426 }
4427 
4428 bool bpf_map__autocreate(const struct bpf_map *map)
4429 {
4430 	return map->autocreate;
4431 }
4432 
4433 int bpf_map__set_autocreate(struct bpf_map *map, bool autocreate)
4434 {
4435 	if (map->obj->loaded)
4436 		return libbpf_err(-EBUSY);
4437 
4438 	map->autocreate = autocreate;
4439 	return 0;
4440 }
4441 
4442 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
4443 {
4444 	struct bpf_map_info info = {};
4445 	__u32 len = sizeof(info);
4446 	int new_fd, err;
4447 	char *new_name;
4448 
4449 	err = bpf_obj_get_info_by_fd(fd, &info, &len);
4450 	if (err && errno == EINVAL)
4451 		err = bpf_get_map_info_from_fdinfo(fd, &info);
4452 	if (err)
4453 		return libbpf_err(err);
4454 
4455 	new_name = strdup(info.name);
4456 	if (!new_name)
4457 		return libbpf_err(-errno);
4458 
4459 	new_fd = open("/", O_RDONLY | O_CLOEXEC);
4460 	if (new_fd < 0) {
4461 		err = -errno;
4462 		goto err_free_new_name;
4463 	}
4464 
4465 	new_fd = dup3(fd, new_fd, O_CLOEXEC);
4466 	if (new_fd < 0) {
4467 		err = -errno;
4468 		goto err_close_new_fd;
4469 	}
4470 
4471 	err = zclose(map->fd);
4472 	if (err) {
4473 		err = -errno;
4474 		goto err_close_new_fd;
4475 	}
4476 	free(map->name);
4477 
4478 	map->fd = new_fd;
4479 	map->name = new_name;
4480 	map->def.type = info.type;
4481 	map->def.key_size = info.key_size;
4482 	map->def.value_size = info.value_size;
4483 	map->def.max_entries = info.max_entries;
4484 	map->def.map_flags = info.map_flags;
4485 	map->btf_key_type_id = info.btf_key_type_id;
4486 	map->btf_value_type_id = info.btf_value_type_id;
4487 	map->reused = true;
4488 	map->map_extra = info.map_extra;
4489 
4490 	return 0;
4491 
4492 err_close_new_fd:
4493 	close(new_fd);
4494 err_free_new_name:
4495 	free(new_name);
4496 	return libbpf_err(err);
4497 }
4498 
4499 __u32 bpf_map__max_entries(const struct bpf_map *map)
4500 {
4501 	return map->def.max_entries;
4502 }
4503 
4504 struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
4505 {
4506 	if (!bpf_map_type__is_map_in_map(map->def.type))
4507 		return errno = EINVAL, NULL;
4508 
4509 	return map->inner_map;
4510 }
4511 
4512 int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
4513 {
4514 	if (map->fd >= 0)
4515 		return libbpf_err(-EBUSY);
4516 	map->def.max_entries = max_entries;
4517 	return 0;
4518 }
4519 
4520 int bpf_map__resize(struct bpf_map *map, __u32 max_entries)
4521 {
4522 	if (!map || !max_entries)
4523 		return libbpf_err(-EINVAL);
4524 
4525 	return bpf_map__set_max_entries(map, max_entries);
4526 }
4527 
4528 static int
4529 bpf_object__probe_loading(struct bpf_object *obj)
4530 {
4531 	char *cp, errmsg[STRERR_BUFSIZE];
4532 	struct bpf_insn insns[] = {
4533 		BPF_MOV64_IMM(BPF_REG_0, 0),
4534 		BPF_EXIT_INSN(),
4535 	};
4536 	int ret, insn_cnt = ARRAY_SIZE(insns);
4537 
4538 	if (obj->gen_loader)
4539 		return 0;
4540 
4541 	ret = bump_rlimit_memlock();
4542 	if (ret)
4543 		pr_warn("Failed to bump RLIMIT_MEMLOCK (err = %d), you might need to do it explicitly!\n", ret);
4544 
4545 	/* make sure basic loading works */
4546 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4547 	if (ret < 0)
4548 		ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
4549 	if (ret < 0) {
4550 		ret = errno;
4551 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4552 		pr_warn("Error in %s():%s(%d). Couldn't load trivial BPF "
4553 			"program. Make sure your kernel supports BPF "
4554 			"(CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is "
4555 			"set to big enough value.\n", __func__, cp, ret);
4556 		return -ret;
4557 	}
4558 	close(ret);
4559 
4560 	return 0;
4561 }
4562 
4563 static int probe_fd(int fd)
4564 {
4565 	if (fd >= 0)
4566 		close(fd);
4567 	return fd >= 0;
4568 }
4569 
4570 static int probe_kern_prog_name(void)
4571 {
4572 	struct bpf_insn insns[] = {
4573 		BPF_MOV64_IMM(BPF_REG_0, 0),
4574 		BPF_EXIT_INSN(),
4575 	};
4576 	int ret, insn_cnt = ARRAY_SIZE(insns);
4577 
4578 	/* make sure loading with name works */
4579 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, "test", "GPL", insns, insn_cnt, NULL);
4580 	return probe_fd(ret);
4581 }
4582 
4583 static int probe_kern_global_data(void)
4584 {
4585 	char *cp, errmsg[STRERR_BUFSIZE];
4586 	struct bpf_insn insns[] = {
4587 		BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
4588 		BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
4589 		BPF_MOV64_IMM(BPF_REG_0, 0),
4590 		BPF_EXIT_INSN(),
4591 	};
4592 	int ret, map, insn_cnt = ARRAY_SIZE(insns);
4593 
4594 	map = bpf_map_create(BPF_MAP_TYPE_ARRAY, NULL, sizeof(int), 32, 1, NULL);
4595 	if (map < 0) {
4596 		ret = -errno;
4597 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4598 		pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4599 			__func__, cp, -ret);
4600 		return ret;
4601 	}
4602 
4603 	insns[0].imm = map;
4604 
4605 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4606 	close(map);
4607 	return probe_fd(ret);
4608 }
4609 
4610 static int probe_kern_btf(void)
4611 {
4612 	static const char strs[] = "\0int";
4613 	__u32 types[] = {
4614 		/* int */
4615 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4616 	};
4617 
4618 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4619 					     strs, sizeof(strs)));
4620 }
4621 
4622 static int probe_kern_btf_func(void)
4623 {
4624 	static const char strs[] = "\0int\0x\0a";
4625 	/* void x(int a) {} */
4626 	__u32 types[] = {
4627 		/* int */
4628 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4629 		/* FUNC_PROTO */                                /* [2] */
4630 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4631 		BTF_PARAM_ENC(7, 1),
4632 		/* FUNC x */                                    /* [3] */
4633 		BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
4634 	};
4635 
4636 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4637 					     strs, sizeof(strs)));
4638 }
4639 
4640 static int probe_kern_btf_func_global(void)
4641 {
4642 	static const char strs[] = "\0int\0x\0a";
4643 	/* static void x(int a) {} */
4644 	__u32 types[] = {
4645 		/* int */
4646 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4647 		/* FUNC_PROTO */                                /* [2] */
4648 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4649 		BTF_PARAM_ENC(7, 1),
4650 		/* FUNC x BTF_FUNC_GLOBAL */                    /* [3] */
4651 		BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, BTF_FUNC_GLOBAL), 2),
4652 	};
4653 
4654 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4655 					     strs, sizeof(strs)));
4656 }
4657 
4658 static int probe_kern_btf_datasec(void)
4659 {
4660 	static const char strs[] = "\0x\0.data";
4661 	/* static int a; */
4662 	__u32 types[] = {
4663 		/* int */
4664 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4665 		/* VAR x */                                     /* [2] */
4666 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4667 		BTF_VAR_STATIC,
4668 		/* DATASEC val */                               /* [3] */
4669 		BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
4670 		BTF_VAR_SECINFO_ENC(2, 0, 4),
4671 	};
4672 
4673 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4674 					     strs, sizeof(strs)));
4675 }
4676 
4677 static int probe_kern_btf_float(void)
4678 {
4679 	static const char strs[] = "\0float";
4680 	__u32 types[] = {
4681 		/* float */
4682 		BTF_TYPE_FLOAT_ENC(1, 4),
4683 	};
4684 
4685 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4686 					     strs, sizeof(strs)));
4687 }
4688 
4689 static int probe_kern_btf_decl_tag(void)
4690 {
4691 	static const char strs[] = "\0tag";
4692 	__u32 types[] = {
4693 		/* int */
4694 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4695 		/* VAR x */                                     /* [2] */
4696 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4697 		BTF_VAR_STATIC,
4698 		/* attr */
4699 		BTF_TYPE_DECL_TAG_ENC(1, 2, -1),
4700 	};
4701 
4702 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4703 					     strs, sizeof(strs)));
4704 }
4705 
4706 static int probe_kern_btf_type_tag(void)
4707 {
4708 	static const char strs[] = "\0tag";
4709 	__u32 types[] = {
4710 		/* int */
4711 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),		/* [1] */
4712 		/* attr */
4713 		BTF_TYPE_TYPE_TAG_ENC(1, 1),				/* [2] */
4714 		/* ptr */
4715 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_PTR, 0, 0), 2),	/* [3] */
4716 	};
4717 
4718 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4719 					     strs, sizeof(strs)));
4720 }
4721 
4722 static int probe_kern_array_mmap(void)
4723 {
4724 	LIBBPF_OPTS(bpf_map_create_opts, opts, .map_flags = BPF_F_MMAPABLE);
4725 	int fd;
4726 
4727 	fd = bpf_map_create(BPF_MAP_TYPE_ARRAY, NULL, sizeof(int), sizeof(int), 1, &opts);
4728 	return probe_fd(fd);
4729 }
4730 
4731 static int probe_kern_exp_attach_type(void)
4732 {
4733 	LIBBPF_OPTS(bpf_prog_load_opts, opts, .expected_attach_type = BPF_CGROUP_INET_SOCK_CREATE);
4734 	struct bpf_insn insns[] = {
4735 		BPF_MOV64_IMM(BPF_REG_0, 0),
4736 		BPF_EXIT_INSN(),
4737 	};
4738 	int fd, insn_cnt = ARRAY_SIZE(insns);
4739 
4740 	/* use any valid combination of program type and (optional)
4741 	 * non-zero expected attach type (i.e., not a BPF_CGROUP_INET_INGRESS)
4742 	 * to see if kernel supports expected_attach_type field for
4743 	 * BPF_PROG_LOAD command
4744 	 */
4745 	fd = bpf_prog_load(BPF_PROG_TYPE_CGROUP_SOCK, NULL, "GPL", insns, insn_cnt, &opts);
4746 	return probe_fd(fd);
4747 }
4748 
4749 static int probe_kern_probe_read_kernel(void)
4750 {
4751 	struct bpf_insn insns[] = {
4752 		BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),	/* r1 = r10 (fp) */
4753 		BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -8),	/* r1 += -8 */
4754 		BPF_MOV64_IMM(BPF_REG_2, 8),		/* r2 = 8 */
4755 		BPF_MOV64_IMM(BPF_REG_3, 0),		/* r3 = 0 */
4756 		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_probe_read_kernel),
4757 		BPF_EXIT_INSN(),
4758 	};
4759 	int fd, insn_cnt = ARRAY_SIZE(insns);
4760 
4761 	fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
4762 	return probe_fd(fd);
4763 }
4764 
4765 static int probe_prog_bind_map(void)
4766 {
4767 	char *cp, errmsg[STRERR_BUFSIZE];
4768 	struct bpf_insn insns[] = {
4769 		BPF_MOV64_IMM(BPF_REG_0, 0),
4770 		BPF_EXIT_INSN(),
4771 	};
4772 	int ret, map, prog, insn_cnt = ARRAY_SIZE(insns);
4773 
4774 	map = bpf_map_create(BPF_MAP_TYPE_ARRAY, NULL, sizeof(int), 32, 1, NULL);
4775 	if (map < 0) {
4776 		ret = -errno;
4777 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4778 		pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4779 			__func__, cp, -ret);
4780 		return ret;
4781 	}
4782 
4783 	prog = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4784 	if (prog < 0) {
4785 		close(map);
4786 		return 0;
4787 	}
4788 
4789 	ret = bpf_prog_bind_map(prog, map, NULL);
4790 
4791 	close(map);
4792 	close(prog);
4793 
4794 	return ret >= 0;
4795 }
4796 
4797 static int probe_module_btf(void)
4798 {
4799 	static const char strs[] = "\0int";
4800 	__u32 types[] = {
4801 		/* int */
4802 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4803 	};
4804 	struct bpf_btf_info info;
4805 	__u32 len = sizeof(info);
4806 	char name[16];
4807 	int fd, err;
4808 
4809 	fd = libbpf__load_raw_btf((char *)types, sizeof(types), strs, sizeof(strs));
4810 	if (fd < 0)
4811 		return 0; /* BTF not supported at all */
4812 
4813 	memset(&info, 0, sizeof(info));
4814 	info.name = ptr_to_u64(name);
4815 	info.name_len = sizeof(name);
4816 
4817 	/* check that BPF_OBJ_GET_INFO_BY_FD supports specifying name pointer;
4818 	 * kernel's module BTF support coincides with support for
4819 	 * name/name_len fields in struct bpf_btf_info.
4820 	 */
4821 	err = bpf_obj_get_info_by_fd(fd, &info, &len);
4822 	close(fd);
4823 	return !err;
4824 }
4825 
4826 static int probe_perf_link(void)
4827 {
4828 	struct bpf_insn insns[] = {
4829 		BPF_MOV64_IMM(BPF_REG_0, 0),
4830 		BPF_EXIT_INSN(),
4831 	};
4832 	int prog_fd, link_fd, err;
4833 
4834 	prog_fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL",
4835 				insns, ARRAY_SIZE(insns), NULL);
4836 	if (prog_fd < 0)
4837 		return -errno;
4838 
4839 	/* use invalid perf_event FD to get EBADF, if link is supported;
4840 	 * otherwise EINVAL should be returned
4841 	 */
4842 	link_fd = bpf_link_create(prog_fd, -1, BPF_PERF_EVENT, NULL);
4843 	err = -errno; /* close() can clobber errno */
4844 
4845 	if (link_fd >= 0)
4846 		close(link_fd);
4847 	close(prog_fd);
4848 
4849 	return link_fd < 0 && err == -EBADF;
4850 }
4851 
4852 static int probe_kern_bpf_cookie(void)
4853 {
4854 	struct bpf_insn insns[] = {
4855 		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_get_attach_cookie),
4856 		BPF_EXIT_INSN(),
4857 	};
4858 	int ret, insn_cnt = ARRAY_SIZE(insns);
4859 
4860 	ret = bpf_prog_load(BPF_PROG_TYPE_KPROBE, NULL, "GPL", insns, insn_cnt, NULL);
4861 	return probe_fd(ret);
4862 }
4863 
4864 enum kern_feature_result {
4865 	FEAT_UNKNOWN = 0,
4866 	FEAT_SUPPORTED = 1,
4867 	FEAT_MISSING = 2,
4868 };
4869 
4870 typedef int (*feature_probe_fn)(void);
4871 
4872 static struct kern_feature_desc {
4873 	const char *desc;
4874 	feature_probe_fn probe;
4875 	enum kern_feature_result res;
4876 } feature_probes[__FEAT_CNT] = {
4877 	[FEAT_PROG_NAME] = {
4878 		"BPF program name", probe_kern_prog_name,
4879 	},
4880 	[FEAT_GLOBAL_DATA] = {
4881 		"global variables", probe_kern_global_data,
4882 	},
4883 	[FEAT_BTF] = {
4884 		"minimal BTF", probe_kern_btf,
4885 	},
4886 	[FEAT_BTF_FUNC] = {
4887 		"BTF functions", probe_kern_btf_func,
4888 	},
4889 	[FEAT_BTF_GLOBAL_FUNC] = {
4890 		"BTF global function", probe_kern_btf_func_global,
4891 	},
4892 	[FEAT_BTF_DATASEC] = {
4893 		"BTF data section and variable", probe_kern_btf_datasec,
4894 	},
4895 	[FEAT_ARRAY_MMAP] = {
4896 		"ARRAY map mmap()", probe_kern_array_mmap,
4897 	},
4898 	[FEAT_EXP_ATTACH_TYPE] = {
4899 		"BPF_PROG_LOAD expected_attach_type attribute",
4900 		probe_kern_exp_attach_type,
4901 	},
4902 	[FEAT_PROBE_READ_KERN] = {
4903 		"bpf_probe_read_kernel() helper", probe_kern_probe_read_kernel,
4904 	},
4905 	[FEAT_PROG_BIND_MAP] = {
4906 		"BPF_PROG_BIND_MAP support", probe_prog_bind_map,
4907 	},
4908 	[FEAT_MODULE_BTF] = {
4909 		"module BTF support", probe_module_btf,
4910 	},
4911 	[FEAT_BTF_FLOAT] = {
4912 		"BTF_KIND_FLOAT support", probe_kern_btf_float,
4913 	},
4914 	[FEAT_PERF_LINK] = {
4915 		"BPF perf link support", probe_perf_link,
4916 	},
4917 	[FEAT_BTF_DECL_TAG] = {
4918 		"BTF_KIND_DECL_TAG support", probe_kern_btf_decl_tag,
4919 	},
4920 	[FEAT_BTF_TYPE_TAG] = {
4921 		"BTF_KIND_TYPE_TAG support", probe_kern_btf_type_tag,
4922 	},
4923 	[FEAT_MEMCG_ACCOUNT] = {
4924 		"memcg-based memory accounting", probe_memcg_account,
4925 	},
4926 	[FEAT_BPF_COOKIE] = {
4927 		"BPF cookie support", probe_kern_bpf_cookie,
4928 	},
4929 };
4930 
4931 bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
4932 {
4933 	struct kern_feature_desc *feat = &feature_probes[feat_id];
4934 	int ret;
4935 
4936 	if (obj && obj->gen_loader)
4937 		/* To generate loader program assume the latest kernel
4938 		 * to avoid doing extra prog_load, map_create syscalls.
4939 		 */
4940 		return true;
4941 
4942 	if (READ_ONCE(feat->res) == FEAT_UNKNOWN) {
4943 		ret = feat->probe();
4944 		if (ret > 0) {
4945 			WRITE_ONCE(feat->res, FEAT_SUPPORTED);
4946 		} else if (ret == 0) {
4947 			WRITE_ONCE(feat->res, FEAT_MISSING);
4948 		} else {
4949 			pr_warn("Detection of kernel %s support failed: %d\n", feat->desc, ret);
4950 			WRITE_ONCE(feat->res, FEAT_MISSING);
4951 		}
4952 	}
4953 
4954 	return READ_ONCE(feat->res) == FEAT_SUPPORTED;
4955 }
4956 
4957 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
4958 {
4959 	struct bpf_map_info map_info = {};
4960 	char msg[STRERR_BUFSIZE];
4961 	__u32 map_info_len;
4962 	int err;
4963 
4964 	map_info_len = sizeof(map_info);
4965 
4966 	err = bpf_obj_get_info_by_fd(map_fd, &map_info, &map_info_len);
4967 	if (err && errno == EINVAL)
4968 		err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
4969 	if (err) {
4970 		pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
4971 			libbpf_strerror_r(errno, msg, sizeof(msg)));
4972 		return false;
4973 	}
4974 
4975 	return (map_info.type == map->def.type &&
4976 		map_info.key_size == map->def.key_size &&
4977 		map_info.value_size == map->def.value_size &&
4978 		map_info.max_entries == map->def.max_entries &&
4979 		map_info.map_flags == map->def.map_flags &&
4980 		map_info.map_extra == map->map_extra);
4981 }
4982 
4983 static int
4984 bpf_object__reuse_map(struct bpf_map *map)
4985 {
4986 	char *cp, errmsg[STRERR_BUFSIZE];
4987 	int err, pin_fd;
4988 
4989 	pin_fd = bpf_obj_get(map->pin_path);
4990 	if (pin_fd < 0) {
4991 		err = -errno;
4992 		if (err == -ENOENT) {
4993 			pr_debug("found no pinned map to reuse at '%s'\n",
4994 				 map->pin_path);
4995 			return 0;
4996 		}
4997 
4998 		cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
4999 		pr_warn("couldn't retrieve pinned map '%s': %s\n",
5000 			map->pin_path, cp);
5001 		return err;
5002 	}
5003 
5004 	if (!map_is_reuse_compat(map, pin_fd)) {
5005 		pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
5006 			map->pin_path);
5007 		close(pin_fd);
5008 		return -EINVAL;
5009 	}
5010 
5011 	err = bpf_map__reuse_fd(map, pin_fd);
5012 	close(pin_fd);
5013 	if (err) {
5014 		return err;
5015 	}
5016 	map->pinned = true;
5017 	pr_debug("reused pinned map at '%s'\n", map->pin_path);
5018 
5019 	return 0;
5020 }
5021 
5022 static int
5023 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
5024 {
5025 	enum libbpf_map_type map_type = map->libbpf_type;
5026 	char *cp, errmsg[STRERR_BUFSIZE];
5027 	int err, zero = 0;
5028 
5029 	if (obj->gen_loader) {
5030 		bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
5031 					 map->mmaped, map->def.value_size);
5032 		if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
5033 			bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
5034 		return 0;
5035 	}
5036 	err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
5037 	if (err) {
5038 		err = -errno;
5039 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5040 		pr_warn("Error setting initial map(%s) contents: %s\n",
5041 			map->name, cp);
5042 		return err;
5043 	}
5044 
5045 	/* Freeze .rodata and .kconfig map as read-only from syscall side. */
5046 	if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
5047 		err = bpf_map_freeze(map->fd);
5048 		if (err) {
5049 			err = -errno;
5050 			cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5051 			pr_warn("Error freezing map(%s) as read-only: %s\n",
5052 				map->name, cp);
5053 			return err;
5054 		}
5055 	}
5056 	return 0;
5057 }
5058 
5059 static void bpf_map__destroy(struct bpf_map *map);
5060 
5061 static bool is_pow_of_2(size_t x)
5062 {
5063 	return x && (x & (x - 1));
5064 }
5065 
5066 static size_t adjust_ringbuf_sz(size_t sz)
5067 {
5068 	__u32 page_sz = sysconf(_SC_PAGE_SIZE);
5069 	__u32 mul;
5070 
5071 	/* if user forgot to set any size, make sure they see error */
5072 	if (sz == 0)
5073 		return 0;
5074 	/* Kernel expects BPF_MAP_TYPE_RINGBUF's max_entries to be
5075 	 * a power-of-2 multiple of kernel's page size. If user diligently
5076 	 * satisified these conditions, pass the size through.
5077 	 */
5078 	if ((sz % page_sz) == 0 && is_pow_of_2(sz / page_sz))
5079 		return sz;
5080 
5081 	/* Otherwise find closest (page_sz * power_of_2) product bigger than
5082 	 * user-set size to satisfy both user size request and kernel
5083 	 * requirements and substitute correct max_entries for map creation.
5084 	 */
5085 	for (mul = 1; mul <= UINT_MAX / page_sz; mul <<= 1) {
5086 		if (mul * page_sz > sz)
5087 			return mul * page_sz;
5088 	}
5089 
5090 	/* if it's impossible to satisfy the conditions (i.e., user size is
5091 	 * very close to UINT_MAX but is not a power-of-2 multiple of
5092 	 * page_size) then just return original size and let kernel reject it
5093 	 */
5094 	return sz;
5095 }
5096 
5097 static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
5098 {
5099 	LIBBPF_OPTS(bpf_map_create_opts, create_attr);
5100 	struct bpf_map_def *def = &map->def;
5101 	const char *map_name = NULL;
5102 	int err = 0;
5103 
5104 	if (kernel_supports(obj, FEAT_PROG_NAME))
5105 		map_name = map->name;
5106 	create_attr.map_ifindex = map->map_ifindex;
5107 	create_attr.map_flags = def->map_flags;
5108 	create_attr.numa_node = map->numa_node;
5109 	create_attr.map_extra = map->map_extra;
5110 
5111 	if (bpf_map__is_struct_ops(map))
5112 		create_attr.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
5113 
5114 	if (obj->btf && btf__fd(obj->btf) >= 0) {
5115 		create_attr.btf_fd = btf__fd(obj->btf);
5116 		create_attr.btf_key_type_id = map->btf_key_type_id;
5117 		create_attr.btf_value_type_id = map->btf_value_type_id;
5118 	}
5119 
5120 	if (bpf_map_type__is_map_in_map(def->type)) {
5121 		if (map->inner_map) {
5122 			err = bpf_object__create_map(obj, map->inner_map, true);
5123 			if (err) {
5124 				pr_warn("map '%s': failed to create inner map: %d\n",
5125 					map->name, err);
5126 				return err;
5127 			}
5128 			map->inner_map_fd = bpf_map__fd(map->inner_map);
5129 		}
5130 		if (map->inner_map_fd >= 0)
5131 			create_attr.inner_map_fd = map->inner_map_fd;
5132 	}
5133 
5134 	switch (def->type) {
5135 	case BPF_MAP_TYPE_RINGBUF:
5136 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
5137 		/* fallthrough */
5138 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5139 	case BPF_MAP_TYPE_CGROUP_ARRAY:
5140 	case BPF_MAP_TYPE_STACK_TRACE:
5141 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5142 	case BPF_MAP_TYPE_HASH_OF_MAPS:
5143 	case BPF_MAP_TYPE_DEVMAP:
5144 	case BPF_MAP_TYPE_DEVMAP_HASH:
5145 	case BPF_MAP_TYPE_CPUMAP:
5146 	case BPF_MAP_TYPE_XSKMAP:
5147 	case BPF_MAP_TYPE_SOCKMAP:
5148 	case BPF_MAP_TYPE_SOCKHASH:
5149 	case BPF_MAP_TYPE_QUEUE:
5150 	case BPF_MAP_TYPE_STACK:
5151 		create_attr.btf_fd = 0;
5152 		create_attr.btf_key_type_id = 0;
5153 		create_attr.btf_value_type_id = 0;
5154 		map->btf_key_type_id = 0;
5155 		map->btf_value_type_id = 0;
5156 	default:
5157 		break;
5158 	}
5159 
5160 	if (obj->gen_loader) {
5161 		bpf_gen__map_create(obj->gen_loader, def->type, map_name,
5162 				    def->key_size, def->value_size, def->max_entries,
5163 				    &create_attr, is_inner ? -1 : map - obj->maps);
5164 		/* Pretend to have valid FD to pass various fd >= 0 checks.
5165 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
5166 		 */
5167 		map->fd = 0;
5168 	} else {
5169 		map->fd = bpf_map_create(def->type, map_name,
5170 					 def->key_size, def->value_size,
5171 					 def->max_entries, &create_attr);
5172 	}
5173 	if (map->fd < 0 && (create_attr.btf_key_type_id ||
5174 			    create_attr.btf_value_type_id)) {
5175 		char *cp, errmsg[STRERR_BUFSIZE];
5176 
5177 		err = -errno;
5178 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5179 		pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
5180 			map->name, cp, err);
5181 		create_attr.btf_fd = 0;
5182 		create_attr.btf_key_type_id = 0;
5183 		create_attr.btf_value_type_id = 0;
5184 		map->btf_key_type_id = 0;
5185 		map->btf_value_type_id = 0;
5186 		map->fd = bpf_map_create(def->type, map_name,
5187 					 def->key_size, def->value_size,
5188 					 def->max_entries, &create_attr);
5189 	}
5190 
5191 	err = map->fd < 0 ? -errno : 0;
5192 
5193 	if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
5194 		if (obj->gen_loader)
5195 			map->inner_map->fd = -1;
5196 		bpf_map__destroy(map->inner_map);
5197 		zfree(&map->inner_map);
5198 	}
5199 
5200 	return err;
5201 }
5202 
5203 static int init_map_in_map_slots(struct bpf_object *obj, struct bpf_map *map)
5204 {
5205 	const struct bpf_map *targ_map;
5206 	unsigned int i;
5207 	int fd, err = 0;
5208 
5209 	for (i = 0; i < map->init_slots_sz; i++) {
5210 		if (!map->init_slots[i])
5211 			continue;
5212 
5213 		targ_map = map->init_slots[i];
5214 		fd = bpf_map__fd(targ_map);
5215 
5216 		if (obj->gen_loader) {
5217 			bpf_gen__populate_outer_map(obj->gen_loader,
5218 						    map - obj->maps, i,
5219 						    targ_map - obj->maps);
5220 		} else {
5221 			err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5222 		}
5223 		if (err) {
5224 			err = -errno;
5225 			pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %d\n",
5226 				map->name, i, targ_map->name, fd, err);
5227 			return err;
5228 		}
5229 		pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
5230 			 map->name, i, targ_map->name, fd);
5231 	}
5232 
5233 	zfree(&map->init_slots);
5234 	map->init_slots_sz = 0;
5235 
5236 	return 0;
5237 }
5238 
5239 static int init_prog_array_slots(struct bpf_object *obj, struct bpf_map *map)
5240 {
5241 	const struct bpf_program *targ_prog;
5242 	unsigned int i;
5243 	int fd, err;
5244 
5245 	if (obj->gen_loader)
5246 		return -ENOTSUP;
5247 
5248 	for (i = 0; i < map->init_slots_sz; i++) {
5249 		if (!map->init_slots[i])
5250 			continue;
5251 
5252 		targ_prog = map->init_slots[i];
5253 		fd = bpf_program__fd(targ_prog);
5254 
5255 		err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5256 		if (err) {
5257 			err = -errno;
5258 			pr_warn("map '%s': failed to initialize slot [%d] to prog '%s' fd=%d: %d\n",
5259 				map->name, i, targ_prog->name, fd, err);
5260 			return err;
5261 		}
5262 		pr_debug("map '%s': slot [%d] set to prog '%s' fd=%d\n",
5263 			 map->name, i, targ_prog->name, fd);
5264 	}
5265 
5266 	zfree(&map->init_slots);
5267 	map->init_slots_sz = 0;
5268 
5269 	return 0;
5270 }
5271 
5272 static int bpf_object_init_prog_arrays(struct bpf_object *obj)
5273 {
5274 	struct bpf_map *map;
5275 	int i, err;
5276 
5277 	for (i = 0; i < obj->nr_maps; i++) {
5278 		map = &obj->maps[i];
5279 
5280 		if (!map->init_slots_sz || map->def.type != BPF_MAP_TYPE_PROG_ARRAY)
5281 			continue;
5282 
5283 		err = init_prog_array_slots(obj, map);
5284 		if (err < 0) {
5285 			zclose(map->fd);
5286 			return err;
5287 		}
5288 	}
5289 	return 0;
5290 }
5291 
5292 static int map_set_def_max_entries(struct bpf_map *map)
5293 {
5294 	if (map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !map->def.max_entries) {
5295 		int nr_cpus;
5296 
5297 		nr_cpus = libbpf_num_possible_cpus();
5298 		if (nr_cpus < 0) {
5299 			pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
5300 				map->name, nr_cpus);
5301 			return nr_cpus;
5302 		}
5303 		pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
5304 		map->def.max_entries = nr_cpus;
5305 	}
5306 
5307 	return 0;
5308 }
5309 
5310 static int
5311 bpf_object__create_maps(struct bpf_object *obj)
5312 {
5313 	struct bpf_map *map;
5314 	char *cp, errmsg[STRERR_BUFSIZE];
5315 	unsigned int i, j;
5316 	int err;
5317 	bool retried;
5318 
5319 	for (i = 0; i < obj->nr_maps; i++) {
5320 		map = &obj->maps[i];
5321 
5322 		/* To support old kernels, we skip creating global data maps
5323 		 * (.rodata, .data, .kconfig, etc); later on, during program
5324 		 * loading, if we detect that at least one of the to-be-loaded
5325 		 * programs is referencing any global data map, we'll error
5326 		 * out with program name and relocation index logged.
5327 		 * This approach allows to accommodate Clang emitting
5328 		 * unnecessary .rodata.str1.1 sections for string literals,
5329 		 * but also it allows to have CO-RE applications that use
5330 		 * global variables in some of BPF programs, but not others.
5331 		 * If those global variable-using programs are not loaded at
5332 		 * runtime due to bpf_program__set_autoload(prog, false),
5333 		 * bpf_object loading will succeed just fine even on old
5334 		 * kernels.
5335 		 */
5336 		if (bpf_map__is_internal(map) && !kernel_supports(obj, FEAT_GLOBAL_DATA))
5337 			map->autocreate = false;
5338 
5339 		if (!map->autocreate) {
5340 			pr_debug("map '%s': skipped auto-creating...\n", map->name);
5341 			continue;
5342 		}
5343 
5344 		err = map_set_def_max_entries(map);
5345 		if (err)
5346 			goto err_out;
5347 
5348 		retried = false;
5349 retry:
5350 		if (map->pin_path) {
5351 			err = bpf_object__reuse_map(map);
5352 			if (err) {
5353 				pr_warn("map '%s': error reusing pinned map\n",
5354 					map->name);
5355 				goto err_out;
5356 			}
5357 			if (retried && map->fd < 0) {
5358 				pr_warn("map '%s': cannot find pinned map\n",
5359 					map->name);
5360 				err = -ENOENT;
5361 				goto err_out;
5362 			}
5363 		}
5364 
5365 		if (map->fd >= 0) {
5366 			pr_debug("map '%s': skipping creation (preset fd=%d)\n",
5367 				 map->name, map->fd);
5368 		} else {
5369 			err = bpf_object__create_map(obj, map, false);
5370 			if (err)
5371 				goto err_out;
5372 
5373 			pr_debug("map '%s': created successfully, fd=%d\n",
5374 				 map->name, map->fd);
5375 
5376 			if (bpf_map__is_internal(map)) {
5377 				err = bpf_object__populate_internal_map(obj, map);
5378 				if (err < 0) {
5379 					zclose(map->fd);
5380 					goto err_out;
5381 				}
5382 			}
5383 
5384 			if (map->init_slots_sz && map->def.type != BPF_MAP_TYPE_PROG_ARRAY) {
5385 				err = init_map_in_map_slots(obj, map);
5386 				if (err < 0) {
5387 					zclose(map->fd);
5388 					goto err_out;
5389 				}
5390 			}
5391 		}
5392 
5393 		if (map->pin_path && !map->pinned) {
5394 			err = bpf_map__pin(map, NULL);
5395 			if (err) {
5396 				zclose(map->fd);
5397 				if (!retried && err == -EEXIST) {
5398 					retried = true;
5399 					goto retry;
5400 				}
5401 				pr_warn("map '%s': failed to auto-pin at '%s': %d\n",
5402 					map->name, map->pin_path, err);
5403 				goto err_out;
5404 			}
5405 		}
5406 	}
5407 
5408 	return 0;
5409 
5410 err_out:
5411 	cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5412 	pr_warn("map '%s': failed to create: %s(%d)\n", map->name, cp, err);
5413 	pr_perm_msg(err);
5414 	for (j = 0; j < i; j++)
5415 		zclose(obj->maps[j].fd);
5416 	return err;
5417 }
5418 
5419 static bool bpf_core_is_flavor_sep(const char *s)
5420 {
5421 	/* check X___Y name pattern, where X and Y are not underscores */
5422 	return s[0] != '_' &&				      /* X */
5423 	       s[1] == '_' && s[2] == '_' && s[3] == '_' &&   /* ___ */
5424 	       s[4] != '_';				      /* Y */
5425 }
5426 
5427 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
5428  * before last triple underscore. Struct name part after last triple
5429  * underscore is ignored by BPF CO-RE relocation during relocation matching.
5430  */
5431 size_t bpf_core_essential_name_len(const char *name)
5432 {
5433 	size_t n = strlen(name);
5434 	int i;
5435 
5436 	for (i = n - 5; i >= 0; i--) {
5437 		if (bpf_core_is_flavor_sep(name + i))
5438 			return i + 1;
5439 	}
5440 	return n;
5441 }
5442 
5443 void bpf_core_free_cands(struct bpf_core_cand_list *cands)
5444 {
5445 	if (!cands)
5446 		return;
5447 
5448 	free(cands->cands);
5449 	free(cands);
5450 }
5451 
5452 int bpf_core_add_cands(struct bpf_core_cand *local_cand,
5453 		       size_t local_essent_len,
5454 		       const struct btf *targ_btf,
5455 		       const char *targ_btf_name,
5456 		       int targ_start_id,
5457 		       struct bpf_core_cand_list *cands)
5458 {
5459 	struct bpf_core_cand *new_cands, *cand;
5460 	const struct btf_type *t, *local_t;
5461 	const char *targ_name, *local_name;
5462 	size_t targ_essent_len;
5463 	int n, i;
5464 
5465 	local_t = btf__type_by_id(local_cand->btf, local_cand->id);
5466 	local_name = btf__str_by_offset(local_cand->btf, local_t->name_off);
5467 
5468 	n = btf__type_cnt(targ_btf);
5469 	for (i = targ_start_id; i < n; i++) {
5470 		t = btf__type_by_id(targ_btf, i);
5471 		if (btf_kind(t) != btf_kind(local_t))
5472 			continue;
5473 
5474 		targ_name = btf__name_by_offset(targ_btf, t->name_off);
5475 		if (str_is_empty(targ_name))
5476 			continue;
5477 
5478 		targ_essent_len = bpf_core_essential_name_len(targ_name);
5479 		if (targ_essent_len != local_essent_len)
5480 			continue;
5481 
5482 		if (strncmp(local_name, targ_name, local_essent_len) != 0)
5483 			continue;
5484 
5485 		pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s in [%s]\n",
5486 			 local_cand->id, btf_kind_str(local_t),
5487 			 local_name, i, btf_kind_str(t), targ_name,
5488 			 targ_btf_name);
5489 		new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
5490 					      sizeof(*cands->cands));
5491 		if (!new_cands)
5492 			return -ENOMEM;
5493 
5494 		cand = &new_cands[cands->len];
5495 		cand->btf = targ_btf;
5496 		cand->id = i;
5497 
5498 		cands->cands = new_cands;
5499 		cands->len++;
5500 	}
5501 	return 0;
5502 }
5503 
5504 static int load_module_btfs(struct bpf_object *obj)
5505 {
5506 	struct bpf_btf_info info;
5507 	struct module_btf *mod_btf;
5508 	struct btf *btf;
5509 	char name[64];
5510 	__u32 id = 0, len;
5511 	int err, fd;
5512 
5513 	if (obj->btf_modules_loaded)
5514 		return 0;
5515 
5516 	if (obj->gen_loader)
5517 		return 0;
5518 
5519 	/* don't do this again, even if we find no module BTFs */
5520 	obj->btf_modules_loaded = true;
5521 
5522 	/* kernel too old to support module BTFs */
5523 	if (!kernel_supports(obj, FEAT_MODULE_BTF))
5524 		return 0;
5525 
5526 	while (true) {
5527 		err = bpf_btf_get_next_id(id, &id);
5528 		if (err && errno == ENOENT)
5529 			return 0;
5530 		if (err) {
5531 			err = -errno;
5532 			pr_warn("failed to iterate BTF objects: %d\n", err);
5533 			return err;
5534 		}
5535 
5536 		fd = bpf_btf_get_fd_by_id(id);
5537 		if (fd < 0) {
5538 			if (errno == ENOENT)
5539 				continue; /* expected race: BTF was unloaded */
5540 			err = -errno;
5541 			pr_warn("failed to get BTF object #%d FD: %d\n", id, err);
5542 			return err;
5543 		}
5544 
5545 		len = sizeof(info);
5546 		memset(&info, 0, sizeof(info));
5547 		info.name = ptr_to_u64(name);
5548 		info.name_len = sizeof(name);
5549 
5550 		err = bpf_obj_get_info_by_fd(fd, &info, &len);
5551 		if (err) {
5552 			err = -errno;
5553 			pr_warn("failed to get BTF object #%d info: %d\n", id, err);
5554 			goto err_out;
5555 		}
5556 
5557 		/* ignore non-module BTFs */
5558 		if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
5559 			close(fd);
5560 			continue;
5561 		}
5562 
5563 		btf = btf_get_from_fd(fd, obj->btf_vmlinux);
5564 		err = libbpf_get_error(btf);
5565 		if (err) {
5566 			pr_warn("failed to load module [%s]'s BTF object #%d: %d\n",
5567 				name, id, err);
5568 			goto err_out;
5569 		}
5570 
5571 		err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
5572 				        sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
5573 		if (err)
5574 			goto err_out;
5575 
5576 		mod_btf = &obj->btf_modules[obj->btf_module_cnt++];
5577 
5578 		mod_btf->btf = btf;
5579 		mod_btf->id = id;
5580 		mod_btf->fd = fd;
5581 		mod_btf->name = strdup(name);
5582 		if (!mod_btf->name) {
5583 			err = -ENOMEM;
5584 			goto err_out;
5585 		}
5586 		continue;
5587 
5588 err_out:
5589 		close(fd);
5590 		return err;
5591 	}
5592 
5593 	return 0;
5594 }
5595 
5596 static struct bpf_core_cand_list *
5597 bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
5598 {
5599 	struct bpf_core_cand local_cand = {};
5600 	struct bpf_core_cand_list *cands;
5601 	const struct btf *main_btf;
5602 	const struct btf_type *local_t;
5603 	const char *local_name;
5604 	size_t local_essent_len;
5605 	int err, i;
5606 
5607 	local_cand.btf = local_btf;
5608 	local_cand.id = local_type_id;
5609 	local_t = btf__type_by_id(local_btf, local_type_id);
5610 	if (!local_t)
5611 		return ERR_PTR(-EINVAL);
5612 
5613 	local_name = btf__name_by_offset(local_btf, local_t->name_off);
5614 	if (str_is_empty(local_name))
5615 		return ERR_PTR(-EINVAL);
5616 	local_essent_len = bpf_core_essential_name_len(local_name);
5617 
5618 	cands = calloc(1, sizeof(*cands));
5619 	if (!cands)
5620 		return ERR_PTR(-ENOMEM);
5621 
5622 	/* Attempt to find target candidates in vmlinux BTF first */
5623 	main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
5624 	err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
5625 	if (err)
5626 		goto err_out;
5627 
5628 	/* if vmlinux BTF has any candidate, don't got for module BTFs */
5629 	if (cands->len)
5630 		return cands;
5631 
5632 	/* if vmlinux BTF was overridden, don't attempt to load module BTFs */
5633 	if (obj->btf_vmlinux_override)
5634 		return cands;
5635 
5636 	/* now look through module BTFs, trying to still find candidates */
5637 	err = load_module_btfs(obj);
5638 	if (err)
5639 		goto err_out;
5640 
5641 	for (i = 0; i < obj->btf_module_cnt; i++) {
5642 		err = bpf_core_add_cands(&local_cand, local_essent_len,
5643 					 obj->btf_modules[i].btf,
5644 					 obj->btf_modules[i].name,
5645 					 btf__type_cnt(obj->btf_vmlinux),
5646 					 cands);
5647 		if (err)
5648 			goto err_out;
5649 	}
5650 
5651 	return cands;
5652 err_out:
5653 	bpf_core_free_cands(cands);
5654 	return ERR_PTR(err);
5655 }
5656 
5657 /* Check local and target types for compatibility. This check is used for
5658  * type-based CO-RE relocations and follow slightly different rules than
5659  * field-based relocations. This function assumes that root types were already
5660  * checked for name match. Beyond that initial root-level name check, names
5661  * are completely ignored. Compatibility rules are as follows:
5662  *   - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
5663  *     kind should match for local and target types (i.e., STRUCT is not
5664  *     compatible with UNION);
5665  *   - for ENUMs, the size is ignored;
5666  *   - for INT, size and signedness are ignored;
5667  *   - for ARRAY, dimensionality is ignored, element types are checked for
5668  *     compatibility recursively;
5669  *   - CONST/VOLATILE/RESTRICT modifiers are ignored;
5670  *   - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
5671  *   - FUNC_PROTOs are compatible if they have compatible signature: same
5672  *     number of input args and compatible return and argument types.
5673  * These rules are not set in stone and probably will be adjusted as we get
5674  * more experience with using BPF CO-RE relocations.
5675  */
5676 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
5677 			      const struct btf *targ_btf, __u32 targ_id)
5678 {
5679 	const struct btf_type *local_type, *targ_type;
5680 	int depth = 32; /* max recursion depth */
5681 
5682 	/* caller made sure that names match (ignoring flavor suffix) */
5683 	local_type = btf__type_by_id(local_btf, local_id);
5684 	targ_type = btf__type_by_id(targ_btf, targ_id);
5685 	if (btf_kind(local_type) != btf_kind(targ_type))
5686 		return 0;
5687 
5688 recur:
5689 	depth--;
5690 	if (depth < 0)
5691 		return -EINVAL;
5692 
5693 	local_type = skip_mods_and_typedefs(local_btf, local_id, &local_id);
5694 	targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
5695 	if (!local_type || !targ_type)
5696 		return -EINVAL;
5697 
5698 	if (btf_kind(local_type) != btf_kind(targ_type))
5699 		return 0;
5700 
5701 	switch (btf_kind(local_type)) {
5702 	case BTF_KIND_UNKN:
5703 	case BTF_KIND_STRUCT:
5704 	case BTF_KIND_UNION:
5705 	case BTF_KIND_ENUM:
5706 	case BTF_KIND_FWD:
5707 		return 1;
5708 	case BTF_KIND_INT:
5709 		/* just reject deprecated bitfield-like integers; all other
5710 		 * integers are by default compatible between each other
5711 		 */
5712 		return btf_int_offset(local_type) == 0 && btf_int_offset(targ_type) == 0;
5713 	case BTF_KIND_PTR:
5714 		local_id = local_type->type;
5715 		targ_id = targ_type->type;
5716 		goto recur;
5717 	case BTF_KIND_ARRAY:
5718 		local_id = btf_array(local_type)->type;
5719 		targ_id = btf_array(targ_type)->type;
5720 		goto recur;
5721 	case BTF_KIND_FUNC_PROTO: {
5722 		struct btf_param *local_p = btf_params(local_type);
5723 		struct btf_param *targ_p = btf_params(targ_type);
5724 		__u16 local_vlen = btf_vlen(local_type);
5725 		__u16 targ_vlen = btf_vlen(targ_type);
5726 		int i, err;
5727 
5728 		if (local_vlen != targ_vlen)
5729 			return 0;
5730 
5731 		for (i = 0; i < local_vlen; i++, local_p++, targ_p++) {
5732 			skip_mods_and_typedefs(local_btf, local_p->type, &local_id);
5733 			skip_mods_and_typedefs(targ_btf, targ_p->type, &targ_id);
5734 			err = bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id);
5735 			if (err <= 0)
5736 				return err;
5737 		}
5738 
5739 		/* tail recurse for return type check */
5740 		skip_mods_and_typedefs(local_btf, local_type->type, &local_id);
5741 		skip_mods_and_typedefs(targ_btf, targ_type->type, &targ_id);
5742 		goto recur;
5743 	}
5744 	default:
5745 		pr_warn("unexpected kind %s relocated, local [%d], target [%d]\n",
5746 			btf_kind_str(local_type), local_id, targ_id);
5747 		return 0;
5748 	}
5749 }
5750 
5751 static size_t bpf_core_hash_fn(const void *key, void *ctx)
5752 {
5753 	return (size_t)key;
5754 }
5755 
5756 static bool bpf_core_equal_fn(const void *k1, const void *k2, void *ctx)
5757 {
5758 	return k1 == k2;
5759 }
5760 
5761 static void *u32_as_hash_key(__u32 x)
5762 {
5763 	return (void *)(uintptr_t)x;
5764 }
5765 
5766 static int record_relo_core(struct bpf_program *prog,
5767 			    const struct bpf_core_relo *core_relo, int insn_idx)
5768 {
5769 	struct reloc_desc *relos, *relo;
5770 
5771 	relos = libbpf_reallocarray(prog->reloc_desc,
5772 				    prog->nr_reloc + 1, sizeof(*relos));
5773 	if (!relos)
5774 		return -ENOMEM;
5775 	relo = &relos[prog->nr_reloc];
5776 	relo->type = RELO_CORE;
5777 	relo->insn_idx = insn_idx;
5778 	relo->core_relo = core_relo;
5779 	prog->reloc_desc = relos;
5780 	prog->nr_reloc++;
5781 	return 0;
5782 }
5783 
5784 static const struct bpf_core_relo *find_relo_core(struct bpf_program *prog, int insn_idx)
5785 {
5786 	struct reloc_desc *relo;
5787 	int i;
5788 
5789 	for (i = 0; i < prog->nr_reloc; i++) {
5790 		relo = &prog->reloc_desc[i];
5791 		if (relo->type != RELO_CORE || relo->insn_idx != insn_idx)
5792 			continue;
5793 
5794 		return relo->core_relo;
5795 	}
5796 
5797 	return NULL;
5798 }
5799 
5800 static int bpf_core_resolve_relo(struct bpf_program *prog,
5801 				 const struct bpf_core_relo *relo,
5802 				 int relo_idx,
5803 				 const struct btf *local_btf,
5804 				 struct hashmap *cand_cache,
5805 				 struct bpf_core_relo_res *targ_res)
5806 {
5807 	struct bpf_core_spec specs_scratch[3] = {};
5808 	const void *type_key = u32_as_hash_key(relo->type_id);
5809 	struct bpf_core_cand_list *cands = NULL;
5810 	const char *prog_name = prog->name;
5811 	const struct btf_type *local_type;
5812 	const char *local_name;
5813 	__u32 local_id = relo->type_id;
5814 	int err;
5815 
5816 	local_type = btf__type_by_id(local_btf, local_id);
5817 	if (!local_type)
5818 		return -EINVAL;
5819 
5820 	local_name = btf__name_by_offset(local_btf, local_type->name_off);
5821 	if (!local_name)
5822 		return -EINVAL;
5823 
5824 	if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
5825 	    !hashmap__find(cand_cache, type_key, (void **)&cands)) {
5826 		cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
5827 		if (IS_ERR(cands)) {
5828 			pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n",
5829 				prog_name, relo_idx, local_id, btf_kind_str(local_type),
5830 				local_name, PTR_ERR(cands));
5831 			return PTR_ERR(cands);
5832 		}
5833 		err = hashmap__set(cand_cache, type_key, cands, NULL, NULL);
5834 		if (err) {
5835 			bpf_core_free_cands(cands);
5836 			return err;
5837 		}
5838 	}
5839 
5840 	return bpf_core_calc_relo_insn(prog_name, relo, relo_idx, local_btf, cands, specs_scratch,
5841 				       targ_res);
5842 }
5843 
5844 static int
5845 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
5846 {
5847 	const struct btf_ext_info_sec *sec;
5848 	struct bpf_core_relo_res targ_res;
5849 	const struct bpf_core_relo *rec;
5850 	const struct btf_ext_info *seg;
5851 	struct hashmap_entry *entry;
5852 	struct hashmap *cand_cache = NULL;
5853 	struct bpf_program *prog;
5854 	struct bpf_insn *insn;
5855 	const char *sec_name;
5856 	int i, err = 0, insn_idx, sec_idx, sec_num;
5857 
5858 	if (obj->btf_ext->core_relo_info.len == 0)
5859 		return 0;
5860 
5861 	if (targ_btf_path) {
5862 		obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
5863 		err = libbpf_get_error(obj->btf_vmlinux_override);
5864 		if (err) {
5865 			pr_warn("failed to parse target BTF: %d\n", err);
5866 			return err;
5867 		}
5868 	}
5869 
5870 	cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
5871 	if (IS_ERR(cand_cache)) {
5872 		err = PTR_ERR(cand_cache);
5873 		goto out;
5874 	}
5875 
5876 	seg = &obj->btf_ext->core_relo_info;
5877 	sec_num = 0;
5878 	for_each_btf_ext_sec(seg, sec) {
5879 		sec_idx = seg->sec_idxs[sec_num];
5880 		sec_num++;
5881 
5882 		sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
5883 		if (str_is_empty(sec_name)) {
5884 			err = -EINVAL;
5885 			goto out;
5886 		}
5887 
5888 		pr_debug("sec '%s': found %d CO-RE relocations\n", sec_name, sec->num_info);
5889 
5890 		for_each_btf_ext_rec(seg, sec, i, rec) {
5891 			if (rec->insn_off % BPF_INSN_SZ)
5892 				return -EINVAL;
5893 			insn_idx = rec->insn_off / BPF_INSN_SZ;
5894 			prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
5895 			if (!prog) {
5896 				/* When __weak subprog is "overridden" by another instance
5897 				 * of the subprog from a different object file, linker still
5898 				 * appends all the .BTF.ext info that used to belong to that
5899 				 * eliminated subprogram.
5900 				 * This is similar to what x86-64 linker does for relocations.
5901 				 * So just ignore such relocations just like we ignore
5902 				 * subprog instructions when discovering subprograms.
5903 				 */
5904 				pr_debug("sec '%s': skipping CO-RE relocation #%d for insn #%d belonging to eliminated weak subprogram\n",
5905 					 sec_name, i, insn_idx);
5906 				continue;
5907 			}
5908 			/* no need to apply CO-RE relocation if the program is
5909 			 * not going to be loaded
5910 			 */
5911 			if (!prog->autoload)
5912 				continue;
5913 
5914 			/* adjust insn_idx from section frame of reference to the local
5915 			 * program's frame of reference; (sub-)program code is not yet
5916 			 * relocated, so it's enough to just subtract in-section offset
5917 			 */
5918 			insn_idx = insn_idx - prog->sec_insn_off;
5919 			if (insn_idx >= prog->insns_cnt)
5920 				return -EINVAL;
5921 			insn = &prog->insns[insn_idx];
5922 
5923 			err = record_relo_core(prog, rec, insn_idx);
5924 			if (err) {
5925 				pr_warn("prog '%s': relo #%d: failed to record relocation: %d\n",
5926 					prog->name, i, err);
5927 				goto out;
5928 			}
5929 
5930 			if (prog->obj->gen_loader)
5931 				continue;
5932 
5933 			err = bpf_core_resolve_relo(prog, rec, i, obj->btf, cand_cache, &targ_res);
5934 			if (err) {
5935 				pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
5936 					prog->name, i, err);
5937 				goto out;
5938 			}
5939 
5940 			err = bpf_core_patch_insn(prog->name, insn, insn_idx, rec, i, &targ_res);
5941 			if (err) {
5942 				pr_warn("prog '%s': relo #%d: failed to patch insn #%u: %d\n",
5943 					prog->name, i, insn_idx, err);
5944 				goto out;
5945 			}
5946 		}
5947 	}
5948 
5949 out:
5950 	/* obj->btf_vmlinux and module BTFs are freed after object load */
5951 	btf__free(obj->btf_vmlinux_override);
5952 	obj->btf_vmlinux_override = NULL;
5953 
5954 	if (!IS_ERR_OR_NULL(cand_cache)) {
5955 		hashmap__for_each_entry(cand_cache, entry, i) {
5956 			bpf_core_free_cands(entry->value);
5957 		}
5958 		hashmap__free(cand_cache);
5959 	}
5960 	return err;
5961 }
5962 
5963 /* base map load ldimm64 special constant, used also for log fixup logic */
5964 #define MAP_LDIMM64_POISON_BASE 2001000000
5965 #define MAP_LDIMM64_POISON_PFX "200100"
5966 
5967 static void poison_map_ldimm64(struct bpf_program *prog, int relo_idx,
5968 			       int insn_idx, struct bpf_insn *insn,
5969 			       int map_idx, const struct bpf_map *map)
5970 {
5971 	int i;
5972 
5973 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that loads map #%d '%s'\n",
5974 		 prog->name, relo_idx, insn_idx, map_idx, map->name);
5975 
5976 	/* we turn single ldimm64 into two identical invalid calls */
5977 	for (i = 0; i < 2; i++) {
5978 		insn->code = BPF_JMP | BPF_CALL;
5979 		insn->dst_reg = 0;
5980 		insn->src_reg = 0;
5981 		insn->off = 0;
5982 		/* if this instruction is reachable (not a dead code),
5983 		 * verifier will complain with something like:
5984 		 * invalid func unknown#2001000123
5985 		 * where lower 123 is map index into obj->maps[] array
5986 		 */
5987 		insn->imm = MAP_LDIMM64_POISON_BASE + map_idx;
5988 
5989 		insn++;
5990 	}
5991 }
5992 
5993 /* Relocate data references within program code:
5994  *  - map references;
5995  *  - global variable references;
5996  *  - extern references.
5997  */
5998 static int
5999 bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
6000 {
6001 	int i;
6002 
6003 	for (i = 0; i < prog->nr_reloc; i++) {
6004 		struct reloc_desc *relo = &prog->reloc_desc[i];
6005 		struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6006 		const struct bpf_map *map;
6007 		struct extern_desc *ext;
6008 
6009 		switch (relo->type) {
6010 		case RELO_LD64:
6011 			map = &obj->maps[relo->map_idx];
6012 			if (obj->gen_loader) {
6013 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
6014 				insn[0].imm = relo->map_idx;
6015 			} else if (map->autocreate) {
6016 				insn[0].src_reg = BPF_PSEUDO_MAP_FD;
6017 				insn[0].imm = map->fd;
6018 			} else {
6019 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6020 						   relo->map_idx, map);
6021 			}
6022 			break;
6023 		case RELO_DATA:
6024 			map = &obj->maps[relo->map_idx];
6025 			insn[1].imm = insn[0].imm + relo->sym_off;
6026 			if (obj->gen_loader) {
6027 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6028 				insn[0].imm = relo->map_idx;
6029 			} else if (map->autocreate) {
6030 				insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6031 				insn[0].imm = map->fd;
6032 			} else {
6033 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6034 						   relo->map_idx, map);
6035 			}
6036 			break;
6037 		case RELO_EXTERN_VAR:
6038 			ext = &obj->externs[relo->sym_off];
6039 			if (ext->type == EXT_KCFG) {
6040 				if (obj->gen_loader) {
6041 					insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6042 					insn[0].imm = obj->kconfig_map_idx;
6043 				} else {
6044 					insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6045 					insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
6046 				}
6047 				insn[1].imm = ext->kcfg.data_off;
6048 			} else /* EXT_KSYM */ {
6049 				if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
6050 					insn[0].src_reg = BPF_PSEUDO_BTF_ID;
6051 					insn[0].imm = ext->ksym.kernel_btf_id;
6052 					insn[1].imm = ext->ksym.kernel_btf_obj_fd;
6053 				} else { /* typeless ksyms or unresolved typed ksyms */
6054 					insn[0].imm = (__u32)ext->ksym.addr;
6055 					insn[1].imm = ext->ksym.addr >> 32;
6056 				}
6057 			}
6058 			break;
6059 		case RELO_EXTERN_FUNC:
6060 			ext = &obj->externs[relo->sym_off];
6061 			insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
6062 			if (ext->is_set) {
6063 				insn[0].imm = ext->ksym.kernel_btf_id;
6064 				insn[0].off = ext->ksym.btf_fd_idx;
6065 			} else { /* unresolved weak kfunc */
6066 				insn[0].imm = 0;
6067 				insn[0].off = 0;
6068 			}
6069 			break;
6070 		case RELO_SUBPROG_ADDR:
6071 			if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
6072 				pr_warn("prog '%s': relo #%d: bad insn\n",
6073 					prog->name, i);
6074 				return -EINVAL;
6075 			}
6076 			/* handled already */
6077 			break;
6078 		case RELO_CALL:
6079 			/* handled already */
6080 			break;
6081 		case RELO_CORE:
6082 			/* will be handled by bpf_program_record_relos() */
6083 			break;
6084 		default:
6085 			pr_warn("prog '%s': relo #%d: bad relo type %d\n",
6086 				prog->name, i, relo->type);
6087 			return -EINVAL;
6088 		}
6089 	}
6090 
6091 	return 0;
6092 }
6093 
6094 static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
6095 				    const struct bpf_program *prog,
6096 				    const struct btf_ext_info *ext_info,
6097 				    void **prog_info, __u32 *prog_rec_cnt,
6098 				    __u32 *prog_rec_sz)
6099 {
6100 	void *copy_start = NULL, *copy_end = NULL;
6101 	void *rec, *rec_end, *new_prog_info;
6102 	const struct btf_ext_info_sec *sec;
6103 	size_t old_sz, new_sz;
6104 	int i, sec_num, sec_idx, off_adj;
6105 
6106 	sec_num = 0;
6107 	for_each_btf_ext_sec(ext_info, sec) {
6108 		sec_idx = ext_info->sec_idxs[sec_num];
6109 		sec_num++;
6110 		if (prog->sec_idx != sec_idx)
6111 			continue;
6112 
6113 		for_each_btf_ext_rec(ext_info, sec, i, rec) {
6114 			__u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
6115 
6116 			if (insn_off < prog->sec_insn_off)
6117 				continue;
6118 			if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
6119 				break;
6120 
6121 			if (!copy_start)
6122 				copy_start = rec;
6123 			copy_end = rec + ext_info->rec_size;
6124 		}
6125 
6126 		if (!copy_start)
6127 			return -ENOENT;
6128 
6129 		/* append func/line info of a given (sub-)program to the main
6130 		 * program func/line info
6131 		 */
6132 		old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
6133 		new_sz = old_sz + (copy_end - copy_start);
6134 		new_prog_info = realloc(*prog_info, new_sz);
6135 		if (!new_prog_info)
6136 			return -ENOMEM;
6137 		*prog_info = new_prog_info;
6138 		*prog_rec_cnt = new_sz / ext_info->rec_size;
6139 		memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
6140 
6141 		/* Kernel instruction offsets are in units of 8-byte
6142 		 * instructions, while .BTF.ext instruction offsets generated
6143 		 * by Clang are in units of bytes. So convert Clang offsets
6144 		 * into kernel offsets and adjust offset according to program
6145 		 * relocated position.
6146 		 */
6147 		off_adj = prog->sub_insn_off - prog->sec_insn_off;
6148 		rec = new_prog_info + old_sz;
6149 		rec_end = new_prog_info + new_sz;
6150 		for (; rec < rec_end; rec += ext_info->rec_size) {
6151 			__u32 *insn_off = rec;
6152 
6153 			*insn_off = *insn_off / BPF_INSN_SZ + off_adj;
6154 		}
6155 		*prog_rec_sz = ext_info->rec_size;
6156 		return 0;
6157 	}
6158 
6159 	return -ENOENT;
6160 }
6161 
6162 static int
6163 reloc_prog_func_and_line_info(const struct bpf_object *obj,
6164 			      struct bpf_program *main_prog,
6165 			      const struct bpf_program *prog)
6166 {
6167 	int err;
6168 
6169 	/* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
6170 	 * supprot func/line info
6171 	 */
6172 	if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
6173 		return 0;
6174 
6175 	/* only attempt func info relocation if main program's func_info
6176 	 * relocation was successful
6177 	 */
6178 	if (main_prog != prog && !main_prog->func_info)
6179 		goto line_info;
6180 
6181 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
6182 				       &main_prog->func_info,
6183 				       &main_prog->func_info_cnt,
6184 				       &main_prog->func_info_rec_size);
6185 	if (err) {
6186 		if (err != -ENOENT) {
6187 			pr_warn("prog '%s': error relocating .BTF.ext function info: %d\n",
6188 				prog->name, err);
6189 			return err;
6190 		}
6191 		if (main_prog->func_info) {
6192 			/*
6193 			 * Some info has already been found but has problem
6194 			 * in the last btf_ext reloc. Must have to error out.
6195 			 */
6196 			pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
6197 			return err;
6198 		}
6199 		/* Have problem loading the very first info. Ignore the rest. */
6200 		pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
6201 			prog->name);
6202 	}
6203 
6204 line_info:
6205 	/* don't relocate line info if main program's relocation failed */
6206 	if (main_prog != prog && !main_prog->line_info)
6207 		return 0;
6208 
6209 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
6210 				       &main_prog->line_info,
6211 				       &main_prog->line_info_cnt,
6212 				       &main_prog->line_info_rec_size);
6213 	if (err) {
6214 		if (err != -ENOENT) {
6215 			pr_warn("prog '%s': error relocating .BTF.ext line info: %d\n",
6216 				prog->name, err);
6217 			return err;
6218 		}
6219 		if (main_prog->line_info) {
6220 			/*
6221 			 * Some info has already been found but has problem
6222 			 * in the last btf_ext reloc. Must have to error out.
6223 			 */
6224 			pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
6225 			return err;
6226 		}
6227 		/* Have problem loading the very first info. Ignore the rest. */
6228 		pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
6229 			prog->name);
6230 	}
6231 	return 0;
6232 }
6233 
6234 static int cmp_relo_by_insn_idx(const void *key, const void *elem)
6235 {
6236 	size_t insn_idx = *(const size_t *)key;
6237 	const struct reloc_desc *relo = elem;
6238 
6239 	if (insn_idx == relo->insn_idx)
6240 		return 0;
6241 	return insn_idx < relo->insn_idx ? -1 : 1;
6242 }
6243 
6244 static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
6245 {
6246 	if (!prog->nr_reloc)
6247 		return NULL;
6248 	return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
6249 		       sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
6250 }
6251 
6252 static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
6253 {
6254 	int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
6255 	struct reloc_desc *relos;
6256 	int i;
6257 
6258 	if (main_prog == subprog)
6259 		return 0;
6260 	relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
6261 	if (!relos)
6262 		return -ENOMEM;
6263 	if (subprog->nr_reloc)
6264 		memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
6265 		       sizeof(*relos) * subprog->nr_reloc);
6266 
6267 	for (i = main_prog->nr_reloc; i < new_cnt; i++)
6268 		relos[i].insn_idx += subprog->sub_insn_off;
6269 	/* After insn_idx adjustment the 'relos' array is still sorted
6270 	 * by insn_idx and doesn't break bsearch.
6271 	 */
6272 	main_prog->reloc_desc = relos;
6273 	main_prog->nr_reloc = new_cnt;
6274 	return 0;
6275 }
6276 
6277 static int
6278 bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
6279 		       struct bpf_program *prog)
6280 {
6281 	size_t sub_insn_idx, insn_idx, new_cnt;
6282 	struct bpf_program *subprog;
6283 	struct bpf_insn *insns, *insn;
6284 	struct reloc_desc *relo;
6285 	int err;
6286 
6287 	err = reloc_prog_func_and_line_info(obj, main_prog, prog);
6288 	if (err)
6289 		return err;
6290 
6291 	for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
6292 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6293 		if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
6294 			continue;
6295 
6296 		relo = find_prog_insn_relo(prog, insn_idx);
6297 		if (relo && relo->type == RELO_EXTERN_FUNC)
6298 			/* kfunc relocations will be handled later
6299 			 * in bpf_object__relocate_data()
6300 			 */
6301 			continue;
6302 		if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
6303 			pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
6304 				prog->name, insn_idx, relo->type);
6305 			return -LIBBPF_ERRNO__RELOC;
6306 		}
6307 		if (relo) {
6308 			/* sub-program instruction index is a combination of
6309 			 * an offset of a symbol pointed to by relocation and
6310 			 * call instruction's imm field; for global functions,
6311 			 * call always has imm = -1, but for static functions
6312 			 * relocation is against STT_SECTION and insn->imm
6313 			 * points to a start of a static function
6314 			 *
6315 			 * for subprog addr relocation, the relo->sym_off + insn->imm is
6316 			 * the byte offset in the corresponding section.
6317 			 */
6318 			if (relo->type == RELO_CALL)
6319 				sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
6320 			else
6321 				sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
6322 		} else if (insn_is_pseudo_func(insn)) {
6323 			/*
6324 			 * RELO_SUBPROG_ADDR relo is always emitted even if both
6325 			 * functions are in the same section, so it shouldn't reach here.
6326 			 */
6327 			pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
6328 				prog->name, insn_idx);
6329 			return -LIBBPF_ERRNO__RELOC;
6330 		} else {
6331 			/* if subprogram call is to a static function within
6332 			 * the same ELF section, there won't be any relocation
6333 			 * emitted, but it also means there is no additional
6334 			 * offset necessary, insns->imm is relative to
6335 			 * instruction's original position within the section
6336 			 */
6337 			sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
6338 		}
6339 
6340 		/* we enforce that sub-programs should be in .text section */
6341 		subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
6342 		if (!subprog) {
6343 			pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
6344 				prog->name);
6345 			return -LIBBPF_ERRNO__RELOC;
6346 		}
6347 
6348 		/* if it's the first call instruction calling into this
6349 		 * subprogram (meaning this subprog hasn't been processed
6350 		 * yet) within the context of current main program:
6351 		 *   - append it at the end of main program's instructions blog;
6352 		 *   - process is recursively, while current program is put on hold;
6353 		 *   - if that subprogram calls some other not yet processes
6354 		 *   subprogram, same thing will happen recursively until
6355 		 *   there are no more unprocesses subprograms left to append
6356 		 *   and relocate.
6357 		 */
6358 		if (subprog->sub_insn_off == 0) {
6359 			subprog->sub_insn_off = main_prog->insns_cnt;
6360 
6361 			new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
6362 			insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
6363 			if (!insns) {
6364 				pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
6365 				return -ENOMEM;
6366 			}
6367 			main_prog->insns = insns;
6368 			main_prog->insns_cnt = new_cnt;
6369 
6370 			memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
6371 			       subprog->insns_cnt * sizeof(*insns));
6372 
6373 			pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
6374 				 main_prog->name, subprog->insns_cnt, subprog->name);
6375 
6376 			/* The subprog insns are now appended. Append its relos too. */
6377 			err = append_subprog_relos(main_prog, subprog);
6378 			if (err)
6379 				return err;
6380 			err = bpf_object__reloc_code(obj, main_prog, subprog);
6381 			if (err)
6382 				return err;
6383 		}
6384 
6385 		/* main_prog->insns memory could have been re-allocated, so
6386 		 * calculate pointer again
6387 		 */
6388 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6389 		/* calculate correct instruction position within current main
6390 		 * prog; each main prog can have a different set of
6391 		 * subprograms appended (potentially in different order as
6392 		 * well), so position of any subprog can be different for
6393 		 * different main programs */
6394 		insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
6395 
6396 		pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
6397 			 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
6398 	}
6399 
6400 	return 0;
6401 }
6402 
6403 /*
6404  * Relocate sub-program calls.
6405  *
6406  * Algorithm operates as follows. Each entry-point BPF program (referred to as
6407  * main prog) is processed separately. For each subprog (non-entry functions,
6408  * that can be called from either entry progs or other subprogs) gets their
6409  * sub_insn_off reset to zero. This serves as indicator that this subprogram
6410  * hasn't been yet appended and relocated within current main prog. Once its
6411  * relocated, sub_insn_off will point at the position within current main prog
6412  * where given subprog was appended. This will further be used to relocate all
6413  * the call instructions jumping into this subprog.
6414  *
6415  * We start with main program and process all call instructions. If the call
6416  * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
6417  * is zero), subprog instructions are appended at the end of main program's
6418  * instruction array. Then main program is "put on hold" while we recursively
6419  * process newly appended subprogram. If that subprogram calls into another
6420  * subprogram that hasn't been appended, new subprogram is appended again to
6421  * the *main* prog's instructions (subprog's instructions are always left
6422  * untouched, as they need to be in unmodified state for subsequent main progs
6423  * and subprog instructions are always sent only as part of a main prog) and
6424  * the process continues recursively. Once all the subprogs called from a main
6425  * prog or any of its subprogs are appended (and relocated), all their
6426  * positions within finalized instructions array are known, so it's easy to
6427  * rewrite call instructions with correct relative offsets, corresponding to
6428  * desired target subprog.
6429  *
6430  * Its important to realize that some subprogs might not be called from some
6431  * main prog and any of its called/used subprogs. Those will keep their
6432  * subprog->sub_insn_off as zero at all times and won't be appended to current
6433  * main prog and won't be relocated within the context of current main prog.
6434  * They might still be used from other main progs later.
6435  *
6436  * Visually this process can be shown as below. Suppose we have two main
6437  * programs mainA and mainB and BPF object contains three subprogs: subA,
6438  * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
6439  * subC both call subB:
6440  *
6441  *        +--------+ +-------+
6442  *        |        v v       |
6443  *     +--+---+ +--+-+-+ +---+--+
6444  *     | subA | | subB | | subC |
6445  *     +--+---+ +------+ +---+--+
6446  *        ^                  ^
6447  *        |                  |
6448  *    +---+-------+   +------+----+
6449  *    |   mainA   |   |   mainB   |
6450  *    +-----------+   +-----------+
6451  *
6452  * We'll start relocating mainA, will find subA, append it and start
6453  * processing sub A recursively:
6454  *
6455  *    +-----------+------+
6456  *    |   mainA   | subA |
6457  *    +-----------+------+
6458  *
6459  * At this point we notice that subB is used from subA, so we append it and
6460  * relocate (there are no further subcalls from subB):
6461  *
6462  *    +-----------+------+------+
6463  *    |   mainA   | subA | subB |
6464  *    +-----------+------+------+
6465  *
6466  * At this point, we relocate subA calls, then go one level up and finish with
6467  * relocatin mainA calls. mainA is done.
6468  *
6469  * For mainB process is similar but results in different order. We start with
6470  * mainB and skip subA and subB, as mainB never calls them (at least
6471  * directly), but we see subC is needed, so we append and start processing it:
6472  *
6473  *    +-----------+------+
6474  *    |   mainB   | subC |
6475  *    +-----------+------+
6476  * Now we see subC needs subB, so we go back to it, append and relocate it:
6477  *
6478  *    +-----------+------+------+
6479  *    |   mainB   | subC | subB |
6480  *    +-----------+------+------+
6481  *
6482  * At this point we unwind recursion, relocate calls in subC, then in mainB.
6483  */
6484 static int
6485 bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
6486 {
6487 	struct bpf_program *subprog;
6488 	int i, err;
6489 
6490 	/* mark all subprogs as not relocated (yet) within the context of
6491 	 * current main program
6492 	 */
6493 	for (i = 0; i < obj->nr_programs; i++) {
6494 		subprog = &obj->programs[i];
6495 		if (!prog_is_subprog(obj, subprog))
6496 			continue;
6497 
6498 		subprog->sub_insn_off = 0;
6499 	}
6500 
6501 	err = bpf_object__reloc_code(obj, prog, prog);
6502 	if (err)
6503 		return err;
6504 
6505 	return 0;
6506 }
6507 
6508 static void
6509 bpf_object__free_relocs(struct bpf_object *obj)
6510 {
6511 	struct bpf_program *prog;
6512 	int i;
6513 
6514 	/* free up relocation descriptors */
6515 	for (i = 0; i < obj->nr_programs; i++) {
6516 		prog = &obj->programs[i];
6517 		zfree(&prog->reloc_desc);
6518 		prog->nr_reloc = 0;
6519 	}
6520 }
6521 
6522 static int cmp_relocs(const void *_a, const void *_b)
6523 {
6524 	const struct reloc_desc *a = _a;
6525 	const struct reloc_desc *b = _b;
6526 
6527 	if (a->insn_idx != b->insn_idx)
6528 		return a->insn_idx < b->insn_idx ? -1 : 1;
6529 
6530 	/* no two relocations should have the same insn_idx, but ... */
6531 	if (a->type != b->type)
6532 		return a->type < b->type ? -1 : 1;
6533 
6534 	return 0;
6535 }
6536 
6537 static void bpf_object__sort_relos(struct bpf_object *obj)
6538 {
6539 	int i;
6540 
6541 	for (i = 0; i < obj->nr_programs; i++) {
6542 		struct bpf_program *p = &obj->programs[i];
6543 
6544 		if (!p->nr_reloc)
6545 			continue;
6546 
6547 		qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
6548 	}
6549 }
6550 
6551 static int
6552 bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
6553 {
6554 	struct bpf_program *prog;
6555 	size_t i, j;
6556 	int err;
6557 
6558 	if (obj->btf_ext) {
6559 		err = bpf_object__relocate_core(obj, targ_btf_path);
6560 		if (err) {
6561 			pr_warn("failed to perform CO-RE relocations: %d\n",
6562 				err);
6563 			return err;
6564 		}
6565 		bpf_object__sort_relos(obj);
6566 	}
6567 
6568 	/* Before relocating calls pre-process relocations and mark
6569 	 * few ld_imm64 instructions that points to subprogs.
6570 	 * Otherwise bpf_object__reloc_code() later would have to consider
6571 	 * all ld_imm64 insns as relocation candidates. That would
6572 	 * reduce relocation speed, since amount of find_prog_insn_relo()
6573 	 * would increase and most of them will fail to find a relo.
6574 	 */
6575 	for (i = 0; i < obj->nr_programs; i++) {
6576 		prog = &obj->programs[i];
6577 		for (j = 0; j < prog->nr_reloc; j++) {
6578 			struct reloc_desc *relo = &prog->reloc_desc[j];
6579 			struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6580 
6581 			/* mark the insn, so it's recognized by insn_is_pseudo_func() */
6582 			if (relo->type == RELO_SUBPROG_ADDR)
6583 				insn[0].src_reg = BPF_PSEUDO_FUNC;
6584 		}
6585 	}
6586 
6587 	/* relocate subprogram calls and append used subprograms to main
6588 	 * programs; each copy of subprogram code needs to be relocated
6589 	 * differently for each main program, because its code location might
6590 	 * have changed.
6591 	 * Append subprog relos to main programs to allow data relos to be
6592 	 * processed after text is completely relocated.
6593 	 */
6594 	for (i = 0; i < obj->nr_programs; i++) {
6595 		prog = &obj->programs[i];
6596 		/* sub-program's sub-calls are relocated within the context of
6597 		 * its main program only
6598 		 */
6599 		if (prog_is_subprog(obj, prog))
6600 			continue;
6601 		if (!prog->autoload)
6602 			continue;
6603 
6604 		err = bpf_object__relocate_calls(obj, prog);
6605 		if (err) {
6606 			pr_warn("prog '%s': failed to relocate calls: %d\n",
6607 				prog->name, err);
6608 			return err;
6609 		}
6610 	}
6611 	/* Process data relos for main programs */
6612 	for (i = 0; i < obj->nr_programs; i++) {
6613 		prog = &obj->programs[i];
6614 		if (prog_is_subprog(obj, prog))
6615 			continue;
6616 		if (!prog->autoload)
6617 			continue;
6618 		err = bpf_object__relocate_data(obj, prog);
6619 		if (err) {
6620 			pr_warn("prog '%s': failed to relocate data references: %d\n",
6621 				prog->name, err);
6622 			return err;
6623 		}
6624 	}
6625 
6626 	return 0;
6627 }
6628 
6629 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
6630 					    Elf64_Shdr *shdr, Elf_Data *data);
6631 
6632 static int bpf_object__collect_map_relos(struct bpf_object *obj,
6633 					 Elf64_Shdr *shdr, Elf_Data *data)
6634 {
6635 	const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
6636 	int i, j, nrels, new_sz;
6637 	const struct btf_var_secinfo *vi = NULL;
6638 	const struct btf_type *sec, *var, *def;
6639 	struct bpf_map *map = NULL, *targ_map = NULL;
6640 	struct bpf_program *targ_prog = NULL;
6641 	bool is_prog_array, is_map_in_map;
6642 	const struct btf_member *member;
6643 	const char *name, *mname, *type;
6644 	unsigned int moff;
6645 	Elf64_Sym *sym;
6646 	Elf64_Rel *rel;
6647 	void *tmp;
6648 
6649 	if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
6650 		return -EINVAL;
6651 	sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
6652 	if (!sec)
6653 		return -EINVAL;
6654 
6655 	nrels = shdr->sh_size / shdr->sh_entsize;
6656 	for (i = 0; i < nrels; i++) {
6657 		rel = elf_rel_by_idx(data, i);
6658 		if (!rel) {
6659 			pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
6660 			return -LIBBPF_ERRNO__FORMAT;
6661 		}
6662 
6663 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
6664 		if (!sym) {
6665 			pr_warn(".maps relo #%d: symbol %zx not found\n",
6666 				i, (size_t)ELF64_R_SYM(rel->r_info));
6667 			return -LIBBPF_ERRNO__FORMAT;
6668 		}
6669 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
6670 
6671 		pr_debug(".maps relo #%d: for %zd value %zd rel->r_offset %zu name %d ('%s')\n",
6672 			 i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
6673 			 (size_t)rel->r_offset, sym->st_name, name);
6674 
6675 		for (j = 0; j < obj->nr_maps; j++) {
6676 			map = &obj->maps[j];
6677 			if (map->sec_idx != obj->efile.btf_maps_shndx)
6678 				continue;
6679 
6680 			vi = btf_var_secinfos(sec) + map->btf_var_idx;
6681 			if (vi->offset <= rel->r_offset &&
6682 			    rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size)
6683 				break;
6684 		}
6685 		if (j == obj->nr_maps) {
6686 			pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
6687 				i, name, (size_t)rel->r_offset);
6688 			return -EINVAL;
6689 		}
6690 
6691 		is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
6692 		is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
6693 		type = is_map_in_map ? "map" : "prog";
6694 		if (is_map_in_map) {
6695 			if (sym->st_shndx != obj->efile.btf_maps_shndx) {
6696 				pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
6697 					i, name);
6698 				return -LIBBPF_ERRNO__RELOC;
6699 			}
6700 			if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
6701 			    map->def.key_size != sizeof(int)) {
6702 				pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
6703 					i, map->name, sizeof(int));
6704 				return -EINVAL;
6705 			}
6706 			targ_map = bpf_object__find_map_by_name(obj, name);
6707 			if (!targ_map) {
6708 				pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
6709 					i, name);
6710 				return -ESRCH;
6711 			}
6712 		} else if (is_prog_array) {
6713 			targ_prog = bpf_object__find_program_by_name(obj, name);
6714 			if (!targ_prog) {
6715 				pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
6716 					i, name);
6717 				return -ESRCH;
6718 			}
6719 			if (targ_prog->sec_idx != sym->st_shndx ||
6720 			    targ_prog->sec_insn_off * 8 != sym->st_value ||
6721 			    prog_is_subprog(obj, targ_prog)) {
6722 				pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
6723 					i, name);
6724 				return -LIBBPF_ERRNO__RELOC;
6725 			}
6726 		} else {
6727 			return -EINVAL;
6728 		}
6729 
6730 		var = btf__type_by_id(obj->btf, vi->type);
6731 		def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
6732 		if (btf_vlen(def) == 0)
6733 			return -EINVAL;
6734 		member = btf_members(def) + btf_vlen(def) - 1;
6735 		mname = btf__name_by_offset(obj->btf, member->name_off);
6736 		if (strcmp(mname, "values"))
6737 			return -EINVAL;
6738 
6739 		moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
6740 		if (rel->r_offset - vi->offset < moff)
6741 			return -EINVAL;
6742 
6743 		moff = rel->r_offset - vi->offset - moff;
6744 		/* here we use BPF pointer size, which is always 64 bit, as we
6745 		 * are parsing ELF that was built for BPF target
6746 		 */
6747 		if (moff % bpf_ptr_sz)
6748 			return -EINVAL;
6749 		moff /= bpf_ptr_sz;
6750 		if (moff >= map->init_slots_sz) {
6751 			new_sz = moff + 1;
6752 			tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
6753 			if (!tmp)
6754 				return -ENOMEM;
6755 			map->init_slots = tmp;
6756 			memset(map->init_slots + map->init_slots_sz, 0,
6757 			       (new_sz - map->init_slots_sz) * host_ptr_sz);
6758 			map->init_slots_sz = new_sz;
6759 		}
6760 		map->init_slots[moff] = is_map_in_map ? (void *)targ_map : (void *)targ_prog;
6761 
6762 		pr_debug(".maps relo #%d: map '%s' slot [%d] points to %s '%s'\n",
6763 			 i, map->name, moff, type, name);
6764 	}
6765 
6766 	return 0;
6767 }
6768 
6769 static int bpf_object__collect_relos(struct bpf_object *obj)
6770 {
6771 	int i, err;
6772 
6773 	for (i = 0; i < obj->efile.sec_cnt; i++) {
6774 		struct elf_sec_desc *sec_desc = &obj->efile.secs[i];
6775 		Elf64_Shdr *shdr;
6776 		Elf_Data *data;
6777 		int idx;
6778 
6779 		if (sec_desc->sec_type != SEC_RELO)
6780 			continue;
6781 
6782 		shdr = sec_desc->shdr;
6783 		data = sec_desc->data;
6784 		idx = shdr->sh_info;
6785 
6786 		if (shdr->sh_type != SHT_REL) {
6787 			pr_warn("internal error at %d\n", __LINE__);
6788 			return -LIBBPF_ERRNO__INTERNAL;
6789 		}
6790 
6791 		if (idx == obj->efile.st_ops_shndx)
6792 			err = bpf_object__collect_st_ops_relos(obj, shdr, data);
6793 		else if (idx == obj->efile.btf_maps_shndx)
6794 			err = bpf_object__collect_map_relos(obj, shdr, data);
6795 		else
6796 			err = bpf_object__collect_prog_relos(obj, shdr, data);
6797 		if (err)
6798 			return err;
6799 	}
6800 
6801 	bpf_object__sort_relos(obj);
6802 	return 0;
6803 }
6804 
6805 static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
6806 {
6807 	if (BPF_CLASS(insn->code) == BPF_JMP &&
6808 	    BPF_OP(insn->code) == BPF_CALL &&
6809 	    BPF_SRC(insn->code) == BPF_K &&
6810 	    insn->src_reg == 0 &&
6811 	    insn->dst_reg == 0) {
6812 		    *func_id = insn->imm;
6813 		    return true;
6814 	}
6815 	return false;
6816 }
6817 
6818 static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
6819 {
6820 	struct bpf_insn *insn = prog->insns;
6821 	enum bpf_func_id func_id;
6822 	int i;
6823 
6824 	if (obj->gen_loader)
6825 		return 0;
6826 
6827 	for (i = 0; i < prog->insns_cnt; i++, insn++) {
6828 		if (!insn_is_helper_call(insn, &func_id))
6829 			continue;
6830 
6831 		/* on kernels that don't yet support
6832 		 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
6833 		 * to bpf_probe_read() which works well for old kernels
6834 		 */
6835 		switch (func_id) {
6836 		case BPF_FUNC_probe_read_kernel:
6837 		case BPF_FUNC_probe_read_user:
6838 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6839 				insn->imm = BPF_FUNC_probe_read;
6840 			break;
6841 		case BPF_FUNC_probe_read_kernel_str:
6842 		case BPF_FUNC_probe_read_user_str:
6843 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6844 				insn->imm = BPF_FUNC_probe_read_str;
6845 			break;
6846 		default:
6847 			break;
6848 		}
6849 	}
6850 	return 0;
6851 }
6852 
6853 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
6854 				     int *btf_obj_fd, int *btf_type_id);
6855 
6856 /* this is called as prog->sec_def->prog_prepare_load_fn for libbpf-supported sec_defs */
6857 static int libbpf_prepare_prog_load(struct bpf_program *prog,
6858 				    struct bpf_prog_load_opts *opts, long cookie)
6859 {
6860 	enum sec_def_flags def = cookie;
6861 
6862 	/* old kernels might not support specifying expected_attach_type */
6863 	if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
6864 		opts->expected_attach_type = 0;
6865 
6866 	if (def & SEC_SLEEPABLE)
6867 		opts->prog_flags |= BPF_F_SLEEPABLE;
6868 
6869 	if (prog->type == BPF_PROG_TYPE_XDP && (def & SEC_XDP_FRAGS))
6870 		opts->prog_flags |= BPF_F_XDP_HAS_FRAGS;
6871 
6872 	if (def & SEC_DEPRECATED) {
6873 		pr_warn("SEC(\"%s\") is deprecated, please see https://github.com/libbpf/libbpf/wiki/Libbpf-1.0-migration-guide#bpf-program-sec-annotation-deprecations for details\n",
6874 			prog->sec_name);
6875 	}
6876 
6877 	if ((def & SEC_ATTACH_BTF) && !prog->attach_btf_id) {
6878 		int btf_obj_fd = 0, btf_type_id = 0, err;
6879 		const char *attach_name;
6880 
6881 		attach_name = strchr(prog->sec_name, '/');
6882 		if (!attach_name) {
6883 			/* if BPF program is annotated with just SEC("fentry")
6884 			 * (or similar) without declaratively specifying
6885 			 * target, then it is expected that target will be
6886 			 * specified with bpf_program__set_attach_target() at
6887 			 * runtime before BPF object load step. If not, then
6888 			 * there is nothing to load into the kernel as BPF
6889 			 * verifier won't be able to validate BPF program
6890 			 * correctness anyways.
6891 			 */
6892 			pr_warn("prog '%s': no BTF-based attach target is specified, use bpf_program__set_attach_target()\n",
6893 				prog->name);
6894 			return -EINVAL;
6895 		}
6896 		attach_name++; /* skip over / */
6897 
6898 		err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
6899 		if (err)
6900 			return err;
6901 
6902 		/* cache resolved BTF FD and BTF type ID in the prog */
6903 		prog->attach_btf_obj_fd = btf_obj_fd;
6904 		prog->attach_btf_id = btf_type_id;
6905 
6906 		/* but by now libbpf common logic is not utilizing
6907 		 * prog->atach_btf_obj_fd/prog->attach_btf_id anymore because
6908 		 * this callback is called after opts were populated by
6909 		 * libbpf, so this callback has to update opts explicitly here
6910 		 */
6911 		opts->attach_btf_obj_fd = btf_obj_fd;
6912 		opts->attach_btf_id = btf_type_id;
6913 	}
6914 	return 0;
6915 }
6916 
6917 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz);
6918 
6919 static int bpf_object_load_prog_instance(struct bpf_object *obj, struct bpf_program *prog,
6920 					 struct bpf_insn *insns, int insns_cnt,
6921 					 const char *license, __u32 kern_version,
6922 					 int *prog_fd)
6923 {
6924 	LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
6925 	const char *prog_name = NULL;
6926 	char *cp, errmsg[STRERR_BUFSIZE];
6927 	size_t log_buf_size = 0;
6928 	char *log_buf = NULL, *tmp;
6929 	int btf_fd, ret, err;
6930 	bool own_log_buf = true;
6931 	__u32 log_level = prog->log_level;
6932 
6933 	if (prog->type == BPF_PROG_TYPE_UNSPEC) {
6934 		/*
6935 		 * The program type must be set.  Most likely we couldn't find a proper
6936 		 * section definition at load time, and thus we didn't infer the type.
6937 		 */
6938 		pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
6939 			prog->name, prog->sec_name);
6940 		return -EINVAL;
6941 	}
6942 
6943 	if (!insns || !insns_cnt)
6944 		return -EINVAL;
6945 
6946 	load_attr.expected_attach_type = prog->expected_attach_type;
6947 	if (kernel_supports(obj, FEAT_PROG_NAME))
6948 		prog_name = prog->name;
6949 	load_attr.attach_prog_fd = prog->attach_prog_fd;
6950 	load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
6951 	load_attr.attach_btf_id = prog->attach_btf_id;
6952 	load_attr.kern_version = kern_version;
6953 	load_attr.prog_ifindex = prog->prog_ifindex;
6954 
6955 	/* specify func_info/line_info only if kernel supports them */
6956 	btf_fd = bpf_object__btf_fd(obj);
6957 	if (btf_fd >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
6958 		load_attr.prog_btf_fd = btf_fd;
6959 		load_attr.func_info = prog->func_info;
6960 		load_attr.func_info_rec_size = prog->func_info_rec_size;
6961 		load_attr.func_info_cnt = prog->func_info_cnt;
6962 		load_attr.line_info = prog->line_info;
6963 		load_attr.line_info_rec_size = prog->line_info_rec_size;
6964 		load_attr.line_info_cnt = prog->line_info_cnt;
6965 	}
6966 	load_attr.log_level = log_level;
6967 	load_attr.prog_flags = prog->prog_flags;
6968 	load_attr.fd_array = obj->fd_array;
6969 
6970 	/* adjust load_attr if sec_def provides custom preload callback */
6971 	if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
6972 		err = prog->sec_def->prog_prepare_load_fn(prog, &load_attr, prog->sec_def->cookie);
6973 		if (err < 0) {
6974 			pr_warn("prog '%s': failed to prepare load attributes: %d\n",
6975 				prog->name, err);
6976 			return err;
6977 		}
6978 		insns = prog->insns;
6979 		insns_cnt = prog->insns_cnt;
6980 	}
6981 
6982 	if (obj->gen_loader) {
6983 		bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
6984 				   license, insns, insns_cnt, &load_attr,
6985 				   prog - obj->programs);
6986 		*prog_fd = -1;
6987 		return 0;
6988 	}
6989 
6990 retry_load:
6991 	/* if log_level is zero, we don't request logs initially even if
6992 	 * custom log_buf is specified; if the program load fails, then we'll
6993 	 * bump log_level to 1 and use either custom log_buf or we'll allocate
6994 	 * our own and retry the load to get details on what failed
6995 	 */
6996 	if (log_level) {
6997 		if (prog->log_buf) {
6998 			log_buf = prog->log_buf;
6999 			log_buf_size = prog->log_size;
7000 			own_log_buf = false;
7001 		} else if (obj->log_buf) {
7002 			log_buf = obj->log_buf;
7003 			log_buf_size = obj->log_size;
7004 			own_log_buf = false;
7005 		} else {
7006 			log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
7007 			tmp = realloc(log_buf, log_buf_size);
7008 			if (!tmp) {
7009 				ret = -ENOMEM;
7010 				goto out;
7011 			}
7012 			log_buf = tmp;
7013 			log_buf[0] = '\0';
7014 			own_log_buf = true;
7015 		}
7016 	}
7017 
7018 	load_attr.log_buf = log_buf;
7019 	load_attr.log_size = log_buf_size;
7020 	load_attr.log_level = log_level;
7021 
7022 	ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
7023 	if (ret >= 0) {
7024 		if (log_level && own_log_buf) {
7025 			pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
7026 				 prog->name, log_buf);
7027 		}
7028 
7029 		if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
7030 			struct bpf_map *map;
7031 			int i;
7032 
7033 			for (i = 0; i < obj->nr_maps; i++) {
7034 				map = &prog->obj->maps[i];
7035 				if (map->libbpf_type != LIBBPF_MAP_RODATA)
7036 					continue;
7037 
7038 				if (bpf_prog_bind_map(ret, bpf_map__fd(map), NULL)) {
7039 					cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
7040 					pr_warn("prog '%s': failed to bind map '%s': %s\n",
7041 						prog->name, map->real_name, cp);
7042 					/* Don't fail hard if can't bind rodata. */
7043 				}
7044 			}
7045 		}
7046 
7047 		*prog_fd = ret;
7048 		ret = 0;
7049 		goto out;
7050 	}
7051 
7052 	if (log_level == 0) {
7053 		log_level = 1;
7054 		goto retry_load;
7055 	}
7056 	/* On ENOSPC, increase log buffer size and retry, unless custom
7057 	 * log_buf is specified.
7058 	 * Be careful to not overflow u32, though. Kernel's log buf size limit
7059 	 * isn't part of UAPI so it can always be bumped to full 4GB. So don't
7060 	 * multiply by 2 unless we are sure we'll fit within 32 bits.
7061 	 * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
7062 	 */
7063 	if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
7064 		goto retry_load;
7065 
7066 	ret = -errno;
7067 
7068 	/* post-process verifier log to improve error descriptions */
7069 	fixup_verifier_log(prog, log_buf, log_buf_size);
7070 
7071 	cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
7072 	pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, cp);
7073 	pr_perm_msg(ret);
7074 
7075 	if (own_log_buf && log_buf && log_buf[0] != '\0') {
7076 		pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
7077 			prog->name, log_buf);
7078 	}
7079 
7080 out:
7081 	if (own_log_buf)
7082 		free(log_buf);
7083 	return ret;
7084 }
7085 
7086 static char *find_prev_line(char *buf, char *cur)
7087 {
7088 	char *p;
7089 
7090 	if (cur == buf) /* end of a log buf */
7091 		return NULL;
7092 
7093 	p = cur - 1;
7094 	while (p - 1 >= buf && *(p - 1) != '\n')
7095 		p--;
7096 
7097 	return p;
7098 }
7099 
7100 static void patch_log(char *buf, size_t buf_sz, size_t log_sz,
7101 		      char *orig, size_t orig_sz, const char *patch)
7102 {
7103 	/* size of the remaining log content to the right from the to-be-replaced part */
7104 	size_t rem_sz = (buf + log_sz) - (orig + orig_sz);
7105 	size_t patch_sz = strlen(patch);
7106 
7107 	if (patch_sz != orig_sz) {
7108 		/* If patch line(s) are longer than original piece of verifier log,
7109 		 * shift log contents by (patch_sz - orig_sz) bytes to the right
7110 		 * starting from after to-be-replaced part of the log.
7111 		 *
7112 		 * If patch line(s) are shorter than original piece of verifier log,
7113 		 * shift log contents by (orig_sz - patch_sz) bytes to the left
7114 		 * starting from after to-be-replaced part of the log
7115 		 *
7116 		 * We need to be careful about not overflowing available
7117 		 * buf_sz capacity. If that's the case, we'll truncate the end
7118 		 * of the original log, as necessary.
7119 		 */
7120 		if (patch_sz > orig_sz) {
7121 			if (orig + patch_sz >= buf + buf_sz) {
7122 				/* patch is big enough to cover remaining space completely */
7123 				patch_sz -= (orig + patch_sz) - (buf + buf_sz) + 1;
7124 				rem_sz = 0;
7125 			} else if (patch_sz - orig_sz > buf_sz - log_sz) {
7126 				/* patch causes part of remaining log to be truncated */
7127 				rem_sz -= (patch_sz - orig_sz) - (buf_sz - log_sz);
7128 			}
7129 		}
7130 		/* shift remaining log to the right by calculated amount */
7131 		memmove(orig + patch_sz, orig + orig_sz, rem_sz);
7132 	}
7133 
7134 	memcpy(orig, patch, patch_sz);
7135 }
7136 
7137 static void fixup_log_failed_core_relo(struct bpf_program *prog,
7138 				       char *buf, size_t buf_sz, size_t log_sz,
7139 				       char *line1, char *line2, char *line3)
7140 {
7141 	/* Expected log for failed and not properly guarded CO-RE relocation:
7142 	 * line1 -> 123: (85) call unknown#195896080
7143 	 * line2 -> invalid func unknown#195896080
7144 	 * line3 -> <anything else or end of buffer>
7145 	 *
7146 	 * "123" is the index of the instruction that was poisoned. We extract
7147 	 * instruction index to find corresponding CO-RE relocation and
7148 	 * replace this part of the log with more relevant information about
7149 	 * failed CO-RE relocation.
7150 	 */
7151 	const struct bpf_core_relo *relo;
7152 	struct bpf_core_spec spec;
7153 	char patch[512], spec_buf[256];
7154 	int insn_idx, err, spec_len;
7155 
7156 	if (sscanf(line1, "%d: (%*d) call unknown#195896080\n", &insn_idx) != 1)
7157 		return;
7158 
7159 	relo = find_relo_core(prog, insn_idx);
7160 	if (!relo)
7161 		return;
7162 
7163 	err = bpf_core_parse_spec(prog->name, prog->obj->btf, relo, &spec);
7164 	if (err)
7165 		return;
7166 
7167 	spec_len = bpf_core_format_spec(spec_buf, sizeof(spec_buf), &spec);
7168 	snprintf(patch, sizeof(patch),
7169 		 "%d: <invalid CO-RE relocation>\n"
7170 		 "failed to resolve CO-RE relocation %s%s\n",
7171 		 insn_idx, spec_buf, spec_len >= sizeof(spec_buf) ? "..." : "");
7172 
7173 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7174 }
7175 
7176 static void fixup_log_missing_map_load(struct bpf_program *prog,
7177 				       char *buf, size_t buf_sz, size_t log_sz,
7178 				       char *line1, char *line2, char *line3)
7179 {
7180 	/* Expected log for failed and not properly guarded CO-RE relocation:
7181 	 * line1 -> 123: (85) call unknown#2001000345
7182 	 * line2 -> invalid func unknown#2001000345
7183 	 * line3 -> <anything else or end of buffer>
7184 	 *
7185 	 * "123" is the index of the instruction that was poisoned.
7186 	 * "345" in "2001000345" are map index in obj->maps to fetch map name.
7187 	 */
7188 	struct bpf_object *obj = prog->obj;
7189 	const struct bpf_map *map;
7190 	int insn_idx, map_idx;
7191 	char patch[128];
7192 
7193 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &map_idx) != 2)
7194 		return;
7195 
7196 	map_idx -= MAP_LDIMM64_POISON_BASE;
7197 	if (map_idx < 0 || map_idx >= obj->nr_maps)
7198 		return;
7199 	map = &obj->maps[map_idx];
7200 
7201 	snprintf(patch, sizeof(patch),
7202 		 "%d: <invalid BPF map reference>\n"
7203 		 "BPF map '%s' is referenced but wasn't created\n",
7204 		 insn_idx, map->name);
7205 
7206 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7207 }
7208 
7209 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz)
7210 {
7211 	/* look for familiar error patterns in last N lines of the log */
7212 	const size_t max_last_line_cnt = 10;
7213 	char *prev_line, *cur_line, *next_line;
7214 	size_t log_sz;
7215 	int i;
7216 
7217 	if (!buf)
7218 		return;
7219 
7220 	log_sz = strlen(buf) + 1;
7221 	next_line = buf + log_sz - 1;
7222 
7223 	for (i = 0; i < max_last_line_cnt; i++, next_line = cur_line) {
7224 		cur_line = find_prev_line(buf, next_line);
7225 		if (!cur_line)
7226 			return;
7227 
7228 		/* failed CO-RE relocation case */
7229 		if (str_has_pfx(cur_line, "invalid func unknown#195896080\n")) {
7230 			prev_line = find_prev_line(buf, cur_line);
7231 			if (!prev_line)
7232 				continue;
7233 
7234 			fixup_log_failed_core_relo(prog, buf, buf_sz, log_sz,
7235 						   prev_line, cur_line, next_line);
7236 			return;
7237 		} else if (str_has_pfx(cur_line, "invalid func unknown#"MAP_LDIMM64_POISON_PFX)) {
7238 			prev_line = find_prev_line(buf, cur_line);
7239 			if (!prev_line)
7240 				continue;
7241 
7242 			fixup_log_missing_map_load(prog, buf, buf_sz, log_sz,
7243 						   prev_line, cur_line, next_line);
7244 			return;
7245 		}
7246 	}
7247 }
7248 
7249 static int bpf_program_record_relos(struct bpf_program *prog)
7250 {
7251 	struct bpf_object *obj = prog->obj;
7252 	int i;
7253 
7254 	for (i = 0; i < prog->nr_reloc; i++) {
7255 		struct reloc_desc *relo = &prog->reloc_desc[i];
7256 		struct extern_desc *ext = &obj->externs[relo->sym_off];
7257 
7258 		switch (relo->type) {
7259 		case RELO_EXTERN_VAR:
7260 			if (ext->type != EXT_KSYM)
7261 				continue;
7262 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7263 					       ext->is_weak, !ext->ksym.type_id,
7264 					       BTF_KIND_VAR, relo->insn_idx);
7265 			break;
7266 		case RELO_EXTERN_FUNC:
7267 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7268 					       ext->is_weak, false, BTF_KIND_FUNC,
7269 					       relo->insn_idx);
7270 			break;
7271 		case RELO_CORE: {
7272 			struct bpf_core_relo cr = {
7273 				.insn_off = relo->insn_idx * 8,
7274 				.type_id = relo->core_relo->type_id,
7275 				.access_str_off = relo->core_relo->access_str_off,
7276 				.kind = relo->core_relo->kind,
7277 			};
7278 
7279 			bpf_gen__record_relo_core(obj->gen_loader, &cr);
7280 			break;
7281 		}
7282 		default:
7283 			continue;
7284 		}
7285 	}
7286 	return 0;
7287 }
7288 
7289 static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
7290 				const char *license, __u32 kern_ver)
7291 {
7292 	int err = 0, fd, i;
7293 
7294 	if (obj->loaded) {
7295 		pr_warn("prog '%s': can't load after object was loaded\n", prog->name);
7296 		return libbpf_err(-EINVAL);
7297 	}
7298 
7299 	if (prog->instances.nr < 0 || !prog->instances.fds) {
7300 		if (prog->preprocessor) {
7301 			pr_warn("Internal error: can't load program '%s'\n",
7302 				prog->name);
7303 			return libbpf_err(-LIBBPF_ERRNO__INTERNAL);
7304 		}
7305 
7306 		prog->instances.fds = malloc(sizeof(int));
7307 		if (!prog->instances.fds) {
7308 			pr_warn("Not enough memory for BPF fds\n");
7309 			return libbpf_err(-ENOMEM);
7310 		}
7311 		prog->instances.nr = 1;
7312 		prog->instances.fds[0] = -1;
7313 	}
7314 
7315 	if (!prog->preprocessor) {
7316 		if (prog->instances.nr != 1) {
7317 			pr_warn("prog '%s': inconsistent nr(%d) != 1\n",
7318 				prog->name, prog->instances.nr);
7319 		}
7320 		if (obj->gen_loader)
7321 			bpf_program_record_relos(prog);
7322 		err = bpf_object_load_prog_instance(obj, prog,
7323 						    prog->insns, prog->insns_cnt,
7324 						    license, kern_ver, &fd);
7325 		if (!err)
7326 			prog->instances.fds[0] = fd;
7327 		goto out;
7328 	}
7329 
7330 	for (i = 0; i < prog->instances.nr; i++) {
7331 		struct bpf_prog_prep_result result;
7332 		bpf_program_prep_t preprocessor = prog->preprocessor;
7333 
7334 		memset(&result, 0, sizeof(result));
7335 		err = preprocessor(prog, i, prog->insns,
7336 				   prog->insns_cnt, &result);
7337 		if (err) {
7338 			pr_warn("Preprocessing the %dth instance of program '%s' failed\n",
7339 				i, prog->name);
7340 			goto out;
7341 		}
7342 
7343 		if (!result.new_insn_ptr || !result.new_insn_cnt) {
7344 			pr_debug("Skip loading the %dth instance of program '%s'\n",
7345 				 i, prog->name);
7346 			prog->instances.fds[i] = -1;
7347 			if (result.pfd)
7348 				*result.pfd = -1;
7349 			continue;
7350 		}
7351 
7352 		err = bpf_object_load_prog_instance(obj, prog,
7353 						    result.new_insn_ptr, result.new_insn_cnt,
7354 						    license, kern_ver, &fd);
7355 		if (err) {
7356 			pr_warn("Loading the %dth instance of program '%s' failed\n",
7357 				i, prog->name);
7358 			goto out;
7359 		}
7360 
7361 		if (result.pfd)
7362 			*result.pfd = fd;
7363 		prog->instances.fds[i] = fd;
7364 	}
7365 out:
7366 	if (err)
7367 		pr_warn("failed to load program '%s'\n", prog->name);
7368 	return libbpf_err(err);
7369 }
7370 
7371 int bpf_program__load(struct bpf_program *prog, const char *license, __u32 kern_ver)
7372 {
7373 	return bpf_object_load_prog(prog->obj, prog, license, kern_ver);
7374 }
7375 
7376 static int
7377 bpf_object__load_progs(struct bpf_object *obj, int log_level)
7378 {
7379 	struct bpf_program *prog;
7380 	size_t i;
7381 	int err;
7382 
7383 	for (i = 0; i < obj->nr_programs; i++) {
7384 		prog = &obj->programs[i];
7385 		err = bpf_object__sanitize_prog(obj, prog);
7386 		if (err)
7387 			return err;
7388 	}
7389 
7390 	for (i = 0; i < obj->nr_programs; i++) {
7391 		prog = &obj->programs[i];
7392 		if (prog_is_subprog(obj, prog))
7393 			continue;
7394 		if (!prog->autoload) {
7395 			pr_debug("prog '%s': skipped loading\n", prog->name);
7396 			continue;
7397 		}
7398 		prog->log_level |= log_level;
7399 		err = bpf_object_load_prog(obj, prog, obj->license, obj->kern_version);
7400 		if (err)
7401 			return err;
7402 	}
7403 
7404 	bpf_object__free_relocs(obj);
7405 	return 0;
7406 }
7407 
7408 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
7409 
7410 static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
7411 {
7412 	struct bpf_program *prog;
7413 	int err;
7414 
7415 	bpf_object__for_each_program(prog, obj) {
7416 		prog->sec_def = find_sec_def(prog->sec_name);
7417 		if (!prog->sec_def) {
7418 			/* couldn't guess, but user might manually specify */
7419 			pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
7420 				prog->name, prog->sec_name);
7421 			continue;
7422 		}
7423 
7424 		prog->type = prog->sec_def->prog_type;
7425 		prog->expected_attach_type = prog->sec_def->expected_attach_type;
7426 
7427 #pragma GCC diagnostic push
7428 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
7429 		if (prog->sec_def->prog_type == BPF_PROG_TYPE_TRACING ||
7430 		    prog->sec_def->prog_type == BPF_PROG_TYPE_EXT)
7431 			prog->attach_prog_fd = OPTS_GET(opts, attach_prog_fd, 0);
7432 #pragma GCC diagnostic pop
7433 
7434 		/* sec_def can have custom callback which should be called
7435 		 * after bpf_program is initialized to adjust its properties
7436 		 */
7437 		if (prog->sec_def->prog_setup_fn) {
7438 			err = prog->sec_def->prog_setup_fn(prog, prog->sec_def->cookie);
7439 			if (err < 0) {
7440 				pr_warn("prog '%s': failed to initialize: %d\n",
7441 					prog->name, err);
7442 				return err;
7443 			}
7444 		}
7445 	}
7446 
7447 	return 0;
7448 }
7449 
7450 static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
7451 					  const struct bpf_object_open_opts *opts)
7452 {
7453 	const char *obj_name, *kconfig, *btf_tmp_path;
7454 	struct bpf_object *obj;
7455 	char tmp_name[64];
7456 	int err;
7457 	char *log_buf;
7458 	size_t log_size;
7459 	__u32 log_level;
7460 
7461 	if (elf_version(EV_CURRENT) == EV_NONE) {
7462 		pr_warn("failed to init libelf for %s\n",
7463 			path ? : "(mem buf)");
7464 		return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
7465 	}
7466 
7467 	if (!OPTS_VALID(opts, bpf_object_open_opts))
7468 		return ERR_PTR(-EINVAL);
7469 
7470 	obj_name = OPTS_GET(opts, object_name, NULL);
7471 	if (obj_buf) {
7472 		if (!obj_name) {
7473 			snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
7474 				 (unsigned long)obj_buf,
7475 				 (unsigned long)obj_buf_sz);
7476 			obj_name = tmp_name;
7477 		}
7478 		path = obj_name;
7479 		pr_debug("loading object '%s' from buffer\n", obj_name);
7480 	}
7481 
7482 	log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
7483 	log_size = OPTS_GET(opts, kernel_log_size, 0);
7484 	log_level = OPTS_GET(opts, kernel_log_level, 0);
7485 	if (log_size > UINT_MAX)
7486 		return ERR_PTR(-EINVAL);
7487 	if (log_size && !log_buf)
7488 		return ERR_PTR(-EINVAL);
7489 
7490 	obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
7491 	if (IS_ERR(obj))
7492 		return obj;
7493 
7494 	obj->log_buf = log_buf;
7495 	obj->log_size = log_size;
7496 	obj->log_level = log_level;
7497 
7498 	btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
7499 	if (btf_tmp_path) {
7500 		if (strlen(btf_tmp_path) >= PATH_MAX) {
7501 			err = -ENAMETOOLONG;
7502 			goto out;
7503 		}
7504 		obj->btf_custom_path = strdup(btf_tmp_path);
7505 		if (!obj->btf_custom_path) {
7506 			err = -ENOMEM;
7507 			goto out;
7508 		}
7509 	}
7510 
7511 	kconfig = OPTS_GET(opts, kconfig, NULL);
7512 	if (kconfig) {
7513 		obj->kconfig = strdup(kconfig);
7514 		if (!obj->kconfig) {
7515 			err = -ENOMEM;
7516 			goto out;
7517 		}
7518 	}
7519 
7520 	err = bpf_object__elf_init(obj);
7521 	err = err ? : bpf_object__check_endianness(obj);
7522 	err = err ? : bpf_object__elf_collect(obj);
7523 	err = err ? : bpf_object__collect_externs(obj);
7524 	err = err ? : bpf_object__finalize_btf(obj);
7525 	err = err ? : bpf_object__init_maps(obj, opts);
7526 	err = err ? : bpf_object_init_progs(obj, opts);
7527 	err = err ? : bpf_object__collect_relos(obj);
7528 	if (err)
7529 		goto out;
7530 
7531 	bpf_object__elf_finish(obj);
7532 
7533 	return obj;
7534 out:
7535 	bpf_object__close(obj);
7536 	return ERR_PTR(err);
7537 }
7538 
7539 static struct bpf_object *
7540 __bpf_object__open_xattr(struct bpf_object_open_attr *attr, int flags)
7541 {
7542 	DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
7543 		.relaxed_maps = flags & MAPS_RELAX_COMPAT,
7544 	);
7545 
7546 	/* param validation */
7547 	if (!attr->file)
7548 		return NULL;
7549 
7550 	pr_debug("loading %s\n", attr->file);
7551 	return bpf_object_open(attr->file, NULL, 0, &opts);
7552 }
7553 
7554 struct bpf_object *bpf_object__open_xattr(struct bpf_object_open_attr *attr)
7555 {
7556 	return libbpf_ptr(__bpf_object__open_xattr(attr, 0));
7557 }
7558 
7559 struct bpf_object *bpf_object__open(const char *path)
7560 {
7561 	struct bpf_object_open_attr attr = {
7562 		.file		= path,
7563 		.prog_type	= BPF_PROG_TYPE_UNSPEC,
7564 	};
7565 
7566 	return libbpf_ptr(__bpf_object__open_xattr(&attr, 0));
7567 }
7568 
7569 struct bpf_object *
7570 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
7571 {
7572 	if (!path)
7573 		return libbpf_err_ptr(-EINVAL);
7574 
7575 	pr_debug("loading %s\n", path);
7576 
7577 	return libbpf_ptr(bpf_object_open(path, NULL, 0, opts));
7578 }
7579 
7580 struct bpf_object *
7581 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
7582 		     const struct bpf_object_open_opts *opts)
7583 {
7584 	if (!obj_buf || obj_buf_sz == 0)
7585 		return libbpf_err_ptr(-EINVAL);
7586 
7587 	return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, opts));
7588 }
7589 
7590 struct bpf_object *
7591 bpf_object__open_buffer(const void *obj_buf, size_t obj_buf_sz,
7592 			const char *name)
7593 {
7594 	DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
7595 		.object_name = name,
7596 		/* wrong default, but backwards-compatible */
7597 		.relaxed_maps = true,
7598 	);
7599 
7600 	/* returning NULL is wrong, but backwards-compatible */
7601 	if (!obj_buf || obj_buf_sz == 0)
7602 		return errno = EINVAL, NULL;
7603 
7604 	return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, &opts));
7605 }
7606 
7607 static int bpf_object_unload(struct bpf_object *obj)
7608 {
7609 	size_t i;
7610 
7611 	if (!obj)
7612 		return libbpf_err(-EINVAL);
7613 
7614 	for (i = 0; i < obj->nr_maps; i++) {
7615 		zclose(obj->maps[i].fd);
7616 		if (obj->maps[i].st_ops)
7617 			zfree(&obj->maps[i].st_ops->kern_vdata);
7618 	}
7619 
7620 	for (i = 0; i < obj->nr_programs; i++)
7621 		bpf_program__unload(&obj->programs[i]);
7622 
7623 	return 0;
7624 }
7625 
7626 int bpf_object__unload(struct bpf_object *obj) __attribute__((alias("bpf_object_unload")));
7627 
7628 static int bpf_object__sanitize_maps(struct bpf_object *obj)
7629 {
7630 	struct bpf_map *m;
7631 
7632 	bpf_object__for_each_map(m, obj) {
7633 		if (!bpf_map__is_internal(m))
7634 			continue;
7635 		if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
7636 			m->def.map_flags ^= BPF_F_MMAPABLE;
7637 	}
7638 
7639 	return 0;
7640 }
7641 
7642 int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
7643 {
7644 	char sym_type, sym_name[500];
7645 	unsigned long long sym_addr;
7646 	int ret, err = 0;
7647 	FILE *f;
7648 
7649 	f = fopen("/proc/kallsyms", "r");
7650 	if (!f) {
7651 		err = -errno;
7652 		pr_warn("failed to open /proc/kallsyms: %d\n", err);
7653 		return err;
7654 	}
7655 
7656 	while (true) {
7657 		ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
7658 			     &sym_addr, &sym_type, sym_name);
7659 		if (ret == EOF && feof(f))
7660 			break;
7661 		if (ret != 3) {
7662 			pr_warn("failed to read kallsyms entry: %d\n", ret);
7663 			err = -EINVAL;
7664 			break;
7665 		}
7666 
7667 		err = cb(sym_addr, sym_type, sym_name, ctx);
7668 		if (err)
7669 			break;
7670 	}
7671 
7672 	fclose(f);
7673 	return err;
7674 }
7675 
7676 static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
7677 		       const char *sym_name, void *ctx)
7678 {
7679 	struct bpf_object *obj = ctx;
7680 	const struct btf_type *t;
7681 	struct extern_desc *ext;
7682 
7683 	ext = find_extern_by_name(obj, sym_name);
7684 	if (!ext || ext->type != EXT_KSYM)
7685 		return 0;
7686 
7687 	t = btf__type_by_id(obj->btf, ext->btf_id);
7688 	if (!btf_is_var(t))
7689 		return 0;
7690 
7691 	if (ext->is_set && ext->ksym.addr != sym_addr) {
7692 		pr_warn("extern (ksym) '%s' resolution is ambiguous: 0x%llx or 0x%llx\n",
7693 			sym_name, ext->ksym.addr, sym_addr);
7694 		return -EINVAL;
7695 	}
7696 	if (!ext->is_set) {
7697 		ext->is_set = true;
7698 		ext->ksym.addr = sym_addr;
7699 		pr_debug("extern (ksym) %s=0x%llx\n", sym_name, sym_addr);
7700 	}
7701 	return 0;
7702 }
7703 
7704 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
7705 {
7706 	return libbpf_kallsyms_parse(kallsyms_cb, obj);
7707 }
7708 
7709 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
7710 			    __u16 kind, struct btf **res_btf,
7711 			    struct module_btf **res_mod_btf)
7712 {
7713 	struct module_btf *mod_btf;
7714 	struct btf *btf;
7715 	int i, id, err;
7716 
7717 	btf = obj->btf_vmlinux;
7718 	mod_btf = NULL;
7719 	id = btf__find_by_name_kind(btf, ksym_name, kind);
7720 
7721 	if (id == -ENOENT) {
7722 		err = load_module_btfs(obj);
7723 		if (err)
7724 			return err;
7725 
7726 		for (i = 0; i < obj->btf_module_cnt; i++) {
7727 			/* we assume module_btf's BTF FD is always >0 */
7728 			mod_btf = &obj->btf_modules[i];
7729 			btf = mod_btf->btf;
7730 			id = btf__find_by_name_kind_own(btf, ksym_name, kind);
7731 			if (id != -ENOENT)
7732 				break;
7733 		}
7734 	}
7735 	if (id <= 0)
7736 		return -ESRCH;
7737 
7738 	*res_btf = btf;
7739 	*res_mod_btf = mod_btf;
7740 	return id;
7741 }
7742 
7743 static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
7744 					       struct extern_desc *ext)
7745 {
7746 	const struct btf_type *targ_var, *targ_type;
7747 	__u32 targ_type_id, local_type_id;
7748 	struct module_btf *mod_btf = NULL;
7749 	const char *targ_var_name;
7750 	struct btf *btf = NULL;
7751 	int id, err;
7752 
7753 	id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
7754 	if (id < 0) {
7755 		if (id == -ESRCH && ext->is_weak)
7756 			return 0;
7757 		pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
7758 			ext->name);
7759 		return id;
7760 	}
7761 
7762 	/* find local type_id */
7763 	local_type_id = ext->ksym.type_id;
7764 
7765 	/* find target type_id */
7766 	targ_var = btf__type_by_id(btf, id);
7767 	targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
7768 	targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
7769 
7770 	err = bpf_core_types_are_compat(obj->btf, local_type_id,
7771 					btf, targ_type_id);
7772 	if (err <= 0) {
7773 		const struct btf_type *local_type;
7774 		const char *targ_name, *local_name;
7775 
7776 		local_type = btf__type_by_id(obj->btf, local_type_id);
7777 		local_name = btf__name_by_offset(obj->btf, local_type->name_off);
7778 		targ_name = btf__name_by_offset(btf, targ_type->name_off);
7779 
7780 		pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
7781 			ext->name, local_type_id,
7782 			btf_kind_str(local_type), local_name, targ_type_id,
7783 			btf_kind_str(targ_type), targ_name);
7784 		return -EINVAL;
7785 	}
7786 
7787 	ext->is_set = true;
7788 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
7789 	ext->ksym.kernel_btf_id = id;
7790 	pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
7791 		 ext->name, id, btf_kind_str(targ_var), targ_var_name);
7792 
7793 	return 0;
7794 }
7795 
7796 static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
7797 						struct extern_desc *ext)
7798 {
7799 	int local_func_proto_id, kfunc_proto_id, kfunc_id;
7800 	struct module_btf *mod_btf = NULL;
7801 	const struct btf_type *kern_func;
7802 	struct btf *kern_btf = NULL;
7803 	int ret;
7804 
7805 	local_func_proto_id = ext->ksym.type_id;
7806 
7807 	kfunc_id = find_ksym_btf_id(obj, ext->name, BTF_KIND_FUNC, &kern_btf, &mod_btf);
7808 	if (kfunc_id < 0) {
7809 		if (kfunc_id == -ESRCH && ext->is_weak)
7810 			return 0;
7811 		pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
7812 			ext->name);
7813 		return kfunc_id;
7814 	}
7815 
7816 	kern_func = btf__type_by_id(kern_btf, kfunc_id);
7817 	kfunc_proto_id = kern_func->type;
7818 
7819 	ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
7820 					kern_btf, kfunc_proto_id);
7821 	if (ret <= 0) {
7822 		pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with kernel [%d]\n",
7823 			ext->name, local_func_proto_id, kfunc_proto_id);
7824 		return -EINVAL;
7825 	}
7826 
7827 	/* set index for module BTF fd in fd_array, if unset */
7828 	if (mod_btf && !mod_btf->fd_array_idx) {
7829 		/* insn->off is s16 */
7830 		if (obj->fd_array_cnt == INT16_MAX) {
7831 			pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
7832 				ext->name, mod_btf->fd_array_idx);
7833 			return -E2BIG;
7834 		}
7835 		/* Cannot use index 0 for module BTF fd */
7836 		if (!obj->fd_array_cnt)
7837 			obj->fd_array_cnt = 1;
7838 
7839 		ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
7840 					obj->fd_array_cnt + 1);
7841 		if (ret)
7842 			return ret;
7843 		mod_btf->fd_array_idx = obj->fd_array_cnt;
7844 		/* we assume module BTF FD is always >0 */
7845 		obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
7846 	}
7847 
7848 	ext->is_set = true;
7849 	ext->ksym.kernel_btf_id = kfunc_id;
7850 	ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
7851 	pr_debug("extern (func ksym) '%s': resolved to kernel [%d]\n",
7852 		 ext->name, kfunc_id);
7853 
7854 	return 0;
7855 }
7856 
7857 static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
7858 {
7859 	const struct btf_type *t;
7860 	struct extern_desc *ext;
7861 	int i, err;
7862 
7863 	for (i = 0; i < obj->nr_extern; i++) {
7864 		ext = &obj->externs[i];
7865 		if (ext->type != EXT_KSYM || !ext->ksym.type_id)
7866 			continue;
7867 
7868 		if (obj->gen_loader) {
7869 			ext->is_set = true;
7870 			ext->ksym.kernel_btf_obj_fd = 0;
7871 			ext->ksym.kernel_btf_id = 0;
7872 			continue;
7873 		}
7874 		t = btf__type_by_id(obj->btf, ext->btf_id);
7875 		if (btf_is_var(t))
7876 			err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
7877 		else
7878 			err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
7879 		if (err)
7880 			return err;
7881 	}
7882 	return 0;
7883 }
7884 
7885 static int bpf_object__resolve_externs(struct bpf_object *obj,
7886 				       const char *extra_kconfig)
7887 {
7888 	bool need_config = false, need_kallsyms = false;
7889 	bool need_vmlinux_btf = false;
7890 	struct extern_desc *ext;
7891 	void *kcfg_data = NULL;
7892 	int err, i;
7893 
7894 	if (obj->nr_extern == 0)
7895 		return 0;
7896 
7897 	if (obj->kconfig_map_idx >= 0)
7898 		kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
7899 
7900 	for (i = 0; i < obj->nr_extern; i++) {
7901 		ext = &obj->externs[i];
7902 
7903 		if (ext->type == EXT_KCFG &&
7904 		    strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
7905 			void *ext_val = kcfg_data + ext->kcfg.data_off;
7906 			__u32 kver = get_kernel_version();
7907 
7908 			if (!kver) {
7909 				pr_warn("failed to get kernel version\n");
7910 				return -EINVAL;
7911 			}
7912 			err = set_kcfg_value_num(ext, ext_val, kver);
7913 			if (err)
7914 				return err;
7915 			pr_debug("extern (kcfg) %s=0x%x\n", ext->name, kver);
7916 		} else if (ext->type == EXT_KCFG && str_has_pfx(ext->name, "CONFIG_")) {
7917 			need_config = true;
7918 		} else if (ext->type == EXT_KSYM) {
7919 			if (ext->ksym.type_id)
7920 				need_vmlinux_btf = true;
7921 			else
7922 				need_kallsyms = true;
7923 		} else {
7924 			pr_warn("unrecognized extern '%s'\n", ext->name);
7925 			return -EINVAL;
7926 		}
7927 	}
7928 	if (need_config && extra_kconfig) {
7929 		err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
7930 		if (err)
7931 			return -EINVAL;
7932 		need_config = false;
7933 		for (i = 0; i < obj->nr_extern; i++) {
7934 			ext = &obj->externs[i];
7935 			if (ext->type == EXT_KCFG && !ext->is_set) {
7936 				need_config = true;
7937 				break;
7938 			}
7939 		}
7940 	}
7941 	if (need_config) {
7942 		err = bpf_object__read_kconfig_file(obj, kcfg_data);
7943 		if (err)
7944 			return -EINVAL;
7945 	}
7946 	if (need_kallsyms) {
7947 		err = bpf_object__read_kallsyms_file(obj);
7948 		if (err)
7949 			return -EINVAL;
7950 	}
7951 	if (need_vmlinux_btf) {
7952 		err = bpf_object__resolve_ksyms_btf_id(obj);
7953 		if (err)
7954 			return -EINVAL;
7955 	}
7956 	for (i = 0; i < obj->nr_extern; i++) {
7957 		ext = &obj->externs[i];
7958 
7959 		if (!ext->is_set && !ext->is_weak) {
7960 			pr_warn("extern %s (strong) not resolved\n", ext->name);
7961 			return -ESRCH;
7962 		} else if (!ext->is_set) {
7963 			pr_debug("extern %s (weak) not resolved, defaulting to zero\n",
7964 				 ext->name);
7965 		}
7966 	}
7967 
7968 	return 0;
7969 }
7970 
7971 static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
7972 {
7973 	int err, i;
7974 
7975 	if (!obj)
7976 		return libbpf_err(-EINVAL);
7977 
7978 	if (obj->loaded) {
7979 		pr_warn("object '%s': load can't be attempted twice\n", obj->name);
7980 		return libbpf_err(-EINVAL);
7981 	}
7982 
7983 	if (obj->gen_loader)
7984 		bpf_gen__init(obj->gen_loader, extra_log_level, obj->nr_programs, obj->nr_maps);
7985 
7986 	err = bpf_object__probe_loading(obj);
7987 	err = err ? : bpf_object__load_vmlinux_btf(obj, false);
7988 	err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
7989 	err = err ? : bpf_object__sanitize_and_load_btf(obj);
7990 	err = err ? : bpf_object__sanitize_maps(obj);
7991 	err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
7992 	err = err ? : bpf_object__create_maps(obj);
7993 	err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
7994 	err = err ? : bpf_object__load_progs(obj, extra_log_level);
7995 	err = err ? : bpf_object_init_prog_arrays(obj);
7996 
7997 	if (obj->gen_loader) {
7998 		/* reset FDs */
7999 		if (obj->btf)
8000 			btf__set_fd(obj->btf, -1);
8001 		for (i = 0; i < obj->nr_maps; i++)
8002 			obj->maps[i].fd = -1;
8003 		if (!err)
8004 			err = bpf_gen__finish(obj->gen_loader, obj->nr_programs, obj->nr_maps);
8005 	}
8006 
8007 	/* clean up fd_array */
8008 	zfree(&obj->fd_array);
8009 
8010 	/* clean up module BTFs */
8011 	for (i = 0; i < obj->btf_module_cnt; i++) {
8012 		close(obj->btf_modules[i].fd);
8013 		btf__free(obj->btf_modules[i].btf);
8014 		free(obj->btf_modules[i].name);
8015 	}
8016 	free(obj->btf_modules);
8017 
8018 	/* clean up vmlinux BTF */
8019 	btf__free(obj->btf_vmlinux);
8020 	obj->btf_vmlinux = NULL;
8021 
8022 	obj->loaded = true; /* doesn't matter if successfully or not */
8023 
8024 	if (err)
8025 		goto out;
8026 
8027 	return 0;
8028 out:
8029 	/* unpin any maps that were auto-pinned during load */
8030 	for (i = 0; i < obj->nr_maps; i++)
8031 		if (obj->maps[i].pinned && !obj->maps[i].reused)
8032 			bpf_map__unpin(&obj->maps[i], NULL);
8033 
8034 	bpf_object_unload(obj);
8035 	pr_warn("failed to load object '%s'\n", obj->path);
8036 	return libbpf_err(err);
8037 }
8038 
8039 int bpf_object__load_xattr(struct bpf_object_load_attr *attr)
8040 {
8041 	return bpf_object_load(attr->obj, attr->log_level, attr->target_btf_path);
8042 }
8043 
8044 int bpf_object__load(struct bpf_object *obj)
8045 {
8046 	return bpf_object_load(obj, 0, NULL);
8047 }
8048 
8049 static int make_parent_dir(const char *path)
8050 {
8051 	char *cp, errmsg[STRERR_BUFSIZE];
8052 	char *dname, *dir;
8053 	int err = 0;
8054 
8055 	dname = strdup(path);
8056 	if (dname == NULL)
8057 		return -ENOMEM;
8058 
8059 	dir = dirname(dname);
8060 	if (mkdir(dir, 0700) && errno != EEXIST)
8061 		err = -errno;
8062 
8063 	free(dname);
8064 	if (err) {
8065 		cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
8066 		pr_warn("failed to mkdir %s: %s\n", path, cp);
8067 	}
8068 	return err;
8069 }
8070 
8071 static int check_path(const char *path)
8072 {
8073 	char *cp, errmsg[STRERR_BUFSIZE];
8074 	struct statfs st_fs;
8075 	char *dname, *dir;
8076 	int err = 0;
8077 
8078 	if (path == NULL)
8079 		return -EINVAL;
8080 
8081 	dname = strdup(path);
8082 	if (dname == NULL)
8083 		return -ENOMEM;
8084 
8085 	dir = dirname(dname);
8086 	if (statfs(dir, &st_fs)) {
8087 		cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
8088 		pr_warn("failed to statfs %s: %s\n", dir, cp);
8089 		err = -errno;
8090 	}
8091 	free(dname);
8092 
8093 	if (!err && st_fs.f_type != BPF_FS_MAGIC) {
8094 		pr_warn("specified path %s is not on BPF FS\n", path);
8095 		err = -EINVAL;
8096 	}
8097 
8098 	return err;
8099 }
8100 
8101 static int bpf_program_pin_instance(struct bpf_program *prog, const char *path, int instance)
8102 {
8103 	char *cp, errmsg[STRERR_BUFSIZE];
8104 	int err;
8105 
8106 	err = make_parent_dir(path);
8107 	if (err)
8108 		return libbpf_err(err);
8109 
8110 	err = check_path(path);
8111 	if (err)
8112 		return libbpf_err(err);
8113 
8114 	if (prog == NULL) {
8115 		pr_warn("invalid program pointer\n");
8116 		return libbpf_err(-EINVAL);
8117 	}
8118 
8119 	if (instance < 0 || instance >= prog->instances.nr) {
8120 		pr_warn("invalid prog instance %d of prog %s (max %d)\n",
8121 			instance, prog->name, prog->instances.nr);
8122 		return libbpf_err(-EINVAL);
8123 	}
8124 
8125 	if (bpf_obj_pin(prog->instances.fds[instance], path)) {
8126 		err = -errno;
8127 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
8128 		pr_warn("failed to pin program: %s\n", cp);
8129 		return libbpf_err(err);
8130 	}
8131 	pr_debug("pinned program '%s'\n", path);
8132 
8133 	return 0;
8134 }
8135 
8136 static int bpf_program_unpin_instance(struct bpf_program *prog, const char *path, int instance)
8137 {
8138 	int err;
8139 
8140 	err = check_path(path);
8141 	if (err)
8142 		return libbpf_err(err);
8143 
8144 	if (prog == NULL) {
8145 		pr_warn("invalid program pointer\n");
8146 		return libbpf_err(-EINVAL);
8147 	}
8148 
8149 	if (instance < 0 || instance >= prog->instances.nr) {
8150 		pr_warn("invalid prog instance %d of prog %s (max %d)\n",
8151 			instance, prog->name, prog->instances.nr);
8152 		return libbpf_err(-EINVAL);
8153 	}
8154 
8155 	err = unlink(path);
8156 	if (err != 0)
8157 		return libbpf_err(-errno);
8158 
8159 	pr_debug("unpinned program '%s'\n", path);
8160 
8161 	return 0;
8162 }
8163 
8164 __attribute__((alias("bpf_program_pin_instance")))
8165 int bpf_object__pin_instance(struct bpf_program *prog, const char *path, int instance);
8166 
8167 __attribute__((alias("bpf_program_unpin_instance")))
8168 int bpf_program__unpin_instance(struct bpf_program *prog, const char *path, int instance);
8169 
8170 int bpf_program__pin(struct bpf_program *prog, const char *path)
8171 {
8172 	int i, err;
8173 
8174 	err = make_parent_dir(path);
8175 	if (err)
8176 		return libbpf_err(err);
8177 
8178 	err = check_path(path);
8179 	if (err)
8180 		return libbpf_err(err);
8181 
8182 	if (prog == NULL) {
8183 		pr_warn("invalid program pointer\n");
8184 		return libbpf_err(-EINVAL);
8185 	}
8186 
8187 	if (prog->instances.nr <= 0) {
8188 		pr_warn("no instances of prog %s to pin\n", prog->name);
8189 		return libbpf_err(-EINVAL);
8190 	}
8191 
8192 	if (prog->instances.nr == 1) {
8193 		/* don't create subdirs when pinning single instance */
8194 		return bpf_program_pin_instance(prog, path, 0);
8195 	}
8196 
8197 	for (i = 0; i < prog->instances.nr; i++) {
8198 		char buf[PATH_MAX];
8199 		int len;
8200 
8201 		len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
8202 		if (len < 0) {
8203 			err = -EINVAL;
8204 			goto err_unpin;
8205 		} else if (len >= PATH_MAX) {
8206 			err = -ENAMETOOLONG;
8207 			goto err_unpin;
8208 		}
8209 
8210 		err = bpf_program_pin_instance(prog, buf, i);
8211 		if (err)
8212 			goto err_unpin;
8213 	}
8214 
8215 	return 0;
8216 
8217 err_unpin:
8218 	for (i = i - 1; i >= 0; i--) {
8219 		char buf[PATH_MAX];
8220 		int len;
8221 
8222 		len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
8223 		if (len < 0)
8224 			continue;
8225 		else if (len >= PATH_MAX)
8226 			continue;
8227 
8228 		bpf_program_unpin_instance(prog, buf, i);
8229 	}
8230 
8231 	rmdir(path);
8232 
8233 	return libbpf_err(err);
8234 }
8235 
8236 int bpf_program__unpin(struct bpf_program *prog, const char *path)
8237 {
8238 	int i, err;
8239 
8240 	err = check_path(path);
8241 	if (err)
8242 		return libbpf_err(err);
8243 
8244 	if (prog == NULL) {
8245 		pr_warn("invalid program pointer\n");
8246 		return libbpf_err(-EINVAL);
8247 	}
8248 
8249 	if (prog->instances.nr <= 0) {
8250 		pr_warn("no instances of prog %s to pin\n", prog->name);
8251 		return libbpf_err(-EINVAL);
8252 	}
8253 
8254 	if (prog->instances.nr == 1) {
8255 		/* don't create subdirs when pinning single instance */
8256 		return bpf_program_unpin_instance(prog, path, 0);
8257 	}
8258 
8259 	for (i = 0; i < prog->instances.nr; i++) {
8260 		char buf[PATH_MAX];
8261 		int len;
8262 
8263 		len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
8264 		if (len < 0)
8265 			return libbpf_err(-EINVAL);
8266 		else if (len >= PATH_MAX)
8267 			return libbpf_err(-ENAMETOOLONG);
8268 
8269 		err = bpf_program_unpin_instance(prog, buf, i);
8270 		if (err)
8271 			return err;
8272 	}
8273 
8274 	err = rmdir(path);
8275 	if (err)
8276 		return libbpf_err(-errno);
8277 
8278 	return 0;
8279 }
8280 
8281 int bpf_map__pin(struct bpf_map *map, const char *path)
8282 {
8283 	char *cp, errmsg[STRERR_BUFSIZE];
8284 	int err;
8285 
8286 	if (map == NULL) {
8287 		pr_warn("invalid map pointer\n");
8288 		return libbpf_err(-EINVAL);
8289 	}
8290 
8291 	if (map->pin_path) {
8292 		if (path && strcmp(path, map->pin_path)) {
8293 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8294 				bpf_map__name(map), map->pin_path, path);
8295 			return libbpf_err(-EINVAL);
8296 		} else if (map->pinned) {
8297 			pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
8298 				 bpf_map__name(map), map->pin_path);
8299 			return 0;
8300 		}
8301 	} else {
8302 		if (!path) {
8303 			pr_warn("missing a path to pin map '%s' at\n",
8304 				bpf_map__name(map));
8305 			return libbpf_err(-EINVAL);
8306 		} else if (map->pinned) {
8307 			pr_warn("map '%s' already pinned\n", bpf_map__name(map));
8308 			return libbpf_err(-EEXIST);
8309 		}
8310 
8311 		map->pin_path = strdup(path);
8312 		if (!map->pin_path) {
8313 			err = -errno;
8314 			goto out_err;
8315 		}
8316 	}
8317 
8318 	err = make_parent_dir(map->pin_path);
8319 	if (err)
8320 		return libbpf_err(err);
8321 
8322 	err = check_path(map->pin_path);
8323 	if (err)
8324 		return libbpf_err(err);
8325 
8326 	if (bpf_obj_pin(map->fd, map->pin_path)) {
8327 		err = -errno;
8328 		goto out_err;
8329 	}
8330 
8331 	map->pinned = true;
8332 	pr_debug("pinned map '%s'\n", map->pin_path);
8333 
8334 	return 0;
8335 
8336 out_err:
8337 	cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
8338 	pr_warn("failed to pin map: %s\n", cp);
8339 	return libbpf_err(err);
8340 }
8341 
8342 int bpf_map__unpin(struct bpf_map *map, const char *path)
8343 {
8344 	int err;
8345 
8346 	if (map == NULL) {
8347 		pr_warn("invalid map pointer\n");
8348 		return libbpf_err(-EINVAL);
8349 	}
8350 
8351 	if (map->pin_path) {
8352 		if (path && strcmp(path, map->pin_path)) {
8353 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8354 				bpf_map__name(map), map->pin_path, path);
8355 			return libbpf_err(-EINVAL);
8356 		}
8357 		path = map->pin_path;
8358 	} else if (!path) {
8359 		pr_warn("no path to unpin map '%s' from\n",
8360 			bpf_map__name(map));
8361 		return libbpf_err(-EINVAL);
8362 	}
8363 
8364 	err = check_path(path);
8365 	if (err)
8366 		return libbpf_err(err);
8367 
8368 	err = unlink(path);
8369 	if (err != 0)
8370 		return libbpf_err(-errno);
8371 
8372 	map->pinned = false;
8373 	pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
8374 
8375 	return 0;
8376 }
8377 
8378 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
8379 {
8380 	char *new = NULL;
8381 
8382 	if (path) {
8383 		new = strdup(path);
8384 		if (!new)
8385 			return libbpf_err(-errno);
8386 	}
8387 
8388 	free(map->pin_path);
8389 	map->pin_path = new;
8390 	return 0;
8391 }
8392 
8393 __alias(bpf_map__pin_path)
8394 const char *bpf_map__get_pin_path(const struct bpf_map *map);
8395 
8396 const char *bpf_map__pin_path(const struct bpf_map *map)
8397 {
8398 	return map->pin_path;
8399 }
8400 
8401 bool bpf_map__is_pinned(const struct bpf_map *map)
8402 {
8403 	return map->pinned;
8404 }
8405 
8406 static void sanitize_pin_path(char *s)
8407 {
8408 	/* bpffs disallows periods in path names */
8409 	while (*s) {
8410 		if (*s == '.')
8411 			*s = '_';
8412 		s++;
8413 	}
8414 }
8415 
8416 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
8417 {
8418 	struct bpf_map *map;
8419 	int err;
8420 
8421 	if (!obj)
8422 		return libbpf_err(-ENOENT);
8423 
8424 	if (!obj->loaded) {
8425 		pr_warn("object not yet loaded; load it first\n");
8426 		return libbpf_err(-ENOENT);
8427 	}
8428 
8429 	bpf_object__for_each_map(map, obj) {
8430 		char *pin_path = NULL;
8431 		char buf[PATH_MAX];
8432 
8433 		if (!map->autocreate)
8434 			continue;
8435 
8436 		if (path) {
8437 			int len;
8438 
8439 			len = snprintf(buf, PATH_MAX, "%s/%s", path,
8440 				       bpf_map__name(map));
8441 			if (len < 0) {
8442 				err = -EINVAL;
8443 				goto err_unpin_maps;
8444 			} else if (len >= PATH_MAX) {
8445 				err = -ENAMETOOLONG;
8446 				goto err_unpin_maps;
8447 			}
8448 			sanitize_pin_path(buf);
8449 			pin_path = buf;
8450 		} else if (!map->pin_path) {
8451 			continue;
8452 		}
8453 
8454 		err = bpf_map__pin(map, pin_path);
8455 		if (err)
8456 			goto err_unpin_maps;
8457 	}
8458 
8459 	return 0;
8460 
8461 err_unpin_maps:
8462 	while ((map = bpf_object__prev_map(obj, map))) {
8463 		if (!map->pin_path)
8464 			continue;
8465 
8466 		bpf_map__unpin(map, NULL);
8467 	}
8468 
8469 	return libbpf_err(err);
8470 }
8471 
8472 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
8473 {
8474 	struct bpf_map *map;
8475 	int err;
8476 
8477 	if (!obj)
8478 		return libbpf_err(-ENOENT);
8479 
8480 	bpf_object__for_each_map(map, obj) {
8481 		char *pin_path = NULL;
8482 		char buf[PATH_MAX];
8483 
8484 		if (path) {
8485 			int len;
8486 
8487 			len = snprintf(buf, PATH_MAX, "%s/%s", path,
8488 				       bpf_map__name(map));
8489 			if (len < 0)
8490 				return libbpf_err(-EINVAL);
8491 			else if (len >= PATH_MAX)
8492 				return libbpf_err(-ENAMETOOLONG);
8493 			sanitize_pin_path(buf);
8494 			pin_path = buf;
8495 		} else if (!map->pin_path) {
8496 			continue;
8497 		}
8498 
8499 		err = bpf_map__unpin(map, pin_path);
8500 		if (err)
8501 			return libbpf_err(err);
8502 	}
8503 
8504 	return 0;
8505 }
8506 
8507 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
8508 {
8509 	struct bpf_program *prog;
8510 	int err;
8511 
8512 	if (!obj)
8513 		return libbpf_err(-ENOENT);
8514 
8515 	if (!obj->loaded) {
8516 		pr_warn("object not yet loaded; load it first\n");
8517 		return libbpf_err(-ENOENT);
8518 	}
8519 
8520 	bpf_object__for_each_program(prog, obj) {
8521 		char buf[PATH_MAX];
8522 		int len;
8523 
8524 		len = snprintf(buf, PATH_MAX, "%s/%s", path,
8525 			       prog->pin_name);
8526 		if (len < 0) {
8527 			err = -EINVAL;
8528 			goto err_unpin_programs;
8529 		} else if (len >= PATH_MAX) {
8530 			err = -ENAMETOOLONG;
8531 			goto err_unpin_programs;
8532 		}
8533 
8534 		err = bpf_program__pin(prog, buf);
8535 		if (err)
8536 			goto err_unpin_programs;
8537 	}
8538 
8539 	return 0;
8540 
8541 err_unpin_programs:
8542 	while ((prog = bpf_object__prev_program(obj, prog))) {
8543 		char buf[PATH_MAX];
8544 		int len;
8545 
8546 		len = snprintf(buf, PATH_MAX, "%s/%s", path,
8547 			       prog->pin_name);
8548 		if (len < 0)
8549 			continue;
8550 		else if (len >= PATH_MAX)
8551 			continue;
8552 
8553 		bpf_program__unpin(prog, buf);
8554 	}
8555 
8556 	return libbpf_err(err);
8557 }
8558 
8559 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
8560 {
8561 	struct bpf_program *prog;
8562 	int err;
8563 
8564 	if (!obj)
8565 		return libbpf_err(-ENOENT);
8566 
8567 	bpf_object__for_each_program(prog, obj) {
8568 		char buf[PATH_MAX];
8569 		int len;
8570 
8571 		len = snprintf(buf, PATH_MAX, "%s/%s", path,
8572 			       prog->pin_name);
8573 		if (len < 0)
8574 			return libbpf_err(-EINVAL);
8575 		else if (len >= PATH_MAX)
8576 			return libbpf_err(-ENAMETOOLONG);
8577 
8578 		err = bpf_program__unpin(prog, buf);
8579 		if (err)
8580 			return libbpf_err(err);
8581 	}
8582 
8583 	return 0;
8584 }
8585 
8586 int bpf_object__pin(struct bpf_object *obj, const char *path)
8587 {
8588 	int err;
8589 
8590 	err = bpf_object__pin_maps(obj, path);
8591 	if (err)
8592 		return libbpf_err(err);
8593 
8594 	err = bpf_object__pin_programs(obj, path);
8595 	if (err) {
8596 		bpf_object__unpin_maps(obj, path);
8597 		return libbpf_err(err);
8598 	}
8599 
8600 	return 0;
8601 }
8602 
8603 static void bpf_map__destroy(struct bpf_map *map)
8604 {
8605 	if (map->clear_priv)
8606 		map->clear_priv(map, map->priv);
8607 	map->priv = NULL;
8608 	map->clear_priv = NULL;
8609 
8610 	if (map->inner_map) {
8611 		bpf_map__destroy(map->inner_map);
8612 		zfree(&map->inner_map);
8613 	}
8614 
8615 	zfree(&map->init_slots);
8616 	map->init_slots_sz = 0;
8617 
8618 	if (map->mmaped) {
8619 		munmap(map->mmaped, bpf_map_mmap_sz(map));
8620 		map->mmaped = NULL;
8621 	}
8622 
8623 	if (map->st_ops) {
8624 		zfree(&map->st_ops->data);
8625 		zfree(&map->st_ops->progs);
8626 		zfree(&map->st_ops->kern_func_off);
8627 		zfree(&map->st_ops);
8628 	}
8629 
8630 	zfree(&map->name);
8631 	zfree(&map->real_name);
8632 	zfree(&map->pin_path);
8633 
8634 	if (map->fd >= 0)
8635 		zclose(map->fd);
8636 }
8637 
8638 void bpf_object__close(struct bpf_object *obj)
8639 {
8640 	size_t i;
8641 
8642 	if (IS_ERR_OR_NULL(obj))
8643 		return;
8644 
8645 	if (obj->clear_priv)
8646 		obj->clear_priv(obj, obj->priv);
8647 
8648 	usdt_manager_free(obj->usdt_man);
8649 	obj->usdt_man = NULL;
8650 
8651 	bpf_gen__free(obj->gen_loader);
8652 	bpf_object__elf_finish(obj);
8653 	bpf_object_unload(obj);
8654 	btf__free(obj->btf);
8655 	btf_ext__free(obj->btf_ext);
8656 
8657 	for (i = 0; i < obj->nr_maps; i++)
8658 		bpf_map__destroy(&obj->maps[i]);
8659 
8660 	zfree(&obj->btf_custom_path);
8661 	zfree(&obj->kconfig);
8662 	zfree(&obj->externs);
8663 	obj->nr_extern = 0;
8664 
8665 	zfree(&obj->maps);
8666 	obj->nr_maps = 0;
8667 
8668 	if (obj->programs && obj->nr_programs) {
8669 		for (i = 0; i < obj->nr_programs; i++)
8670 			bpf_program__exit(&obj->programs[i]);
8671 	}
8672 	zfree(&obj->programs);
8673 
8674 	list_del(&obj->list);
8675 	free(obj);
8676 }
8677 
8678 struct bpf_object *
8679 bpf_object__next(struct bpf_object *prev)
8680 {
8681 	struct bpf_object *next;
8682 	bool strict = (libbpf_mode & LIBBPF_STRICT_NO_OBJECT_LIST);
8683 
8684 	if (strict)
8685 		return NULL;
8686 
8687 	if (!prev)
8688 		next = list_first_entry(&bpf_objects_list,
8689 					struct bpf_object,
8690 					list);
8691 	else
8692 		next = list_next_entry(prev, list);
8693 
8694 	/* Empty list is noticed here so don't need checking on entry. */
8695 	if (&next->list == &bpf_objects_list)
8696 		return NULL;
8697 
8698 	return next;
8699 }
8700 
8701 const char *bpf_object__name(const struct bpf_object *obj)
8702 {
8703 	return obj ? obj->name : libbpf_err_ptr(-EINVAL);
8704 }
8705 
8706 unsigned int bpf_object__kversion(const struct bpf_object *obj)
8707 {
8708 	return obj ? obj->kern_version : 0;
8709 }
8710 
8711 struct btf *bpf_object__btf(const struct bpf_object *obj)
8712 {
8713 	return obj ? obj->btf : NULL;
8714 }
8715 
8716 int bpf_object__btf_fd(const struct bpf_object *obj)
8717 {
8718 	return obj->btf ? btf__fd(obj->btf) : -1;
8719 }
8720 
8721 int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
8722 {
8723 	if (obj->loaded)
8724 		return libbpf_err(-EINVAL);
8725 
8726 	obj->kern_version = kern_version;
8727 
8728 	return 0;
8729 }
8730 
8731 int bpf_object__set_priv(struct bpf_object *obj, void *priv,
8732 			 bpf_object_clear_priv_t clear_priv)
8733 {
8734 	if (obj->priv && obj->clear_priv)
8735 		obj->clear_priv(obj, obj->priv);
8736 
8737 	obj->priv = priv;
8738 	obj->clear_priv = clear_priv;
8739 	return 0;
8740 }
8741 
8742 void *bpf_object__priv(const struct bpf_object *obj)
8743 {
8744 	return obj ? obj->priv : libbpf_err_ptr(-EINVAL);
8745 }
8746 
8747 int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
8748 {
8749 	struct bpf_gen *gen;
8750 
8751 	if (!opts)
8752 		return -EFAULT;
8753 	if (!OPTS_VALID(opts, gen_loader_opts))
8754 		return -EINVAL;
8755 	gen = calloc(sizeof(*gen), 1);
8756 	if (!gen)
8757 		return -ENOMEM;
8758 	gen->opts = opts;
8759 	obj->gen_loader = gen;
8760 	return 0;
8761 }
8762 
8763 static struct bpf_program *
8764 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
8765 		    bool forward)
8766 {
8767 	size_t nr_programs = obj->nr_programs;
8768 	ssize_t idx;
8769 
8770 	if (!nr_programs)
8771 		return NULL;
8772 
8773 	if (!p)
8774 		/* Iter from the beginning */
8775 		return forward ? &obj->programs[0] :
8776 			&obj->programs[nr_programs - 1];
8777 
8778 	if (p->obj != obj) {
8779 		pr_warn("error: program handler doesn't match object\n");
8780 		return errno = EINVAL, NULL;
8781 	}
8782 
8783 	idx = (p - obj->programs) + (forward ? 1 : -1);
8784 	if (idx >= obj->nr_programs || idx < 0)
8785 		return NULL;
8786 	return &obj->programs[idx];
8787 }
8788 
8789 struct bpf_program *
8790 bpf_program__next(struct bpf_program *prev, const struct bpf_object *obj)
8791 {
8792 	return bpf_object__next_program(obj, prev);
8793 }
8794 
8795 struct bpf_program *
8796 bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
8797 {
8798 	struct bpf_program *prog = prev;
8799 
8800 	do {
8801 		prog = __bpf_program__iter(prog, obj, true);
8802 	} while (prog && prog_is_subprog(obj, prog));
8803 
8804 	return prog;
8805 }
8806 
8807 struct bpf_program *
8808 bpf_program__prev(struct bpf_program *next, const struct bpf_object *obj)
8809 {
8810 	return bpf_object__prev_program(obj, next);
8811 }
8812 
8813 struct bpf_program *
8814 bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
8815 {
8816 	struct bpf_program *prog = next;
8817 
8818 	do {
8819 		prog = __bpf_program__iter(prog, obj, false);
8820 	} while (prog && prog_is_subprog(obj, prog));
8821 
8822 	return prog;
8823 }
8824 
8825 int bpf_program__set_priv(struct bpf_program *prog, void *priv,
8826 			  bpf_program_clear_priv_t clear_priv)
8827 {
8828 	if (prog->priv && prog->clear_priv)
8829 		prog->clear_priv(prog, prog->priv);
8830 
8831 	prog->priv = priv;
8832 	prog->clear_priv = clear_priv;
8833 	return 0;
8834 }
8835 
8836 void *bpf_program__priv(const struct bpf_program *prog)
8837 {
8838 	return prog ? prog->priv : libbpf_err_ptr(-EINVAL);
8839 }
8840 
8841 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
8842 {
8843 	prog->prog_ifindex = ifindex;
8844 }
8845 
8846 const char *bpf_program__name(const struct bpf_program *prog)
8847 {
8848 	return prog->name;
8849 }
8850 
8851 const char *bpf_program__section_name(const struct bpf_program *prog)
8852 {
8853 	return prog->sec_name;
8854 }
8855 
8856 const char *bpf_program__title(const struct bpf_program *prog, bool needs_copy)
8857 {
8858 	const char *title;
8859 
8860 	title = prog->sec_name;
8861 	if (needs_copy) {
8862 		title = strdup(title);
8863 		if (!title) {
8864 			pr_warn("failed to strdup program title\n");
8865 			return libbpf_err_ptr(-ENOMEM);
8866 		}
8867 	}
8868 
8869 	return title;
8870 }
8871 
8872 bool bpf_program__autoload(const struct bpf_program *prog)
8873 {
8874 	return prog->autoload;
8875 }
8876 
8877 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
8878 {
8879 	if (prog->obj->loaded)
8880 		return libbpf_err(-EINVAL);
8881 
8882 	prog->autoload = autoload;
8883 	return 0;
8884 }
8885 
8886 static int bpf_program_nth_fd(const struct bpf_program *prog, int n);
8887 
8888 int bpf_program__fd(const struct bpf_program *prog)
8889 {
8890 	return bpf_program_nth_fd(prog, 0);
8891 }
8892 
8893 size_t bpf_program__size(const struct bpf_program *prog)
8894 {
8895 	return prog->insns_cnt * BPF_INSN_SZ;
8896 }
8897 
8898 const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
8899 {
8900 	return prog->insns;
8901 }
8902 
8903 size_t bpf_program__insn_cnt(const struct bpf_program *prog)
8904 {
8905 	return prog->insns_cnt;
8906 }
8907 
8908 int bpf_program__set_insns(struct bpf_program *prog,
8909 			   struct bpf_insn *new_insns, size_t new_insn_cnt)
8910 {
8911 	struct bpf_insn *insns;
8912 
8913 	if (prog->obj->loaded)
8914 		return -EBUSY;
8915 
8916 	insns = libbpf_reallocarray(prog->insns, new_insn_cnt, sizeof(*insns));
8917 	if (!insns) {
8918 		pr_warn("prog '%s': failed to realloc prog code\n", prog->name);
8919 		return -ENOMEM;
8920 	}
8921 	memcpy(insns, new_insns, new_insn_cnt * sizeof(*insns));
8922 
8923 	prog->insns = insns;
8924 	prog->insns_cnt = new_insn_cnt;
8925 	return 0;
8926 }
8927 
8928 int bpf_program__set_prep(struct bpf_program *prog, int nr_instances,
8929 			  bpf_program_prep_t prep)
8930 {
8931 	int *instances_fds;
8932 
8933 	if (nr_instances <= 0 || !prep)
8934 		return libbpf_err(-EINVAL);
8935 
8936 	if (prog->instances.nr > 0 || prog->instances.fds) {
8937 		pr_warn("Can't set pre-processor after loading\n");
8938 		return libbpf_err(-EINVAL);
8939 	}
8940 
8941 	instances_fds = malloc(sizeof(int) * nr_instances);
8942 	if (!instances_fds) {
8943 		pr_warn("alloc memory failed for fds\n");
8944 		return libbpf_err(-ENOMEM);
8945 	}
8946 
8947 	/* fill all fd with -1 */
8948 	memset(instances_fds, -1, sizeof(int) * nr_instances);
8949 
8950 	prog->instances.nr = nr_instances;
8951 	prog->instances.fds = instances_fds;
8952 	prog->preprocessor = prep;
8953 	return 0;
8954 }
8955 
8956 __attribute__((alias("bpf_program_nth_fd")))
8957 int bpf_program__nth_fd(const struct bpf_program *prog, int n);
8958 
8959 static int bpf_program_nth_fd(const struct bpf_program *prog, int n)
8960 {
8961 	int fd;
8962 
8963 	if (!prog)
8964 		return libbpf_err(-EINVAL);
8965 
8966 	if (n >= prog->instances.nr || n < 0) {
8967 		pr_warn("Can't get the %dth fd from program %s: only %d instances\n",
8968 			n, prog->name, prog->instances.nr);
8969 		return libbpf_err(-EINVAL);
8970 	}
8971 
8972 	fd = prog->instances.fds[n];
8973 	if (fd < 0) {
8974 		pr_warn("%dth instance of program '%s' is invalid\n",
8975 			n, prog->name);
8976 		return libbpf_err(-ENOENT);
8977 	}
8978 
8979 	return fd;
8980 }
8981 
8982 __alias(bpf_program__type)
8983 enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog);
8984 
8985 enum bpf_prog_type bpf_program__type(const struct bpf_program *prog)
8986 {
8987 	return prog->type;
8988 }
8989 
8990 int bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
8991 {
8992 	if (prog->obj->loaded)
8993 		return libbpf_err(-EBUSY);
8994 
8995 	prog->type = type;
8996 	return 0;
8997 }
8998 
8999 static bool bpf_program__is_type(const struct bpf_program *prog,
9000 				 enum bpf_prog_type type)
9001 {
9002 	return prog ? (prog->type == type) : false;
9003 }
9004 
9005 #define BPF_PROG_TYPE_FNS(NAME, TYPE)				\
9006 int bpf_program__set_##NAME(struct bpf_program *prog)		\
9007 {								\
9008 	if (!prog)						\
9009 		return libbpf_err(-EINVAL);			\
9010 	return bpf_program__set_type(prog, TYPE);			\
9011 }								\
9012 								\
9013 bool bpf_program__is_##NAME(const struct bpf_program *prog)	\
9014 {								\
9015 	return bpf_program__is_type(prog, TYPE);		\
9016 }								\
9017 
9018 BPF_PROG_TYPE_FNS(socket_filter, BPF_PROG_TYPE_SOCKET_FILTER);
9019 BPF_PROG_TYPE_FNS(lsm, BPF_PROG_TYPE_LSM);
9020 BPF_PROG_TYPE_FNS(kprobe, BPF_PROG_TYPE_KPROBE);
9021 BPF_PROG_TYPE_FNS(sched_cls, BPF_PROG_TYPE_SCHED_CLS);
9022 BPF_PROG_TYPE_FNS(sched_act, BPF_PROG_TYPE_SCHED_ACT);
9023 BPF_PROG_TYPE_FNS(tracepoint, BPF_PROG_TYPE_TRACEPOINT);
9024 BPF_PROG_TYPE_FNS(raw_tracepoint, BPF_PROG_TYPE_RAW_TRACEPOINT);
9025 BPF_PROG_TYPE_FNS(xdp, BPF_PROG_TYPE_XDP);
9026 BPF_PROG_TYPE_FNS(perf_event, BPF_PROG_TYPE_PERF_EVENT);
9027 BPF_PROG_TYPE_FNS(tracing, BPF_PROG_TYPE_TRACING);
9028 BPF_PROG_TYPE_FNS(struct_ops, BPF_PROG_TYPE_STRUCT_OPS);
9029 BPF_PROG_TYPE_FNS(extension, BPF_PROG_TYPE_EXT);
9030 BPF_PROG_TYPE_FNS(sk_lookup, BPF_PROG_TYPE_SK_LOOKUP);
9031 
9032 __alias(bpf_program__expected_attach_type)
9033 enum bpf_attach_type bpf_program__get_expected_attach_type(const struct bpf_program *prog);
9034 
9035 enum bpf_attach_type bpf_program__expected_attach_type(const struct bpf_program *prog)
9036 {
9037 	return prog->expected_attach_type;
9038 }
9039 
9040 int bpf_program__set_expected_attach_type(struct bpf_program *prog,
9041 					   enum bpf_attach_type type)
9042 {
9043 	if (prog->obj->loaded)
9044 		return libbpf_err(-EBUSY);
9045 
9046 	prog->expected_attach_type = type;
9047 	return 0;
9048 }
9049 
9050 __u32 bpf_program__flags(const struct bpf_program *prog)
9051 {
9052 	return prog->prog_flags;
9053 }
9054 
9055 int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
9056 {
9057 	if (prog->obj->loaded)
9058 		return libbpf_err(-EBUSY);
9059 
9060 	prog->prog_flags = flags;
9061 	return 0;
9062 }
9063 
9064 __u32 bpf_program__log_level(const struct bpf_program *prog)
9065 {
9066 	return prog->log_level;
9067 }
9068 
9069 int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
9070 {
9071 	if (prog->obj->loaded)
9072 		return libbpf_err(-EBUSY);
9073 
9074 	prog->log_level = log_level;
9075 	return 0;
9076 }
9077 
9078 const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
9079 {
9080 	*log_size = prog->log_size;
9081 	return prog->log_buf;
9082 }
9083 
9084 int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
9085 {
9086 	if (log_size && !log_buf)
9087 		return -EINVAL;
9088 	if (prog->log_size > UINT_MAX)
9089 		return -EINVAL;
9090 	if (prog->obj->loaded)
9091 		return -EBUSY;
9092 
9093 	prog->log_buf = log_buf;
9094 	prog->log_size = log_size;
9095 	return 0;
9096 }
9097 
9098 #define SEC_DEF(sec_pfx, ptype, atype, flags, ...) {			    \
9099 	.sec = (char *)sec_pfx,						    \
9100 	.prog_type = BPF_PROG_TYPE_##ptype,				    \
9101 	.expected_attach_type = atype,					    \
9102 	.cookie = (long)(flags),					    \
9103 	.prog_prepare_load_fn = libbpf_prepare_prog_load,		    \
9104 	__VA_ARGS__							    \
9105 }
9106 
9107 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9108 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9109 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9110 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9111 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9112 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9113 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9114 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9115 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9116 
9117 static const struct bpf_sec_def section_defs[] = {
9118 	SEC_DEF("socket",		SOCKET_FILTER, 0, SEC_NONE | SEC_SLOPPY_PFX),
9119 	SEC_DEF("sk_reuseport/migrate",	SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9120 	SEC_DEF("sk_reuseport",		SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9121 	SEC_DEF("kprobe+",		KPROBE,	0, SEC_NONE, attach_kprobe),
9122 	SEC_DEF("uprobe+",		KPROBE,	0, SEC_NONE, attach_uprobe),
9123 	SEC_DEF("kretprobe+",		KPROBE, 0, SEC_NONE, attach_kprobe),
9124 	SEC_DEF("uretprobe+",		KPROBE, 0, SEC_NONE, attach_uprobe),
9125 	SEC_DEF("kprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
9126 	SEC_DEF("kretprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
9127 	SEC_DEF("usdt+",		KPROBE,	0, SEC_NONE, attach_usdt),
9128 	SEC_DEF("tc",			SCHED_CLS, 0, SEC_NONE),
9129 	SEC_DEF("classifier",		SCHED_CLS, 0, SEC_NONE | SEC_SLOPPY_PFX | SEC_DEPRECATED),
9130 	SEC_DEF("action",		SCHED_ACT, 0, SEC_NONE | SEC_SLOPPY_PFX),
9131 	SEC_DEF("tracepoint+",		TRACEPOINT, 0, SEC_NONE, attach_tp),
9132 	SEC_DEF("tp+",			TRACEPOINT, 0, SEC_NONE, attach_tp),
9133 	SEC_DEF("raw_tracepoint+",	RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
9134 	SEC_DEF("raw_tp+",		RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
9135 	SEC_DEF("raw_tracepoint.w+",	RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
9136 	SEC_DEF("raw_tp.w+",		RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
9137 	SEC_DEF("tp_btf+",		TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
9138 	SEC_DEF("fentry+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
9139 	SEC_DEF("fmod_ret+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
9140 	SEC_DEF("fexit+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
9141 	SEC_DEF("fentry.s+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
9142 	SEC_DEF("fmod_ret.s+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
9143 	SEC_DEF("fexit.s+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
9144 	SEC_DEF("freplace+",		EXT, 0, SEC_ATTACH_BTF, attach_trace),
9145 	SEC_DEF("lsm+",			LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
9146 	SEC_DEF("lsm.s+",		LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
9147 	SEC_DEF("iter+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
9148 	SEC_DEF("iter.s+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_iter),
9149 	SEC_DEF("syscall",		SYSCALL, 0, SEC_SLEEPABLE),
9150 	SEC_DEF("xdp.frags/devmap",	XDP, BPF_XDP_DEVMAP, SEC_XDP_FRAGS),
9151 	SEC_DEF("xdp/devmap",		XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
9152 	SEC_DEF("xdp_devmap/",		XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE | SEC_DEPRECATED),
9153 	SEC_DEF("xdp.frags/cpumap",	XDP, BPF_XDP_CPUMAP, SEC_XDP_FRAGS),
9154 	SEC_DEF("xdp/cpumap",		XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
9155 	SEC_DEF("xdp_cpumap/",		XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE | SEC_DEPRECATED),
9156 	SEC_DEF("xdp.frags",		XDP, BPF_XDP, SEC_XDP_FRAGS),
9157 	SEC_DEF("xdp",			XDP, BPF_XDP, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
9158 	SEC_DEF("perf_event",		PERF_EVENT, 0, SEC_NONE | SEC_SLOPPY_PFX),
9159 	SEC_DEF("lwt_in",		LWT_IN, 0, SEC_NONE | SEC_SLOPPY_PFX),
9160 	SEC_DEF("lwt_out",		LWT_OUT, 0, SEC_NONE | SEC_SLOPPY_PFX),
9161 	SEC_DEF("lwt_xmit",		LWT_XMIT, 0, SEC_NONE | SEC_SLOPPY_PFX),
9162 	SEC_DEF("lwt_seg6local",	LWT_SEG6LOCAL, 0, SEC_NONE | SEC_SLOPPY_PFX),
9163 	SEC_DEF("cgroup_skb/ingress",	CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
9164 	SEC_DEF("cgroup_skb/egress",	CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
9165 	SEC_DEF("cgroup/skb",		CGROUP_SKB, 0, SEC_NONE | SEC_SLOPPY_PFX),
9166 	SEC_DEF("cgroup/sock_create",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9167 	SEC_DEF("cgroup/sock_release",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9168 	SEC_DEF("cgroup/sock",		CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
9169 	SEC_DEF("cgroup/post_bind4",	CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9170 	SEC_DEF("cgroup/post_bind6",	CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9171 	SEC_DEF("cgroup/dev",		CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
9172 	SEC_DEF("sockops",		SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
9173 	SEC_DEF("sk_skb/stream_parser",	SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
9174 	SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
9175 	SEC_DEF("sk_skb",		SK_SKB, 0, SEC_NONE | SEC_SLOPPY_PFX),
9176 	SEC_DEF("sk_msg",		SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
9177 	SEC_DEF("lirc_mode2",		LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
9178 	SEC_DEF("flow_dissector",	FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
9179 	SEC_DEF("cgroup/bind4",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9180 	SEC_DEF("cgroup/bind6",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9181 	SEC_DEF("cgroup/connect4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9182 	SEC_DEF("cgroup/connect6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9183 	SEC_DEF("cgroup/sendmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9184 	SEC_DEF("cgroup/sendmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9185 	SEC_DEF("cgroup/recvmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9186 	SEC_DEF("cgroup/recvmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9187 	SEC_DEF("cgroup/getpeername4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9188 	SEC_DEF("cgroup/getpeername6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9189 	SEC_DEF("cgroup/getsockname4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9190 	SEC_DEF("cgroup/getsockname6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9191 	SEC_DEF("cgroup/sysctl",	CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9192 	SEC_DEF("cgroup/getsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9193 	SEC_DEF("cgroup/setsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9194 	SEC_DEF("struct_ops+",		STRUCT_OPS, 0, SEC_NONE),
9195 	SEC_DEF("sk_lookup",		SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9196 };
9197 
9198 static size_t custom_sec_def_cnt;
9199 static struct bpf_sec_def *custom_sec_defs;
9200 static struct bpf_sec_def custom_fallback_def;
9201 static bool has_custom_fallback_def;
9202 
9203 static int last_custom_sec_def_handler_id;
9204 
9205 int libbpf_register_prog_handler(const char *sec,
9206 				 enum bpf_prog_type prog_type,
9207 				 enum bpf_attach_type exp_attach_type,
9208 				 const struct libbpf_prog_handler_opts *opts)
9209 {
9210 	struct bpf_sec_def *sec_def;
9211 
9212 	if (!OPTS_VALID(opts, libbpf_prog_handler_opts))
9213 		return libbpf_err(-EINVAL);
9214 
9215 	if (last_custom_sec_def_handler_id == INT_MAX) /* prevent overflow */
9216 		return libbpf_err(-E2BIG);
9217 
9218 	if (sec) {
9219 		sec_def = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt + 1,
9220 					      sizeof(*sec_def));
9221 		if (!sec_def)
9222 			return libbpf_err(-ENOMEM);
9223 
9224 		custom_sec_defs = sec_def;
9225 		sec_def = &custom_sec_defs[custom_sec_def_cnt];
9226 	} else {
9227 		if (has_custom_fallback_def)
9228 			return libbpf_err(-EBUSY);
9229 
9230 		sec_def = &custom_fallback_def;
9231 	}
9232 
9233 	sec_def->sec = sec ? strdup(sec) : NULL;
9234 	if (sec && !sec_def->sec)
9235 		return libbpf_err(-ENOMEM);
9236 
9237 	sec_def->prog_type = prog_type;
9238 	sec_def->expected_attach_type = exp_attach_type;
9239 	sec_def->cookie = OPTS_GET(opts, cookie, 0);
9240 
9241 	sec_def->prog_setup_fn = OPTS_GET(opts, prog_setup_fn, NULL);
9242 	sec_def->prog_prepare_load_fn = OPTS_GET(opts, prog_prepare_load_fn, NULL);
9243 	sec_def->prog_attach_fn = OPTS_GET(opts, prog_attach_fn, NULL);
9244 
9245 	sec_def->handler_id = ++last_custom_sec_def_handler_id;
9246 
9247 	if (sec)
9248 		custom_sec_def_cnt++;
9249 	else
9250 		has_custom_fallback_def = true;
9251 
9252 	return sec_def->handler_id;
9253 }
9254 
9255 int libbpf_unregister_prog_handler(int handler_id)
9256 {
9257 	struct bpf_sec_def *sec_defs;
9258 	int i;
9259 
9260 	if (handler_id <= 0)
9261 		return libbpf_err(-EINVAL);
9262 
9263 	if (has_custom_fallback_def && custom_fallback_def.handler_id == handler_id) {
9264 		memset(&custom_fallback_def, 0, sizeof(custom_fallback_def));
9265 		has_custom_fallback_def = false;
9266 		return 0;
9267 	}
9268 
9269 	for (i = 0; i < custom_sec_def_cnt; i++) {
9270 		if (custom_sec_defs[i].handler_id == handler_id)
9271 			break;
9272 	}
9273 
9274 	if (i == custom_sec_def_cnt)
9275 		return libbpf_err(-ENOENT);
9276 
9277 	free(custom_sec_defs[i].sec);
9278 	for (i = i + 1; i < custom_sec_def_cnt; i++)
9279 		custom_sec_defs[i - 1] = custom_sec_defs[i];
9280 	custom_sec_def_cnt--;
9281 
9282 	/* try to shrink the array, but it's ok if we couldn't */
9283 	sec_defs = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt, sizeof(*sec_defs));
9284 	if (sec_defs)
9285 		custom_sec_defs = sec_defs;
9286 
9287 	return 0;
9288 }
9289 
9290 static bool sec_def_matches(const struct bpf_sec_def *sec_def, const char *sec_name,
9291 			    bool allow_sloppy)
9292 {
9293 	size_t len = strlen(sec_def->sec);
9294 
9295 	/* "type/" always has to have proper SEC("type/extras") form */
9296 	if (sec_def->sec[len - 1] == '/') {
9297 		if (str_has_pfx(sec_name, sec_def->sec))
9298 			return true;
9299 		return false;
9300 	}
9301 
9302 	/* "type+" means it can be either exact SEC("type") or
9303 	 * well-formed SEC("type/extras") with proper '/' separator
9304 	 */
9305 	if (sec_def->sec[len - 1] == '+') {
9306 		len--;
9307 		/* not even a prefix */
9308 		if (strncmp(sec_name, sec_def->sec, len) != 0)
9309 			return false;
9310 		/* exact match or has '/' separator */
9311 		if (sec_name[len] == '\0' || sec_name[len] == '/')
9312 			return true;
9313 		return false;
9314 	}
9315 
9316 	/* SEC_SLOPPY_PFX definitions are allowed to be just prefix
9317 	 * matches, unless strict section name mode
9318 	 * (LIBBPF_STRICT_SEC_NAME) is enabled, in which case the
9319 	 * match has to be exact.
9320 	 */
9321 	if (allow_sloppy && str_has_pfx(sec_name, sec_def->sec))
9322 		return true;
9323 
9324 	/* Definitions not marked SEC_SLOPPY_PFX (e.g.,
9325 	 * SEC("syscall")) are exact matches in both modes.
9326 	 */
9327 	return strcmp(sec_name, sec_def->sec) == 0;
9328 }
9329 
9330 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
9331 {
9332 	const struct bpf_sec_def *sec_def;
9333 	int i, n;
9334 	bool strict = libbpf_mode & LIBBPF_STRICT_SEC_NAME, allow_sloppy;
9335 
9336 	n = custom_sec_def_cnt;
9337 	for (i = 0; i < n; i++) {
9338 		sec_def = &custom_sec_defs[i];
9339 		if (sec_def_matches(sec_def, sec_name, false))
9340 			return sec_def;
9341 	}
9342 
9343 	n = ARRAY_SIZE(section_defs);
9344 	for (i = 0; i < n; i++) {
9345 		sec_def = &section_defs[i];
9346 		allow_sloppy = (sec_def->cookie & SEC_SLOPPY_PFX) && !strict;
9347 		if (sec_def_matches(sec_def, sec_name, allow_sloppy))
9348 			return sec_def;
9349 	}
9350 
9351 	if (has_custom_fallback_def)
9352 		return &custom_fallback_def;
9353 
9354 	return NULL;
9355 }
9356 
9357 #define MAX_TYPE_NAME_SIZE 32
9358 
9359 static char *libbpf_get_type_names(bool attach_type)
9360 {
9361 	int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
9362 	char *buf;
9363 
9364 	buf = malloc(len);
9365 	if (!buf)
9366 		return NULL;
9367 
9368 	buf[0] = '\0';
9369 	/* Forge string buf with all available names */
9370 	for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
9371 		const struct bpf_sec_def *sec_def = &section_defs[i];
9372 
9373 		if (attach_type) {
9374 			if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
9375 				continue;
9376 
9377 			if (!(sec_def->cookie & SEC_ATTACHABLE))
9378 				continue;
9379 		}
9380 
9381 		if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
9382 			free(buf);
9383 			return NULL;
9384 		}
9385 		strcat(buf, " ");
9386 		strcat(buf, section_defs[i].sec);
9387 	}
9388 
9389 	return buf;
9390 }
9391 
9392 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
9393 			     enum bpf_attach_type *expected_attach_type)
9394 {
9395 	const struct bpf_sec_def *sec_def;
9396 	char *type_names;
9397 
9398 	if (!name)
9399 		return libbpf_err(-EINVAL);
9400 
9401 	sec_def = find_sec_def(name);
9402 	if (sec_def) {
9403 		*prog_type = sec_def->prog_type;
9404 		*expected_attach_type = sec_def->expected_attach_type;
9405 		return 0;
9406 	}
9407 
9408 	pr_debug("failed to guess program type from ELF section '%s'\n", name);
9409 	type_names = libbpf_get_type_names(false);
9410 	if (type_names != NULL) {
9411 		pr_debug("supported section(type) names are:%s\n", type_names);
9412 		free(type_names);
9413 	}
9414 
9415 	return libbpf_err(-ESRCH);
9416 }
9417 
9418 const char *libbpf_bpf_attach_type_str(enum bpf_attach_type t)
9419 {
9420 	if (t < 0 || t >= ARRAY_SIZE(attach_type_name))
9421 		return NULL;
9422 
9423 	return attach_type_name[t];
9424 }
9425 
9426 const char *libbpf_bpf_map_type_str(enum bpf_map_type t)
9427 {
9428 	if (t < 0 || t >= ARRAY_SIZE(map_type_name))
9429 		return NULL;
9430 
9431 	return map_type_name[t];
9432 }
9433 
9434 const char *libbpf_bpf_prog_type_str(enum bpf_prog_type t)
9435 {
9436 	if (t < 0 || t >= ARRAY_SIZE(prog_type_name))
9437 		return NULL;
9438 
9439 	return prog_type_name[t];
9440 }
9441 
9442 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
9443 						     size_t offset)
9444 {
9445 	struct bpf_map *map;
9446 	size_t i;
9447 
9448 	for (i = 0; i < obj->nr_maps; i++) {
9449 		map = &obj->maps[i];
9450 		if (!bpf_map__is_struct_ops(map))
9451 			continue;
9452 		if (map->sec_offset <= offset &&
9453 		    offset - map->sec_offset < map->def.value_size)
9454 			return map;
9455 	}
9456 
9457 	return NULL;
9458 }
9459 
9460 /* Collect the reloc from ELF and populate the st_ops->progs[] */
9461 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
9462 					    Elf64_Shdr *shdr, Elf_Data *data)
9463 {
9464 	const struct btf_member *member;
9465 	struct bpf_struct_ops *st_ops;
9466 	struct bpf_program *prog;
9467 	unsigned int shdr_idx;
9468 	const struct btf *btf;
9469 	struct bpf_map *map;
9470 	unsigned int moff, insn_idx;
9471 	const char *name;
9472 	__u32 member_idx;
9473 	Elf64_Sym *sym;
9474 	Elf64_Rel *rel;
9475 	int i, nrels;
9476 
9477 	btf = obj->btf;
9478 	nrels = shdr->sh_size / shdr->sh_entsize;
9479 	for (i = 0; i < nrels; i++) {
9480 		rel = elf_rel_by_idx(data, i);
9481 		if (!rel) {
9482 			pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
9483 			return -LIBBPF_ERRNO__FORMAT;
9484 		}
9485 
9486 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
9487 		if (!sym) {
9488 			pr_warn("struct_ops reloc: symbol %zx not found\n",
9489 				(size_t)ELF64_R_SYM(rel->r_info));
9490 			return -LIBBPF_ERRNO__FORMAT;
9491 		}
9492 
9493 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
9494 		map = find_struct_ops_map_by_offset(obj, rel->r_offset);
9495 		if (!map) {
9496 			pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
9497 				(size_t)rel->r_offset);
9498 			return -EINVAL;
9499 		}
9500 
9501 		moff = rel->r_offset - map->sec_offset;
9502 		shdr_idx = sym->st_shndx;
9503 		st_ops = map->st_ops;
9504 		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",
9505 			 map->name,
9506 			 (long long)(rel->r_info >> 32),
9507 			 (long long)sym->st_value,
9508 			 shdr_idx, (size_t)rel->r_offset,
9509 			 map->sec_offset, sym->st_name, name);
9510 
9511 		if (shdr_idx >= SHN_LORESERVE) {
9512 			pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
9513 				map->name, (size_t)rel->r_offset, shdr_idx);
9514 			return -LIBBPF_ERRNO__RELOC;
9515 		}
9516 		if (sym->st_value % BPF_INSN_SZ) {
9517 			pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
9518 				map->name, (unsigned long long)sym->st_value);
9519 			return -LIBBPF_ERRNO__FORMAT;
9520 		}
9521 		insn_idx = sym->st_value / BPF_INSN_SZ;
9522 
9523 		member = find_member_by_offset(st_ops->type, moff * 8);
9524 		if (!member) {
9525 			pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
9526 				map->name, moff);
9527 			return -EINVAL;
9528 		}
9529 		member_idx = member - btf_members(st_ops->type);
9530 		name = btf__name_by_offset(btf, member->name_off);
9531 
9532 		if (!resolve_func_ptr(btf, member->type, NULL)) {
9533 			pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
9534 				map->name, name);
9535 			return -EINVAL;
9536 		}
9537 
9538 		prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
9539 		if (!prog) {
9540 			pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
9541 				map->name, shdr_idx, name);
9542 			return -EINVAL;
9543 		}
9544 
9545 		/* prevent the use of BPF prog with invalid type */
9546 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
9547 			pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
9548 				map->name, prog->name);
9549 			return -EINVAL;
9550 		}
9551 
9552 		/* if we haven't yet processed this BPF program, record proper
9553 		 * attach_btf_id and member_idx
9554 		 */
9555 		if (!prog->attach_btf_id) {
9556 			prog->attach_btf_id = st_ops->type_id;
9557 			prog->expected_attach_type = member_idx;
9558 		}
9559 
9560 		/* struct_ops BPF prog can be re-used between multiple
9561 		 * .struct_ops as long as it's the same struct_ops struct
9562 		 * definition and the same function pointer field
9563 		 */
9564 		if (prog->attach_btf_id != st_ops->type_id ||
9565 		    prog->expected_attach_type != member_idx) {
9566 			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",
9567 				map->name, prog->name, prog->sec_name, prog->type,
9568 				prog->attach_btf_id, prog->expected_attach_type, name);
9569 			return -EINVAL;
9570 		}
9571 
9572 		st_ops->progs[member_idx] = prog;
9573 	}
9574 
9575 	return 0;
9576 }
9577 
9578 #define BTF_TRACE_PREFIX "btf_trace_"
9579 #define BTF_LSM_PREFIX "bpf_lsm_"
9580 #define BTF_ITER_PREFIX "bpf_iter_"
9581 #define BTF_MAX_NAME_SIZE 128
9582 
9583 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
9584 				const char **prefix, int *kind)
9585 {
9586 	switch (attach_type) {
9587 	case BPF_TRACE_RAW_TP:
9588 		*prefix = BTF_TRACE_PREFIX;
9589 		*kind = BTF_KIND_TYPEDEF;
9590 		break;
9591 	case BPF_LSM_MAC:
9592 		*prefix = BTF_LSM_PREFIX;
9593 		*kind = BTF_KIND_FUNC;
9594 		break;
9595 	case BPF_TRACE_ITER:
9596 		*prefix = BTF_ITER_PREFIX;
9597 		*kind = BTF_KIND_FUNC;
9598 		break;
9599 	default:
9600 		*prefix = "";
9601 		*kind = BTF_KIND_FUNC;
9602 	}
9603 }
9604 
9605 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
9606 				   const char *name, __u32 kind)
9607 {
9608 	char btf_type_name[BTF_MAX_NAME_SIZE];
9609 	int ret;
9610 
9611 	ret = snprintf(btf_type_name, sizeof(btf_type_name),
9612 		       "%s%s", prefix, name);
9613 	/* snprintf returns the number of characters written excluding the
9614 	 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
9615 	 * indicates truncation.
9616 	 */
9617 	if (ret < 0 || ret >= sizeof(btf_type_name))
9618 		return -ENAMETOOLONG;
9619 	return btf__find_by_name_kind(btf, btf_type_name, kind);
9620 }
9621 
9622 static inline int find_attach_btf_id(struct btf *btf, const char *name,
9623 				     enum bpf_attach_type attach_type)
9624 {
9625 	const char *prefix;
9626 	int kind;
9627 
9628 	btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
9629 	return find_btf_by_prefix_kind(btf, prefix, name, kind);
9630 }
9631 
9632 int libbpf_find_vmlinux_btf_id(const char *name,
9633 			       enum bpf_attach_type attach_type)
9634 {
9635 	struct btf *btf;
9636 	int err;
9637 
9638 	btf = btf__load_vmlinux_btf();
9639 	err = libbpf_get_error(btf);
9640 	if (err) {
9641 		pr_warn("vmlinux BTF is not found\n");
9642 		return libbpf_err(err);
9643 	}
9644 
9645 	err = find_attach_btf_id(btf, name, attach_type);
9646 	if (err <= 0)
9647 		pr_warn("%s is not found in vmlinux BTF\n", name);
9648 
9649 	btf__free(btf);
9650 	return libbpf_err(err);
9651 }
9652 
9653 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
9654 {
9655 	struct bpf_prog_info info = {};
9656 	__u32 info_len = sizeof(info);
9657 	struct btf *btf;
9658 	int err;
9659 
9660 	err = bpf_obj_get_info_by_fd(attach_prog_fd, &info, &info_len);
9661 	if (err) {
9662 		pr_warn("failed bpf_obj_get_info_by_fd for FD %d: %d\n",
9663 			attach_prog_fd, err);
9664 		return err;
9665 	}
9666 
9667 	err = -EINVAL;
9668 	if (!info.btf_id) {
9669 		pr_warn("The target program doesn't have BTF\n");
9670 		goto out;
9671 	}
9672 	btf = btf__load_from_kernel_by_id(info.btf_id);
9673 	err = libbpf_get_error(btf);
9674 	if (err) {
9675 		pr_warn("Failed to get BTF %d of the program: %d\n", info.btf_id, err);
9676 		goto out;
9677 	}
9678 	err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
9679 	btf__free(btf);
9680 	if (err <= 0) {
9681 		pr_warn("%s is not found in prog's BTF\n", name);
9682 		goto out;
9683 	}
9684 out:
9685 	return err;
9686 }
9687 
9688 static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
9689 			      enum bpf_attach_type attach_type,
9690 			      int *btf_obj_fd, int *btf_type_id)
9691 {
9692 	int ret, i;
9693 
9694 	ret = find_attach_btf_id(obj->btf_vmlinux, attach_name, attach_type);
9695 	if (ret > 0) {
9696 		*btf_obj_fd = 0; /* vmlinux BTF */
9697 		*btf_type_id = ret;
9698 		return 0;
9699 	}
9700 	if (ret != -ENOENT)
9701 		return ret;
9702 
9703 	ret = load_module_btfs(obj);
9704 	if (ret)
9705 		return ret;
9706 
9707 	for (i = 0; i < obj->btf_module_cnt; i++) {
9708 		const struct module_btf *mod = &obj->btf_modules[i];
9709 
9710 		ret = find_attach_btf_id(mod->btf, attach_name, attach_type);
9711 		if (ret > 0) {
9712 			*btf_obj_fd = mod->fd;
9713 			*btf_type_id = ret;
9714 			return 0;
9715 		}
9716 		if (ret == -ENOENT)
9717 			continue;
9718 
9719 		return ret;
9720 	}
9721 
9722 	return -ESRCH;
9723 }
9724 
9725 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
9726 				     int *btf_obj_fd, int *btf_type_id)
9727 {
9728 	enum bpf_attach_type attach_type = prog->expected_attach_type;
9729 	__u32 attach_prog_fd = prog->attach_prog_fd;
9730 	int err = 0;
9731 
9732 	/* BPF program's BTF ID */
9733 	if (attach_prog_fd) {
9734 		err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd);
9735 		if (err < 0) {
9736 			pr_warn("failed to find BPF program (FD %d) BTF ID for '%s': %d\n",
9737 				 attach_prog_fd, attach_name, err);
9738 			return err;
9739 		}
9740 		*btf_obj_fd = 0;
9741 		*btf_type_id = err;
9742 		return 0;
9743 	}
9744 
9745 	/* kernel/module BTF ID */
9746 	if (prog->obj->gen_loader) {
9747 		bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
9748 		*btf_obj_fd = 0;
9749 		*btf_type_id = 1;
9750 	} else {
9751 		err = find_kernel_btf_id(prog->obj, attach_name, attach_type, btf_obj_fd, btf_type_id);
9752 	}
9753 	if (err) {
9754 		pr_warn("failed to find kernel BTF type ID of '%s': %d\n", attach_name, err);
9755 		return err;
9756 	}
9757 	return 0;
9758 }
9759 
9760 int libbpf_attach_type_by_name(const char *name,
9761 			       enum bpf_attach_type *attach_type)
9762 {
9763 	char *type_names;
9764 	const struct bpf_sec_def *sec_def;
9765 
9766 	if (!name)
9767 		return libbpf_err(-EINVAL);
9768 
9769 	sec_def = find_sec_def(name);
9770 	if (!sec_def) {
9771 		pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
9772 		type_names = libbpf_get_type_names(true);
9773 		if (type_names != NULL) {
9774 			pr_debug("attachable section(type) names are:%s\n", type_names);
9775 			free(type_names);
9776 		}
9777 
9778 		return libbpf_err(-EINVAL);
9779 	}
9780 
9781 	if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
9782 		return libbpf_err(-EINVAL);
9783 	if (!(sec_def->cookie & SEC_ATTACHABLE))
9784 		return libbpf_err(-EINVAL);
9785 
9786 	*attach_type = sec_def->expected_attach_type;
9787 	return 0;
9788 }
9789 
9790 int bpf_map__fd(const struct bpf_map *map)
9791 {
9792 	return map ? map->fd : libbpf_err(-EINVAL);
9793 }
9794 
9795 const struct bpf_map_def *bpf_map__def(const struct bpf_map *map)
9796 {
9797 	return map ? &map->def : libbpf_err_ptr(-EINVAL);
9798 }
9799 
9800 static bool map_uses_real_name(const struct bpf_map *map)
9801 {
9802 	/* Since libbpf started to support custom .data.* and .rodata.* maps,
9803 	 * their user-visible name differs from kernel-visible name. Users see
9804 	 * such map's corresponding ELF section name as a map name.
9805 	 * This check distinguishes .data/.rodata from .data.* and .rodata.*
9806 	 * maps to know which name has to be returned to the user.
9807 	 */
9808 	if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
9809 		return true;
9810 	if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
9811 		return true;
9812 	return false;
9813 }
9814 
9815 const char *bpf_map__name(const struct bpf_map *map)
9816 {
9817 	if (!map)
9818 		return NULL;
9819 
9820 	if (map_uses_real_name(map))
9821 		return map->real_name;
9822 
9823 	return map->name;
9824 }
9825 
9826 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
9827 {
9828 	return map->def.type;
9829 }
9830 
9831 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
9832 {
9833 	if (map->fd >= 0)
9834 		return libbpf_err(-EBUSY);
9835 	map->def.type = type;
9836 	return 0;
9837 }
9838 
9839 __u32 bpf_map__map_flags(const struct bpf_map *map)
9840 {
9841 	return map->def.map_flags;
9842 }
9843 
9844 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
9845 {
9846 	if (map->fd >= 0)
9847 		return libbpf_err(-EBUSY);
9848 	map->def.map_flags = flags;
9849 	return 0;
9850 }
9851 
9852 __u64 bpf_map__map_extra(const struct bpf_map *map)
9853 {
9854 	return map->map_extra;
9855 }
9856 
9857 int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
9858 {
9859 	if (map->fd >= 0)
9860 		return libbpf_err(-EBUSY);
9861 	map->map_extra = map_extra;
9862 	return 0;
9863 }
9864 
9865 __u32 bpf_map__numa_node(const struct bpf_map *map)
9866 {
9867 	return map->numa_node;
9868 }
9869 
9870 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
9871 {
9872 	if (map->fd >= 0)
9873 		return libbpf_err(-EBUSY);
9874 	map->numa_node = numa_node;
9875 	return 0;
9876 }
9877 
9878 __u32 bpf_map__key_size(const struct bpf_map *map)
9879 {
9880 	return map->def.key_size;
9881 }
9882 
9883 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
9884 {
9885 	if (map->fd >= 0)
9886 		return libbpf_err(-EBUSY);
9887 	map->def.key_size = size;
9888 	return 0;
9889 }
9890 
9891 __u32 bpf_map__value_size(const struct bpf_map *map)
9892 {
9893 	return map->def.value_size;
9894 }
9895 
9896 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
9897 {
9898 	if (map->fd >= 0)
9899 		return libbpf_err(-EBUSY);
9900 	map->def.value_size = size;
9901 	return 0;
9902 }
9903 
9904 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
9905 {
9906 	return map ? map->btf_key_type_id : 0;
9907 }
9908 
9909 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
9910 {
9911 	return map ? map->btf_value_type_id : 0;
9912 }
9913 
9914 int bpf_map__set_priv(struct bpf_map *map, void *priv,
9915 		     bpf_map_clear_priv_t clear_priv)
9916 {
9917 	if (!map)
9918 		return libbpf_err(-EINVAL);
9919 
9920 	if (map->priv) {
9921 		if (map->clear_priv)
9922 			map->clear_priv(map, map->priv);
9923 	}
9924 
9925 	map->priv = priv;
9926 	map->clear_priv = clear_priv;
9927 	return 0;
9928 }
9929 
9930 void *bpf_map__priv(const struct bpf_map *map)
9931 {
9932 	return map ? map->priv : libbpf_err_ptr(-EINVAL);
9933 }
9934 
9935 int bpf_map__set_initial_value(struct bpf_map *map,
9936 			       const void *data, size_t size)
9937 {
9938 	if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG ||
9939 	    size != map->def.value_size || map->fd >= 0)
9940 		return libbpf_err(-EINVAL);
9941 
9942 	memcpy(map->mmaped, data, size);
9943 	return 0;
9944 }
9945 
9946 const void *bpf_map__initial_value(struct bpf_map *map, size_t *psize)
9947 {
9948 	if (!map->mmaped)
9949 		return NULL;
9950 	*psize = map->def.value_size;
9951 	return map->mmaped;
9952 }
9953 
9954 bool bpf_map__is_offload_neutral(const struct bpf_map *map)
9955 {
9956 	return map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY;
9957 }
9958 
9959 bool bpf_map__is_internal(const struct bpf_map *map)
9960 {
9961 	return map->libbpf_type != LIBBPF_MAP_UNSPEC;
9962 }
9963 
9964 __u32 bpf_map__ifindex(const struct bpf_map *map)
9965 {
9966 	return map->map_ifindex;
9967 }
9968 
9969 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
9970 {
9971 	if (map->fd >= 0)
9972 		return libbpf_err(-EBUSY);
9973 	map->map_ifindex = ifindex;
9974 	return 0;
9975 }
9976 
9977 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
9978 {
9979 	if (!bpf_map_type__is_map_in_map(map->def.type)) {
9980 		pr_warn("error: unsupported map type\n");
9981 		return libbpf_err(-EINVAL);
9982 	}
9983 	if (map->inner_map_fd != -1) {
9984 		pr_warn("error: inner_map_fd already specified\n");
9985 		return libbpf_err(-EINVAL);
9986 	}
9987 	if (map->inner_map) {
9988 		bpf_map__destroy(map->inner_map);
9989 		zfree(&map->inner_map);
9990 	}
9991 	map->inner_map_fd = fd;
9992 	return 0;
9993 }
9994 
9995 static struct bpf_map *
9996 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
9997 {
9998 	ssize_t idx;
9999 	struct bpf_map *s, *e;
10000 
10001 	if (!obj || !obj->maps)
10002 		return errno = EINVAL, NULL;
10003 
10004 	s = obj->maps;
10005 	e = obj->maps + obj->nr_maps;
10006 
10007 	if ((m < s) || (m >= e)) {
10008 		pr_warn("error in %s: map handler doesn't belong to object\n",
10009 			 __func__);
10010 		return errno = EINVAL, NULL;
10011 	}
10012 
10013 	idx = (m - obj->maps) + i;
10014 	if (idx >= obj->nr_maps || idx < 0)
10015 		return NULL;
10016 	return &obj->maps[idx];
10017 }
10018 
10019 struct bpf_map *
10020 bpf_map__next(const struct bpf_map *prev, const struct bpf_object *obj)
10021 {
10022 	return bpf_object__next_map(obj, prev);
10023 }
10024 
10025 struct bpf_map *
10026 bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
10027 {
10028 	if (prev == NULL)
10029 		return obj->maps;
10030 
10031 	return __bpf_map__iter(prev, obj, 1);
10032 }
10033 
10034 struct bpf_map *
10035 bpf_map__prev(const struct bpf_map *next, const struct bpf_object *obj)
10036 {
10037 	return bpf_object__prev_map(obj, next);
10038 }
10039 
10040 struct bpf_map *
10041 bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
10042 {
10043 	if (next == NULL) {
10044 		if (!obj->nr_maps)
10045 			return NULL;
10046 		return obj->maps + obj->nr_maps - 1;
10047 	}
10048 
10049 	return __bpf_map__iter(next, obj, -1);
10050 }
10051 
10052 struct bpf_map *
10053 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
10054 {
10055 	struct bpf_map *pos;
10056 
10057 	bpf_object__for_each_map(pos, obj) {
10058 		/* if it's a special internal map name (which always starts
10059 		 * with dot) then check if that special name matches the
10060 		 * real map name (ELF section name)
10061 		 */
10062 		if (name[0] == '.') {
10063 			if (pos->real_name && strcmp(pos->real_name, name) == 0)
10064 				return pos;
10065 			continue;
10066 		}
10067 		/* otherwise map name has to be an exact match */
10068 		if (map_uses_real_name(pos)) {
10069 			if (strcmp(pos->real_name, name) == 0)
10070 				return pos;
10071 			continue;
10072 		}
10073 		if (strcmp(pos->name, name) == 0)
10074 			return pos;
10075 	}
10076 	return errno = ENOENT, NULL;
10077 }
10078 
10079 int
10080 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
10081 {
10082 	return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
10083 }
10084 
10085 struct bpf_map *
10086 bpf_object__find_map_by_offset(struct bpf_object *obj, size_t offset)
10087 {
10088 	return libbpf_err_ptr(-ENOTSUP);
10089 }
10090 
10091 static int validate_map_op(const struct bpf_map *map, size_t key_sz,
10092 			   size_t value_sz, bool check_value_sz)
10093 {
10094 	if (map->fd <= 0)
10095 		return -ENOENT;
10096 
10097 	if (map->def.key_size != key_sz) {
10098 		pr_warn("map '%s': unexpected key size %zu provided, expected %u\n",
10099 			map->name, key_sz, map->def.key_size);
10100 		return -EINVAL;
10101 	}
10102 
10103 	if (!check_value_sz)
10104 		return 0;
10105 
10106 	switch (map->def.type) {
10107 	case BPF_MAP_TYPE_PERCPU_ARRAY:
10108 	case BPF_MAP_TYPE_PERCPU_HASH:
10109 	case BPF_MAP_TYPE_LRU_PERCPU_HASH:
10110 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: {
10111 		int num_cpu = libbpf_num_possible_cpus();
10112 		size_t elem_sz = roundup(map->def.value_size, 8);
10113 
10114 		if (value_sz != num_cpu * elem_sz) {
10115 			pr_warn("map '%s': unexpected value size %zu provided for per-CPU map, expected %d * %zu = %zd\n",
10116 				map->name, value_sz, num_cpu, elem_sz, num_cpu * elem_sz);
10117 			return -EINVAL;
10118 		}
10119 		break;
10120 	}
10121 	default:
10122 		if (map->def.value_size != value_sz) {
10123 			pr_warn("map '%s': unexpected value size %zu provided, expected %u\n",
10124 				map->name, value_sz, map->def.value_size);
10125 			return -EINVAL;
10126 		}
10127 		break;
10128 	}
10129 	return 0;
10130 }
10131 
10132 int bpf_map__lookup_elem(const struct bpf_map *map,
10133 			 const void *key, size_t key_sz,
10134 			 void *value, size_t value_sz, __u64 flags)
10135 {
10136 	int err;
10137 
10138 	err = validate_map_op(map, key_sz, value_sz, true);
10139 	if (err)
10140 		return libbpf_err(err);
10141 
10142 	return bpf_map_lookup_elem_flags(map->fd, key, value, flags);
10143 }
10144 
10145 int bpf_map__update_elem(const struct bpf_map *map,
10146 			 const void *key, size_t key_sz,
10147 			 const void *value, size_t value_sz, __u64 flags)
10148 {
10149 	int err;
10150 
10151 	err = validate_map_op(map, key_sz, value_sz, true);
10152 	if (err)
10153 		return libbpf_err(err);
10154 
10155 	return bpf_map_update_elem(map->fd, key, value, flags);
10156 }
10157 
10158 int bpf_map__delete_elem(const struct bpf_map *map,
10159 			 const void *key, size_t key_sz, __u64 flags)
10160 {
10161 	int err;
10162 
10163 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
10164 	if (err)
10165 		return libbpf_err(err);
10166 
10167 	return bpf_map_delete_elem_flags(map->fd, key, flags);
10168 }
10169 
10170 int bpf_map__lookup_and_delete_elem(const struct bpf_map *map,
10171 				    const void *key, size_t key_sz,
10172 				    void *value, size_t value_sz, __u64 flags)
10173 {
10174 	int err;
10175 
10176 	err = validate_map_op(map, key_sz, value_sz, true);
10177 	if (err)
10178 		return libbpf_err(err);
10179 
10180 	return bpf_map_lookup_and_delete_elem_flags(map->fd, key, value, flags);
10181 }
10182 
10183 int bpf_map__get_next_key(const struct bpf_map *map,
10184 			  const void *cur_key, void *next_key, size_t key_sz)
10185 {
10186 	int err;
10187 
10188 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
10189 	if (err)
10190 		return libbpf_err(err);
10191 
10192 	return bpf_map_get_next_key(map->fd, cur_key, next_key);
10193 }
10194 
10195 long libbpf_get_error(const void *ptr)
10196 {
10197 	if (!IS_ERR_OR_NULL(ptr))
10198 		return 0;
10199 
10200 	if (IS_ERR(ptr))
10201 		errno = -PTR_ERR(ptr);
10202 
10203 	/* If ptr == NULL, then errno should be already set by the failing
10204 	 * API, because libbpf never returns NULL on success and it now always
10205 	 * sets errno on error. So no extra errno handling for ptr == NULL
10206 	 * case.
10207 	 */
10208 	return -errno;
10209 }
10210 
10211 __attribute__((alias("bpf_prog_load_xattr2")))
10212 int bpf_prog_load_xattr(const struct bpf_prog_load_attr *attr,
10213 			struct bpf_object **pobj, int *prog_fd);
10214 
10215 static int bpf_prog_load_xattr2(const struct bpf_prog_load_attr *attr,
10216 				struct bpf_object **pobj, int *prog_fd)
10217 {
10218 	struct bpf_object_open_attr open_attr = {};
10219 	struct bpf_program *prog, *first_prog = NULL;
10220 	struct bpf_object *obj;
10221 	struct bpf_map *map;
10222 	int err;
10223 
10224 	if (!attr)
10225 		return libbpf_err(-EINVAL);
10226 	if (!attr->file)
10227 		return libbpf_err(-EINVAL);
10228 
10229 	open_attr.file = attr->file;
10230 	open_attr.prog_type = attr->prog_type;
10231 
10232 	obj = __bpf_object__open_xattr(&open_attr, 0);
10233 	err = libbpf_get_error(obj);
10234 	if (err)
10235 		return libbpf_err(-ENOENT);
10236 
10237 	bpf_object__for_each_program(prog, obj) {
10238 		enum bpf_attach_type attach_type = attr->expected_attach_type;
10239 		/*
10240 		 * to preserve backwards compatibility, bpf_prog_load treats
10241 		 * attr->prog_type, if specified, as an override to whatever
10242 		 * bpf_object__open guessed
10243 		 */
10244 		if (attr->prog_type != BPF_PROG_TYPE_UNSPEC) {
10245 			prog->type = attr->prog_type;
10246 			prog->expected_attach_type = attach_type;
10247 		}
10248 		if (bpf_program__type(prog) == BPF_PROG_TYPE_UNSPEC) {
10249 			/*
10250 			 * we haven't guessed from section name and user
10251 			 * didn't provide a fallback type, too bad...
10252 			 */
10253 			bpf_object__close(obj);
10254 			return libbpf_err(-EINVAL);
10255 		}
10256 
10257 		prog->prog_ifindex = attr->ifindex;
10258 		prog->log_level = attr->log_level;
10259 		prog->prog_flags |= attr->prog_flags;
10260 		if (!first_prog)
10261 			first_prog = prog;
10262 	}
10263 
10264 	bpf_object__for_each_map(map, obj) {
10265 		if (map->def.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
10266 			map->map_ifindex = attr->ifindex;
10267 	}
10268 
10269 	if (!first_prog) {
10270 		pr_warn("object file doesn't contain bpf program\n");
10271 		bpf_object__close(obj);
10272 		return libbpf_err(-ENOENT);
10273 	}
10274 
10275 	err = bpf_object__load(obj);
10276 	if (err) {
10277 		bpf_object__close(obj);
10278 		return libbpf_err(err);
10279 	}
10280 
10281 	*pobj = obj;
10282 	*prog_fd = bpf_program__fd(first_prog);
10283 	return 0;
10284 }
10285 
10286 COMPAT_VERSION(bpf_prog_load_deprecated, bpf_prog_load, LIBBPF_0.0.1)
10287 int bpf_prog_load_deprecated(const char *file, enum bpf_prog_type type,
10288 			     struct bpf_object **pobj, int *prog_fd)
10289 {
10290 	struct bpf_prog_load_attr attr;
10291 
10292 	memset(&attr, 0, sizeof(struct bpf_prog_load_attr));
10293 	attr.file = file;
10294 	attr.prog_type = type;
10295 	attr.expected_attach_type = 0;
10296 
10297 	return bpf_prog_load_xattr2(&attr, pobj, prog_fd);
10298 }
10299 
10300 /* Replace link's underlying BPF program with the new one */
10301 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
10302 {
10303 	int ret;
10304 
10305 	ret = bpf_link_update(bpf_link__fd(link), bpf_program__fd(prog), NULL);
10306 	return libbpf_err_errno(ret);
10307 }
10308 
10309 /* Release "ownership" of underlying BPF resource (typically, BPF program
10310  * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
10311  * link, when destructed through bpf_link__destroy() call won't attempt to
10312  * detach/unregisted that BPF resource. This is useful in situations where,
10313  * say, attached BPF program has to outlive userspace program that attached it
10314  * in the system. Depending on type of BPF program, though, there might be
10315  * additional steps (like pinning BPF program in BPF FS) necessary to ensure
10316  * exit of userspace program doesn't trigger automatic detachment and clean up
10317  * inside the kernel.
10318  */
10319 void bpf_link__disconnect(struct bpf_link *link)
10320 {
10321 	link->disconnected = true;
10322 }
10323 
10324 int bpf_link__destroy(struct bpf_link *link)
10325 {
10326 	int err = 0;
10327 
10328 	if (IS_ERR_OR_NULL(link))
10329 		return 0;
10330 
10331 	if (!link->disconnected && link->detach)
10332 		err = link->detach(link);
10333 	if (link->pin_path)
10334 		free(link->pin_path);
10335 	if (link->dealloc)
10336 		link->dealloc(link);
10337 	else
10338 		free(link);
10339 
10340 	return libbpf_err(err);
10341 }
10342 
10343 int bpf_link__fd(const struct bpf_link *link)
10344 {
10345 	return link->fd;
10346 }
10347 
10348 const char *bpf_link__pin_path(const struct bpf_link *link)
10349 {
10350 	return link->pin_path;
10351 }
10352 
10353 static int bpf_link__detach_fd(struct bpf_link *link)
10354 {
10355 	return libbpf_err_errno(close(link->fd));
10356 }
10357 
10358 struct bpf_link *bpf_link__open(const char *path)
10359 {
10360 	struct bpf_link *link;
10361 	int fd;
10362 
10363 	fd = bpf_obj_get(path);
10364 	if (fd < 0) {
10365 		fd = -errno;
10366 		pr_warn("failed to open link at %s: %d\n", path, fd);
10367 		return libbpf_err_ptr(fd);
10368 	}
10369 
10370 	link = calloc(1, sizeof(*link));
10371 	if (!link) {
10372 		close(fd);
10373 		return libbpf_err_ptr(-ENOMEM);
10374 	}
10375 	link->detach = &bpf_link__detach_fd;
10376 	link->fd = fd;
10377 
10378 	link->pin_path = strdup(path);
10379 	if (!link->pin_path) {
10380 		bpf_link__destroy(link);
10381 		return libbpf_err_ptr(-ENOMEM);
10382 	}
10383 
10384 	return link;
10385 }
10386 
10387 int bpf_link__detach(struct bpf_link *link)
10388 {
10389 	return bpf_link_detach(link->fd) ? -errno : 0;
10390 }
10391 
10392 int bpf_link__pin(struct bpf_link *link, const char *path)
10393 {
10394 	int err;
10395 
10396 	if (link->pin_path)
10397 		return libbpf_err(-EBUSY);
10398 	err = make_parent_dir(path);
10399 	if (err)
10400 		return libbpf_err(err);
10401 	err = check_path(path);
10402 	if (err)
10403 		return libbpf_err(err);
10404 
10405 	link->pin_path = strdup(path);
10406 	if (!link->pin_path)
10407 		return libbpf_err(-ENOMEM);
10408 
10409 	if (bpf_obj_pin(link->fd, link->pin_path)) {
10410 		err = -errno;
10411 		zfree(&link->pin_path);
10412 		return libbpf_err(err);
10413 	}
10414 
10415 	pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
10416 	return 0;
10417 }
10418 
10419 int bpf_link__unpin(struct bpf_link *link)
10420 {
10421 	int err;
10422 
10423 	if (!link->pin_path)
10424 		return libbpf_err(-EINVAL);
10425 
10426 	err = unlink(link->pin_path);
10427 	if (err != 0)
10428 		return -errno;
10429 
10430 	pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
10431 	zfree(&link->pin_path);
10432 	return 0;
10433 }
10434 
10435 struct bpf_link_perf {
10436 	struct bpf_link link;
10437 	int perf_event_fd;
10438 	/* legacy kprobe support: keep track of probe identifier and type */
10439 	char *legacy_probe_name;
10440 	bool legacy_is_kprobe;
10441 	bool legacy_is_retprobe;
10442 };
10443 
10444 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
10445 static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
10446 
10447 static int bpf_link_perf_detach(struct bpf_link *link)
10448 {
10449 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10450 	int err = 0;
10451 
10452 	if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
10453 		err = -errno;
10454 
10455 	if (perf_link->perf_event_fd != link->fd)
10456 		close(perf_link->perf_event_fd);
10457 	close(link->fd);
10458 
10459 	/* legacy uprobe/kprobe needs to be removed after perf event fd closure */
10460 	if (perf_link->legacy_probe_name) {
10461 		if (perf_link->legacy_is_kprobe) {
10462 			err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
10463 							 perf_link->legacy_is_retprobe);
10464 		} else {
10465 			err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
10466 							 perf_link->legacy_is_retprobe);
10467 		}
10468 	}
10469 
10470 	return err;
10471 }
10472 
10473 static void bpf_link_perf_dealloc(struct bpf_link *link)
10474 {
10475 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10476 
10477 	free(perf_link->legacy_probe_name);
10478 	free(perf_link);
10479 }
10480 
10481 struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
10482 						     const struct bpf_perf_event_opts *opts)
10483 {
10484 	char errmsg[STRERR_BUFSIZE];
10485 	struct bpf_link_perf *link;
10486 	int prog_fd, link_fd = -1, err;
10487 
10488 	if (!OPTS_VALID(opts, bpf_perf_event_opts))
10489 		return libbpf_err_ptr(-EINVAL);
10490 
10491 	if (pfd < 0) {
10492 		pr_warn("prog '%s': invalid perf event FD %d\n",
10493 			prog->name, pfd);
10494 		return libbpf_err_ptr(-EINVAL);
10495 	}
10496 	prog_fd = bpf_program__fd(prog);
10497 	if (prog_fd < 0) {
10498 		pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
10499 			prog->name);
10500 		return libbpf_err_ptr(-EINVAL);
10501 	}
10502 
10503 	link = calloc(1, sizeof(*link));
10504 	if (!link)
10505 		return libbpf_err_ptr(-ENOMEM);
10506 	link->link.detach = &bpf_link_perf_detach;
10507 	link->link.dealloc = &bpf_link_perf_dealloc;
10508 	link->perf_event_fd = pfd;
10509 
10510 	if (kernel_supports(prog->obj, FEAT_PERF_LINK)) {
10511 		DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
10512 			.perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
10513 
10514 		link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
10515 		if (link_fd < 0) {
10516 			err = -errno;
10517 			pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %d (%s)\n",
10518 				prog->name, pfd,
10519 				err, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10520 			goto err_out;
10521 		}
10522 		link->link.fd = link_fd;
10523 	} else {
10524 		if (OPTS_GET(opts, bpf_cookie, 0)) {
10525 			pr_warn("prog '%s': user context value is not supported\n", prog->name);
10526 			err = -EOPNOTSUPP;
10527 			goto err_out;
10528 		}
10529 
10530 		if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
10531 			err = -errno;
10532 			pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
10533 				prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10534 			if (err == -EPROTO)
10535 				pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
10536 					prog->name, pfd);
10537 			goto err_out;
10538 		}
10539 		link->link.fd = pfd;
10540 	}
10541 	if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
10542 		err = -errno;
10543 		pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
10544 			prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10545 		goto err_out;
10546 	}
10547 
10548 	return &link->link;
10549 err_out:
10550 	if (link_fd >= 0)
10551 		close(link_fd);
10552 	free(link);
10553 	return libbpf_err_ptr(err);
10554 }
10555 
10556 struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
10557 {
10558 	return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
10559 }
10560 
10561 /*
10562  * this function is expected to parse integer in the range of [0, 2^31-1] from
10563  * given file using scanf format string fmt. If actual parsed value is
10564  * negative, the result might be indistinguishable from error
10565  */
10566 static int parse_uint_from_file(const char *file, const char *fmt)
10567 {
10568 	char buf[STRERR_BUFSIZE];
10569 	int err, ret;
10570 	FILE *f;
10571 
10572 	f = fopen(file, "r");
10573 	if (!f) {
10574 		err = -errno;
10575 		pr_debug("failed to open '%s': %s\n", file,
10576 			 libbpf_strerror_r(err, buf, sizeof(buf)));
10577 		return err;
10578 	}
10579 	err = fscanf(f, fmt, &ret);
10580 	if (err != 1) {
10581 		err = err == EOF ? -EIO : -errno;
10582 		pr_debug("failed to parse '%s': %s\n", file,
10583 			libbpf_strerror_r(err, buf, sizeof(buf)));
10584 		fclose(f);
10585 		return err;
10586 	}
10587 	fclose(f);
10588 	return ret;
10589 }
10590 
10591 static int determine_kprobe_perf_type(void)
10592 {
10593 	const char *file = "/sys/bus/event_source/devices/kprobe/type";
10594 
10595 	return parse_uint_from_file(file, "%d\n");
10596 }
10597 
10598 static int determine_uprobe_perf_type(void)
10599 {
10600 	const char *file = "/sys/bus/event_source/devices/uprobe/type";
10601 
10602 	return parse_uint_from_file(file, "%d\n");
10603 }
10604 
10605 static int determine_kprobe_retprobe_bit(void)
10606 {
10607 	const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
10608 
10609 	return parse_uint_from_file(file, "config:%d\n");
10610 }
10611 
10612 static int determine_uprobe_retprobe_bit(void)
10613 {
10614 	const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
10615 
10616 	return parse_uint_from_file(file, "config:%d\n");
10617 }
10618 
10619 #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
10620 #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
10621 
10622 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
10623 				 uint64_t offset, int pid, size_t ref_ctr_off)
10624 {
10625 	struct perf_event_attr attr = {};
10626 	char errmsg[STRERR_BUFSIZE];
10627 	int type, pfd, err;
10628 
10629 	if (ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
10630 		return -EINVAL;
10631 
10632 	type = uprobe ? determine_uprobe_perf_type()
10633 		      : determine_kprobe_perf_type();
10634 	if (type < 0) {
10635 		pr_warn("failed to determine %s perf type: %s\n",
10636 			uprobe ? "uprobe" : "kprobe",
10637 			libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
10638 		return type;
10639 	}
10640 	if (retprobe) {
10641 		int bit = uprobe ? determine_uprobe_retprobe_bit()
10642 				 : determine_kprobe_retprobe_bit();
10643 
10644 		if (bit < 0) {
10645 			pr_warn("failed to determine %s retprobe bit: %s\n",
10646 				uprobe ? "uprobe" : "kprobe",
10647 				libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
10648 			return bit;
10649 		}
10650 		attr.config |= 1 << bit;
10651 	}
10652 	attr.size = sizeof(attr);
10653 	attr.type = type;
10654 	attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
10655 	attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
10656 	attr.config2 = offset;		 /* kprobe_addr or probe_offset */
10657 
10658 	/* pid filter is meaningful only for uprobes */
10659 	pfd = syscall(__NR_perf_event_open, &attr,
10660 		      pid < 0 ? -1 : pid /* pid */,
10661 		      pid == -1 ? 0 : -1 /* cpu */,
10662 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
10663 	if (pfd < 0) {
10664 		err = -errno;
10665 		pr_warn("%s perf_event_open() failed: %s\n",
10666 			uprobe ? "uprobe" : "kprobe",
10667 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10668 		return err;
10669 	}
10670 	return pfd;
10671 }
10672 
10673 static int append_to_file(const char *file, const char *fmt, ...)
10674 {
10675 	int fd, n, err = 0;
10676 	va_list ap;
10677 
10678 	fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
10679 	if (fd < 0)
10680 		return -errno;
10681 
10682 	va_start(ap, fmt);
10683 	n = vdprintf(fd, fmt, ap);
10684 	va_end(ap);
10685 
10686 	if (n < 0)
10687 		err = -errno;
10688 
10689 	close(fd);
10690 	return err;
10691 }
10692 
10693 static void gen_kprobe_legacy_event_name(char *buf, size_t buf_sz,
10694 					 const char *kfunc_name, size_t offset)
10695 {
10696 	static int index = 0;
10697 
10698 	snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx_%d", getpid(), kfunc_name, offset,
10699 		 __sync_fetch_and_add(&index, 1));
10700 }
10701 
10702 static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
10703 				   const char *kfunc_name, size_t offset)
10704 {
10705 	const char *file = "/sys/kernel/debug/tracing/kprobe_events";
10706 
10707 	return append_to_file(file, "%c:%s/%s %s+0x%zx",
10708 			      retprobe ? 'r' : 'p',
10709 			      retprobe ? "kretprobes" : "kprobes",
10710 			      probe_name, kfunc_name, offset);
10711 }
10712 
10713 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
10714 {
10715 	const char *file = "/sys/kernel/debug/tracing/kprobe_events";
10716 
10717 	return append_to_file(file, "-:%s/%s", retprobe ? "kretprobes" : "kprobes", probe_name);
10718 }
10719 
10720 static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
10721 {
10722 	char file[256];
10723 
10724 	snprintf(file, sizeof(file),
10725 		 "/sys/kernel/debug/tracing/events/%s/%s/id",
10726 		 retprobe ? "kretprobes" : "kprobes", probe_name);
10727 
10728 	return parse_uint_from_file(file, "%d\n");
10729 }
10730 
10731 static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
10732 					 const char *kfunc_name, size_t offset, int pid)
10733 {
10734 	struct perf_event_attr attr = {};
10735 	char errmsg[STRERR_BUFSIZE];
10736 	int type, pfd, err;
10737 
10738 	err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
10739 	if (err < 0) {
10740 		pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
10741 			kfunc_name, offset,
10742 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10743 		return err;
10744 	}
10745 	type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
10746 	if (type < 0) {
10747 		pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
10748 			kfunc_name, offset,
10749 			libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
10750 		return type;
10751 	}
10752 	attr.size = sizeof(attr);
10753 	attr.config = type;
10754 	attr.type = PERF_TYPE_TRACEPOINT;
10755 
10756 	pfd = syscall(__NR_perf_event_open, &attr,
10757 		      pid < 0 ? -1 : pid, /* pid */
10758 		      pid == -1 ? 0 : -1, /* cpu */
10759 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
10760 	if (pfd < 0) {
10761 		err = -errno;
10762 		pr_warn("legacy kprobe perf_event_open() failed: %s\n",
10763 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10764 		return err;
10765 	}
10766 	return pfd;
10767 }
10768 
10769 struct bpf_link *
10770 bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
10771 				const char *func_name,
10772 				const struct bpf_kprobe_opts *opts)
10773 {
10774 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
10775 	char errmsg[STRERR_BUFSIZE];
10776 	char *legacy_probe = NULL;
10777 	struct bpf_link *link;
10778 	size_t offset;
10779 	bool retprobe, legacy;
10780 	int pfd, err;
10781 
10782 	if (!OPTS_VALID(opts, bpf_kprobe_opts))
10783 		return libbpf_err_ptr(-EINVAL);
10784 
10785 	retprobe = OPTS_GET(opts, retprobe, false);
10786 	offset = OPTS_GET(opts, offset, 0);
10787 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10788 
10789 	legacy = determine_kprobe_perf_type() < 0;
10790 	if (!legacy) {
10791 		pfd = perf_event_open_probe(false /* uprobe */, retprobe,
10792 					    func_name, offset,
10793 					    -1 /* pid */, 0 /* ref_ctr_off */);
10794 	} else {
10795 		char probe_name[256];
10796 
10797 		gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name),
10798 					     func_name, offset);
10799 
10800 		legacy_probe = strdup(probe_name);
10801 		if (!legacy_probe)
10802 			return libbpf_err_ptr(-ENOMEM);
10803 
10804 		pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
10805 						    offset, -1 /* pid */);
10806 	}
10807 	if (pfd < 0) {
10808 		err = -errno;
10809 		pr_warn("prog '%s': failed to create %s '%s+0x%zx' perf event: %s\n",
10810 			prog->name, retprobe ? "kretprobe" : "kprobe",
10811 			func_name, offset,
10812 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10813 		goto err_out;
10814 	}
10815 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
10816 	err = libbpf_get_error(link);
10817 	if (err) {
10818 		close(pfd);
10819 		pr_warn("prog '%s': failed to attach to %s '%s+0x%zx': %s\n",
10820 			prog->name, retprobe ? "kretprobe" : "kprobe",
10821 			func_name, offset,
10822 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10823 		goto err_out;
10824 	}
10825 	if (legacy) {
10826 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10827 
10828 		perf_link->legacy_probe_name = legacy_probe;
10829 		perf_link->legacy_is_kprobe = true;
10830 		perf_link->legacy_is_retprobe = retprobe;
10831 	}
10832 
10833 	return link;
10834 err_out:
10835 	free(legacy_probe);
10836 	return libbpf_err_ptr(err);
10837 }
10838 
10839 struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
10840 					    bool retprobe,
10841 					    const char *func_name)
10842 {
10843 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
10844 		.retprobe = retprobe,
10845 	);
10846 
10847 	return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
10848 }
10849 
10850 /* Adapted from perf/util/string.c */
10851 static bool glob_match(const char *str, const char *pat)
10852 {
10853 	while (*str && *pat && *pat != '*') {
10854 		if (*pat == '?') {      /* Matches any single character */
10855 			str++;
10856 			pat++;
10857 			continue;
10858 		}
10859 		if (*str != *pat)
10860 			return false;
10861 		str++;
10862 		pat++;
10863 	}
10864 	/* Check wild card */
10865 	if (*pat == '*') {
10866 		while (*pat == '*')
10867 			pat++;
10868 		if (!*pat) /* Tail wild card matches all */
10869 			return true;
10870 		while (*str)
10871 			if (glob_match(str++, pat))
10872 				return true;
10873 	}
10874 	return !*str && !*pat;
10875 }
10876 
10877 struct kprobe_multi_resolve {
10878 	const char *pattern;
10879 	unsigned long *addrs;
10880 	size_t cap;
10881 	size_t cnt;
10882 };
10883 
10884 static int
10885 resolve_kprobe_multi_cb(unsigned long long sym_addr, char sym_type,
10886 			const char *sym_name, void *ctx)
10887 {
10888 	struct kprobe_multi_resolve *res = ctx;
10889 	int err;
10890 
10891 	if (!glob_match(sym_name, res->pattern))
10892 		return 0;
10893 
10894 	err = libbpf_ensure_mem((void **) &res->addrs, &res->cap, sizeof(unsigned long),
10895 				res->cnt + 1);
10896 	if (err)
10897 		return err;
10898 
10899 	res->addrs[res->cnt++] = (unsigned long) sym_addr;
10900 	return 0;
10901 }
10902 
10903 struct bpf_link *
10904 bpf_program__attach_kprobe_multi_opts(const struct bpf_program *prog,
10905 				      const char *pattern,
10906 				      const struct bpf_kprobe_multi_opts *opts)
10907 {
10908 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
10909 	struct kprobe_multi_resolve res = {
10910 		.pattern = pattern,
10911 	};
10912 	struct bpf_link *link = NULL;
10913 	char errmsg[STRERR_BUFSIZE];
10914 	const unsigned long *addrs;
10915 	int err, link_fd, prog_fd;
10916 	const __u64 *cookies;
10917 	const char **syms;
10918 	bool retprobe;
10919 	size_t cnt;
10920 
10921 	if (!OPTS_VALID(opts, bpf_kprobe_multi_opts))
10922 		return libbpf_err_ptr(-EINVAL);
10923 
10924 	syms    = OPTS_GET(opts, syms, false);
10925 	addrs   = OPTS_GET(opts, addrs, false);
10926 	cnt     = OPTS_GET(opts, cnt, false);
10927 	cookies = OPTS_GET(opts, cookies, false);
10928 
10929 	if (!pattern && !addrs && !syms)
10930 		return libbpf_err_ptr(-EINVAL);
10931 	if (pattern && (addrs || syms || cookies || cnt))
10932 		return libbpf_err_ptr(-EINVAL);
10933 	if (!pattern && !cnt)
10934 		return libbpf_err_ptr(-EINVAL);
10935 	if (addrs && syms)
10936 		return libbpf_err_ptr(-EINVAL);
10937 
10938 	if (pattern) {
10939 		err = libbpf_kallsyms_parse(resolve_kprobe_multi_cb, &res);
10940 		if (err)
10941 			goto error;
10942 		if (!res.cnt) {
10943 			err = -ENOENT;
10944 			goto error;
10945 		}
10946 		addrs = res.addrs;
10947 		cnt = res.cnt;
10948 	}
10949 
10950 	retprobe = OPTS_GET(opts, retprobe, false);
10951 
10952 	lopts.kprobe_multi.syms = syms;
10953 	lopts.kprobe_multi.addrs = addrs;
10954 	lopts.kprobe_multi.cookies = cookies;
10955 	lopts.kprobe_multi.cnt = cnt;
10956 	lopts.kprobe_multi.flags = retprobe ? BPF_F_KPROBE_MULTI_RETURN : 0;
10957 
10958 	link = calloc(1, sizeof(*link));
10959 	if (!link) {
10960 		err = -ENOMEM;
10961 		goto error;
10962 	}
10963 	link->detach = &bpf_link__detach_fd;
10964 
10965 	prog_fd = bpf_program__fd(prog);
10966 	link_fd = bpf_link_create(prog_fd, 0, BPF_TRACE_KPROBE_MULTI, &lopts);
10967 	if (link_fd < 0) {
10968 		err = -errno;
10969 		pr_warn("prog '%s': failed to attach: %s\n",
10970 			prog->name, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10971 		goto error;
10972 	}
10973 	link->fd = link_fd;
10974 	free(res.addrs);
10975 	return link;
10976 
10977 error:
10978 	free(link);
10979 	free(res.addrs);
10980 	return libbpf_err_ptr(err);
10981 }
10982 
10983 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10984 {
10985 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
10986 	unsigned long offset = 0;
10987 	const char *func_name;
10988 	char *func;
10989 	int n;
10990 
10991 	*link = NULL;
10992 
10993 	/* no auto-attach for SEC("kprobe") and SEC("kretprobe") */
10994 	if (strcmp(prog->sec_name, "kprobe") == 0 || strcmp(prog->sec_name, "kretprobe") == 0)
10995 		return 0;
10996 
10997 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
10998 	if (opts.retprobe)
10999 		func_name = prog->sec_name + sizeof("kretprobe/") - 1;
11000 	else
11001 		func_name = prog->sec_name + sizeof("kprobe/") - 1;
11002 
11003 	n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
11004 	if (n < 1) {
11005 		pr_warn("kprobe name is invalid: %s\n", func_name);
11006 		return -EINVAL;
11007 	}
11008 	if (opts.retprobe && offset != 0) {
11009 		free(func);
11010 		pr_warn("kretprobes do not support offset specification\n");
11011 		return -EINVAL;
11012 	}
11013 
11014 	opts.offset = offset;
11015 	*link = bpf_program__attach_kprobe_opts(prog, func, &opts);
11016 	free(func);
11017 	return libbpf_get_error(*link);
11018 }
11019 
11020 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11021 {
11022 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts);
11023 	const char *spec;
11024 	char *pattern;
11025 	int n;
11026 
11027 	*link = NULL;
11028 
11029 	/* no auto-attach for SEC("kprobe.multi") and SEC("kretprobe.multi") */
11030 	if (strcmp(prog->sec_name, "kprobe.multi") == 0 ||
11031 	    strcmp(prog->sec_name, "kretprobe.multi") == 0)
11032 		return 0;
11033 
11034 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe.multi/");
11035 	if (opts.retprobe)
11036 		spec = prog->sec_name + sizeof("kretprobe.multi/") - 1;
11037 	else
11038 		spec = prog->sec_name + sizeof("kprobe.multi/") - 1;
11039 
11040 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
11041 	if (n < 1) {
11042 		pr_warn("kprobe multi pattern is invalid: %s\n", pattern);
11043 		return -EINVAL;
11044 	}
11045 
11046 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
11047 	free(pattern);
11048 	return libbpf_get_error(*link);
11049 }
11050 
11051 static void gen_uprobe_legacy_event_name(char *buf, size_t buf_sz,
11052 					 const char *binary_path, uint64_t offset)
11053 {
11054 	int i;
11055 
11056 	snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx", getpid(), binary_path, (size_t)offset);
11057 
11058 	/* sanitize binary_path in the probe name */
11059 	for (i = 0; buf[i]; i++) {
11060 		if (!isalnum(buf[i]))
11061 			buf[i] = '_';
11062 	}
11063 }
11064 
11065 static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
11066 					  const char *binary_path, size_t offset)
11067 {
11068 	const char *file = "/sys/kernel/debug/tracing/uprobe_events";
11069 
11070 	return append_to_file(file, "%c:%s/%s %s:0x%zx",
11071 			      retprobe ? 'r' : 'p',
11072 			      retprobe ? "uretprobes" : "uprobes",
11073 			      probe_name, binary_path, offset);
11074 }
11075 
11076 static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
11077 {
11078 	const char *file = "/sys/kernel/debug/tracing/uprobe_events";
11079 
11080 	return append_to_file(file, "-:%s/%s", retprobe ? "uretprobes" : "uprobes", probe_name);
11081 }
11082 
11083 static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
11084 {
11085 	char file[512];
11086 
11087 	snprintf(file, sizeof(file),
11088 		 "/sys/kernel/debug/tracing/events/%s/%s/id",
11089 		 retprobe ? "uretprobes" : "uprobes", probe_name);
11090 
11091 	return parse_uint_from_file(file, "%d\n");
11092 }
11093 
11094 static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
11095 					 const char *binary_path, size_t offset, int pid)
11096 {
11097 	struct perf_event_attr attr;
11098 	int type, pfd, err;
11099 
11100 	err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
11101 	if (err < 0) {
11102 		pr_warn("failed to add legacy uprobe event for %s:0x%zx: %d\n",
11103 			binary_path, (size_t)offset, err);
11104 		return err;
11105 	}
11106 	type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
11107 	if (type < 0) {
11108 		pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %d\n",
11109 			binary_path, offset, err);
11110 		return type;
11111 	}
11112 
11113 	memset(&attr, 0, sizeof(attr));
11114 	attr.size = sizeof(attr);
11115 	attr.config = type;
11116 	attr.type = PERF_TYPE_TRACEPOINT;
11117 
11118 	pfd = syscall(__NR_perf_event_open, &attr,
11119 		      pid < 0 ? -1 : pid, /* pid */
11120 		      pid == -1 ? 0 : -1, /* cpu */
11121 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
11122 	if (pfd < 0) {
11123 		err = -errno;
11124 		pr_warn("legacy uprobe perf_event_open() failed: %d\n", err);
11125 		return err;
11126 	}
11127 	return pfd;
11128 }
11129 
11130 /* uprobes deal in relative offsets; subtract the base address associated with
11131  * the mapped binary.  See Documentation/trace/uprobetracer.rst for more
11132  * details.
11133  */
11134 static long elf_find_relative_offset(const char *filename, Elf *elf, long addr)
11135 {
11136 	size_t n;
11137 	int i;
11138 
11139 	if (elf_getphdrnum(elf, &n)) {
11140 		pr_warn("elf: failed to find program headers for '%s': %s\n", filename,
11141 			elf_errmsg(-1));
11142 		return -ENOENT;
11143 	}
11144 
11145 	for (i = 0; i < n; i++) {
11146 		int seg_start, seg_end, seg_offset;
11147 		GElf_Phdr phdr;
11148 
11149 		if (!gelf_getphdr(elf, i, &phdr)) {
11150 			pr_warn("elf: failed to get program header %d from '%s': %s\n", i, filename,
11151 				elf_errmsg(-1));
11152 			return -ENOENT;
11153 		}
11154 		if (phdr.p_type != PT_LOAD || !(phdr.p_flags & PF_X))
11155 			continue;
11156 
11157 		seg_start = phdr.p_vaddr;
11158 		seg_end = seg_start + phdr.p_memsz;
11159 		seg_offset = phdr.p_offset;
11160 		if (addr >= seg_start && addr < seg_end)
11161 			return addr - seg_start + seg_offset;
11162 	}
11163 	pr_warn("elf: failed to find prog header containing 0x%lx in '%s'\n", addr, filename);
11164 	return -ENOENT;
11165 }
11166 
11167 /* Return next ELF section of sh_type after scn, or first of that type if scn is NULL. */
11168 static Elf_Scn *elf_find_next_scn_by_type(Elf *elf, int sh_type, Elf_Scn *scn)
11169 {
11170 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
11171 		GElf_Shdr sh;
11172 
11173 		if (!gelf_getshdr(scn, &sh))
11174 			continue;
11175 		if (sh.sh_type == sh_type)
11176 			return scn;
11177 	}
11178 	return NULL;
11179 }
11180 
11181 /* Find offset of function name in object specified by path.  "name" matches
11182  * symbol name or name@@LIB for library functions.
11183  */
11184 static long elf_find_func_offset(const char *binary_path, const char *name)
11185 {
11186 	int fd, i, sh_types[2] = { SHT_DYNSYM, SHT_SYMTAB };
11187 	bool is_shared_lib, is_name_qualified;
11188 	char errmsg[STRERR_BUFSIZE];
11189 	long ret = -ENOENT;
11190 	size_t name_len;
11191 	GElf_Ehdr ehdr;
11192 	Elf *elf;
11193 
11194 	fd = open(binary_path, O_RDONLY | O_CLOEXEC);
11195 	if (fd < 0) {
11196 		ret = -errno;
11197 		pr_warn("failed to open %s: %s\n", binary_path,
11198 			libbpf_strerror_r(ret, errmsg, sizeof(errmsg)));
11199 		return ret;
11200 	}
11201 	elf = elf_begin(fd, ELF_C_READ_MMAP, NULL);
11202 	if (!elf) {
11203 		pr_warn("elf: could not read elf from %s: %s\n", binary_path, elf_errmsg(-1));
11204 		close(fd);
11205 		return -LIBBPF_ERRNO__FORMAT;
11206 	}
11207 	if (!gelf_getehdr(elf, &ehdr)) {
11208 		pr_warn("elf: failed to get ehdr from %s: %s\n", binary_path, elf_errmsg(-1));
11209 		ret = -LIBBPF_ERRNO__FORMAT;
11210 		goto out;
11211 	}
11212 	/* for shared lib case, we do not need to calculate relative offset */
11213 	is_shared_lib = ehdr.e_type == ET_DYN;
11214 
11215 	name_len = strlen(name);
11216 	/* Does name specify "@@LIB"? */
11217 	is_name_qualified = strstr(name, "@@") != NULL;
11218 
11219 	/* Search SHT_DYNSYM, SHT_SYMTAB for symbol.  This search order is used because if
11220 	 * a binary is stripped, it may only have SHT_DYNSYM, and a fully-statically
11221 	 * linked binary may not have SHT_DYMSYM, so absence of a section should not be
11222 	 * reported as a warning/error.
11223 	 */
11224 	for (i = 0; i < ARRAY_SIZE(sh_types); i++) {
11225 		size_t nr_syms, strtabidx, idx;
11226 		Elf_Data *symbols = NULL;
11227 		Elf_Scn *scn = NULL;
11228 		int last_bind = -1;
11229 		const char *sname;
11230 		GElf_Shdr sh;
11231 
11232 		scn = elf_find_next_scn_by_type(elf, sh_types[i], NULL);
11233 		if (!scn) {
11234 			pr_debug("elf: failed to find symbol table ELF sections in '%s'\n",
11235 				 binary_path);
11236 			continue;
11237 		}
11238 		if (!gelf_getshdr(scn, &sh))
11239 			continue;
11240 		strtabidx = sh.sh_link;
11241 		symbols = elf_getdata(scn, 0);
11242 		if (!symbols) {
11243 			pr_warn("elf: failed to get symbols for symtab section in '%s': %s\n",
11244 				binary_path, elf_errmsg(-1));
11245 			ret = -LIBBPF_ERRNO__FORMAT;
11246 			goto out;
11247 		}
11248 		nr_syms = symbols->d_size / sh.sh_entsize;
11249 
11250 		for (idx = 0; idx < nr_syms; idx++) {
11251 			int curr_bind;
11252 			GElf_Sym sym;
11253 
11254 			if (!gelf_getsym(symbols, idx, &sym))
11255 				continue;
11256 
11257 			if (GELF_ST_TYPE(sym.st_info) != STT_FUNC)
11258 				continue;
11259 
11260 			sname = elf_strptr(elf, strtabidx, sym.st_name);
11261 			if (!sname)
11262 				continue;
11263 
11264 			curr_bind = GELF_ST_BIND(sym.st_info);
11265 
11266 			/* User can specify func, func@@LIB or func@@LIB_VERSION. */
11267 			if (strncmp(sname, name, name_len) != 0)
11268 				continue;
11269 			/* ...but we don't want a search for "foo" to match 'foo2" also, so any
11270 			 * additional characters in sname should be of the form "@@LIB".
11271 			 */
11272 			if (!is_name_qualified && sname[name_len] != '\0' && sname[name_len] != '@')
11273 				continue;
11274 
11275 			if (ret >= 0) {
11276 				/* handle multiple matches */
11277 				if (last_bind != STB_WEAK && curr_bind != STB_WEAK) {
11278 					/* Only accept one non-weak bind. */
11279 					pr_warn("elf: ambiguous match for '%s', '%s' in '%s'\n",
11280 						sname, name, binary_path);
11281 					ret = -LIBBPF_ERRNO__FORMAT;
11282 					goto out;
11283 				} else if (curr_bind == STB_WEAK) {
11284 					/* already have a non-weak bind, and
11285 					 * this is a weak bind, so ignore.
11286 					 */
11287 					continue;
11288 				}
11289 			}
11290 			ret = sym.st_value;
11291 			last_bind = curr_bind;
11292 		}
11293 		/* For binaries that are not shared libraries, we need relative offset */
11294 		if (ret > 0 && !is_shared_lib)
11295 			ret = elf_find_relative_offset(binary_path, elf, ret);
11296 		if (ret > 0)
11297 			break;
11298 	}
11299 
11300 	if (ret > 0) {
11301 		pr_debug("elf: symbol address match for '%s' in '%s': 0x%lx\n", name, binary_path,
11302 			 ret);
11303 	} else {
11304 		if (ret == 0) {
11305 			pr_warn("elf: '%s' is 0 in symtab for '%s': %s\n", name, binary_path,
11306 				is_shared_lib ? "should not be 0 in a shared library" :
11307 						"try using shared library path instead");
11308 			ret = -ENOENT;
11309 		} else {
11310 			pr_warn("elf: failed to find symbol '%s' in '%s'\n", name, binary_path);
11311 		}
11312 	}
11313 out:
11314 	elf_end(elf);
11315 	close(fd);
11316 	return ret;
11317 }
11318 
11319 static const char *arch_specific_lib_paths(void)
11320 {
11321 	/*
11322 	 * Based on https://packages.debian.org/sid/libc6.
11323 	 *
11324 	 * Assume that the traced program is built for the same architecture
11325 	 * as libbpf, which should cover the vast majority of cases.
11326 	 */
11327 #if defined(__x86_64__)
11328 	return "/lib/x86_64-linux-gnu";
11329 #elif defined(__i386__)
11330 	return "/lib/i386-linux-gnu";
11331 #elif defined(__s390x__)
11332 	return "/lib/s390x-linux-gnu";
11333 #elif defined(__s390__)
11334 	return "/lib/s390-linux-gnu";
11335 #elif defined(__arm__) && defined(__SOFTFP__)
11336 	return "/lib/arm-linux-gnueabi";
11337 #elif defined(__arm__) && !defined(__SOFTFP__)
11338 	return "/lib/arm-linux-gnueabihf";
11339 #elif defined(__aarch64__)
11340 	return "/lib/aarch64-linux-gnu";
11341 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 64
11342 	return "/lib/mips64el-linux-gnuabi64";
11343 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 32
11344 	return "/lib/mipsel-linux-gnu";
11345 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
11346 	return "/lib/powerpc64le-linux-gnu";
11347 #elif defined(__sparc__) && defined(__arch64__)
11348 	return "/lib/sparc64-linux-gnu";
11349 #elif defined(__riscv) && __riscv_xlen == 64
11350 	return "/lib/riscv64-linux-gnu";
11351 #else
11352 	return NULL;
11353 #endif
11354 }
11355 
11356 /* Get full path to program/shared library. */
11357 static int resolve_full_path(const char *file, char *result, size_t result_sz)
11358 {
11359 	const char *search_paths[3] = {};
11360 	int i;
11361 
11362 	if (str_has_sfx(file, ".so") || strstr(file, ".so.")) {
11363 		search_paths[0] = getenv("LD_LIBRARY_PATH");
11364 		search_paths[1] = "/usr/lib64:/usr/lib";
11365 		search_paths[2] = arch_specific_lib_paths();
11366 	} else {
11367 		search_paths[0] = getenv("PATH");
11368 		search_paths[1] = "/usr/bin:/usr/sbin";
11369 	}
11370 
11371 	for (i = 0; i < ARRAY_SIZE(search_paths); i++) {
11372 		const char *s;
11373 
11374 		if (!search_paths[i])
11375 			continue;
11376 		for (s = search_paths[i]; s != NULL; s = strchr(s, ':')) {
11377 			char *next_path;
11378 			int seg_len;
11379 
11380 			if (s[0] == ':')
11381 				s++;
11382 			next_path = strchr(s, ':');
11383 			seg_len = next_path ? next_path - s : strlen(s);
11384 			if (!seg_len)
11385 				continue;
11386 			snprintf(result, result_sz, "%.*s/%s", seg_len, s, file);
11387 			/* ensure it is an executable file/link */
11388 			if (access(result, R_OK | X_OK) < 0)
11389 				continue;
11390 			pr_debug("resolved '%s' to '%s'\n", file, result);
11391 			return 0;
11392 		}
11393 	}
11394 	return -ENOENT;
11395 }
11396 
11397 LIBBPF_API struct bpf_link *
11398 bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
11399 				const char *binary_path, size_t func_offset,
11400 				const struct bpf_uprobe_opts *opts)
11401 {
11402 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11403 	char errmsg[STRERR_BUFSIZE], *legacy_probe = NULL;
11404 	char full_binary_path[PATH_MAX];
11405 	struct bpf_link *link;
11406 	size_t ref_ctr_off;
11407 	int pfd, err;
11408 	bool retprobe, legacy;
11409 	const char *func_name;
11410 
11411 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
11412 		return libbpf_err_ptr(-EINVAL);
11413 
11414 	retprobe = OPTS_GET(opts, retprobe, false);
11415 	ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
11416 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11417 
11418 	if (binary_path && !strchr(binary_path, '/')) {
11419 		err = resolve_full_path(binary_path, full_binary_path,
11420 					sizeof(full_binary_path));
11421 		if (err) {
11422 			pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11423 				prog->name, binary_path, err);
11424 			return libbpf_err_ptr(err);
11425 		}
11426 		binary_path = full_binary_path;
11427 	}
11428 	func_name = OPTS_GET(opts, func_name, NULL);
11429 	if (func_name) {
11430 		long sym_off;
11431 
11432 		if (!binary_path) {
11433 			pr_warn("prog '%s': name-based attach requires binary_path\n",
11434 				prog->name);
11435 			return libbpf_err_ptr(-EINVAL);
11436 		}
11437 		sym_off = elf_find_func_offset(binary_path, func_name);
11438 		if (sym_off < 0)
11439 			return libbpf_err_ptr(sym_off);
11440 		func_offset += sym_off;
11441 	}
11442 
11443 	legacy = determine_uprobe_perf_type() < 0;
11444 	if (!legacy) {
11445 		pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
11446 					    func_offset, pid, ref_ctr_off);
11447 	} else {
11448 		char probe_name[PATH_MAX + 64];
11449 
11450 		if (ref_ctr_off)
11451 			return libbpf_err_ptr(-EINVAL);
11452 
11453 		gen_uprobe_legacy_event_name(probe_name, sizeof(probe_name),
11454 					     binary_path, func_offset);
11455 
11456 		legacy_probe = strdup(probe_name);
11457 		if (!legacy_probe)
11458 			return libbpf_err_ptr(-ENOMEM);
11459 
11460 		pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
11461 						    binary_path, func_offset, pid);
11462 	}
11463 	if (pfd < 0) {
11464 		err = -errno;
11465 		pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
11466 			prog->name, retprobe ? "uretprobe" : "uprobe",
11467 			binary_path, func_offset,
11468 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11469 		goto err_out;
11470 	}
11471 
11472 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11473 	err = libbpf_get_error(link);
11474 	if (err) {
11475 		close(pfd);
11476 		pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
11477 			prog->name, retprobe ? "uretprobe" : "uprobe",
11478 			binary_path, func_offset,
11479 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11480 		goto err_out;
11481 	}
11482 	if (legacy) {
11483 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
11484 
11485 		perf_link->legacy_probe_name = legacy_probe;
11486 		perf_link->legacy_is_kprobe = false;
11487 		perf_link->legacy_is_retprobe = retprobe;
11488 	}
11489 	return link;
11490 err_out:
11491 	free(legacy_probe);
11492 	return libbpf_err_ptr(err);
11493 
11494 }
11495 
11496 /* Format of u[ret]probe section definition supporting auto-attach:
11497  * u[ret]probe/binary:function[+offset]
11498  *
11499  * binary can be an absolute/relative path or a filename; the latter is resolved to a
11500  * full binary path via bpf_program__attach_uprobe_opts.
11501  *
11502  * Specifying uprobe+ ensures we carry out strict matching; either "uprobe" must be
11503  * specified (and auto-attach is not possible) or the above format is specified for
11504  * auto-attach.
11505  */
11506 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11507 {
11508 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts);
11509 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
11510 	int n, ret = -EINVAL;
11511 	long offset = 0;
11512 
11513 	*link = NULL;
11514 
11515 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[a-zA-Z0-9_.]+%li",
11516 		   &probe_type, &binary_path, &func_name, &offset);
11517 	switch (n) {
11518 	case 1:
11519 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
11520 		ret = 0;
11521 		break;
11522 	case 2:
11523 		pr_warn("prog '%s': section '%s' missing ':function[+offset]' specification\n",
11524 			prog->name, prog->sec_name);
11525 		break;
11526 	case 3:
11527 	case 4:
11528 		opts.retprobe = strcmp(probe_type, "uretprobe") == 0;
11529 		if (opts.retprobe && offset != 0) {
11530 			pr_warn("prog '%s': uretprobes do not support offset specification\n",
11531 				prog->name);
11532 			break;
11533 		}
11534 		opts.func_name = func_name;
11535 		*link = bpf_program__attach_uprobe_opts(prog, -1, binary_path, offset, &opts);
11536 		ret = libbpf_get_error(*link);
11537 		break;
11538 	default:
11539 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
11540 			prog->sec_name);
11541 		break;
11542 	}
11543 	free(probe_type);
11544 	free(binary_path);
11545 	free(func_name);
11546 
11547 	return ret;
11548 }
11549 
11550 struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
11551 					    bool retprobe, pid_t pid,
11552 					    const char *binary_path,
11553 					    size_t func_offset)
11554 {
11555 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
11556 
11557 	return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
11558 }
11559 
11560 struct bpf_link *bpf_program__attach_usdt(const struct bpf_program *prog,
11561 					  pid_t pid, const char *binary_path,
11562 					  const char *usdt_provider, const char *usdt_name,
11563 					  const struct bpf_usdt_opts *opts)
11564 {
11565 	char resolved_path[512];
11566 	struct bpf_object *obj = prog->obj;
11567 	struct bpf_link *link;
11568 	__u64 usdt_cookie;
11569 	int err;
11570 
11571 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
11572 		return libbpf_err_ptr(-EINVAL);
11573 
11574 	if (bpf_program__fd(prog) < 0) {
11575 		pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
11576 			prog->name);
11577 		return libbpf_err_ptr(-EINVAL);
11578 	}
11579 
11580 	if (!strchr(binary_path, '/')) {
11581 		err = resolve_full_path(binary_path, resolved_path, sizeof(resolved_path));
11582 		if (err) {
11583 			pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11584 				prog->name, binary_path, err);
11585 			return libbpf_err_ptr(err);
11586 		}
11587 		binary_path = resolved_path;
11588 	}
11589 
11590 	/* USDT manager is instantiated lazily on first USDT attach. It will
11591 	 * be destroyed together with BPF object in bpf_object__close().
11592 	 */
11593 	if (IS_ERR(obj->usdt_man))
11594 		return libbpf_ptr(obj->usdt_man);
11595 	if (!obj->usdt_man) {
11596 		obj->usdt_man = usdt_manager_new(obj);
11597 		if (IS_ERR(obj->usdt_man))
11598 			return libbpf_ptr(obj->usdt_man);
11599 	}
11600 
11601 	usdt_cookie = OPTS_GET(opts, usdt_cookie, 0);
11602 	link = usdt_manager_attach_usdt(obj->usdt_man, prog, pid, binary_path,
11603 				        usdt_provider, usdt_name, usdt_cookie);
11604 	err = libbpf_get_error(link);
11605 	if (err)
11606 		return libbpf_err_ptr(err);
11607 	return link;
11608 }
11609 
11610 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11611 {
11612 	char *path = NULL, *provider = NULL, *name = NULL;
11613 	const char *sec_name;
11614 	int n, err;
11615 
11616 	sec_name = bpf_program__section_name(prog);
11617 	if (strcmp(sec_name, "usdt") == 0) {
11618 		/* no auto-attach for just SEC("usdt") */
11619 		*link = NULL;
11620 		return 0;
11621 	}
11622 
11623 	n = sscanf(sec_name, "usdt/%m[^:]:%m[^:]:%m[^:]", &path, &provider, &name);
11624 	if (n != 3) {
11625 		pr_warn("invalid section '%s', expected SEC(\"usdt/<path>:<provider>:<name>\")\n",
11626 			sec_name);
11627 		err = -EINVAL;
11628 	} else {
11629 		*link = bpf_program__attach_usdt(prog, -1 /* any process */, path,
11630 						 provider, name, NULL);
11631 		err = libbpf_get_error(*link);
11632 	}
11633 	free(path);
11634 	free(provider);
11635 	free(name);
11636 	return err;
11637 }
11638 
11639 static int determine_tracepoint_id(const char *tp_category,
11640 				   const char *tp_name)
11641 {
11642 	char file[PATH_MAX];
11643 	int ret;
11644 
11645 	ret = snprintf(file, sizeof(file),
11646 		       "/sys/kernel/debug/tracing/events/%s/%s/id",
11647 		       tp_category, tp_name);
11648 	if (ret < 0)
11649 		return -errno;
11650 	if (ret >= sizeof(file)) {
11651 		pr_debug("tracepoint %s/%s path is too long\n",
11652 			 tp_category, tp_name);
11653 		return -E2BIG;
11654 	}
11655 	return parse_uint_from_file(file, "%d\n");
11656 }
11657 
11658 static int perf_event_open_tracepoint(const char *tp_category,
11659 				      const char *tp_name)
11660 {
11661 	struct perf_event_attr attr = {};
11662 	char errmsg[STRERR_BUFSIZE];
11663 	int tp_id, pfd, err;
11664 
11665 	tp_id = determine_tracepoint_id(tp_category, tp_name);
11666 	if (tp_id < 0) {
11667 		pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
11668 			tp_category, tp_name,
11669 			libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
11670 		return tp_id;
11671 	}
11672 
11673 	attr.type = PERF_TYPE_TRACEPOINT;
11674 	attr.size = sizeof(attr);
11675 	attr.config = tp_id;
11676 
11677 	pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
11678 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
11679 	if (pfd < 0) {
11680 		err = -errno;
11681 		pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
11682 			tp_category, tp_name,
11683 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11684 		return err;
11685 	}
11686 	return pfd;
11687 }
11688 
11689 struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
11690 						     const char *tp_category,
11691 						     const char *tp_name,
11692 						     const struct bpf_tracepoint_opts *opts)
11693 {
11694 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11695 	char errmsg[STRERR_BUFSIZE];
11696 	struct bpf_link *link;
11697 	int pfd, err;
11698 
11699 	if (!OPTS_VALID(opts, bpf_tracepoint_opts))
11700 		return libbpf_err_ptr(-EINVAL);
11701 
11702 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11703 
11704 	pfd = perf_event_open_tracepoint(tp_category, tp_name);
11705 	if (pfd < 0) {
11706 		pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
11707 			prog->name, tp_category, tp_name,
11708 			libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11709 		return libbpf_err_ptr(pfd);
11710 	}
11711 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11712 	err = libbpf_get_error(link);
11713 	if (err) {
11714 		close(pfd);
11715 		pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
11716 			prog->name, tp_category, tp_name,
11717 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11718 		return libbpf_err_ptr(err);
11719 	}
11720 	return link;
11721 }
11722 
11723 struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
11724 						const char *tp_category,
11725 						const char *tp_name)
11726 {
11727 	return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
11728 }
11729 
11730 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11731 {
11732 	char *sec_name, *tp_cat, *tp_name;
11733 
11734 	*link = NULL;
11735 
11736 	/* no auto-attach for SEC("tp") or SEC("tracepoint") */
11737 	if (strcmp(prog->sec_name, "tp") == 0 || strcmp(prog->sec_name, "tracepoint") == 0)
11738 		return 0;
11739 
11740 	sec_name = strdup(prog->sec_name);
11741 	if (!sec_name)
11742 		return -ENOMEM;
11743 
11744 	/* extract "tp/<category>/<name>" or "tracepoint/<category>/<name>" */
11745 	if (str_has_pfx(prog->sec_name, "tp/"))
11746 		tp_cat = sec_name + sizeof("tp/") - 1;
11747 	else
11748 		tp_cat = sec_name + sizeof("tracepoint/") - 1;
11749 	tp_name = strchr(tp_cat, '/');
11750 	if (!tp_name) {
11751 		free(sec_name);
11752 		return -EINVAL;
11753 	}
11754 	*tp_name = '\0';
11755 	tp_name++;
11756 
11757 	*link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
11758 	free(sec_name);
11759 	return libbpf_get_error(*link);
11760 }
11761 
11762 struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
11763 						    const char *tp_name)
11764 {
11765 	char errmsg[STRERR_BUFSIZE];
11766 	struct bpf_link *link;
11767 	int prog_fd, pfd;
11768 
11769 	prog_fd = bpf_program__fd(prog);
11770 	if (prog_fd < 0) {
11771 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11772 		return libbpf_err_ptr(-EINVAL);
11773 	}
11774 
11775 	link = calloc(1, sizeof(*link));
11776 	if (!link)
11777 		return libbpf_err_ptr(-ENOMEM);
11778 	link->detach = &bpf_link__detach_fd;
11779 
11780 	pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
11781 	if (pfd < 0) {
11782 		pfd = -errno;
11783 		free(link);
11784 		pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
11785 			prog->name, tp_name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11786 		return libbpf_err_ptr(pfd);
11787 	}
11788 	link->fd = pfd;
11789 	return link;
11790 }
11791 
11792 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11793 {
11794 	static const char *const prefixes[] = {
11795 		"raw_tp",
11796 		"raw_tracepoint",
11797 		"raw_tp.w",
11798 		"raw_tracepoint.w",
11799 	};
11800 	size_t i;
11801 	const char *tp_name = NULL;
11802 
11803 	*link = NULL;
11804 
11805 	for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
11806 		size_t pfx_len;
11807 
11808 		if (!str_has_pfx(prog->sec_name, prefixes[i]))
11809 			continue;
11810 
11811 		pfx_len = strlen(prefixes[i]);
11812 		/* no auto-attach case of, e.g., SEC("raw_tp") */
11813 		if (prog->sec_name[pfx_len] == '\0')
11814 			return 0;
11815 
11816 		if (prog->sec_name[pfx_len] != '/')
11817 			continue;
11818 
11819 		tp_name = prog->sec_name + pfx_len + 1;
11820 		break;
11821 	}
11822 
11823 	if (!tp_name) {
11824 		pr_warn("prog '%s': invalid section name '%s'\n",
11825 			prog->name, prog->sec_name);
11826 		return -EINVAL;
11827 	}
11828 
11829 	*link = bpf_program__attach_raw_tracepoint(prog, tp_name);
11830 	return libbpf_get_error(link);
11831 }
11832 
11833 /* Common logic for all BPF program types that attach to a btf_id */
11834 static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog,
11835 						   const struct bpf_trace_opts *opts)
11836 {
11837 	LIBBPF_OPTS(bpf_link_create_opts, link_opts);
11838 	char errmsg[STRERR_BUFSIZE];
11839 	struct bpf_link *link;
11840 	int prog_fd, pfd;
11841 
11842 	if (!OPTS_VALID(opts, bpf_trace_opts))
11843 		return libbpf_err_ptr(-EINVAL);
11844 
11845 	prog_fd = bpf_program__fd(prog);
11846 	if (prog_fd < 0) {
11847 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11848 		return libbpf_err_ptr(-EINVAL);
11849 	}
11850 
11851 	link = calloc(1, sizeof(*link));
11852 	if (!link)
11853 		return libbpf_err_ptr(-ENOMEM);
11854 	link->detach = &bpf_link__detach_fd;
11855 
11856 	/* libbpf is smart enough to redirect to BPF_RAW_TRACEPOINT_OPEN on old kernels */
11857 	link_opts.tracing.cookie = OPTS_GET(opts, cookie, 0);
11858 	pfd = bpf_link_create(prog_fd, 0, bpf_program__expected_attach_type(prog), &link_opts);
11859 	if (pfd < 0) {
11860 		pfd = -errno;
11861 		free(link);
11862 		pr_warn("prog '%s': failed to attach: %s\n",
11863 			prog->name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11864 		return libbpf_err_ptr(pfd);
11865 	}
11866 	link->fd = pfd;
11867 	return link;
11868 }
11869 
11870 struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
11871 {
11872 	return bpf_program__attach_btf_id(prog, NULL);
11873 }
11874 
11875 struct bpf_link *bpf_program__attach_trace_opts(const struct bpf_program *prog,
11876 						const struct bpf_trace_opts *opts)
11877 {
11878 	return bpf_program__attach_btf_id(prog, opts);
11879 }
11880 
11881 struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
11882 {
11883 	return bpf_program__attach_btf_id(prog, NULL);
11884 }
11885 
11886 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11887 {
11888 	*link = bpf_program__attach_trace(prog);
11889 	return libbpf_get_error(*link);
11890 }
11891 
11892 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11893 {
11894 	*link = bpf_program__attach_lsm(prog);
11895 	return libbpf_get_error(*link);
11896 }
11897 
11898 static struct bpf_link *
11899 bpf_program__attach_fd(const struct bpf_program *prog, int target_fd, int btf_id,
11900 		       const char *target_name)
11901 {
11902 	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, opts,
11903 			    .target_btf_id = btf_id);
11904 	enum bpf_attach_type attach_type;
11905 	char errmsg[STRERR_BUFSIZE];
11906 	struct bpf_link *link;
11907 	int prog_fd, link_fd;
11908 
11909 	prog_fd = bpf_program__fd(prog);
11910 	if (prog_fd < 0) {
11911 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11912 		return libbpf_err_ptr(-EINVAL);
11913 	}
11914 
11915 	link = calloc(1, sizeof(*link));
11916 	if (!link)
11917 		return libbpf_err_ptr(-ENOMEM);
11918 	link->detach = &bpf_link__detach_fd;
11919 
11920 	attach_type = bpf_program__expected_attach_type(prog);
11921 	link_fd = bpf_link_create(prog_fd, target_fd, attach_type, &opts);
11922 	if (link_fd < 0) {
11923 		link_fd = -errno;
11924 		free(link);
11925 		pr_warn("prog '%s': failed to attach to %s: %s\n",
11926 			prog->name, target_name,
11927 			libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
11928 		return libbpf_err_ptr(link_fd);
11929 	}
11930 	link->fd = link_fd;
11931 	return link;
11932 }
11933 
11934 struct bpf_link *
11935 bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
11936 {
11937 	return bpf_program__attach_fd(prog, cgroup_fd, 0, "cgroup");
11938 }
11939 
11940 struct bpf_link *
11941 bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
11942 {
11943 	return bpf_program__attach_fd(prog, netns_fd, 0, "netns");
11944 }
11945 
11946 struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
11947 {
11948 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
11949 	return bpf_program__attach_fd(prog, ifindex, 0, "xdp");
11950 }
11951 
11952 struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
11953 					      int target_fd,
11954 					      const char *attach_func_name)
11955 {
11956 	int btf_id;
11957 
11958 	if (!!target_fd != !!attach_func_name) {
11959 		pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
11960 			prog->name);
11961 		return libbpf_err_ptr(-EINVAL);
11962 	}
11963 
11964 	if (prog->type != BPF_PROG_TYPE_EXT) {
11965 		pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace",
11966 			prog->name);
11967 		return libbpf_err_ptr(-EINVAL);
11968 	}
11969 
11970 	if (target_fd) {
11971 		btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd);
11972 		if (btf_id < 0)
11973 			return libbpf_err_ptr(btf_id);
11974 
11975 		return bpf_program__attach_fd(prog, target_fd, btf_id, "freplace");
11976 	} else {
11977 		/* no target, so use raw_tracepoint_open for compatibility
11978 		 * with old kernels
11979 		 */
11980 		return bpf_program__attach_trace(prog);
11981 	}
11982 }
11983 
11984 struct bpf_link *
11985 bpf_program__attach_iter(const struct bpf_program *prog,
11986 			 const struct bpf_iter_attach_opts *opts)
11987 {
11988 	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
11989 	char errmsg[STRERR_BUFSIZE];
11990 	struct bpf_link *link;
11991 	int prog_fd, link_fd;
11992 	__u32 target_fd = 0;
11993 
11994 	if (!OPTS_VALID(opts, bpf_iter_attach_opts))
11995 		return libbpf_err_ptr(-EINVAL);
11996 
11997 	link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
11998 	link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
11999 
12000 	prog_fd = bpf_program__fd(prog);
12001 	if (prog_fd < 0) {
12002 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12003 		return libbpf_err_ptr(-EINVAL);
12004 	}
12005 
12006 	link = calloc(1, sizeof(*link));
12007 	if (!link)
12008 		return libbpf_err_ptr(-ENOMEM);
12009 	link->detach = &bpf_link__detach_fd;
12010 
12011 	link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
12012 				  &link_create_opts);
12013 	if (link_fd < 0) {
12014 		link_fd = -errno;
12015 		free(link);
12016 		pr_warn("prog '%s': failed to attach to iterator: %s\n",
12017 			prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
12018 		return libbpf_err_ptr(link_fd);
12019 	}
12020 	link->fd = link_fd;
12021 	return link;
12022 }
12023 
12024 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12025 {
12026 	*link = bpf_program__attach_iter(prog, NULL);
12027 	return libbpf_get_error(*link);
12028 }
12029 
12030 struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
12031 {
12032 	struct bpf_link *link = NULL;
12033 	int err;
12034 
12035 	if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
12036 		return libbpf_err_ptr(-EOPNOTSUPP);
12037 
12038 	err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, &link);
12039 	if (err)
12040 		return libbpf_err_ptr(err);
12041 
12042 	/* When calling bpf_program__attach() explicitly, auto-attach support
12043 	 * is expected to work, so NULL returned link is considered an error.
12044 	 * This is different for skeleton's attach, see comment in
12045 	 * bpf_object__attach_skeleton().
12046 	 */
12047 	if (!link)
12048 		return libbpf_err_ptr(-EOPNOTSUPP);
12049 
12050 	return link;
12051 }
12052 
12053 static int bpf_link__detach_struct_ops(struct bpf_link *link)
12054 {
12055 	__u32 zero = 0;
12056 
12057 	if (bpf_map_delete_elem(link->fd, &zero))
12058 		return -errno;
12059 
12060 	return 0;
12061 }
12062 
12063 struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
12064 {
12065 	struct bpf_struct_ops *st_ops;
12066 	struct bpf_link *link;
12067 	__u32 i, zero = 0;
12068 	int err;
12069 
12070 	if (!bpf_map__is_struct_ops(map) || map->fd == -1)
12071 		return libbpf_err_ptr(-EINVAL);
12072 
12073 	link = calloc(1, sizeof(*link));
12074 	if (!link)
12075 		return libbpf_err_ptr(-EINVAL);
12076 
12077 	st_ops = map->st_ops;
12078 	for (i = 0; i < btf_vlen(st_ops->type); i++) {
12079 		struct bpf_program *prog = st_ops->progs[i];
12080 		void *kern_data;
12081 		int prog_fd;
12082 
12083 		if (!prog)
12084 			continue;
12085 
12086 		prog_fd = bpf_program__fd(prog);
12087 		kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
12088 		*(unsigned long *)kern_data = prog_fd;
12089 	}
12090 
12091 	err = bpf_map_update_elem(map->fd, &zero, st_ops->kern_vdata, 0);
12092 	if (err) {
12093 		err = -errno;
12094 		free(link);
12095 		return libbpf_err_ptr(err);
12096 	}
12097 
12098 	link->detach = bpf_link__detach_struct_ops;
12099 	link->fd = map->fd;
12100 
12101 	return link;
12102 }
12103 
12104 static enum bpf_perf_event_ret
12105 perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
12106 		       void **copy_mem, size_t *copy_size,
12107 		       bpf_perf_event_print_t fn, void *private_data)
12108 {
12109 	struct perf_event_mmap_page *header = mmap_mem;
12110 	__u64 data_head = ring_buffer_read_head(header);
12111 	__u64 data_tail = header->data_tail;
12112 	void *base = ((__u8 *)header) + page_size;
12113 	int ret = LIBBPF_PERF_EVENT_CONT;
12114 	struct perf_event_header *ehdr;
12115 	size_t ehdr_size;
12116 
12117 	while (data_head != data_tail) {
12118 		ehdr = base + (data_tail & (mmap_size - 1));
12119 		ehdr_size = ehdr->size;
12120 
12121 		if (((void *)ehdr) + ehdr_size > base + mmap_size) {
12122 			void *copy_start = ehdr;
12123 			size_t len_first = base + mmap_size - copy_start;
12124 			size_t len_secnd = ehdr_size - len_first;
12125 
12126 			if (*copy_size < ehdr_size) {
12127 				free(*copy_mem);
12128 				*copy_mem = malloc(ehdr_size);
12129 				if (!*copy_mem) {
12130 					*copy_size = 0;
12131 					ret = LIBBPF_PERF_EVENT_ERROR;
12132 					break;
12133 				}
12134 				*copy_size = ehdr_size;
12135 			}
12136 
12137 			memcpy(*copy_mem, copy_start, len_first);
12138 			memcpy(*copy_mem + len_first, base, len_secnd);
12139 			ehdr = *copy_mem;
12140 		}
12141 
12142 		ret = fn(ehdr, private_data);
12143 		data_tail += ehdr_size;
12144 		if (ret != LIBBPF_PERF_EVENT_CONT)
12145 			break;
12146 	}
12147 
12148 	ring_buffer_write_tail(header, data_tail);
12149 	return libbpf_err(ret);
12150 }
12151 
12152 __attribute__((alias("perf_event_read_simple")))
12153 enum bpf_perf_event_ret
12154 bpf_perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
12155 			   void **copy_mem, size_t *copy_size,
12156 			   bpf_perf_event_print_t fn, void *private_data);
12157 
12158 struct perf_buffer;
12159 
12160 struct perf_buffer_params {
12161 	struct perf_event_attr *attr;
12162 	/* if event_cb is specified, it takes precendence */
12163 	perf_buffer_event_fn event_cb;
12164 	/* sample_cb and lost_cb are higher-level common-case callbacks */
12165 	perf_buffer_sample_fn sample_cb;
12166 	perf_buffer_lost_fn lost_cb;
12167 	void *ctx;
12168 	int cpu_cnt;
12169 	int *cpus;
12170 	int *map_keys;
12171 };
12172 
12173 struct perf_cpu_buf {
12174 	struct perf_buffer *pb;
12175 	void *base; /* mmap()'ed memory */
12176 	void *buf; /* for reconstructing segmented data */
12177 	size_t buf_size;
12178 	int fd;
12179 	int cpu;
12180 	int map_key;
12181 };
12182 
12183 struct perf_buffer {
12184 	perf_buffer_event_fn event_cb;
12185 	perf_buffer_sample_fn sample_cb;
12186 	perf_buffer_lost_fn lost_cb;
12187 	void *ctx; /* passed into callbacks */
12188 
12189 	size_t page_size;
12190 	size_t mmap_size;
12191 	struct perf_cpu_buf **cpu_bufs;
12192 	struct epoll_event *events;
12193 	int cpu_cnt; /* number of allocated CPU buffers */
12194 	int epoll_fd; /* perf event FD */
12195 	int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
12196 };
12197 
12198 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
12199 				      struct perf_cpu_buf *cpu_buf)
12200 {
12201 	if (!cpu_buf)
12202 		return;
12203 	if (cpu_buf->base &&
12204 	    munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
12205 		pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
12206 	if (cpu_buf->fd >= 0) {
12207 		ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
12208 		close(cpu_buf->fd);
12209 	}
12210 	free(cpu_buf->buf);
12211 	free(cpu_buf);
12212 }
12213 
12214 void perf_buffer__free(struct perf_buffer *pb)
12215 {
12216 	int i;
12217 
12218 	if (IS_ERR_OR_NULL(pb))
12219 		return;
12220 	if (pb->cpu_bufs) {
12221 		for (i = 0; i < pb->cpu_cnt; i++) {
12222 			struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
12223 
12224 			if (!cpu_buf)
12225 				continue;
12226 
12227 			bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
12228 			perf_buffer__free_cpu_buf(pb, cpu_buf);
12229 		}
12230 		free(pb->cpu_bufs);
12231 	}
12232 	if (pb->epoll_fd >= 0)
12233 		close(pb->epoll_fd);
12234 	free(pb->events);
12235 	free(pb);
12236 }
12237 
12238 static struct perf_cpu_buf *
12239 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
12240 			  int cpu, int map_key)
12241 {
12242 	struct perf_cpu_buf *cpu_buf;
12243 	char msg[STRERR_BUFSIZE];
12244 	int err;
12245 
12246 	cpu_buf = calloc(1, sizeof(*cpu_buf));
12247 	if (!cpu_buf)
12248 		return ERR_PTR(-ENOMEM);
12249 
12250 	cpu_buf->pb = pb;
12251 	cpu_buf->cpu = cpu;
12252 	cpu_buf->map_key = map_key;
12253 
12254 	cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
12255 			      -1, PERF_FLAG_FD_CLOEXEC);
12256 	if (cpu_buf->fd < 0) {
12257 		err = -errno;
12258 		pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
12259 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
12260 		goto error;
12261 	}
12262 
12263 	cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
12264 			     PROT_READ | PROT_WRITE, MAP_SHARED,
12265 			     cpu_buf->fd, 0);
12266 	if (cpu_buf->base == MAP_FAILED) {
12267 		cpu_buf->base = NULL;
12268 		err = -errno;
12269 		pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
12270 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
12271 		goto error;
12272 	}
12273 
12274 	if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
12275 		err = -errno;
12276 		pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
12277 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
12278 		goto error;
12279 	}
12280 
12281 	return cpu_buf;
12282 
12283 error:
12284 	perf_buffer__free_cpu_buf(pb, cpu_buf);
12285 	return (struct perf_cpu_buf *)ERR_PTR(err);
12286 }
12287 
12288 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
12289 					      struct perf_buffer_params *p);
12290 
12291 DEFAULT_VERSION(perf_buffer__new_v0_6_0, perf_buffer__new, LIBBPF_0.6.0)
12292 struct perf_buffer *perf_buffer__new_v0_6_0(int map_fd, size_t page_cnt,
12293 					    perf_buffer_sample_fn sample_cb,
12294 					    perf_buffer_lost_fn lost_cb,
12295 					    void *ctx,
12296 					    const struct perf_buffer_opts *opts)
12297 {
12298 	struct perf_buffer_params p = {};
12299 	struct perf_event_attr attr = {};
12300 
12301 	if (!OPTS_VALID(opts, perf_buffer_opts))
12302 		return libbpf_err_ptr(-EINVAL);
12303 
12304 	attr.config = PERF_COUNT_SW_BPF_OUTPUT;
12305 	attr.type = PERF_TYPE_SOFTWARE;
12306 	attr.sample_type = PERF_SAMPLE_RAW;
12307 	attr.sample_period = 1;
12308 	attr.wakeup_events = 1;
12309 
12310 	p.attr = &attr;
12311 	p.sample_cb = sample_cb;
12312 	p.lost_cb = lost_cb;
12313 	p.ctx = ctx;
12314 
12315 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
12316 }
12317 
12318 COMPAT_VERSION(perf_buffer__new_deprecated, perf_buffer__new, LIBBPF_0.0.4)
12319 struct perf_buffer *perf_buffer__new_deprecated(int map_fd, size_t page_cnt,
12320 						const struct perf_buffer_opts *opts)
12321 {
12322 	return perf_buffer__new_v0_6_0(map_fd, page_cnt,
12323 				       opts ? opts->sample_cb : NULL,
12324 				       opts ? opts->lost_cb : NULL,
12325 				       opts ? opts->ctx : NULL,
12326 				       NULL);
12327 }
12328 
12329 DEFAULT_VERSION(perf_buffer__new_raw_v0_6_0, perf_buffer__new_raw, LIBBPF_0.6.0)
12330 struct perf_buffer *perf_buffer__new_raw_v0_6_0(int map_fd, size_t page_cnt,
12331 						struct perf_event_attr *attr,
12332 						perf_buffer_event_fn event_cb, void *ctx,
12333 						const struct perf_buffer_raw_opts *opts)
12334 {
12335 	struct perf_buffer_params p = {};
12336 
12337 	if (!attr)
12338 		return libbpf_err_ptr(-EINVAL);
12339 
12340 	if (!OPTS_VALID(opts, perf_buffer_raw_opts))
12341 		return libbpf_err_ptr(-EINVAL);
12342 
12343 	p.attr = attr;
12344 	p.event_cb = event_cb;
12345 	p.ctx = ctx;
12346 	p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
12347 	p.cpus = OPTS_GET(opts, cpus, NULL);
12348 	p.map_keys = OPTS_GET(opts, map_keys, NULL);
12349 
12350 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
12351 }
12352 
12353 COMPAT_VERSION(perf_buffer__new_raw_deprecated, perf_buffer__new_raw, LIBBPF_0.0.4)
12354 struct perf_buffer *perf_buffer__new_raw_deprecated(int map_fd, size_t page_cnt,
12355 						    const struct perf_buffer_raw_opts *opts)
12356 {
12357 	LIBBPF_OPTS(perf_buffer_raw_opts, inner_opts,
12358 		.cpu_cnt = opts->cpu_cnt,
12359 		.cpus = opts->cpus,
12360 		.map_keys = opts->map_keys,
12361 	);
12362 
12363 	return perf_buffer__new_raw_v0_6_0(map_fd, page_cnt, opts->attr,
12364 					   opts->event_cb, opts->ctx, &inner_opts);
12365 }
12366 
12367 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
12368 					      struct perf_buffer_params *p)
12369 {
12370 	const char *online_cpus_file = "/sys/devices/system/cpu/online";
12371 	struct bpf_map_info map;
12372 	char msg[STRERR_BUFSIZE];
12373 	struct perf_buffer *pb;
12374 	bool *online = NULL;
12375 	__u32 map_info_len;
12376 	int err, i, j, n;
12377 
12378 	if (page_cnt == 0 || (page_cnt & (page_cnt - 1))) {
12379 		pr_warn("page count should be power of two, but is %zu\n",
12380 			page_cnt);
12381 		return ERR_PTR(-EINVAL);
12382 	}
12383 
12384 	/* best-effort sanity checks */
12385 	memset(&map, 0, sizeof(map));
12386 	map_info_len = sizeof(map);
12387 	err = bpf_obj_get_info_by_fd(map_fd, &map, &map_info_len);
12388 	if (err) {
12389 		err = -errno;
12390 		/* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
12391 		 * -EBADFD, -EFAULT, or -E2BIG on real error
12392 		 */
12393 		if (err != -EINVAL) {
12394 			pr_warn("failed to get map info for map FD %d: %s\n",
12395 				map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
12396 			return ERR_PTR(err);
12397 		}
12398 		pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
12399 			 map_fd);
12400 	} else {
12401 		if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
12402 			pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
12403 				map.name);
12404 			return ERR_PTR(-EINVAL);
12405 		}
12406 	}
12407 
12408 	pb = calloc(1, sizeof(*pb));
12409 	if (!pb)
12410 		return ERR_PTR(-ENOMEM);
12411 
12412 	pb->event_cb = p->event_cb;
12413 	pb->sample_cb = p->sample_cb;
12414 	pb->lost_cb = p->lost_cb;
12415 	pb->ctx = p->ctx;
12416 
12417 	pb->page_size = getpagesize();
12418 	pb->mmap_size = pb->page_size * page_cnt;
12419 	pb->map_fd = map_fd;
12420 
12421 	pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
12422 	if (pb->epoll_fd < 0) {
12423 		err = -errno;
12424 		pr_warn("failed to create epoll instance: %s\n",
12425 			libbpf_strerror_r(err, msg, sizeof(msg)));
12426 		goto error;
12427 	}
12428 
12429 	if (p->cpu_cnt > 0) {
12430 		pb->cpu_cnt = p->cpu_cnt;
12431 	} else {
12432 		pb->cpu_cnt = libbpf_num_possible_cpus();
12433 		if (pb->cpu_cnt < 0) {
12434 			err = pb->cpu_cnt;
12435 			goto error;
12436 		}
12437 		if (map.max_entries && map.max_entries < pb->cpu_cnt)
12438 			pb->cpu_cnt = map.max_entries;
12439 	}
12440 
12441 	pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
12442 	if (!pb->events) {
12443 		err = -ENOMEM;
12444 		pr_warn("failed to allocate events: out of memory\n");
12445 		goto error;
12446 	}
12447 	pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
12448 	if (!pb->cpu_bufs) {
12449 		err = -ENOMEM;
12450 		pr_warn("failed to allocate buffers: out of memory\n");
12451 		goto error;
12452 	}
12453 
12454 	err = parse_cpu_mask_file(online_cpus_file, &online, &n);
12455 	if (err) {
12456 		pr_warn("failed to get online CPU mask: %d\n", err);
12457 		goto error;
12458 	}
12459 
12460 	for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
12461 		struct perf_cpu_buf *cpu_buf;
12462 		int cpu, map_key;
12463 
12464 		cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
12465 		map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
12466 
12467 		/* in case user didn't explicitly requested particular CPUs to
12468 		 * be attached to, skip offline/not present CPUs
12469 		 */
12470 		if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
12471 			continue;
12472 
12473 		cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
12474 		if (IS_ERR(cpu_buf)) {
12475 			err = PTR_ERR(cpu_buf);
12476 			goto error;
12477 		}
12478 
12479 		pb->cpu_bufs[j] = cpu_buf;
12480 
12481 		err = bpf_map_update_elem(pb->map_fd, &map_key,
12482 					  &cpu_buf->fd, 0);
12483 		if (err) {
12484 			err = -errno;
12485 			pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
12486 				cpu, map_key, cpu_buf->fd,
12487 				libbpf_strerror_r(err, msg, sizeof(msg)));
12488 			goto error;
12489 		}
12490 
12491 		pb->events[j].events = EPOLLIN;
12492 		pb->events[j].data.ptr = cpu_buf;
12493 		if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
12494 			      &pb->events[j]) < 0) {
12495 			err = -errno;
12496 			pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
12497 				cpu, cpu_buf->fd,
12498 				libbpf_strerror_r(err, msg, sizeof(msg)));
12499 			goto error;
12500 		}
12501 		j++;
12502 	}
12503 	pb->cpu_cnt = j;
12504 	free(online);
12505 
12506 	return pb;
12507 
12508 error:
12509 	free(online);
12510 	if (pb)
12511 		perf_buffer__free(pb);
12512 	return ERR_PTR(err);
12513 }
12514 
12515 struct perf_sample_raw {
12516 	struct perf_event_header header;
12517 	uint32_t size;
12518 	char data[];
12519 };
12520 
12521 struct perf_sample_lost {
12522 	struct perf_event_header header;
12523 	uint64_t id;
12524 	uint64_t lost;
12525 	uint64_t sample_id;
12526 };
12527 
12528 static enum bpf_perf_event_ret
12529 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
12530 {
12531 	struct perf_cpu_buf *cpu_buf = ctx;
12532 	struct perf_buffer *pb = cpu_buf->pb;
12533 	void *data = e;
12534 
12535 	/* user wants full control over parsing perf event */
12536 	if (pb->event_cb)
12537 		return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
12538 
12539 	switch (e->type) {
12540 	case PERF_RECORD_SAMPLE: {
12541 		struct perf_sample_raw *s = data;
12542 
12543 		if (pb->sample_cb)
12544 			pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
12545 		break;
12546 	}
12547 	case PERF_RECORD_LOST: {
12548 		struct perf_sample_lost *s = data;
12549 
12550 		if (pb->lost_cb)
12551 			pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
12552 		break;
12553 	}
12554 	default:
12555 		pr_warn("unknown perf sample type %d\n", e->type);
12556 		return LIBBPF_PERF_EVENT_ERROR;
12557 	}
12558 	return LIBBPF_PERF_EVENT_CONT;
12559 }
12560 
12561 static int perf_buffer__process_records(struct perf_buffer *pb,
12562 					struct perf_cpu_buf *cpu_buf)
12563 {
12564 	enum bpf_perf_event_ret ret;
12565 
12566 	ret = perf_event_read_simple(cpu_buf->base, pb->mmap_size,
12567 				     pb->page_size, &cpu_buf->buf,
12568 				     &cpu_buf->buf_size,
12569 				     perf_buffer__process_record, cpu_buf);
12570 	if (ret != LIBBPF_PERF_EVENT_CONT)
12571 		return ret;
12572 	return 0;
12573 }
12574 
12575 int perf_buffer__epoll_fd(const struct perf_buffer *pb)
12576 {
12577 	return pb->epoll_fd;
12578 }
12579 
12580 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
12581 {
12582 	int i, cnt, err;
12583 
12584 	cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
12585 	if (cnt < 0)
12586 		return -errno;
12587 
12588 	for (i = 0; i < cnt; i++) {
12589 		struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
12590 
12591 		err = perf_buffer__process_records(pb, cpu_buf);
12592 		if (err) {
12593 			pr_warn("error while processing records: %d\n", err);
12594 			return libbpf_err(err);
12595 		}
12596 	}
12597 	return cnt;
12598 }
12599 
12600 /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
12601  * manager.
12602  */
12603 size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
12604 {
12605 	return pb->cpu_cnt;
12606 }
12607 
12608 /*
12609  * Return perf_event FD of a ring buffer in *buf_idx* slot of
12610  * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
12611  * select()/poll()/epoll() Linux syscalls.
12612  */
12613 int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
12614 {
12615 	struct perf_cpu_buf *cpu_buf;
12616 
12617 	if (buf_idx >= pb->cpu_cnt)
12618 		return libbpf_err(-EINVAL);
12619 
12620 	cpu_buf = pb->cpu_bufs[buf_idx];
12621 	if (!cpu_buf)
12622 		return libbpf_err(-ENOENT);
12623 
12624 	return cpu_buf->fd;
12625 }
12626 
12627 /*
12628  * Consume data from perf ring buffer corresponding to slot *buf_idx* in
12629  * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
12630  * consume, do nothing and return success.
12631  * Returns:
12632  *   - 0 on success;
12633  *   - <0 on failure.
12634  */
12635 int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
12636 {
12637 	struct perf_cpu_buf *cpu_buf;
12638 
12639 	if (buf_idx >= pb->cpu_cnt)
12640 		return libbpf_err(-EINVAL);
12641 
12642 	cpu_buf = pb->cpu_bufs[buf_idx];
12643 	if (!cpu_buf)
12644 		return libbpf_err(-ENOENT);
12645 
12646 	return perf_buffer__process_records(pb, cpu_buf);
12647 }
12648 
12649 int perf_buffer__consume(struct perf_buffer *pb)
12650 {
12651 	int i, err;
12652 
12653 	for (i = 0; i < pb->cpu_cnt; i++) {
12654 		struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
12655 
12656 		if (!cpu_buf)
12657 			continue;
12658 
12659 		err = perf_buffer__process_records(pb, cpu_buf);
12660 		if (err) {
12661 			pr_warn("perf_buffer: failed to process records in buffer #%d: %d\n", i, err);
12662 			return libbpf_err(err);
12663 		}
12664 	}
12665 	return 0;
12666 }
12667 
12668 struct bpf_prog_info_array_desc {
12669 	int	array_offset;	/* e.g. offset of jited_prog_insns */
12670 	int	count_offset;	/* e.g. offset of jited_prog_len */
12671 	int	size_offset;	/* > 0: offset of rec size,
12672 				 * < 0: fix size of -size_offset
12673 				 */
12674 };
12675 
12676 static struct bpf_prog_info_array_desc bpf_prog_info_array_desc[] = {
12677 	[BPF_PROG_INFO_JITED_INSNS] = {
12678 		offsetof(struct bpf_prog_info, jited_prog_insns),
12679 		offsetof(struct bpf_prog_info, jited_prog_len),
12680 		-1,
12681 	},
12682 	[BPF_PROG_INFO_XLATED_INSNS] = {
12683 		offsetof(struct bpf_prog_info, xlated_prog_insns),
12684 		offsetof(struct bpf_prog_info, xlated_prog_len),
12685 		-1,
12686 	},
12687 	[BPF_PROG_INFO_MAP_IDS] = {
12688 		offsetof(struct bpf_prog_info, map_ids),
12689 		offsetof(struct bpf_prog_info, nr_map_ids),
12690 		-(int)sizeof(__u32),
12691 	},
12692 	[BPF_PROG_INFO_JITED_KSYMS] = {
12693 		offsetof(struct bpf_prog_info, jited_ksyms),
12694 		offsetof(struct bpf_prog_info, nr_jited_ksyms),
12695 		-(int)sizeof(__u64),
12696 	},
12697 	[BPF_PROG_INFO_JITED_FUNC_LENS] = {
12698 		offsetof(struct bpf_prog_info, jited_func_lens),
12699 		offsetof(struct bpf_prog_info, nr_jited_func_lens),
12700 		-(int)sizeof(__u32),
12701 	},
12702 	[BPF_PROG_INFO_FUNC_INFO] = {
12703 		offsetof(struct bpf_prog_info, func_info),
12704 		offsetof(struct bpf_prog_info, nr_func_info),
12705 		offsetof(struct bpf_prog_info, func_info_rec_size),
12706 	},
12707 	[BPF_PROG_INFO_LINE_INFO] = {
12708 		offsetof(struct bpf_prog_info, line_info),
12709 		offsetof(struct bpf_prog_info, nr_line_info),
12710 		offsetof(struct bpf_prog_info, line_info_rec_size),
12711 	},
12712 	[BPF_PROG_INFO_JITED_LINE_INFO] = {
12713 		offsetof(struct bpf_prog_info, jited_line_info),
12714 		offsetof(struct bpf_prog_info, nr_jited_line_info),
12715 		offsetof(struct bpf_prog_info, jited_line_info_rec_size),
12716 	},
12717 	[BPF_PROG_INFO_PROG_TAGS] = {
12718 		offsetof(struct bpf_prog_info, prog_tags),
12719 		offsetof(struct bpf_prog_info, nr_prog_tags),
12720 		-(int)sizeof(__u8) * BPF_TAG_SIZE,
12721 	},
12722 
12723 };
12724 
12725 static __u32 bpf_prog_info_read_offset_u32(struct bpf_prog_info *info,
12726 					   int offset)
12727 {
12728 	__u32 *array = (__u32 *)info;
12729 
12730 	if (offset >= 0)
12731 		return array[offset / sizeof(__u32)];
12732 	return -(int)offset;
12733 }
12734 
12735 static __u64 bpf_prog_info_read_offset_u64(struct bpf_prog_info *info,
12736 					   int offset)
12737 {
12738 	__u64 *array = (__u64 *)info;
12739 
12740 	if (offset >= 0)
12741 		return array[offset / sizeof(__u64)];
12742 	return -(int)offset;
12743 }
12744 
12745 static void bpf_prog_info_set_offset_u32(struct bpf_prog_info *info, int offset,
12746 					 __u32 val)
12747 {
12748 	__u32 *array = (__u32 *)info;
12749 
12750 	if (offset >= 0)
12751 		array[offset / sizeof(__u32)] = val;
12752 }
12753 
12754 static void bpf_prog_info_set_offset_u64(struct bpf_prog_info *info, int offset,
12755 					 __u64 val)
12756 {
12757 	__u64 *array = (__u64 *)info;
12758 
12759 	if (offset >= 0)
12760 		array[offset / sizeof(__u64)] = val;
12761 }
12762 
12763 struct bpf_prog_info_linear *
12764 bpf_program__get_prog_info_linear(int fd, __u64 arrays)
12765 {
12766 	struct bpf_prog_info_linear *info_linear;
12767 	struct bpf_prog_info info = {};
12768 	__u32 info_len = sizeof(info);
12769 	__u32 data_len = 0;
12770 	int i, err;
12771 	void *ptr;
12772 
12773 	if (arrays >> BPF_PROG_INFO_LAST_ARRAY)
12774 		return libbpf_err_ptr(-EINVAL);
12775 
12776 	/* step 1: get array dimensions */
12777 	err = bpf_obj_get_info_by_fd(fd, &info, &info_len);
12778 	if (err) {
12779 		pr_debug("can't get prog info: %s", strerror(errno));
12780 		return libbpf_err_ptr(-EFAULT);
12781 	}
12782 
12783 	/* step 2: calculate total size of all arrays */
12784 	for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
12785 		bool include_array = (arrays & (1UL << i)) > 0;
12786 		struct bpf_prog_info_array_desc *desc;
12787 		__u32 count, size;
12788 
12789 		desc = bpf_prog_info_array_desc + i;
12790 
12791 		/* kernel is too old to support this field */
12792 		if (info_len < desc->array_offset + sizeof(__u32) ||
12793 		    info_len < desc->count_offset + sizeof(__u32) ||
12794 		    (desc->size_offset > 0 && info_len < desc->size_offset))
12795 			include_array = false;
12796 
12797 		if (!include_array) {
12798 			arrays &= ~(1UL << i);	/* clear the bit */
12799 			continue;
12800 		}
12801 
12802 		count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
12803 		size  = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
12804 
12805 		data_len += count * size;
12806 	}
12807 
12808 	/* step 3: allocate continuous memory */
12809 	data_len = roundup(data_len, sizeof(__u64));
12810 	info_linear = malloc(sizeof(struct bpf_prog_info_linear) + data_len);
12811 	if (!info_linear)
12812 		return libbpf_err_ptr(-ENOMEM);
12813 
12814 	/* step 4: fill data to info_linear->info */
12815 	info_linear->arrays = arrays;
12816 	memset(&info_linear->info, 0, sizeof(info));
12817 	ptr = info_linear->data;
12818 
12819 	for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
12820 		struct bpf_prog_info_array_desc *desc;
12821 		__u32 count, size;
12822 
12823 		if ((arrays & (1UL << i)) == 0)
12824 			continue;
12825 
12826 		desc  = bpf_prog_info_array_desc + i;
12827 		count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
12828 		size  = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
12829 		bpf_prog_info_set_offset_u32(&info_linear->info,
12830 					     desc->count_offset, count);
12831 		bpf_prog_info_set_offset_u32(&info_linear->info,
12832 					     desc->size_offset, size);
12833 		bpf_prog_info_set_offset_u64(&info_linear->info,
12834 					     desc->array_offset,
12835 					     ptr_to_u64(ptr));
12836 		ptr += count * size;
12837 	}
12838 
12839 	/* step 5: call syscall again to get required arrays */
12840 	err = bpf_obj_get_info_by_fd(fd, &info_linear->info, &info_len);
12841 	if (err) {
12842 		pr_debug("can't get prog info: %s", strerror(errno));
12843 		free(info_linear);
12844 		return libbpf_err_ptr(-EFAULT);
12845 	}
12846 
12847 	/* step 6: verify the data */
12848 	for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
12849 		struct bpf_prog_info_array_desc *desc;
12850 		__u32 v1, v2;
12851 
12852 		if ((arrays & (1UL << i)) == 0)
12853 			continue;
12854 
12855 		desc = bpf_prog_info_array_desc + i;
12856 		v1 = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
12857 		v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
12858 						   desc->count_offset);
12859 		if (v1 != v2)
12860 			pr_warn("%s: mismatch in element count\n", __func__);
12861 
12862 		v1 = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
12863 		v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
12864 						   desc->size_offset);
12865 		if (v1 != v2)
12866 			pr_warn("%s: mismatch in rec size\n", __func__);
12867 	}
12868 
12869 	/* step 7: update info_len and data_len */
12870 	info_linear->info_len = sizeof(struct bpf_prog_info);
12871 	info_linear->data_len = data_len;
12872 
12873 	return info_linear;
12874 }
12875 
12876 void bpf_program__bpil_addr_to_offs(struct bpf_prog_info_linear *info_linear)
12877 {
12878 	int i;
12879 
12880 	for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
12881 		struct bpf_prog_info_array_desc *desc;
12882 		__u64 addr, offs;
12883 
12884 		if ((info_linear->arrays & (1UL << i)) == 0)
12885 			continue;
12886 
12887 		desc = bpf_prog_info_array_desc + i;
12888 		addr = bpf_prog_info_read_offset_u64(&info_linear->info,
12889 						     desc->array_offset);
12890 		offs = addr - ptr_to_u64(info_linear->data);
12891 		bpf_prog_info_set_offset_u64(&info_linear->info,
12892 					     desc->array_offset, offs);
12893 	}
12894 }
12895 
12896 void bpf_program__bpil_offs_to_addr(struct bpf_prog_info_linear *info_linear)
12897 {
12898 	int i;
12899 
12900 	for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
12901 		struct bpf_prog_info_array_desc *desc;
12902 		__u64 addr, offs;
12903 
12904 		if ((info_linear->arrays & (1UL << i)) == 0)
12905 			continue;
12906 
12907 		desc = bpf_prog_info_array_desc + i;
12908 		offs = bpf_prog_info_read_offset_u64(&info_linear->info,
12909 						     desc->array_offset);
12910 		addr = offs + ptr_to_u64(info_linear->data);
12911 		bpf_prog_info_set_offset_u64(&info_linear->info,
12912 					     desc->array_offset, addr);
12913 	}
12914 }
12915 
12916 int bpf_program__set_attach_target(struct bpf_program *prog,
12917 				   int attach_prog_fd,
12918 				   const char *attach_func_name)
12919 {
12920 	int btf_obj_fd = 0, btf_id = 0, err;
12921 
12922 	if (!prog || attach_prog_fd < 0)
12923 		return libbpf_err(-EINVAL);
12924 
12925 	if (prog->obj->loaded)
12926 		return libbpf_err(-EINVAL);
12927 
12928 	if (attach_prog_fd && !attach_func_name) {
12929 		/* remember attach_prog_fd and let bpf_program__load() find
12930 		 * BTF ID during the program load
12931 		 */
12932 		prog->attach_prog_fd = attach_prog_fd;
12933 		return 0;
12934 	}
12935 
12936 	if (attach_prog_fd) {
12937 		btf_id = libbpf_find_prog_btf_id(attach_func_name,
12938 						 attach_prog_fd);
12939 		if (btf_id < 0)
12940 			return libbpf_err(btf_id);
12941 	} else {
12942 		if (!attach_func_name)
12943 			return libbpf_err(-EINVAL);
12944 
12945 		/* load btf_vmlinux, if not yet */
12946 		err = bpf_object__load_vmlinux_btf(prog->obj, true);
12947 		if (err)
12948 			return libbpf_err(err);
12949 		err = find_kernel_btf_id(prog->obj, attach_func_name,
12950 					 prog->expected_attach_type,
12951 					 &btf_obj_fd, &btf_id);
12952 		if (err)
12953 			return libbpf_err(err);
12954 	}
12955 
12956 	prog->attach_btf_id = btf_id;
12957 	prog->attach_btf_obj_fd = btf_obj_fd;
12958 	prog->attach_prog_fd = attach_prog_fd;
12959 	return 0;
12960 }
12961 
12962 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
12963 {
12964 	int err = 0, n, len, start, end = -1;
12965 	bool *tmp;
12966 
12967 	*mask = NULL;
12968 	*mask_sz = 0;
12969 
12970 	/* Each sub string separated by ',' has format \d+-\d+ or \d+ */
12971 	while (*s) {
12972 		if (*s == ',' || *s == '\n') {
12973 			s++;
12974 			continue;
12975 		}
12976 		n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
12977 		if (n <= 0 || n > 2) {
12978 			pr_warn("Failed to get CPU range %s: %d\n", s, n);
12979 			err = -EINVAL;
12980 			goto cleanup;
12981 		} else if (n == 1) {
12982 			end = start;
12983 		}
12984 		if (start < 0 || start > end) {
12985 			pr_warn("Invalid CPU range [%d,%d] in %s\n",
12986 				start, end, s);
12987 			err = -EINVAL;
12988 			goto cleanup;
12989 		}
12990 		tmp = realloc(*mask, end + 1);
12991 		if (!tmp) {
12992 			err = -ENOMEM;
12993 			goto cleanup;
12994 		}
12995 		*mask = tmp;
12996 		memset(tmp + *mask_sz, 0, start - *mask_sz);
12997 		memset(tmp + start, 1, end - start + 1);
12998 		*mask_sz = end + 1;
12999 		s += len;
13000 	}
13001 	if (!*mask_sz) {
13002 		pr_warn("Empty CPU range\n");
13003 		return -EINVAL;
13004 	}
13005 	return 0;
13006 cleanup:
13007 	free(*mask);
13008 	*mask = NULL;
13009 	return err;
13010 }
13011 
13012 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
13013 {
13014 	int fd, err = 0, len;
13015 	char buf[128];
13016 
13017 	fd = open(fcpu, O_RDONLY | O_CLOEXEC);
13018 	if (fd < 0) {
13019 		err = -errno;
13020 		pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
13021 		return err;
13022 	}
13023 	len = read(fd, buf, sizeof(buf));
13024 	close(fd);
13025 	if (len <= 0) {
13026 		err = len ? -errno : -EINVAL;
13027 		pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
13028 		return err;
13029 	}
13030 	if (len >= sizeof(buf)) {
13031 		pr_warn("CPU mask is too big in file %s\n", fcpu);
13032 		return -E2BIG;
13033 	}
13034 	buf[len] = '\0';
13035 
13036 	return parse_cpu_mask_str(buf, mask, mask_sz);
13037 }
13038 
13039 int libbpf_num_possible_cpus(void)
13040 {
13041 	static const char *fcpu = "/sys/devices/system/cpu/possible";
13042 	static int cpus;
13043 	int err, n, i, tmp_cpus;
13044 	bool *mask;
13045 
13046 	tmp_cpus = READ_ONCE(cpus);
13047 	if (tmp_cpus > 0)
13048 		return tmp_cpus;
13049 
13050 	err = parse_cpu_mask_file(fcpu, &mask, &n);
13051 	if (err)
13052 		return libbpf_err(err);
13053 
13054 	tmp_cpus = 0;
13055 	for (i = 0; i < n; i++) {
13056 		if (mask[i])
13057 			tmp_cpus++;
13058 	}
13059 	free(mask);
13060 
13061 	WRITE_ONCE(cpus, tmp_cpus);
13062 	return tmp_cpus;
13063 }
13064 
13065 static int populate_skeleton_maps(const struct bpf_object *obj,
13066 				  struct bpf_map_skeleton *maps,
13067 				  size_t map_cnt)
13068 {
13069 	int i;
13070 
13071 	for (i = 0; i < map_cnt; i++) {
13072 		struct bpf_map **map = maps[i].map;
13073 		const char *name = maps[i].name;
13074 		void **mmaped = maps[i].mmaped;
13075 
13076 		*map = bpf_object__find_map_by_name(obj, name);
13077 		if (!*map) {
13078 			pr_warn("failed to find skeleton map '%s'\n", name);
13079 			return -ESRCH;
13080 		}
13081 
13082 		/* externs shouldn't be pre-setup from user code */
13083 		if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
13084 			*mmaped = (*map)->mmaped;
13085 	}
13086 	return 0;
13087 }
13088 
13089 static int populate_skeleton_progs(const struct bpf_object *obj,
13090 				   struct bpf_prog_skeleton *progs,
13091 				   size_t prog_cnt)
13092 {
13093 	int i;
13094 
13095 	for (i = 0; i < prog_cnt; i++) {
13096 		struct bpf_program **prog = progs[i].prog;
13097 		const char *name = progs[i].name;
13098 
13099 		*prog = bpf_object__find_program_by_name(obj, name);
13100 		if (!*prog) {
13101 			pr_warn("failed to find skeleton program '%s'\n", name);
13102 			return -ESRCH;
13103 		}
13104 	}
13105 	return 0;
13106 }
13107 
13108 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
13109 			      const struct bpf_object_open_opts *opts)
13110 {
13111 	DECLARE_LIBBPF_OPTS(bpf_object_open_opts, skel_opts,
13112 		.object_name = s->name,
13113 	);
13114 	struct bpf_object *obj;
13115 	int err;
13116 
13117 	/* Attempt to preserve opts->object_name, unless overriden by user
13118 	 * explicitly. Overwriting object name for skeletons is discouraged,
13119 	 * as it breaks global data maps, because they contain object name
13120 	 * prefix as their own map name prefix. When skeleton is generated,
13121 	 * bpftool is making an assumption that this name will stay the same.
13122 	 */
13123 	if (opts) {
13124 		memcpy(&skel_opts, opts, sizeof(*opts));
13125 		if (!opts->object_name)
13126 			skel_opts.object_name = s->name;
13127 	}
13128 
13129 	obj = bpf_object__open_mem(s->data, s->data_sz, &skel_opts);
13130 	err = libbpf_get_error(obj);
13131 	if (err) {
13132 		pr_warn("failed to initialize skeleton BPF object '%s': %d\n",
13133 			s->name, err);
13134 		return libbpf_err(err);
13135 	}
13136 
13137 	*s->obj = obj;
13138 	err = populate_skeleton_maps(obj, s->maps, s->map_cnt);
13139 	if (err) {
13140 		pr_warn("failed to populate skeleton maps for '%s': %d\n", s->name, err);
13141 		return libbpf_err(err);
13142 	}
13143 
13144 	err = populate_skeleton_progs(obj, s->progs, s->prog_cnt);
13145 	if (err) {
13146 		pr_warn("failed to populate skeleton progs for '%s': %d\n", s->name, err);
13147 		return libbpf_err(err);
13148 	}
13149 
13150 	return 0;
13151 }
13152 
13153 int bpf_object__open_subskeleton(struct bpf_object_subskeleton *s)
13154 {
13155 	int err, len, var_idx, i;
13156 	const char *var_name;
13157 	const struct bpf_map *map;
13158 	struct btf *btf;
13159 	__u32 map_type_id;
13160 	const struct btf_type *map_type, *var_type;
13161 	const struct bpf_var_skeleton *var_skel;
13162 	struct btf_var_secinfo *var;
13163 
13164 	if (!s->obj)
13165 		return libbpf_err(-EINVAL);
13166 
13167 	btf = bpf_object__btf(s->obj);
13168 	if (!btf) {
13169 		pr_warn("subskeletons require BTF at runtime (object %s)\n",
13170 		        bpf_object__name(s->obj));
13171 		return libbpf_err(-errno);
13172 	}
13173 
13174 	err = populate_skeleton_maps(s->obj, s->maps, s->map_cnt);
13175 	if (err) {
13176 		pr_warn("failed to populate subskeleton maps: %d\n", err);
13177 		return libbpf_err(err);
13178 	}
13179 
13180 	err = populate_skeleton_progs(s->obj, s->progs, s->prog_cnt);
13181 	if (err) {
13182 		pr_warn("failed to populate subskeleton maps: %d\n", err);
13183 		return libbpf_err(err);
13184 	}
13185 
13186 	for (var_idx = 0; var_idx < s->var_cnt; var_idx++) {
13187 		var_skel = &s->vars[var_idx];
13188 		map = *var_skel->map;
13189 		map_type_id = bpf_map__btf_value_type_id(map);
13190 		map_type = btf__type_by_id(btf, map_type_id);
13191 
13192 		if (!btf_is_datasec(map_type)) {
13193 			pr_warn("type for map '%1$s' is not a datasec: %2$s",
13194 				bpf_map__name(map),
13195 				__btf_kind_str(btf_kind(map_type)));
13196 			return libbpf_err(-EINVAL);
13197 		}
13198 
13199 		len = btf_vlen(map_type);
13200 		var = btf_var_secinfos(map_type);
13201 		for (i = 0; i < len; i++, var++) {
13202 			var_type = btf__type_by_id(btf, var->type);
13203 			var_name = btf__name_by_offset(btf, var_type->name_off);
13204 			if (strcmp(var_name, var_skel->name) == 0) {
13205 				*var_skel->addr = map->mmaped + var->offset;
13206 				break;
13207 			}
13208 		}
13209 	}
13210 	return 0;
13211 }
13212 
13213 void bpf_object__destroy_subskeleton(struct bpf_object_subskeleton *s)
13214 {
13215 	if (!s)
13216 		return;
13217 	free(s->maps);
13218 	free(s->progs);
13219 	free(s->vars);
13220 	free(s);
13221 }
13222 
13223 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
13224 {
13225 	int i, err;
13226 
13227 	err = bpf_object__load(*s->obj);
13228 	if (err) {
13229 		pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
13230 		return libbpf_err(err);
13231 	}
13232 
13233 	for (i = 0; i < s->map_cnt; i++) {
13234 		struct bpf_map *map = *s->maps[i].map;
13235 		size_t mmap_sz = bpf_map_mmap_sz(map);
13236 		int prot, map_fd = bpf_map__fd(map);
13237 		void **mmaped = s->maps[i].mmaped;
13238 
13239 		if (!mmaped)
13240 			continue;
13241 
13242 		if (!(map->def.map_flags & BPF_F_MMAPABLE)) {
13243 			*mmaped = NULL;
13244 			continue;
13245 		}
13246 
13247 		if (map->def.map_flags & BPF_F_RDONLY_PROG)
13248 			prot = PROT_READ;
13249 		else
13250 			prot = PROT_READ | PROT_WRITE;
13251 
13252 		/* Remap anonymous mmap()-ed "map initialization image" as
13253 		 * a BPF map-backed mmap()-ed memory, but preserving the same
13254 		 * memory address. This will cause kernel to change process'
13255 		 * page table to point to a different piece of kernel memory,
13256 		 * but from userspace point of view memory address (and its
13257 		 * contents, being identical at this point) will stay the
13258 		 * same. This mapping will be released by bpf_object__close()
13259 		 * as per normal clean up procedure, so we don't need to worry
13260 		 * about it from skeleton's clean up perspective.
13261 		 */
13262 		*mmaped = mmap(map->mmaped, mmap_sz, prot,
13263 				MAP_SHARED | MAP_FIXED, map_fd, 0);
13264 		if (*mmaped == MAP_FAILED) {
13265 			err = -errno;
13266 			*mmaped = NULL;
13267 			pr_warn("failed to re-mmap() map '%s': %d\n",
13268 				 bpf_map__name(map), err);
13269 			return libbpf_err(err);
13270 		}
13271 	}
13272 
13273 	return 0;
13274 }
13275 
13276 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
13277 {
13278 	int i, err;
13279 
13280 	for (i = 0; i < s->prog_cnt; i++) {
13281 		struct bpf_program *prog = *s->progs[i].prog;
13282 		struct bpf_link **link = s->progs[i].link;
13283 
13284 		if (!prog->autoload)
13285 			continue;
13286 
13287 		/* auto-attaching not supported for this program */
13288 		if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
13289 			continue;
13290 
13291 		/* if user already set the link manually, don't attempt auto-attach */
13292 		if (*link)
13293 			continue;
13294 
13295 		err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, link);
13296 		if (err) {
13297 			pr_warn("prog '%s': failed to auto-attach: %d\n",
13298 				bpf_program__name(prog), err);
13299 			return libbpf_err(err);
13300 		}
13301 
13302 		/* It's possible that for some SEC() definitions auto-attach
13303 		 * is supported in some cases (e.g., if definition completely
13304 		 * specifies target information), but is not in other cases.
13305 		 * SEC("uprobe") is one such case. If user specified target
13306 		 * binary and function name, such BPF program can be
13307 		 * auto-attached. But if not, it shouldn't trigger skeleton's
13308 		 * attach to fail. It should just be skipped.
13309 		 * attach_fn signals such case with returning 0 (no error) and
13310 		 * setting link to NULL.
13311 		 */
13312 	}
13313 
13314 	return 0;
13315 }
13316 
13317 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
13318 {
13319 	int i;
13320 
13321 	for (i = 0; i < s->prog_cnt; i++) {
13322 		struct bpf_link **link = s->progs[i].link;
13323 
13324 		bpf_link__destroy(*link);
13325 		*link = NULL;
13326 	}
13327 }
13328 
13329 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
13330 {
13331 	if (!s)
13332 		return;
13333 
13334 	if (s->progs)
13335 		bpf_object__detach_skeleton(s);
13336 	if (s->obj)
13337 		bpf_object__close(*s->obj);
13338 	free(s->maps);
13339 	free(s->progs);
13340 	free(s);
13341 }
13342