xref: /openbmc/linux/tools/lib/bpf/libbpf.c (revision 3ce7547e)
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 link_type_name[] = {
122 	[BPF_LINK_TYPE_UNSPEC]			= "unspec",
123 	[BPF_LINK_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
124 	[BPF_LINK_TYPE_TRACING]			= "tracing",
125 	[BPF_LINK_TYPE_CGROUP]			= "cgroup",
126 	[BPF_LINK_TYPE_ITER]			= "iter",
127 	[BPF_LINK_TYPE_NETNS]			= "netns",
128 	[BPF_LINK_TYPE_XDP]			= "xdp",
129 	[BPF_LINK_TYPE_PERF_EVENT]		= "perf_event",
130 	[BPF_LINK_TYPE_KPROBE_MULTI]		= "kprobe_multi",
131 	[BPF_LINK_TYPE_STRUCT_OPS]		= "struct_ops",
132 };
133 
134 static const char * const map_type_name[] = {
135 	[BPF_MAP_TYPE_UNSPEC]			= "unspec",
136 	[BPF_MAP_TYPE_HASH]			= "hash",
137 	[BPF_MAP_TYPE_ARRAY]			= "array",
138 	[BPF_MAP_TYPE_PROG_ARRAY]		= "prog_array",
139 	[BPF_MAP_TYPE_PERF_EVENT_ARRAY]		= "perf_event_array",
140 	[BPF_MAP_TYPE_PERCPU_HASH]		= "percpu_hash",
141 	[BPF_MAP_TYPE_PERCPU_ARRAY]		= "percpu_array",
142 	[BPF_MAP_TYPE_STACK_TRACE]		= "stack_trace",
143 	[BPF_MAP_TYPE_CGROUP_ARRAY]		= "cgroup_array",
144 	[BPF_MAP_TYPE_LRU_HASH]			= "lru_hash",
145 	[BPF_MAP_TYPE_LRU_PERCPU_HASH]		= "lru_percpu_hash",
146 	[BPF_MAP_TYPE_LPM_TRIE]			= "lpm_trie",
147 	[BPF_MAP_TYPE_ARRAY_OF_MAPS]		= "array_of_maps",
148 	[BPF_MAP_TYPE_HASH_OF_MAPS]		= "hash_of_maps",
149 	[BPF_MAP_TYPE_DEVMAP]			= "devmap",
150 	[BPF_MAP_TYPE_DEVMAP_HASH]		= "devmap_hash",
151 	[BPF_MAP_TYPE_SOCKMAP]			= "sockmap",
152 	[BPF_MAP_TYPE_CPUMAP]			= "cpumap",
153 	[BPF_MAP_TYPE_XSKMAP]			= "xskmap",
154 	[BPF_MAP_TYPE_SOCKHASH]			= "sockhash",
155 	[BPF_MAP_TYPE_CGROUP_STORAGE]		= "cgroup_storage",
156 	[BPF_MAP_TYPE_REUSEPORT_SOCKARRAY]	= "reuseport_sockarray",
157 	[BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE]	= "percpu_cgroup_storage",
158 	[BPF_MAP_TYPE_QUEUE]			= "queue",
159 	[BPF_MAP_TYPE_STACK]			= "stack",
160 	[BPF_MAP_TYPE_SK_STORAGE]		= "sk_storage",
161 	[BPF_MAP_TYPE_STRUCT_OPS]		= "struct_ops",
162 	[BPF_MAP_TYPE_RINGBUF]			= "ringbuf",
163 	[BPF_MAP_TYPE_INODE_STORAGE]		= "inode_storage",
164 	[BPF_MAP_TYPE_TASK_STORAGE]		= "task_storage",
165 	[BPF_MAP_TYPE_BLOOM_FILTER]		= "bloom_filter",
166 };
167 
168 static const char * const prog_type_name[] = {
169 	[BPF_PROG_TYPE_UNSPEC]			= "unspec",
170 	[BPF_PROG_TYPE_SOCKET_FILTER]		= "socket_filter",
171 	[BPF_PROG_TYPE_KPROBE]			= "kprobe",
172 	[BPF_PROG_TYPE_SCHED_CLS]		= "sched_cls",
173 	[BPF_PROG_TYPE_SCHED_ACT]		= "sched_act",
174 	[BPF_PROG_TYPE_TRACEPOINT]		= "tracepoint",
175 	[BPF_PROG_TYPE_XDP]			= "xdp",
176 	[BPF_PROG_TYPE_PERF_EVENT]		= "perf_event",
177 	[BPF_PROG_TYPE_CGROUP_SKB]		= "cgroup_skb",
178 	[BPF_PROG_TYPE_CGROUP_SOCK]		= "cgroup_sock",
179 	[BPF_PROG_TYPE_LWT_IN]			= "lwt_in",
180 	[BPF_PROG_TYPE_LWT_OUT]			= "lwt_out",
181 	[BPF_PROG_TYPE_LWT_XMIT]		= "lwt_xmit",
182 	[BPF_PROG_TYPE_SOCK_OPS]		= "sock_ops",
183 	[BPF_PROG_TYPE_SK_SKB]			= "sk_skb",
184 	[BPF_PROG_TYPE_CGROUP_DEVICE]		= "cgroup_device",
185 	[BPF_PROG_TYPE_SK_MSG]			= "sk_msg",
186 	[BPF_PROG_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
187 	[BPF_PROG_TYPE_CGROUP_SOCK_ADDR]	= "cgroup_sock_addr",
188 	[BPF_PROG_TYPE_LWT_SEG6LOCAL]		= "lwt_seg6local",
189 	[BPF_PROG_TYPE_LIRC_MODE2]		= "lirc_mode2",
190 	[BPF_PROG_TYPE_SK_REUSEPORT]		= "sk_reuseport",
191 	[BPF_PROG_TYPE_FLOW_DISSECTOR]		= "flow_dissector",
192 	[BPF_PROG_TYPE_CGROUP_SYSCTL]		= "cgroup_sysctl",
193 	[BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE]	= "raw_tracepoint_writable",
194 	[BPF_PROG_TYPE_CGROUP_SOCKOPT]		= "cgroup_sockopt",
195 	[BPF_PROG_TYPE_TRACING]			= "tracing",
196 	[BPF_PROG_TYPE_STRUCT_OPS]		= "struct_ops",
197 	[BPF_PROG_TYPE_EXT]			= "ext",
198 	[BPF_PROG_TYPE_LSM]			= "lsm",
199 	[BPF_PROG_TYPE_SK_LOOKUP]		= "sk_lookup",
200 	[BPF_PROG_TYPE_SYSCALL]			= "syscall",
201 };
202 
203 static int __base_pr(enum libbpf_print_level level, const char *format,
204 		     va_list args)
205 {
206 	if (level == LIBBPF_DEBUG)
207 		return 0;
208 
209 	return vfprintf(stderr, format, args);
210 }
211 
212 static libbpf_print_fn_t __libbpf_pr = __base_pr;
213 
214 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
215 {
216 	libbpf_print_fn_t old_print_fn = __libbpf_pr;
217 
218 	__libbpf_pr = fn;
219 	return old_print_fn;
220 }
221 
222 __printf(2, 3)
223 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
224 {
225 	va_list args;
226 
227 	if (!__libbpf_pr)
228 		return;
229 
230 	va_start(args, format);
231 	__libbpf_pr(level, format, args);
232 	va_end(args);
233 }
234 
235 static void pr_perm_msg(int err)
236 {
237 	struct rlimit limit;
238 	char buf[100];
239 
240 	if (err != -EPERM || geteuid() != 0)
241 		return;
242 
243 	err = getrlimit(RLIMIT_MEMLOCK, &limit);
244 	if (err)
245 		return;
246 
247 	if (limit.rlim_cur == RLIM_INFINITY)
248 		return;
249 
250 	if (limit.rlim_cur < 1024)
251 		snprintf(buf, sizeof(buf), "%zu bytes", (size_t)limit.rlim_cur);
252 	else if (limit.rlim_cur < 1024*1024)
253 		snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
254 	else
255 		snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
256 
257 	pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
258 		buf);
259 }
260 
261 #define STRERR_BUFSIZE  128
262 
263 /* Copied from tools/perf/util/util.h */
264 #ifndef zfree
265 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
266 #endif
267 
268 #ifndef zclose
269 # define zclose(fd) ({			\
270 	int ___err = 0;			\
271 	if ((fd) >= 0)			\
272 		___err = close((fd));	\
273 	fd = -1;			\
274 	___err; })
275 #endif
276 
277 static inline __u64 ptr_to_u64(const void *ptr)
278 {
279 	return (__u64) (unsigned long) ptr;
280 }
281 
282 /* this goes away in libbpf 1.0 */
283 enum libbpf_strict_mode libbpf_mode = LIBBPF_STRICT_NONE;
284 
285 int libbpf_set_strict_mode(enum libbpf_strict_mode mode)
286 {
287 	libbpf_mode = mode;
288 	return 0;
289 }
290 
291 __u32 libbpf_major_version(void)
292 {
293 	return LIBBPF_MAJOR_VERSION;
294 }
295 
296 __u32 libbpf_minor_version(void)
297 {
298 	return LIBBPF_MINOR_VERSION;
299 }
300 
301 const char *libbpf_version_string(void)
302 {
303 #define __S(X) #X
304 #define _S(X) __S(X)
305 	return  "v" _S(LIBBPF_MAJOR_VERSION) "." _S(LIBBPF_MINOR_VERSION);
306 #undef _S
307 #undef __S
308 }
309 
310 enum reloc_type {
311 	RELO_LD64,
312 	RELO_CALL,
313 	RELO_DATA,
314 	RELO_EXTERN_VAR,
315 	RELO_EXTERN_FUNC,
316 	RELO_SUBPROG_ADDR,
317 	RELO_CORE,
318 };
319 
320 struct reloc_desc {
321 	enum reloc_type type;
322 	int insn_idx;
323 	union {
324 		const struct bpf_core_relo *core_relo; /* used when type == RELO_CORE */
325 		struct {
326 			int map_idx;
327 			int sym_off;
328 		};
329 	};
330 };
331 
332 /* stored as sec_def->cookie for all libbpf-supported SEC()s */
333 enum sec_def_flags {
334 	SEC_NONE = 0,
335 	/* expected_attach_type is optional, if kernel doesn't support that */
336 	SEC_EXP_ATTACH_OPT = 1,
337 	/* legacy, only used by libbpf_get_type_names() and
338 	 * libbpf_attach_type_by_name(), not used by libbpf itself at all.
339 	 * This used to be associated with cgroup (and few other) BPF programs
340 	 * that were attachable through BPF_PROG_ATTACH command. Pretty
341 	 * meaningless nowadays, though.
342 	 */
343 	SEC_ATTACHABLE = 2,
344 	SEC_ATTACHABLE_OPT = SEC_ATTACHABLE | SEC_EXP_ATTACH_OPT,
345 	/* attachment target is specified through BTF ID in either kernel or
346 	 * other BPF program's BTF object */
347 	SEC_ATTACH_BTF = 4,
348 	/* BPF program type allows sleeping/blocking in kernel */
349 	SEC_SLEEPABLE = 8,
350 	/* allow non-strict prefix matching */
351 	SEC_SLOPPY_PFX = 16,
352 	/* BPF program support non-linear XDP buffer */
353 	SEC_XDP_FRAGS = 32,
354 	/* deprecated sec definitions not supposed to be used */
355 	SEC_DEPRECATED = 64,
356 };
357 
358 struct bpf_sec_def {
359 	char *sec;
360 	enum bpf_prog_type prog_type;
361 	enum bpf_attach_type expected_attach_type;
362 	long cookie;
363 	int handler_id;
364 
365 	libbpf_prog_setup_fn_t prog_setup_fn;
366 	libbpf_prog_prepare_load_fn_t prog_prepare_load_fn;
367 	libbpf_prog_attach_fn_t prog_attach_fn;
368 };
369 
370 /*
371  * bpf_prog should be a better name but it has been used in
372  * linux/filter.h.
373  */
374 struct bpf_program {
375 	const struct bpf_sec_def *sec_def;
376 	char *sec_name;
377 	size_t sec_idx;
378 	/* this program's instruction offset (in number of instructions)
379 	 * within its containing ELF section
380 	 */
381 	size_t sec_insn_off;
382 	/* number of original instructions in ELF section belonging to this
383 	 * program, not taking into account subprogram instructions possible
384 	 * appended later during relocation
385 	 */
386 	size_t sec_insn_cnt;
387 	/* Offset (in number of instructions) of the start of instruction
388 	 * belonging to this BPF program  within its containing main BPF
389 	 * program. For the entry-point (main) BPF program, this is always
390 	 * zero. For a sub-program, this gets reset before each of main BPF
391 	 * programs are processed and relocated and is used to determined
392 	 * whether sub-program was already appended to the main program, and
393 	 * if yes, at which instruction offset.
394 	 */
395 	size_t sub_insn_off;
396 
397 	char *name;
398 	/* name with / replaced by _; makes recursive pinning
399 	 * in bpf_object__pin_programs easier
400 	 */
401 	char *pin_name;
402 
403 	/* instructions that belong to BPF program; insns[0] is located at
404 	 * sec_insn_off instruction within its ELF section in ELF file, so
405 	 * when mapping ELF file instruction index to the local instruction,
406 	 * one needs to subtract sec_insn_off; and vice versa.
407 	 */
408 	struct bpf_insn *insns;
409 	/* actual number of instruction in this BPF program's image; for
410 	 * entry-point BPF programs this includes the size of main program
411 	 * itself plus all the used sub-programs, appended at the end
412 	 */
413 	size_t insns_cnt;
414 
415 	struct reloc_desc *reloc_desc;
416 	int nr_reloc;
417 
418 	/* BPF verifier log settings */
419 	char *log_buf;
420 	size_t log_size;
421 	__u32 log_level;
422 
423 	struct {
424 		int nr;
425 		int *fds;
426 	} instances;
427 	bpf_program_prep_t preprocessor;
428 
429 	struct bpf_object *obj;
430 	void *priv;
431 	bpf_program_clear_priv_t clear_priv;
432 
433 	bool autoload;
434 	bool mark_btf_static;
435 	enum bpf_prog_type type;
436 	enum bpf_attach_type expected_attach_type;
437 	int prog_ifindex;
438 	__u32 attach_btf_obj_fd;
439 	__u32 attach_btf_id;
440 	__u32 attach_prog_fd;
441 	void *func_info;
442 	__u32 func_info_rec_size;
443 	__u32 func_info_cnt;
444 
445 	void *line_info;
446 	__u32 line_info_rec_size;
447 	__u32 line_info_cnt;
448 	__u32 prog_flags;
449 };
450 
451 struct bpf_struct_ops {
452 	const char *tname;
453 	const struct btf_type *type;
454 	struct bpf_program **progs;
455 	__u32 *kern_func_off;
456 	/* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
457 	void *data;
458 	/* e.g. struct bpf_struct_ops_tcp_congestion_ops in
459 	 *      btf_vmlinux's format.
460 	 * struct bpf_struct_ops_tcp_congestion_ops {
461 	 *	[... some other kernel fields ...]
462 	 *	struct tcp_congestion_ops data;
463 	 * }
464 	 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
465 	 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
466 	 * from "data".
467 	 */
468 	void *kern_vdata;
469 	__u32 type_id;
470 };
471 
472 #define DATA_SEC ".data"
473 #define BSS_SEC ".bss"
474 #define RODATA_SEC ".rodata"
475 #define KCONFIG_SEC ".kconfig"
476 #define KSYMS_SEC ".ksyms"
477 #define STRUCT_OPS_SEC ".struct_ops"
478 
479 enum libbpf_map_type {
480 	LIBBPF_MAP_UNSPEC,
481 	LIBBPF_MAP_DATA,
482 	LIBBPF_MAP_BSS,
483 	LIBBPF_MAP_RODATA,
484 	LIBBPF_MAP_KCONFIG,
485 };
486 
487 struct bpf_map {
488 	struct bpf_object *obj;
489 	char *name;
490 	/* real_name is defined for special internal maps (.rodata*,
491 	 * .data*, .bss, .kconfig) and preserves their original ELF section
492 	 * name. This is important to be be able to find corresponding BTF
493 	 * DATASEC information.
494 	 */
495 	char *real_name;
496 	int fd;
497 	int sec_idx;
498 	size_t sec_offset;
499 	int map_ifindex;
500 	int inner_map_fd;
501 	struct bpf_map_def def;
502 	__u32 numa_node;
503 	__u32 btf_var_idx;
504 	__u32 btf_key_type_id;
505 	__u32 btf_value_type_id;
506 	__u32 btf_vmlinux_value_type_id;
507 	void *priv;
508 	bpf_map_clear_priv_t clear_priv;
509 	enum libbpf_map_type libbpf_type;
510 	void *mmaped;
511 	struct bpf_struct_ops *st_ops;
512 	struct bpf_map *inner_map;
513 	void **init_slots;
514 	int init_slots_sz;
515 	char *pin_path;
516 	bool pinned;
517 	bool reused;
518 	bool autocreate;
519 	__u64 map_extra;
520 };
521 
522 enum extern_type {
523 	EXT_UNKNOWN,
524 	EXT_KCFG,
525 	EXT_KSYM,
526 };
527 
528 enum kcfg_type {
529 	KCFG_UNKNOWN,
530 	KCFG_CHAR,
531 	KCFG_BOOL,
532 	KCFG_INT,
533 	KCFG_TRISTATE,
534 	KCFG_CHAR_ARR,
535 };
536 
537 struct extern_desc {
538 	enum extern_type type;
539 	int sym_idx;
540 	int btf_id;
541 	int sec_btf_id;
542 	const char *name;
543 	bool is_set;
544 	bool is_weak;
545 	union {
546 		struct {
547 			enum kcfg_type type;
548 			int sz;
549 			int align;
550 			int data_off;
551 			bool is_signed;
552 		} kcfg;
553 		struct {
554 			unsigned long long addr;
555 
556 			/* target btf_id of the corresponding kernel var. */
557 			int kernel_btf_obj_fd;
558 			int kernel_btf_id;
559 
560 			/* local btf_id of the ksym extern's type. */
561 			__u32 type_id;
562 			/* BTF fd index to be patched in for insn->off, this is
563 			 * 0 for vmlinux BTF, index in obj->fd_array for module
564 			 * BTF
565 			 */
566 			__s16 btf_fd_idx;
567 		} ksym;
568 	};
569 };
570 
571 static LIST_HEAD(bpf_objects_list);
572 
573 struct module_btf {
574 	struct btf *btf;
575 	char *name;
576 	__u32 id;
577 	int fd;
578 	int fd_array_idx;
579 };
580 
581 enum sec_type {
582 	SEC_UNUSED = 0,
583 	SEC_RELO,
584 	SEC_BSS,
585 	SEC_DATA,
586 	SEC_RODATA,
587 };
588 
589 struct elf_sec_desc {
590 	enum sec_type sec_type;
591 	Elf64_Shdr *shdr;
592 	Elf_Data *data;
593 };
594 
595 struct elf_state {
596 	int fd;
597 	const void *obj_buf;
598 	size_t obj_buf_sz;
599 	Elf *elf;
600 	Elf64_Ehdr *ehdr;
601 	Elf_Data *symbols;
602 	Elf_Data *st_ops_data;
603 	size_t shstrndx; /* section index for section name strings */
604 	size_t strtabidx;
605 	struct elf_sec_desc *secs;
606 	int sec_cnt;
607 	int maps_shndx;
608 	int btf_maps_shndx;
609 	__u32 btf_maps_sec_btf_id;
610 	int text_shndx;
611 	int symbols_shndx;
612 	int st_ops_shndx;
613 };
614 
615 struct usdt_manager;
616 
617 struct bpf_object {
618 	char name[BPF_OBJ_NAME_LEN];
619 	char license[64];
620 	__u32 kern_version;
621 
622 	struct bpf_program *programs;
623 	size_t nr_programs;
624 	struct bpf_map *maps;
625 	size_t nr_maps;
626 	size_t maps_cap;
627 
628 	char *kconfig;
629 	struct extern_desc *externs;
630 	int nr_extern;
631 	int kconfig_map_idx;
632 
633 	bool loaded;
634 	bool has_subcalls;
635 	bool has_rodata;
636 
637 	struct bpf_gen *gen_loader;
638 
639 	/* Information when doing ELF related work. Only valid if efile.elf is not NULL */
640 	struct elf_state efile;
641 	/*
642 	 * All loaded bpf_object are linked in a list, which is
643 	 * hidden to caller. bpf_objects__<func> handlers deal with
644 	 * all objects.
645 	 */
646 	struct list_head list;
647 
648 	struct btf *btf;
649 	struct btf_ext *btf_ext;
650 
651 	/* Parse and load BTF vmlinux if any of the programs in the object need
652 	 * it at load time.
653 	 */
654 	struct btf *btf_vmlinux;
655 	/* Path to the custom BTF to be used for BPF CO-RE relocations as an
656 	 * override for vmlinux BTF.
657 	 */
658 	char *btf_custom_path;
659 	/* vmlinux BTF override for CO-RE relocations */
660 	struct btf *btf_vmlinux_override;
661 	/* Lazily initialized kernel module BTFs */
662 	struct module_btf *btf_modules;
663 	bool btf_modules_loaded;
664 	size_t btf_module_cnt;
665 	size_t btf_module_cap;
666 
667 	/* optional log settings passed to BPF_BTF_LOAD and BPF_PROG_LOAD commands */
668 	char *log_buf;
669 	size_t log_size;
670 	__u32 log_level;
671 
672 	void *priv;
673 	bpf_object_clear_priv_t clear_priv;
674 
675 	int *fd_array;
676 	size_t fd_array_cap;
677 	size_t fd_array_cnt;
678 
679 	struct usdt_manager *usdt_man;
680 
681 	char path[];
682 };
683 
684 static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
685 static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
686 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
687 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
688 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn);
689 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
690 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
691 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx);
692 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx);
693 
694 void bpf_program__unload(struct bpf_program *prog)
695 {
696 	int i;
697 
698 	if (!prog)
699 		return;
700 
701 	/*
702 	 * If the object is opened but the program was never loaded,
703 	 * it is possible that prog->instances.nr == -1.
704 	 */
705 	if (prog->instances.nr > 0) {
706 		for (i = 0; i < prog->instances.nr; i++)
707 			zclose(prog->instances.fds[i]);
708 	} else if (prog->instances.nr != -1) {
709 		pr_warn("Internal error: instances.nr is %d\n",
710 			prog->instances.nr);
711 	}
712 
713 	prog->instances.nr = -1;
714 	zfree(&prog->instances.fds);
715 
716 	zfree(&prog->func_info);
717 	zfree(&prog->line_info);
718 }
719 
720 static void bpf_program__exit(struct bpf_program *prog)
721 {
722 	if (!prog)
723 		return;
724 
725 	if (prog->clear_priv)
726 		prog->clear_priv(prog, prog->priv);
727 
728 	prog->priv = NULL;
729 	prog->clear_priv = NULL;
730 
731 	bpf_program__unload(prog);
732 	zfree(&prog->name);
733 	zfree(&prog->sec_name);
734 	zfree(&prog->pin_name);
735 	zfree(&prog->insns);
736 	zfree(&prog->reloc_desc);
737 
738 	prog->nr_reloc = 0;
739 	prog->insns_cnt = 0;
740 	prog->sec_idx = -1;
741 }
742 
743 static char *__bpf_program__pin_name(struct bpf_program *prog)
744 {
745 	char *name, *p;
746 
747 	if (libbpf_mode & LIBBPF_STRICT_SEC_NAME)
748 		name = strdup(prog->name);
749 	else
750 		name = strdup(prog->sec_name);
751 
752 	if (!name)
753 		return NULL;
754 
755 	p = name;
756 
757 	while ((p = strchr(p, '/')))
758 		*p = '_';
759 
760 	return name;
761 }
762 
763 static bool insn_is_subprog_call(const struct bpf_insn *insn)
764 {
765 	return BPF_CLASS(insn->code) == BPF_JMP &&
766 	       BPF_OP(insn->code) == BPF_CALL &&
767 	       BPF_SRC(insn->code) == BPF_K &&
768 	       insn->src_reg == BPF_PSEUDO_CALL &&
769 	       insn->dst_reg == 0 &&
770 	       insn->off == 0;
771 }
772 
773 static bool is_call_insn(const struct bpf_insn *insn)
774 {
775 	return insn->code == (BPF_JMP | BPF_CALL);
776 }
777 
778 static bool insn_is_pseudo_func(struct bpf_insn *insn)
779 {
780 	return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
781 }
782 
783 static int
784 bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
785 		      const char *name, size_t sec_idx, const char *sec_name,
786 		      size_t sec_off, void *insn_data, size_t insn_data_sz)
787 {
788 	if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
789 		pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
790 			sec_name, name, sec_off, insn_data_sz);
791 		return -EINVAL;
792 	}
793 
794 	memset(prog, 0, sizeof(*prog));
795 	prog->obj = obj;
796 
797 	prog->sec_idx = sec_idx;
798 	prog->sec_insn_off = sec_off / BPF_INSN_SZ;
799 	prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
800 	/* insns_cnt can later be increased by appending used subprograms */
801 	prog->insns_cnt = prog->sec_insn_cnt;
802 
803 	prog->type = BPF_PROG_TYPE_UNSPEC;
804 
805 	/* libbpf's convention for SEC("?abc...") is that it's just like
806 	 * SEC("abc...") but the corresponding bpf_program starts out with
807 	 * autoload set to false.
808 	 */
809 	if (sec_name[0] == '?') {
810 		prog->autoload = false;
811 		/* from now on forget there was ? in section name */
812 		sec_name++;
813 	} else {
814 		prog->autoload = true;
815 	}
816 
817 	prog->instances.fds = NULL;
818 	prog->instances.nr = -1;
819 
820 	/* inherit object's log_level */
821 	prog->log_level = obj->log_level;
822 
823 	prog->sec_name = strdup(sec_name);
824 	if (!prog->sec_name)
825 		goto errout;
826 
827 	prog->name = strdup(name);
828 	if (!prog->name)
829 		goto errout;
830 
831 	prog->pin_name = __bpf_program__pin_name(prog);
832 	if (!prog->pin_name)
833 		goto errout;
834 
835 	prog->insns = malloc(insn_data_sz);
836 	if (!prog->insns)
837 		goto errout;
838 	memcpy(prog->insns, insn_data, insn_data_sz);
839 
840 	return 0;
841 errout:
842 	pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
843 	bpf_program__exit(prog);
844 	return -ENOMEM;
845 }
846 
847 static int
848 bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
849 			 const char *sec_name, int sec_idx)
850 {
851 	Elf_Data *symbols = obj->efile.symbols;
852 	struct bpf_program *prog, *progs;
853 	void *data = sec_data->d_buf;
854 	size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
855 	int nr_progs, err, i;
856 	const char *name;
857 	Elf64_Sym *sym;
858 
859 	progs = obj->programs;
860 	nr_progs = obj->nr_programs;
861 	nr_syms = symbols->d_size / sizeof(Elf64_Sym);
862 	sec_off = 0;
863 
864 	for (i = 0; i < nr_syms; i++) {
865 		sym = elf_sym_by_idx(obj, i);
866 
867 		if (sym->st_shndx != sec_idx)
868 			continue;
869 		if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC)
870 			continue;
871 
872 		prog_sz = sym->st_size;
873 		sec_off = sym->st_value;
874 
875 		name = elf_sym_str(obj, sym->st_name);
876 		if (!name) {
877 			pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
878 				sec_name, sec_off);
879 			return -LIBBPF_ERRNO__FORMAT;
880 		}
881 
882 		if (sec_off + prog_sz > sec_sz) {
883 			pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
884 				sec_name, sec_off);
885 			return -LIBBPF_ERRNO__FORMAT;
886 		}
887 
888 		if (sec_idx != obj->efile.text_shndx && ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
889 			pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
890 			return -ENOTSUP;
891 		}
892 
893 		pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
894 			 sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
895 
896 		progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
897 		if (!progs) {
898 			/*
899 			 * In this case the original obj->programs
900 			 * is still valid, so don't need special treat for
901 			 * bpf_close_object().
902 			 */
903 			pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
904 				sec_name, name);
905 			return -ENOMEM;
906 		}
907 		obj->programs = progs;
908 
909 		prog = &progs[nr_progs];
910 
911 		err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
912 					    sec_off, data + sec_off, prog_sz);
913 		if (err)
914 			return err;
915 
916 		/* if function is a global/weak symbol, but has restricted
917 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
918 		 * as static to enable more permissive BPF verification mode
919 		 * with more outside context available to BPF verifier
920 		 */
921 		if (ELF64_ST_BIND(sym->st_info) != STB_LOCAL
922 		    && (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
923 			|| ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL))
924 			prog->mark_btf_static = true;
925 
926 		nr_progs++;
927 		obj->nr_programs = nr_progs;
928 	}
929 
930 	return 0;
931 }
932 
933 __u32 get_kernel_version(void)
934 {
935 	/* On Ubuntu LINUX_VERSION_CODE doesn't correspond to info.release,
936 	 * but Ubuntu provides /proc/version_signature file, as described at
937 	 * https://ubuntu.com/kernel, with an example contents below, which we
938 	 * can use to get a proper LINUX_VERSION_CODE.
939 	 *
940 	 *   Ubuntu 5.4.0-12.15-generic 5.4.8
941 	 *
942 	 * In the above, 5.4.8 is what kernel is actually expecting, while
943 	 * uname() call will return 5.4.0 in info.release.
944 	 */
945 	const char *ubuntu_kver_file = "/proc/version_signature";
946 	__u32 major, minor, patch;
947 	struct utsname info;
948 
949 	if (access(ubuntu_kver_file, R_OK) == 0) {
950 		FILE *f;
951 
952 		f = fopen(ubuntu_kver_file, "r");
953 		if (f) {
954 			if (fscanf(f, "%*s %*s %d.%d.%d\n", &major, &minor, &patch) == 3) {
955 				fclose(f);
956 				return KERNEL_VERSION(major, minor, patch);
957 			}
958 			fclose(f);
959 		}
960 		/* something went wrong, fall back to uname() approach */
961 	}
962 
963 	uname(&info);
964 	if (sscanf(info.release, "%u.%u.%u", &major, &minor, &patch) != 3)
965 		return 0;
966 	return KERNEL_VERSION(major, minor, patch);
967 }
968 
969 static const struct btf_member *
970 find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
971 {
972 	struct btf_member *m;
973 	int i;
974 
975 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
976 		if (btf_member_bit_offset(t, i) == bit_offset)
977 			return m;
978 	}
979 
980 	return NULL;
981 }
982 
983 static const struct btf_member *
984 find_member_by_name(const struct btf *btf, const struct btf_type *t,
985 		    const char *name)
986 {
987 	struct btf_member *m;
988 	int i;
989 
990 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
991 		if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
992 			return m;
993 	}
994 
995 	return NULL;
996 }
997 
998 #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
999 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
1000 				   const char *name, __u32 kind);
1001 
1002 static int
1003 find_struct_ops_kern_types(const struct btf *btf, const char *tname,
1004 			   const struct btf_type **type, __u32 *type_id,
1005 			   const struct btf_type **vtype, __u32 *vtype_id,
1006 			   const struct btf_member **data_member)
1007 {
1008 	const struct btf_type *kern_type, *kern_vtype;
1009 	const struct btf_member *kern_data_member;
1010 	__s32 kern_vtype_id, kern_type_id;
1011 	__u32 i;
1012 
1013 	kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
1014 	if (kern_type_id < 0) {
1015 		pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n",
1016 			tname);
1017 		return kern_type_id;
1018 	}
1019 	kern_type = btf__type_by_id(btf, kern_type_id);
1020 
1021 	/* Find the corresponding "map_value" type that will be used
1022 	 * in map_update(BPF_MAP_TYPE_STRUCT_OPS).  For example,
1023 	 * find "struct bpf_struct_ops_tcp_congestion_ops" from the
1024 	 * btf_vmlinux.
1025 	 */
1026 	kern_vtype_id = find_btf_by_prefix_kind(btf, STRUCT_OPS_VALUE_PREFIX,
1027 						tname, BTF_KIND_STRUCT);
1028 	if (kern_vtype_id < 0) {
1029 		pr_warn("struct_ops init_kern: struct %s%s is not found in kernel BTF\n",
1030 			STRUCT_OPS_VALUE_PREFIX, tname);
1031 		return kern_vtype_id;
1032 	}
1033 	kern_vtype = btf__type_by_id(btf, kern_vtype_id);
1034 
1035 	/* Find "struct tcp_congestion_ops" from
1036 	 * struct bpf_struct_ops_tcp_congestion_ops {
1037 	 *	[ ... ]
1038 	 *	struct tcp_congestion_ops data;
1039 	 * }
1040 	 */
1041 	kern_data_member = btf_members(kern_vtype);
1042 	for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
1043 		if (kern_data_member->type == kern_type_id)
1044 			break;
1045 	}
1046 	if (i == btf_vlen(kern_vtype)) {
1047 		pr_warn("struct_ops init_kern: struct %s data is not found in struct %s%s\n",
1048 			tname, STRUCT_OPS_VALUE_PREFIX, tname);
1049 		return -EINVAL;
1050 	}
1051 
1052 	*type = kern_type;
1053 	*type_id = kern_type_id;
1054 	*vtype = kern_vtype;
1055 	*vtype_id = kern_vtype_id;
1056 	*data_member = kern_data_member;
1057 
1058 	return 0;
1059 }
1060 
1061 static bool bpf_map__is_struct_ops(const struct bpf_map *map)
1062 {
1063 	return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
1064 }
1065 
1066 /* Init the map's fields that depend on kern_btf */
1067 static int bpf_map__init_kern_struct_ops(struct bpf_map *map,
1068 					 const struct btf *btf,
1069 					 const struct btf *kern_btf)
1070 {
1071 	const struct btf_member *member, *kern_member, *kern_data_member;
1072 	const struct btf_type *type, *kern_type, *kern_vtype;
1073 	__u32 i, kern_type_id, kern_vtype_id, kern_data_off;
1074 	struct bpf_struct_ops *st_ops;
1075 	void *data, *kern_data;
1076 	const char *tname;
1077 	int err;
1078 
1079 	st_ops = map->st_ops;
1080 	type = st_ops->type;
1081 	tname = st_ops->tname;
1082 	err = find_struct_ops_kern_types(kern_btf, tname,
1083 					 &kern_type, &kern_type_id,
1084 					 &kern_vtype, &kern_vtype_id,
1085 					 &kern_data_member);
1086 	if (err)
1087 		return err;
1088 
1089 	pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
1090 		 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
1091 
1092 	map->def.value_size = kern_vtype->size;
1093 	map->btf_vmlinux_value_type_id = kern_vtype_id;
1094 
1095 	st_ops->kern_vdata = calloc(1, kern_vtype->size);
1096 	if (!st_ops->kern_vdata)
1097 		return -ENOMEM;
1098 
1099 	data = st_ops->data;
1100 	kern_data_off = kern_data_member->offset / 8;
1101 	kern_data = st_ops->kern_vdata + kern_data_off;
1102 
1103 	member = btf_members(type);
1104 	for (i = 0; i < btf_vlen(type); i++, member++) {
1105 		const struct btf_type *mtype, *kern_mtype;
1106 		__u32 mtype_id, kern_mtype_id;
1107 		void *mdata, *kern_mdata;
1108 		__s64 msize, kern_msize;
1109 		__u32 moff, kern_moff;
1110 		__u32 kern_member_idx;
1111 		const char *mname;
1112 
1113 		mname = btf__name_by_offset(btf, member->name_off);
1114 		kern_member = find_member_by_name(kern_btf, kern_type, mname);
1115 		if (!kern_member) {
1116 			pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
1117 				map->name, mname);
1118 			return -ENOTSUP;
1119 		}
1120 
1121 		kern_member_idx = kern_member - btf_members(kern_type);
1122 		if (btf_member_bitfield_size(type, i) ||
1123 		    btf_member_bitfield_size(kern_type, kern_member_idx)) {
1124 			pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
1125 				map->name, mname);
1126 			return -ENOTSUP;
1127 		}
1128 
1129 		moff = member->offset / 8;
1130 		kern_moff = kern_member->offset / 8;
1131 
1132 		mdata = data + moff;
1133 		kern_mdata = kern_data + kern_moff;
1134 
1135 		mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
1136 		kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
1137 						    &kern_mtype_id);
1138 		if (BTF_INFO_KIND(mtype->info) !=
1139 		    BTF_INFO_KIND(kern_mtype->info)) {
1140 			pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
1141 				map->name, mname, BTF_INFO_KIND(mtype->info),
1142 				BTF_INFO_KIND(kern_mtype->info));
1143 			return -ENOTSUP;
1144 		}
1145 
1146 		if (btf_is_ptr(mtype)) {
1147 			struct bpf_program *prog;
1148 
1149 			prog = st_ops->progs[i];
1150 			if (!prog)
1151 				continue;
1152 
1153 			kern_mtype = skip_mods_and_typedefs(kern_btf,
1154 							    kern_mtype->type,
1155 							    &kern_mtype_id);
1156 
1157 			/* mtype->type must be a func_proto which was
1158 			 * guaranteed in bpf_object__collect_st_ops_relos(),
1159 			 * so only check kern_mtype for func_proto here.
1160 			 */
1161 			if (!btf_is_func_proto(kern_mtype)) {
1162 				pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
1163 					map->name, mname);
1164 				return -ENOTSUP;
1165 			}
1166 
1167 			prog->attach_btf_id = kern_type_id;
1168 			prog->expected_attach_type = kern_member_idx;
1169 
1170 			st_ops->kern_func_off[i] = kern_data_off + kern_moff;
1171 
1172 			pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
1173 				 map->name, mname, prog->name, moff,
1174 				 kern_moff);
1175 
1176 			continue;
1177 		}
1178 
1179 		msize = btf__resolve_size(btf, mtype_id);
1180 		kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
1181 		if (msize < 0 || kern_msize < 0 || msize != kern_msize) {
1182 			pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
1183 				map->name, mname, (ssize_t)msize,
1184 				(ssize_t)kern_msize);
1185 			return -ENOTSUP;
1186 		}
1187 
1188 		pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
1189 			 map->name, mname, (unsigned int)msize,
1190 			 moff, kern_moff);
1191 		memcpy(kern_mdata, mdata, msize);
1192 	}
1193 
1194 	return 0;
1195 }
1196 
1197 static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
1198 {
1199 	struct bpf_map *map;
1200 	size_t i;
1201 	int err;
1202 
1203 	for (i = 0; i < obj->nr_maps; i++) {
1204 		map = &obj->maps[i];
1205 
1206 		if (!bpf_map__is_struct_ops(map))
1207 			continue;
1208 
1209 		err = bpf_map__init_kern_struct_ops(map, obj->btf,
1210 						    obj->btf_vmlinux);
1211 		if (err)
1212 			return err;
1213 	}
1214 
1215 	return 0;
1216 }
1217 
1218 static int bpf_object__init_struct_ops_maps(struct bpf_object *obj)
1219 {
1220 	const struct btf_type *type, *datasec;
1221 	const struct btf_var_secinfo *vsi;
1222 	struct bpf_struct_ops *st_ops;
1223 	const char *tname, *var_name;
1224 	__s32 type_id, datasec_id;
1225 	const struct btf *btf;
1226 	struct bpf_map *map;
1227 	__u32 i;
1228 
1229 	if (obj->efile.st_ops_shndx == -1)
1230 		return 0;
1231 
1232 	btf = obj->btf;
1233 	datasec_id = btf__find_by_name_kind(btf, STRUCT_OPS_SEC,
1234 					    BTF_KIND_DATASEC);
1235 	if (datasec_id < 0) {
1236 		pr_warn("struct_ops init: DATASEC %s not found\n",
1237 			STRUCT_OPS_SEC);
1238 		return -EINVAL;
1239 	}
1240 
1241 	datasec = btf__type_by_id(btf, datasec_id);
1242 	vsi = btf_var_secinfos(datasec);
1243 	for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
1244 		type = btf__type_by_id(obj->btf, vsi->type);
1245 		var_name = btf__name_by_offset(obj->btf, type->name_off);
1246 
1247 		type_id = btf__resolve_type(obj->btf, vsi->type);
1248 		if (type_id < 0) {
1249 			pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
1250 				vsi->type, STRUCT_OPS_SEC);
1251 			return -EINVAL;
1252 		}
1253 
1254 		type = btf__type_by_id(obj->btf, type_id);
1255 		tname = btf__name_by_offset(obj->btf, type->name_off);
1256 		if (!tname[0]) {
1257 			pr_warn("struct_ops init: anonymous type is not supported\n");
1258 			return -ENOTSUP;
1259 		}
1260 		if (!btf_is_struct(type)) {
1261 			pr_warn("struct_ops init: %s is not a struct\n", tname);
1262 			return -EINVAL;
1263 		}
1264 
1265 		map = bpf_object__add_map(obj);
1266 		if (IS_ERR(map))
1267 			return PTR_ERR(map);
1268 
1269 		map->sec_idx = obj->efile.st_ops_shndx;
1270 		map->sec_offset = vsi->offset;
1271 		map->name = strdup(var_name);
1272 		if (!map->name)
1273 			return -ENOMEM;
1274 
1275 		map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
1276 		map->def.key_size = sizeof(int);
1277 		map->def.value_size = type->size;
1278 		map->def.max_entries = 1;
1279 
1280 		map->st_ops = calloc(1, sizeof(*map->st_ops));
1281 		if (!map->st_ops)
1282 			return -ENOMEM;
1283 		st_ops = map->st_ops;
1284 		st_ops->data = malloc(type->size);
1285 		st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1286 		st_ops->kern_func_off = malloc(btf_vlen(type) *
1287 					       sizeof(*st_ops->kern_func_off));
1288 		if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1289 			return -ENOMEM;
1290 
1291 		if (vsi->offset + type->size > obj->efile.st_ops_data->d_size) {
1292 			pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1293 				var_name, STRUCT_OPS_SEC);
1294 			return -EINVAL;
1295 		}
1296 
1297 		memcpy(st_ops->data,
1298 		       obj->efile.st_ops_data->d_buf + vsi->offset,
1299 		       type->size);
1300 		st_ops->tname = tname;
1301 		st_ops->type = type;
1302 		st_ops->type_id = type_id;
1303 
1304 		pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
1305 			 tname, type_id, var_name, vsi->offset);
1306 	}
1307 
1308 	return 0;
1309 }
1310 
1311 static struct bpf_object *bpf_object__new(const char *path,
1312 					  const void *obj_buf,
1313 					  size_t obj_buf_sz,
1314 					  const char *obj_name)
1315 {
1316 	bool strict = (libbpf_mode & LIBBPF_STRICT_NO_OBJECT_LIST);
1317 	struct bpf_object *obj;
1318 	char *end;
1319 
1320 	obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1321 	if (!obj) {
1322 		pr_warn("alloc memory failed for %s\n", path);
1323 		return ERR_PTR(-ENOMEM);
1324 	}
1325 
1326 	strcpy(obj->path, path);
1327 	if (obj_name) {
1328 		libbpf_strlcpy(obj->name, obj_name, sizeof(obj->name));
1329 	} else {
1330 		/* Using basename() GNU version which doesn't modify arg. */
1331 		libbpf_strlcpy(obj->name, basename((void *)path), sizeof(obj->name));
1332 		end = strchr(obj->name, '.');
1333 		if (end)
1334 			*end = 0;
1335 	}
1336 
1337 	obj->efile.fd = -1;
1338 	/*
1339 	 * Caller of this function should also call
1340 	 * bpf_object__elf_finish() after data collection to return
1341 	 * obj_buf to user. If not, we should duplicate the buffer to
1342 	 * avoid user freeing them before elf finish.
1343 	 */
1344 	obj->efile.obj_buf = obj_buf;
1345 	obj->efile.obj_buf_sz = obj_buf_sz;
1346 	obj->efile.maps_shndx = -1;
1347 	obj->efile.btf_maps_shndx = -1;
1348 	obj->efile.st_ops_shndx = -1;
1349 	obj->kconfig_map_idx = -1;
1350 
1351 	obj->kern_version = get_kernel_version();
1352 	obj->loaded = false;
1353 
1354 	INIT_LIST_HEAD(&obj->list);
1355 	if (!strict)
1356 		list_add(&obj->list, &bpf_objects_list);
1357 	return obj;
1358 }
1359 
1360 static void bpf_object__elf_finish(struct bpf_object *obj)
1361 {
1362 	if (!obj->efile.elf)
1363 		return;
1364 
1365 	elf_end(obj->efile.elf);
1366 	obj->efile.elf = NULL;
1367 	obj->efile.symbols = NULL;
1368 	obj->efile.st_ops_data = NULL;
1369 
1370 	zfree(&obj->efile.secs);
1371 	obj->efile.sec_cnt = 0;
1372 	zclose(obj->efile.fd);
1373 	obj->efile.obj_buf = NULL;
1374 	obj->efile.obj_buf_sz = 0;
1375 }
1376 
1377 static int bpf_object__elf_init(struct bpf_object *obj)
1378 {
1379 	Elf64_Ehdr *ehdr;
1380 	int err = 0;
1381 	Elf *elf;
1382 
1383 	if (obj->efile.elf) {
1384 		pr_warn("elf: init internal error\n");
1385 		return -LIBBPF_ERRNO__LIBELF;
1386 	}
1387 
1388 	if (obj->efile.obj_buf_sz > 0) {
1389 		/*
1390 		 * obj_buf should have been validated by
1391 		 * bpf_object__open_buffer().
1392 		 */
1393 		elf = elf_memory((char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
1394 	} else {
1395 		obj->efile.fd = open(obj->path, O_RDONLY | O_CLOEXEC);
1396 		if (obj->efile.fd < 0) {
1397 			char errmsg[STRERR_BUFSIZE], *cp;
1398 
1399 			err = -errno;
1400 			cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
1401 			pr_warn("elf: failed to open %s: %s\n", obj->path, cp);
1402 			return err;
1403 		}
1404 
1405 		elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1406 	}
1407 
1408 	if (!elf) {
1409 		pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
1410 		err = -LIBBPF_ERRNO__LIBELF;
1411 		goto errout;
1412 	}
1413 
1414 	obj->efile.elf = elf;
1415 
1416 	if (elf_kind(elf) != ELF_K_ELF) {
1417 		err = -LIBBPF_ERRNO__FORMAT;
1418 		pr_warn("elf: '%s' is not a proper ELF object\n", obj->path);
1419 		goto errout;
1420 	}
1421 
1422 	if (gelf_getclass(elf) != ELFCLASS64) {
1423 		err = -LIBBPF_ERRNO__FORMAT;
1424 		pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path);
1425 		goto errout;
1426 	}
1427 
1428 	obj->efile.ehdr = ehdr = elf64_getehdr(elf);
1429 	if (!obj->efile.ehdr) {
1430 		pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
1431 		err = -LIBBPF_ERRNO__FORMAT;
1432 		goto errout;
1433 	}
1434 
1435 	if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
1436 		pr_warn("elf: failed to get section names section index for %s: %s\n",
1437 			obj->path, elf_errmsg(-1));
1438 		err = -LIBBPF_ERRNO__FORMAT;
1439 		goto errout;
1440 	}
1441 
1442 	/* Elf is corrupted/truncated, avoid calling elf_strptr. */
1443 	if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
1444 		pr_warn("elf: failed to get section names strings from %s: %s\n",
1445 			obj->path, elf_errmsg(-1));
1446 		err = -LIBBPF_ERRNO__FORMAT;
1447 		goto errout;
1448 	}
1449 
1450 	/* Old LLVM set e_machine to EM_NONE */
1451 	if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
1452 		pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
1453 		err = -LIBBPF_ERRNO__FORMAT;
1454 		goto errout;
1455 	}
1456 
1457 	return 0;
1458 errout:
1459 	bpf_object__elf_finish(obj);
1460 	return err;
1461 }
1462 
1463 static int bpf_object__check_endianness(struct bpf_object *obj)
1464 {
1465 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1466 	if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2LSB)
1467 		return 0;
1468 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1469 	if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2MSB)
1470 		return 0;
1471 #else
1472 # error "Unrecognized __BYTE_ORDER__"
1473 #endif
1474 	pr_warn("elf: endianness mismatch in %s.\n", obj->path);
1475 	return -LIBBPF_ERRNO__ENDIAN;
1476 }
1477 
1478 static int
1479 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1480 {
1481 	/* libbpf_strlcpy() only copies first N - 1 bytes, so size + 1 won't
1482 	 * go over allowed ELF data section buffer
1483 	 */
1484 	libbpf_strlcpy(obj->license, data, min(size + 1, sizeof(obj->license)));
1485 	pr_debug("license of %s is %s\n", obj->path, obj->license);
1486 	return 0;
1487 }
1488 
1489 static int
1490 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1491 {
1492 	__u32 kver;
1493 
1494 	if (size != sizeof(kver)) {
1495 		pr_warn("invalid kver section in %s\n", obj->path);
1496 		return -LIBBPF_ERRNO__FORMAT;
1497 	}
1498 	memcpy(&kver, data, sizeof(kver));
1499 	obj->kern_version = kver;
1500 	pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1501 	return 0;
1502 }
1503 
1504 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1505 {
1506 	if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1507 	    type == BPF_MAP_TYPE_HASH_OF_MAPS)
1508 		return true;
1509 	return false;
1510 }
1511 
1512 static int find_elf_sec_sz(const struct bpf_object *obj, const char *name, __u32 *size)
1513 {
1514 	Elf_Data *data;
1515 	Elf_Scn *scn;
1516 
1517 	if (!name)
1518 		return -EINVAL;
1519 
1520 	scn = elf_sec_by_name(obj, name);
1521 	data = elf_sec_data(obj, scn);
1522 	if (data) {
1523 		*size = data->d_size;
1524 		return 0; /* found it */
1525 	}
1526 
1527 	return -ENOENT;
1528 }
1529 
1530 static int find_elf_var_offset(const struct bpf_object *obj, const char *name, __u32 *off)
1531 {
1532 	Elf_Data *symbols = obj->efile.symbols;
1533 	const char *sname;
1534 	size_t si;
1535 
1536 	if (!name || !off)
1537 		return -EINVAL;
1538 
1539 	for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
1540 		Elf64_Sym *sym = elf_sym_by_idx(obj, si);
1541 
1542 		if (ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)
1543 			continue;
1544 
1545 		if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL &&
1546 		    ELF64_ST_BIND(sym->st_info) != STB_WEAK)
1547 			continue;
1548 
1549 		sname = elf_sym_str(obj, sym->st_name);
1550 		if (!sname) {
1551 			pr_warn("failed to get sym name string for var %s\n", name);
1552 			return -EIO;
1553 		}
1554 		if (strcmp(name, sname) == 0) {
1555 			*off = sym->st_value;
1556 			return 0;
1557 		}
1558 	}
1559 
1560 	return -ENOENT;
1561 }
1562 
1563 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1564 {
1565 	struct bpf_map *map;
1566 	int err;
1567 
1568 	err = libbpf_ensure_mem((void **)&obj->maps, &obj->maps_cap,
1569 				sizeof(*obj->maps), obj->nr_maps + 1);
1570 	if (err)
1571 		return ERR_PTR(err);
1572 
1573 	map = &obj->maps[obj->nr_maps++];
1574 	map->obj = obj;
1575 	map->fd = -1;
1576 	map->inner_map_fd = -1;
1577 	map->autocreate = true;
1578 
1579 	return map;
1580 }
1581 
1582 static size_t bpf_map_mmap_sz(const struct bpf_map *map)
1583 {
1584 	long page_sz = sysconf(_SC_PAGE_SIZE);
1585 	size_t map_sz;
1586 
1587 	map_sz = (size_t)roundup(map->def.value_size, 8) * map->def.max_entries;
1588 	map_sz = roundup(map_sz, page_sz);
1589 	return map_sz;
1590 }
1591 
1592 static char *internal_map_name(struct bpf_object *obj, const char *real_name)
1593 {
1594 	char map_name[BPF_OBJ_NAME_LEN], *p;
1595 	int pfx_len, sfx_len = max((size_t)7, strlen(real_name));
1596 
1597 	/* This is one of the more confusing parts of libbpf for various
1598 	 * reasons, some of which are historical. The original idea for naming
1599 	 * internal names was to include as much of BPF object name prefix as
1600 	 * possible, so that it can be distinguished from similar internal
1601 	 * maps of a different BPF object.
1602 	 * As an example, let's say we have bpf_object named 'my_object_name'
1603 	 * and internal map corresponding to '.rodata' ELF section. The final
1604 	 * map name advertised to user and to the kernel will be
1605 	 * 'my_objec.rodata', taking first 8 characters of object name and
1606 	 * entire 7 characters of '.rodata'.
1607 	 * Somewhat confusingly, if internal map ELF section name is shorter
1608 	 * than 7 characters, e.g., '.bss', we still reserve 7 characters
1609 	 * for the suffix, even though we only have 4 actual characters, and
1610 	 * resulting map will be called 'my_objec.bss', not even using all 15
1611 	 * characters allowed by the kernel. Oh well, at least the truncated
1612 	 * object name is somewhat consistent in this case. But if the map
1613 	 * name is '.kconfig', we'll still have entirety of '.kconfig' added
1614 	 * (8 chars) and thus will be left with only first 7 characters of the
1615 	 * object name ('my_obje'). Happy guessing, user, that the final map
1616 	 * name will be "my_obje.kconfig".
1617 	 * Now, with libbpf starting to support arbitrarily named .rodata.*
1618 	 * and .data.* data sections, it's possible that ELF section name is
1619 	 * longer than allowed 15 chars, so we now need to be careful to take
1620 	 * only up to 15 first characters of ELF name, taking no BPF object
1621 	 * name characters at all. So '.rodata.abracadabra' will result in
1622 	 * '.rodata.abracad' kernel and user-visible name.
1623 	 * We need to keep this convoluted logic intact for .data, .bss and
1624 	 * .rodata maps, but for new custom .data.custom and .rodata.custom
1625 	 * maps we use their ELF names as is, not prepending bpf_object name
1626 	 * in front. We still need to truncate them to 15 characters for the
1627 	 * kernel. Full name can be recovered for such maps by using DATASEC
1628 	 * BTF type associated with such map's value type, though.
1629 	 */
1630 	if (sfx_len >= BPF_OBJ_NAME_LEN)
1631 		sfx_len = BPF_OBJ_NAME_LEN - 1;
1632 
1633 	/* if there are two or more dots in map name, it's a custom dot map */
1634 	if (strchr(real_name + 1, '.') != NULL)
1635 		pfx_len = 0;
1636 	else
1637 		pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
1638 
1639 	snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1640 		 sfx_len, real_name);
1641 
1642 	/* sanitise map name to characters allowed by kernel */
1643 	for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1644 		if (!isalnum(*p) && *p != '_' && *p != '.')
1645 			*p = '_';
1646 
1647 	return strdup(map_name);
1648 }
1649 
1650 static int
1651 bpf_map_find_btf_info(struct bpf_object *obj, struct bpf_map *map);
1652 
1653 static int
1654 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
1655 			      const char *real_name, int sec_idx, void *data, size_t data_sz)
1656 {
1657 	struct bpf_map_def *def;
1658 	struct bpf_map *map;
1659 	int err;
1660 
1661 	map = bpf_object__add_map(obj);
1662 	if (IS_ERR(map))
1663 		return PTR_ERR(map);
1664 
1665 	map->libbpf_type = type;
1666 	map->sec_idx = sec_idx;
1667 	map->sec_offset = 0;
1668 	map->real_name = strdup(real_name);
1669 	map->name = internal_map_name(obj, real_name);
1670 	if (!map->real_name || !map->name) {
1671 		zfree(&map->real_name);
1672 		zfree(&map->name);
1673 		return -ENOMEM;
1674 	}
1675 
1676 	def = &map->def;
1677 	def->type = BPF_MAP_TYPE_ARRAY;
1678 	def->key_size = sizeof(int);
1679 	def->value_size = data_sz;
1680 	def->max_entries = 1;
1681 	def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
1682 			 ? BPF_F_RDONLY_PROG : 0;
1683 	def->map_flags |= BPF_F_MMAPABLE;
1684 
1685 	pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
1686 		 map->name, map->sec_idx, map->sec_offset, def->map_flags);
1687 
1688 	map->mmaped = mmap(NULL, bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
1689 			   MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1690 	if (map->mmaped == MAP_FAILED) {
1691 		err = -errno;
1692 		map->mmaped = NULL;
1693 		pr_warn("failed to alloc map '%s' content buffer: %d\n",
1694 			map->name, err);
1695 		zfree(&map->real_name);
1696 		zfree(&map->name);
1697 		return err;
1698 	}
1699 
1700 	/* failures are fine because of maps like .rodata.str1.1 */
1701 	(void) bpf_map_find_btf_info(obj, map);
1702 
1703 	if (data)
1704 		memcpy(map->mmaped, data, data_sz);
1705 
1706 	pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
1707 	return 0;
1708 }
1709 
1710 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
1711 {
1712 	struct elf_sec_desc *sec_desc;
1713 	const char *sec_name;
1714 	int err = 0, sec_idx;
1715 
1716 	/*
1717 	 * Populate obj->maps with libbpf internal maps.
1718 	 */
1719 	for (sec_idx = 1; sec_idx < obj->efile.sec_cnt; sec_idx++) {
1720 		sec_desc = &obj->efile.secs[sec_idx];
1721 
1722 		switch (sec_desc->sec_type) {
1723 		case SEC_DATA:
1724 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1725 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
1726 							    sec_name, sec_idx,
1727 							    sec_desc->data->d_buf,
1728 							    sec_desc->data->d_size);
1729 			break;
1730 		case SEC_RODATA:
1731 			obj->has_rodata = true;
1732 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1733 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
1734 							    sec_name, sec_idx,
1735 							    sec_desc->data->d_buf,
1736 							    sec_desc->data->d_size);
1737 			break;
1738 		case SEC_BSS:
1739 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1740 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
1741 							    sec_name, sec_idx,
1742 							    NULL,
1743 							    sec_desc->data->d_size);
1744 			break;
1745 		default:
1746 			/* skip */
1747 			break;
1748 		}
1749 		if (err)
1750 			return err;
1751 	}
1752 	return 0;
1753 }
1754 
1755 
1756 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
1757 					       const void *name)
1758 {
1759 	int i;
1760 
1761 	for (i = 0; i < obj->nr_extern; i++) {
1762 		if (strcmp(obj->externs[i].name, name) == 0)
1763 			return &obj->externs[i];
1764 	}
1765 	return NULL;
1766 }
1767 
1768 static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
1769 			      char value)
1770 {
1771 	switch (ext->kcfg.type) {
1772 	case KCFG_BOOL:
1773 		if (value == 'm') {
1774 			pr_warn("extern (kcfg) %s=%c should be tristate or char\n",
1775 				ext->name, value);
1776 			return -EINVAL;
1777 		}
1778 		*(bool *)ext_val = value == 'y' ? true : false;
1779 		break;
1780 	case KCFG_TRISTATE:
1781 		if (value == 'y')
1782 			*(enum libbpf_tristate *)ext_val = TRI_YES;
1783 		else if (value == 'm')
1784 			*(enum libbpf_tristate *)ext_val = TRI_MODULE;
1785 		else /* value == 'n' */
1786 			*(enum libbpf_tristate *)ext_val = TRI_NO;
1787 		break;
1788 	case KCFG_CHAR:
1789 		*(char *)ext_val = value;
1790 		break;
1791 	case KCFG_UNKNOWN:
1792 	case KCFG_INT:
1793 	case KCFG_CHAR_ARR:
1794 	default:
1795 		pr_warn("extern (kcfg) %s=%c should be bool, tristate, or char\n",
1796 			ext->name, value);
1797 		return -EINVAL;
1798 	}
1799 	ext->is_set = true;
1800 	return 0;
1801 }
1802 
1803 static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
1804 			      const char *value)
1805 {
1806 	size_t len;
1807 
1808 	if (ext->kcfg.type != KCFG_CHAR_ARR) {
1809 		pr_warn("extern (kcfg) %s=%s should be char array\n", ext->name, value);
1810 		return -EINVAL;
1811 	}
1812 
1813 	len = strlen(value);
1814 	if (value[len - 1] != '"') {
1815 		pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
1816 			ext->name, value);
1817 		return -EINVAL;
1818 	}
1819 
1820 	/* strip quotes */
1821 	len -= 2;
1822 	if (len >= ext->kcfg.sz) {
1823 		pr_warn("extern (kcfg) '%s': long string config %s of (%zu bytes) truncated to %d bytes\n",
1824 			ext->name, value, len, ext->kcfg.sz - 1);
1825 		len = ext->kcfg.sz - 1;
1826 	}
1827 	memcpy(ext_val, value + 1, len);
1828 	ext_val[len] = '\0';
1829 	ext->is_set = true;
1830 	return 0;
1831 }
1832 
1833 static int parse_u64(const char *value, __u64 *res)
1834 {
1835 	char *value_end;
1836 	int err;
1837 
1838 	errno = 0;
1839 	*res = strtoull(value, &value_end, 0);
1840 	if (errno) {
1841 		err = -errno;
1842 		pr_warn("failed to parse '%s' as integer: %d\n", value, err);
1843 		return err;
1844 	}
1845 	if (*value_end) {
1846 		pr_warn("failed to parse '%s' as integer completely\n", value);
1847 		return -EINVAL;
1848 	}
1849 	return 0;
1850 }
1851 
1852 static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
1853 {
1854 	int bit_sz = ext->kcfg.sz * 8;
1855 
1856 	if (ext->kcfg.sz == 8)
1857 		return true;
1858 
1859 	/* Validate that value stored in u64 fits in integer of `ext->sz`
1860 	 * bytes size without any loss of information. If the target integer
1861 	 * is signed, we rely on the following limits of integer type of
1862 	 * Y bits and subsequent transformation:
1863 	 *
1864 	 *     -2^(Y-1) <= X           <= 2^(Y-1) - 1
1865 	 *            0 <= X + 2^(Y-1) <= 2^Y - 1
1866 	 *            0 <= X + 2^(Y-1) <  2^Y
1867 	 *
1868 	 *  For unsigned target integer, check that all the (64 - Y) bits are
1869 	 *  zero.
1870 	 */
1871 	if (ext->kcfg.is_signed)
1872 		return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
1873 	else
1874 		return (v >> bit_sz) == 0;
1875 }
1876 
1877 static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
1878 			      __u64 value)
1879 {
1880 	if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
1881 		pr_warn("extern (kcfg) %s=%llu should be integer\n",
1882 			ext->name, (unsigned long long)value);
1883 		return -EINVAL;
1884 	}
1885 	if (!is_kcfg_value_in_range(ext, value)) {
1886 		pr_warn("extern (kcfg) %s=%llu value doesn't fit in %d bytes\n",
1887 			ext->name, (unsigned long long)value, ext->kcfg.sz);
1888 		return -ERANGE;
1889 	}
1890 	switch (ext->kcfg.sz) {
1891 		case 1: *(__u8 *)ext_val = value; break;
1892 		case 2: *(__u16 *)ext_val = value; break;
1893 		case 4: *(__u32 *)ext_val = value; break;
1894 		case 8: *(__u64 *)ext_val = value; break;
1895 		default:
1896 			return -EINVAL;
1897 	}
1898 	ext->is_set = true;
1899 	return 0;
1900 }
1901 
1902 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
1903 					    char *buf, void *data)
1904 {
1905 	struct extern_desc *ext;
1906 	char *sep, *value;
1907 	int len, err = 0;
1908 	void *ext_val;
1909 	__u64 num;
1910 
1911 	if (!str_has_pfx(buf, "CONFIG_"))
1912 		return 0;
1913 
1914 	sep = strchr(buf, '=');
1915 	if (!sep) {
1916 		pr_warn("failed to parse '%s': no separator\n", buf);
1917 		return -EINVAL;
1918 	}
1919 
1920 	/* Trim ending '\n' */
1921 	len = strlen(buf);
1922 	if (buf[len - 1] == '\n')
1923 		buf[len - 1] = '\0';
1924 	/* Split on '=' and ensure that a value is present. */
1925 	*sep = '\0';
1926 	if (!sep[1]) {
1927 		*sep = '=';
1928 		pr_warn("failed to parse '%s': no value\n", buf);
1929 		return -EINVAL;
1930 	}
1931 
1932 	ext = find_extern_by_name(obj, buf);
1933 	if (!ext || ext->is_set)
1934 		return 0;
1935 
1936 	ext_val = data + ext->kcfg.data_off;
1937 	value = sep + 1;
1938 
1939 	switch (*value) {
1940 	case 'y': case 'n': case 'm':
1941 		err = set_kcfg_value_tri(ext, ext_val, *value);
1942 		break;
1943 	case '"':
1944 		err = set_kcfg_value_str(ext, ext_val, value);
1945 		break;
1946 	default:
1947 		/* assume integer */
1948 		err = parse_u64(value, &num);
1949 		if (err) {
1950 			pr_warn("extern (kcfg) %s=%s should be integer\n",
1951 				ext->name, value);
1952 			return err;
1953 		}
1954 		err = set_kcfg_value_num(ext, ext_val, num);
1955 		break;
1956 	}
1957 	if (err)
1958 		return err;
1959 	pr_debug("extern (kcfg) %s=%s\n", ext->name, value);
1960 	return 0;
1961 }
1962 
1963 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
1964 {
1965 	char buf[PATH_MAX];
1966 	struct utsname uts;
1967 	int len, err = 0;
1968 	gzFile file;
1969 
1970 	uname(&uts);
1971 	len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
1972 	if (len < 0)
1973 		return -EINVAL;
1974 	else if (len >= PATH_MAX)
1975 		return -ENAMETOOLONG;
1976 
1977 	/* gzopen also accepts uncompressed files. */
1978 	file = gzopen(buf, "r");
1979 	if (!file)
1980 		file = gzopen("/proc/config.gz", "r");
1981 
1982 	if (!file) {
1983 		pr_warn("failed to open system Kconfig\n");
1984 		return -ENOENT;
1985 	}
1986 
1987 	while (gzgets(file, buf, sizeof(buf))) {
1988 		err = bpf_object__process_kconfig_line(obj, buf, data);
1989 		if (err) {
1990 			pr_warn("error parsing system Kconfig line '%s': %d\n",
1991 				buf, err);
1992 			goto out;
1993 		}
1994 	}
1995 
1996 out:
1997 	gzclose(file);
1998 	return err;
1999 }
2000 
2001 static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
2002 					const char *config, void *data)
2003 {
2004 	char buf[PATH_MAX];
2005 	int err = 0;
2006 	FILE *file;
2007 
2008 	file = fmemopen((void *)config, strlen(config), "r");
2009 	if (!file) {
2010 		err = -errno;
2011 		pr_warn("failed to open in-memory Kconfig: %d\n", err);
2012 		return err;
2013 	}
2014 
2015 	while (fgets(buf, sizeof(buf), file)) {
2016 		err = bpf_object__process_kconfig_line(obj, buf, data);
2017 		if (err) {
2018 			pr_warn("error parsing in-memory Kconfig line '%s': %d\n",
2019 				buf, err);
2020 			break;
2021 		}
2022 	}
2023 
2024 	fclose(file);
2025 	return err;
2026 }
2027 
2028 static int bpf_object__init_kconfig_map(struct bpf_object *obj)
2029 {
2030 	struct extern_desc *last_ext = NULL, *ext;
2031 	size_t map_sz;
2032 	int i, err;
2033 
2034 	for (i = 0; i < obj->nr_extern; i++) {
2035 		ext = &obj->externs[i];
2036 		if (ext->type == EXT_KCFG)
2037 			last_ext = ext;
2038 	}
2039 
2040 	if (!last_ext)
2041 		return 0;
2042 
2043 	map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
2044 	err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
2045 					    ".kconfig", obj->efile.symbols_shndx,
2046 					    NULL, map_sz);
2047 	if (err)
2048 		return err;
2049 
2050 	obj->kconfig_map_idx = obj->nr_maps - 1;
2051 
2052 	return 0;
2053 }
2054 
2055 static int bpf_object__init_user_maps(struct bpf_object *obj, bool strict)
2056 {
2057 	Elf_Data *symbols = obj->efile.symbols;
2058 	int i, map_def_sz = 0, nr_maps = 0, nr_syms;
2059 	Elf_Data *data = NULL;
2060 	Elf_Scn *scn;
2061 
2062 	if (obj->efile.maps_shndx < 0)
2063 		return 0;
2064 
2065 	if (libbpf_mode & LIBBPF_STRICT_MAP_DEFINITIONS) {
2066 		pr_warn("legacy map definitions in SEC(\"maps\") are not supported\n");
2067 		return -EOPNOTSUPP;
2068 	}
2069 
2070 	if (!symbols)
2071 		return -EINVAL;
2072 
2073 	scn = elf_sec_by_idx(obj, obj->efile.maps_shndx);
2074 	data = elf_sec_data(obj, scn);
2075 	if (!scn || !data) {
2076 		pr_warn("elf: failed to get legacy map definitions for %s\n",
2077 			obj->path);
2078 		return -EINVAL;
2079 	}
2080 
2081 	/*
2082 	 * Count number of maps. Each map has a name.
2083 	 * Array of maps is not supported: only the first element is
2084 	 * considered.
2085 	 *
2086 	 * TODO: Detect array of map and report error.
2087 	 */
2088 	nr_syms = symbols->d_size / sizeof(Elf64_Sym);
2089 	for (i = 0; i < nr_syms; i++) {
2090 		Elf64_Sym *sym = elf_sym_by_idx(obj, i);
2091 
2092 		if (sym->st_shndx != obj->efile.maps_shndx)
2093 			continue;
2094 		if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION)
2095 			continue;
2096 		nr_maps++;
2097 	}
2098 	/* Assume equally sized map definitions */
2099 	pr_debug("elf: found %d legacy map definitions (%zd bytes) in %s\n",
2100 		 nr_maps, data->d_size, obj->path);
2101 
2102 	if (!data->d_size || nr_maps == 0 || (data->d_size % nr_maps) != 0) {
2103 		pr_warn("elf: unable to determine legacy map definition size in %s\n",
2104 			obj->path);
2105 		return -EINVAL;
2106 	}
2107 	map_def_sz = data->d_size / nr_maps;
2108 
2109 	/* Fill obj->maps using data in "maps" section.  */
2110 	for (i = 0; i < nr_syms; i++) {
2111 		Elf64_Sym *sym = elf_sym_by_idx(obj, i);
2112 		const char *map_name;
2113 		struct bpf_map_def *def;
2114 		struct bpf_map *map;
2115 
2116 		if (sym->st_shndx != obj->efile.maps_shndx)
2117 			continue;
2118 		if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION)
2119 			continue;
2120 
2121 		map = bpf_object__add_map(obj);
2122 		if (IS_ERR(map))
2123 			return PTR_ERR(map);
2124 
2125 		map_name = elf_sym_str(obj, sym->st_name);
2126 		if (!map_name) {
2127 			pr_warn("failed to get map #%d name sym string for obj %s\n",
2128 				i, obj->path);
2129 			return -LIBBPF_ERRNO__FORMAT;
2130 		}
2131 
2132 		pr_warn("map '%s' (legacy): legacy map definitions are deprecated, use BTF-defined maps instead\n", map_name);
2133 
2134 		if (ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
2135 			pr_warn("map '%s' (legacy): static maps are not supported\n", map_name);
2136 			return -ENOTSUP;
2137 		}
2138 
2139 		map->libbpf_type = LIBBPF_MAP_UNSPEC;
2140 		map->sec_idx = sym->st_shndx;
2141 		map->sec_offset = sym->st_value;
2142 		pr_debug("map '%s' (legacy): at sec_idx %d, offset %zu.\n",
2143 			 map_name, map->sec_idx, map->sec_offset);
2144 		if (sym->st_value + map_def_sz > data->d_size) {
2145 			pr_warn("corrupted maps section in %s: last map \"%s\" too small\n",
2146 				obj->path, map_name);
2147 			return -EINVAL;
2148 		}
2149 
2150 		map->name = strdup(map_name);
2151 		if (!map->name) {
2152 			pr_warn("map '%s': failed to alloc map name\n", map_name);
2153 			return -ENOMEM;
2154 		}
2155 		pr_debug("map %d is \"%s\"\n", i, map->name);
2156 		def = (struct bpf_map_def *)(data->d_buf + sym->st_value);
2157 		/*
2158 		 * If the definition of the map in the object file fits in
2159 		 * bpf_map_def, copy it.  Any extra fields in our version
2160 		 * of bpf_map_def will default to zero as a result of the
2161 		 * calloc above.
2162 		 */
2163 		if (map_def_sz <= sizeof(struct bpf_map_def)) {
2164 			memcpy(&map->def, def, map_def_sz);
2165 		} else {
2166 			/*
2167 			 * Here the map structure being read is bigger than what
2168 			 * we expect, truncate if the excess bits are all zero.
2169 			 * If they are not zero, reject this map as
2170 			 * incompatible.
2171 			 */
2172 			char *b;
2173 
2174 			for (b = ((char *)def) + sizeof(struct bpf_map_def);
2175 			     b < ((char *)def) + map_def_sz; b++) {
2176 				if (*b != 0) {
2177 					pr_warn("maps section in %s: \"%s\" has unrecognized, non-zero options\n",
2178 						obj->path, map_name);
2179 					if (strict)
2180 						return -EINVAL;
2181 				}
2182 			}
2183 			memcpy(&map->def, def, sizeof(struct bpf_map_def));
2184 		}
2185 
2186 		/* btf info may not exist but fill it in if it does exist */
2187 		(void) bpf_map_find_btf_info(obj, map);
2188 	}
2189 	return 0;
2190 }
2191 
2192 const struct btf_type *
2193 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
2194 {
2195 	const struct btf_type *t = btf__type_by_id(btf, id);
2196 
2197 	if (res_id)
2198 		*res_id = id;
2199 
2200 	while (btf_is_mod(t) || btf_is_typedef(t)) {
2201 		if (res_id)
2202 			*res_id = t->type;
2203 		t = btf__type_by_id(btf, t->type);
2204 	}
2205 
2206 	return t;
2207 }
2208 
2209 static const struct btf_type *
2210 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
2211 {
2212 	const struct btf_type *t;
2213 
2214 	t = skip_mods_and_typedefs(btf, id, NULL);
2215 	if (!btf_is_ptr(t))
2216 		return NULL;
2217 
2218 	t = skip_mods_and_typedefs(btf, t->type, res_id);
2219 
2220 	return btf_is_func_proto(t) ? t : NULL;
2221 }
2222 
2223 static const char *__btf_kind_str(__u16 kind)
2224 {
2225 	switch (kind) {
2226 	case BTF_KIND_UNKN: return "void";
2227 	case BTF_KIND_INT: return "int";
2228 	case BTF_KIND_PTR: return "ptr";
2229 	case BTF_KIND_ARRAY: return "array";
2230 	case BTF_KIND_STRUCT: return "struct";
2231 	case BTF_KIND_UNION: return "union";
2232 	case BTF_KIND_ENUM: return "enum";
2233 	case BTF_KIND_FWD: return "fwd";
2234 	case BTF_KIND_TYPEDEF: return "typedef";
2235 	case BTF_KIND_VOLATILE: return "volatile";
2236 	case BTF_KIND_CONST: return "const";
2237 	case BTF_KIND_RESTRICT: return "restrict";
2238 	case BTF_KIND_FUNC: return "func";
2239 	case BTF_KIND_FUNC_PROTO: return "func_proto";
2240 	case BTF_KIND_VAR: return "var";
2241 	case BTF_KIND_DATASEC: return "datasec";
2242 	case BTF_KIND_FLOAT: return "float";
2243 	case BTF_KIND_DECL_TAG: return "decl_tag";
2244 	case BTF_KIND_TYPE_TAG: return "type_tag";
2245 	case BTF_KIND_ENUM64: return "enum64";
2246 	default: return "unknown";
2247 	}
2248 }
2249 
2250 const char *btf_kind_str(const struct btf_type *t)
2251 {
2252 	return __btf_kind_str(btf_kind(t));
2253 }
2254 
2255 /*
2256  * Fetch integer attribute of BTF map definition. Such attributes are
2257  * represented using a pointer to an array, in which dimensionality of array
2258  * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2259  * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2260  * type definition, while using only sizeof(void *) space in ELF data section.
2261  */
2262 static bool get_map_field_int(const char *map_name, const struct btf *btf,
2263 			      const struct btf_member *m, __u32 *res)
2264 {
2265 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2266 	const char *name = btf__name_by_offset(btf, m->name_off);
2267 	const struct btf_array *arr_info;
2268 	const struct btf_type *arr_t;
2269 
2270 	if (!btf_is_ptr(t)) {
2271 		pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2272 			map_name, name, btf_kind_str(t));
2273 		return false;
2274 	}
2275 
2276 	arr_t = btf__type_by_id(btf, t->type);
2277 	if (!arr_t) {
2278 		pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2279 			map_name, name, t->type);
2280 		return false;
2281 	}
2282 	if (!btf_is_array(arr_t)) {
2283 		pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2284 			map_name, name, btf_kind_str(arr_t));
2285 		return false;
2286 	}
2287 	arr_info = btf_array(arr_t);
2288 	*res = arr_info->nelems;
2289 	return true;
2290 }
2291 
2292 static int build_map_pin_path(struct bpf_map *map, const char *path)
2293 {
2294 	char buf[PATH_MAX];
2295 	int len;
2296 
2297 	if (!path)
2298 		path = "/sys/fs/bpf";
2299 
2300 	len = snprintf(buf, PATH_MAX, "%s/%s", path, bpf_map__name(map));
2301 	if (len < 0)
2302 		return -EINVAL;
2303 	else if (len >= PATH_MAX)
2304 		return -ENAMETOOLONG;
2305 
2306 	return bpf_map__set_pin_path(map, buf);
2307 }
2308 
2309 int parse_btf_map_def(const char *map_name, struct btf *btf,
2310 		      const struct btf_type *def_t, bool strict,
2311 		      struct btf_map_def *map_def, struct btf_map_def *inner_def)
2312 {
2313 	const struct btf_type *t;
2314 	const struct btf_member *m;
2315 	bool is_inner = inner_def == NULL;
2316 	int vlen, i;
2317 
2318 	vlen = btf_vlen(def_t);
2319 	m = btf_members(def_t);
2320 	for (i = 0; i < vlen; i++, m++) {
2321 		const char *name = btf__name_by_offset(btf, m->name_off);
2322 
2323 		if (!name) {
2324 			pr_warn("map '%s': invalid field #%d.\n", map_name, i);
2325 			return -EINVAL;
2326 		}
2327 		if (strcmp(name, "type") == 0) {
2328 			if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
2329 				return -EINVAL;
2330 			map_def->parts |= MAP_DEF_MAP_TYPE;
2331 		} else if (strcmp(name, "max_entries") == 0) {
2332 			if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
2333 				return -EINVAL;
2334 			map_def->parts |= MAP_DEF_MAX_ENTRIES;
2335 		} else if (strcmp(name, "map_flags") == 0) {
2336 			if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
2337 				return -EINVAL;
2338 			map_def->parts |= MAP_DEF_MAP_FLAGS;
2339 		} else if (strcmp(name, "numa_node") == 0) {
2340 			if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
2341 				return -EINVAL;
2342 			map_def->parts |= MAP_DEF_NUMA_NODE;
2343 		} else if (strcmp(name, "key_size") == 0) {
2344 			__u32 sz;
2345 
2346 			if (!get_map_field_int(map_name, btf, m, &sz))
2347 				return -EINVAL;
2348 			if (map_def->key_size && map_def->key_size != sz) {
2349 				pr_warn("map '%s': conflicting key size %u != %u.\n",
2350 					map_name, map_def->key_size, sz);
2351 				return -EINVAL;
2352 			}
2353 			map_def->key_size = sz;
2354 			map_def->parts |= MAP_DEF_KEY_SIZE;
2355 		} else if (strcmp(name, "key") == 0) {
2356 			__s64 sz;
2357 
2358 			t = btf__type_by_id(btf, m->type);
2359 			if (!t) {
2360 				pr_warn("map '%s': key type [%d] not found.\n",
2361 					map_name, m->type);
2362 				return -EINVAL;
2363 			}
2364 			if (!btf_is_ptr(t)) {
2365 				pr_warn("map '%s': key spec is not PTR: %s.\n",
2366 					map_name, btf_kind_str(t));
2367 				return -EINVAL;
2368 			}
2369 			sz = btf__resolve_size(btf, t->type);
2370 			if (sz < 0) {
2371 				pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2372 					map_name, t->type, (ssize_t)sz);
2373 				return sz;
2374 			}
2375 			if (map_def->key_size && map_def->key_size != sz) {
2376 				pr_warn("map '%s': conflicting key size %u != %zd.\n",
2377 					map_name, map_def->key_size, (ssize_t)sz);
2378 				return -EINVAL;
2379 			}
2380 			map_def->key_size = sz;
2381 			map_def->key_type_id = t->type;
2382 			map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
2383 		} else if (strcmp(name, "value_size") == 0) {
2384 			__u32 sz;
2385 
2386 			if (!get_map_field_int(map_name, btf, m, &sz))
2387 				return -EINVAL;
2388 			if (map_def->value_size && map_def->value_size != sz) {
2389 				pr_warn("map '%s': conflicting value size %u != %u.\n",
2390 					map_name, map_def->value_size, sz);
2391 				return -EINVAL;
2392 			}
2393 			map_def->value_size = sz;
2394 			map_def->parts |= MAP_DEF_VALUE_SIZE;
2395 		} else if (strcmp(name, "value") == 0) {
2396 			__s64 sz;
2397 
2398 			t = btf__type_by_id(btf, m->type);
2399 			if (!t) {
2400 				pr_warn("map '%s': value type [%d] not found.\n",
2401 					map_name, m->type);
2402 				return -EINVAL;
2403 			}
2404 			if (!btf_is_ptr(t)) {
2405 				pr_warn("map '%s': value spec is not PTR: %s.\n",
2406 					map_name, btf_kind_str(t));
2407 				return -EINVAL;
2408 			}
2409 			sz = btf__resolve_size(btf, t->type);
2410 			if (sz < 0) {
2411 				pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2412 					map_name, t->type, (ssize_t)sz);
2413 				return sz;
2414 			}
2415 			if (map_def->value_size && map_def->value_size != sz) {
2416 				pr_warn("map '%s': conflicting value size %u != %zd.\n",
2417 					map_name, map_def->value_size, (ssize_t)sz);
2418 				return -EINVAL;
2419 			}
2420 			map_def->value_size = sz;
2421 			map_def->value_type_id = t->type;
2422 			map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
2423 		}
2424 		else if (strcmp(name, "values") == 0) {
2425 			bool is_map_in_map = bpf_map_type__is_map_in_map(map_def->map_type);
2426 			bool is_prog_array = map_def->map_type == BPF_MAP_TYPE_PROG_ARRAY;
2427 			const char *desc = is_map_in_map ? "map-in-map inner" : "prog-array value";
2428 			char inner_map_name[128];
2429 			int err;
2430 
2431 			if (is_inner) {
2432 				pr_warn("map '%s': multi-level inner maps not supported.\n",
2433 					map_name);
2434 				return -ENOTSUP;
2435 			}
2436 			if (i != vlen - 1) {
2437 				pr_warn("map '%s': '%s' member should be last.\n",
2438 					map_name, name);
2439 				return -EINVAL;
2440 			}
2441 			if (!is_map_in_map && !is_prog_array) {
2442 				pr_warn("map '%s': should be map-in-map or prog-array.\n",
2443 					map_name);
2444 				return -ENOTSUP;
2445 			}
2446 			if (map_def->value_size && map_def->value_size != 4) {
2447 				pr_warn("map '%s': conflicting value size %u != 4.\n",
2448 					map_name, map_def->value_size);
2449 				return -EINVAL;
2450 			}
2451 			map_def->value_size = 4;
2452 			t = btf__type_by_id(btf, m->type);
2453 			if (!t) {
2454 				pr_warn("map '%s': %s type [%d] not found.\n",
2455 					map_name, desc, m->type);
2456 				return -EINVAL;
2457 			}
2458 			if (!btf_is_array(t) || btf_array(t)->nelems) {
2459 				pr_warn("map '%s': %s spec is not a zero-sized array.\n",
2460 					map_name, desc);
2461 				return -EINVAL;
2462 			}
2463 			t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
2464 			if (!btf_is_ptr(t)) {
2465 				pr_warn("map '%s': %s def is of unexpected kind %s.\n",
2466 					map_name, desc, btf_kind_str(t));
2467 				return -EINVAL;
2468 			}
2469 			t = skip_mods_and_typedefs(btf, t->type, NULL);
2470 			if (is_prog_array) {
2471 				if (!btf_is_func_proto(t)) {
2472 					pr_warn("map '%s': prog-array value def is of unexpected kind %s.\n",
2473 						map_name, btf_kind_str(t));
2474 					return -EINVAL;
2475 				}
2476 				continue;
2477 			}
2478 			if (!btf_is_struct(t)) {
2479 				pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2480 					map_name, btf_kind_str(t));
2481 				return -EINVAL;
2482 			}
2483 
2484 			snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2485 			err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
2486 			if (err)
2487 				return err;
2488 
2489 			map_def->parts |= MAP_DEF_INNER_MAP;
2490 		} else if (strcmp(name, "pinning") == 0) {
2491 			__u32 val;
2492 
2493 			if (is_inner) {
2494 				pr_warn("map '%s': inner def can't be pinned.\n", map_name);
2495 				return -EINVAL;
2496 			}
2497 			if (!get_map_field_int(map_name, btf, m, &val))
2498 				return -EINVAL;
2499 			if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
2500 				pr_warn("map '%s': invalid pinning value %u.\n",
2501 					map_name, val);
2502 				return -EINVAL;
2503 			}
2504 			map_def->pinning = val;
2505 			map_def->parts |= MAP_DEF_PINNING;
2506 		} else if (strcmp(name, "map_extra") == 0) {
2507 			__u32 map_extra;
2508 
2509 			if (!get_map_field_int(map_name, btf, m, &map_extra))
2510 				return -EINVAL;
2511 			map_def->map_extra = map_extra;
2512 			map_def->parts |= MAP_DEF_MAP_EXTRA;
2513 		} else {
2514 			if (strict) {
2515 				pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
2516 				return -ENOTSUP;
2517 			}
2518 			pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
2519 		}
2520 	}
2521 
2522 	if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2523 		pr_warn("map '%s': map type isn't specified.\n", map_name);
2524 		return -EINVAL;
2525 	}
2526 
2527 	return 0;
2528 }
2529 
2530 static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2531 {
2532 	map->def.type = def->map_type;
2533 	map->def.key_size = def->key_size;
2534 	map->def.value_size = def->value_size;
2535 	map->def.max_entries = def->max_entries;
2536 	map->def.map_flags = def->map_flags;
2537 	map->map_extra = def->map_extra;
2538 
2539 	map->numa_node = def->numa_node;
2540 	map->btf_key_type_id = def->key_type_id;
2541 	map->btf_value_type_id = def->value_type_id;
2542 
2543 	if (def->parts & MAP_DEF_MAP_TYPE)
2544 		pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2545 
2546 	if (def->parts & MAP_DEF_KEY_TYPE)
2547 		pr_debug("map '%s': found key [%u], sz = %u.\n",
2548 			 map->name, def->key_type_id, def->key_size);
2549 	else if (def->parts & MAP_DEF_KEY_SIZE)
2550 		pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2551 
2552 	if (def->parts & MAP_DEF_VALUE_TYPE)
2553 		pr_debug("map '%s': found value [%u], sz = %u.\n",
2554 			 map->name, def->value_type_id, def->value_size);
2555 	else if (def->parts & MAP_DEF_VALUE_SIZE)
2556 		pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2557 
2558 	if (def->parts & MAP_DEF_MAX_ENTRIES)
2559 		pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2560 	if (def->parts & MAP_DEF_MAP_FLAGS)
2561 		pr_debug("map '%s': found map_flags = 0x%x.\n", map->name, def->map_flags);
2562 	if (def->parts & MAP_DEF_MAP_EXTRA)
2563 		pr_debug("map '%s': found map_extra = 0x%llx.\n", map->name,
2564 			 (unsigned long long)def->map_extra);
2565 	if (def->parts & MAP_DEF_PINNING)
2566 		pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2567 	if (def->parts & MAP_DEF_NUMA_NODE)
2568 		pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2569 
2570 	if (def->parts & MAP_DEF_INNER_MAP)
2571 		pr_debug("map '%s': found inner map definition.\n", map->name);
2572 }
2573 
2574 static const char *btf_var_linkage_str(__u32 linkage)
2575 {
2576 	switch (linkage) {
2577 	case BTF_VAR_STATIC: return "static";
2578 	case BTF_VAR_GLOBAL_ALLOCATED: return "global";
2579 	case BTF_VAR_GLOBAL_EXTERN: return "extern";
2580 	default: return "unknown";
2581 	}
2582 }
2583 
2584 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2585 					 const struct btf_type *sec,
2586 					 int var_idx, int sec_idx,
2587 					 const Elf_Data *data, bool strict,
2588 					 const char *pin_root_path)
2589 {
2590 	struct btf_map_def map_def = {}, inner_def = {};
2591 	const struct btf_type *var, *def;
2592 	const struct btf_var_secinfo *vi;
2593 	const struct btf_var *var_extra;
2594 	const char *map_name;
2595 	struct bpf_map *map;
2596 	int err;
2597 
2598 	vi = btf_var_secinfos(sec) + var_idx;
2599 	var = btf__type_by_id(obj->btf, vi->type);
2600 	var_extra = btf_var(var);
2601 	map_name = btf__name_by_offset(obj->btf, var->name_off);
2602 
2603 	if (map_name == NULL || map_name[0] == '\0') {
2604 		pr_warn("map #%d: empty name.\n", var_idx);
2605 		return -EINVAL;
2606 	}
2607 	if ((__u64)vi->offset + vi->size > data->d_size) {
2608 		pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2609 		return -EINVAL;
2610 	}
2611 	if (!btf_is_var(var)) {
2612 		pr_warn("map '%s': unexpected var kind %s.\n",
2613 			map_name, btf_kind_str(var));
2614 		return -EINVAL;
2615 	}
2616 	if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
2617 		pr_warn("map '%s': unsupported map linkage %s.\n",
2618 			map_name, btf_var_linkage_str(var_extra->linkage));
2619 		return -EOPNOTSUPP;
2620 	}
2621 
2622 	def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2623 	if (!btf_is_struct(def)) {
2624 		pr_warn("map '%s': unexpected def kind %s.\n",
2625 			map_name, btf_kind_str(var));
2626 		return -EINVAL;
2627 	}
2628 	if (def->size > vi->size) {
2629 		pr_warn("map '%s': invalid def size.\n", map_name);
2630 		return -EINVAL;
2631 	}
2632 
2633 	map = bpf_object__add_map(obj);
2634 	if (IS_ERR(map))
2635 		return PTR_ERR(map);
2636 	map->name = strdup(map_name);
2637 	if (!map->name) {
2638 		pr_warn("map '%s': failed to alloc map name.\n", map_name);
2639 		return -ENOMEM;
2640 	}
2641 	map->libbpf_type = LIBBPF_MAP_UNSPEC;
2642 	map->def.type = BPF_MAP_TYPE_UNSPEC;
2643 	map->sec_idx = sec_idx;
2644 	map->sec_offset = vi->offset;
2645 	map->btf_var_idx = var_idx;
2646 	pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2647 		 map_name, map->sec_idx, map->sec_offset);
2648 
2649 	err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
2650 	if (err)
2651 		return err;
2652 
2653 	fill_map_from_def(map, &map_def);
2654 
2655 	if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
2656 		err = build_map_pin_path(map, pin_root_path);
2657 		if (err) {
2658 			pr_warn("map '%s': couldn't build pin path.\n", map->name);
2659 			return err;
2660 		}
2661 	}
2662 
2663 	if (map_def.parts & MAP_DEF_INNER_MAP) {
2664 		map->inner_map = calloc(1, sizeof(*map->inner_map));
2665 		if (!map->inner_map)
2666 			return -ENOMEM;
2667 		map->inner_map->fd = -1;
2668 		map->inner_map->sec_idx = sec_idx;
2669 		map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
2670 		if (!map->inner_map->name)
2671 			return -ENOMEM;
2672 		sprintf(map->inner_map->name, "%s.inner", map_name);
2673 
2674 		fill_map_from_def(map->inner_map, &inner_def);
2675 	}
2676 
2677 	err = bpf_map_find_btf_info(obj, map);
2678 	if (err)
2679 		return err;
2680 
2681 	return 0;
2682 }
2683 
2684 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
2685 					  const char *pin_root_path)
2686 {
2687 	const struct btf_type *sec = NULL;
2688 	int nr_types, i, vlen, err;
2689 	const struct btf_type *t;
2690 	const char *name;
2691 	Elf_Data *data;
2692 	Elf_Scn *scn;
2693 
2694 	if (obj->efile.btf_maps_shndx < 0)
2695 		return 0;
2696 
2697 	scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
2698 	data = elf_sec_data(obj, scn);
2699 	if (!scn || !data) {
2700 		pr_warn("elf: failed to get %s map definitions for %s\n",
2701 			MAPS_ELF_SEC, obj->path);
2702 		return -EINVAL;
2703 	}
2704 
2705 	nr_types = btf__type_cnt(obj->btf);
2706 	for (i = 1; i < nr_types; i++) {
2707 		t = btf__type_by_id(obj->btf, i);
2708 		if (!btf_is_datasec(t))
2709 			continue;
2710 		name = btf__name_by_offset(obj->btf, t->name_off);
2711 		if (strcmp(name, MAPS_ELF_SEC) == 0) {
2712 			sec = t;
2713 			obj->efile.btf_maps_sec_btf_id = i;
2714 			break;
2715 		}
2716 	}
2717 
2718 	if (!sec) {
2719 		pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
2720 		return -ENOENT;
2721 	}
2722 
2723 	vlen = btf_vlen(sec);
2724 	for (i = 0; i < vlen; i++) {
2725 		err = bpf_object__init_user_btf_map(obj, sec, i,
2726 						    obj->efile.btf_maps_shndx,
2727 						    data, strict,
2728 						    pin_root_path);
2729 		if (err)
2730 			return err;
2731 	}
2732 
2733 	return 0;
2734 }
2735 
2736 static int bpf_object__init_maps(struct bpf_object *obj,
2737 				 const struct bpf_object_open_opts *opts)
2738 {
2739 	const char *pin_root_path;
2740 	bool strict;
2741 	int err;
2742 
2743 	strict = !OPTS_GET(opts, relaxed_maps, false);
2744 	pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
2745 
2746 	err = bpf_object__init_user_maps(obj, strict);
2747 	err = err ?: bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
2748 	err = err ?: bpf_object__init_global_data_maps(obj);
2749 	err = err ?: bpf_object__init_kconfig_map(obj);
2750 	err = err ?: bpf_object__init_struct_ops_maps(obj);
2751 
2752 	return err;
2753 }
2754 
2755 static bool section_have_execinstr(struct bpf_object *obj, int idx)
2756 {
2757 	Elf64_Shdr *sh;
2758 
2759 	sh = elf_sec_hdr(obj, elf_sec_by_idx(obj, idx));
2760 	if (!sh)
2761 		return false;
2762 
2763 	return sh->sh_flags & SHF_EXECINSTR;
2764 }
2765 
2766 static bool btf_needs_sanitization(struct bpf_object *obj)
2767 {
2768 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2769 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2770 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2771 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2772 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2773 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2774 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
2775 
2776 	return !has_func || !has_datasec || !has_func_global || !has_float ||
2777 	       !has_decl_tag || !has_type_tag || !has_enum64;
2778 }
2779 
2780 static int bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *btf)
2781 {
2782 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2783 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2784 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2785 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2786 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2787 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2788 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
2789 	int enum64_placeholder_id = 0;
2790 	struct btf_type *t;
2791 	int i, j, vlen;
2792 
2793 	for (i = 1; i < btf__type_cnt(btf); i++) {
2794 		t = (struct btf_type *)btf__type_by_id(btf, i);
2795 
2796 		if ((!has_datasec && btf_is_var(t)) || (!has_decl_tag && btf_is_decl_tag(t))) {
2797 			/* replace VAR/DECL_TAG with INT */
2798 			t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
2799 			/*
2800 			 * using size = 1 is the safest choice, 4 will be too
2801 			 * big and cause kernel BTF validation failure if
2802 			 * original variable took less than 4 bytes
2803 			 */
2804 			t->size = 1;
2805 			*(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
2806 		} else if (!has_datasec && btf_is_datasec(t)) {
2807 			/* replace DATASEC with STRUCT */
2808 			const struct btf_var_secinfo *v = btf_var_secinfos(t);
2809 			struct btf_member *m = btf_members(t);
2810 			struct btf_type *vt;
2811 			char *name;
2812 
2813 			name = (char *)btf__name_by_offset(btf, t->name_off);
2814 			while (*name) {
2815 				if (*name == '.')
2816 					*name = '_';
2817 				name++;
2818 			}
2819 
2820 			vlen = btf_vlen(t);
2821 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
2822 			for (j = 0; j < vlen; j++, v++, m++) {
2823 				/* order of field assignments is important */
2824 				m->offset = v->offset * 8;
2825 				m->type = v->type;
2826 				/* preserve variable name as member name */
2827 				vt = (void *)btf__type_by_id(btf, v->type);
2828 				m->name_off = vt->name_off;
2829 			}
2830 		} else if (!has_func && btf_is_func_proto(t)) {
2831 			/* replace FUNC_PROTO with ENUM */
2832 			vlen = btf_vlen(t);
2833 			t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
2834 			t->size = sizeof(__u32); /* kernel enforced */
2835 		} else if (!has_func && btf_is_func(t)) {
2836 			/* replace FUNC with TYPEDEF */
2837 			t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
2838 		} else if (!has_func_global && btf_is_func(t)) {
2839 			/* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
2840 			t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
2841 		} else if (!has_float && btf_is_float(t)) {
2842 			/* replace FLOAT with an equally-sized empty STRUCT;
2843 			 * since C compilers do not accept e.g. "float" as a
2844 			 * valid struct name, make it anonymous
2845 			 */
2846 			t->name_off = 0;
2847 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
2848 		} else if (!has_type_tag && btf_is_type_tag(t)) {
2849 			/* replace TYPE_TAG with a CONST */
2850 			t->name_off = 0;
2851 			t->info = BTF_INFO_ENC(BTF_KIND_CONST, 0, 0);
2852 		} else if (!has_enum64 && btf_is_enum(t)) {
2853 			/* clear the kflag */
2854 			t->info = btf_type_info(btf_kind(t), btf_vlen(t), false);
2855 		} else if (!has_enum64 && btf_is_enum64(t)) {
2856 			/* replace ENUM64 with a union */
2857 			struct btf_member *m;
2858 
2859 			if (enum64_placeholder_id == 0) {
2860 				enum64_placeholder_id = btf__add_int(btf, "enum64_placeholder", 1, 0);
2861 				if (enum64_placeholder_id < 0)
2862 					return enum64_placeholder_id;
2863 
2864 				t = (struct btf_type *)btf__type_by_id(btf, i);
2865 			}
2866 
2867 			m = btf_members(t);
2868 			vlen = btf_vlen(t);
2869 			t->info = BTF_INFO_ENC(BTF_KIND_UNION, 0, vlen);
2870 			for (j = 0; j < vlen; j++, m++) {
2871 				m->type = enum64_placeholder_id;
2872 				m->offset = 0;
2873 			}
2874                 }
2875 	}
2876 
2877 	return 0;
2878 }
2879 
2880 static bool libbpf_needs_btf(const struct bpf_object *obj)
2881 {
2882 	return obj->efile.btf_maps_shndx >= 0 ||
2883 	       obj->efile.st_ops_shndx >= 0 ||
2884 	       obj->nr_extern > 0;
2885 }
2886 
2887 static bool kernel_needs_btf(const struct bpf_object *obj)
2888 {
2889 	return obj->efile.st_ops_shndx >= 0;
2890 }
2891 
2892 static int bpf_object__init_btf(struct bpf_object *obj,
2893 				Elf_Data *btf_data,
2894 				Elf_Data *btf_ext_data)
2895 {
2896 	int err = -ENOENT;
2897 
2898 	if (btf_data) {
2899 		obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
2900 		err = libbpf_get_error(obj->btf);
2901 		if (err) {
2902 			obj->btf = NULL;
2903 			pr_warn("Error loading ELF section %s: %d.\n", BTF_ELF_SEC, err);
2904 			goto out;
2905 		}
2906 		/* enforce 8-byte pointers for BPF-targeted BTFs */
2907 		btf__set_pointer_size(obj->btf, 8);
2908 	}
2909 	if (btf_ext_data) {
2910 		struct btf_ext_info *ext_segs[3];
2911 		int seg_num, sec_num;
2912 
2913 		if (!obj->btf) {
2914 			pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
2915 				 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
2916 			goto out;
2917 		}
2918 		obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
2919 		err = libbpf_get_error(obj->btf_ext);
2920 		if (err) {
2921 			pr_warn("Error loading ELF section %s: %d. Ignored and continue.\n",
2922 				BTF_EXT_ELF_SEC, err);
2923 			obj->btf_ext = NULL;
2924 			goto out;
2925 		}
2926 
2927 		/* setup .BTF.ext to ELF section mapping */
2928 		ext_segs[0] = &obj->btf_ext->func_info;
2929 		ext_segs[1] = &obj->btf_ext->line_info;
2930 		ext_segs[2] = &obj->btf_ext->core_relo_info;
2931 		for (seg_num = 0; seg_num < ARRAY_SIZE(ext_segs); seg_num++) {
2932 			struct btf_ext_info *seg = ext_segs[seg_num];
2933 			const struct btf_ext_info_sec *sec;
2934 			const char *sec_name;
2935 			Elf_Scn *scn;
2936 
2937 			if (seg->sec_cnt == 0)
2938 				continue;
2939 
2940 			seg->sec_idxs = calloc(seg->sec_cnt, sizeof(*seg->sec_idxs));
2941 			if (!seg->sec_idxs) {
2942 				err = -ENOMEM;
2943 				goto out;
2944 			}
2945 
2946 			sec_num = 0;
2947 			for_each_btf_ext_sec(seg, sec) {
2948 				/* preventively increment index to avoid doing
2949 				 * this before every continue below
2950 				 */
2951 				sec_num++;
2952 
2953 				sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
2954 				if (str_is_empty(sec_name))
2955 					continue;
2956 				scn = elf_sec_by_name(obj, sec_name);
2957 				if (!scn)
2958 					continue;
2959 
2960 				seg->sec_idxs[sec_num - 1] = elf_ndxscn(scn);
2961 			}
2962 		}
2963 	}
2964 out:
2965 	if (err && libbpf_needs_btf(obj)) {
2966 		pr_warn("BTF is required, but is missing or corrupted.\n");
2967 		return err;
2968 	}
2969 	return 0;
2970 }
2971 
2972 static int compare_vsi_off(const void *_a, const void *_b)
2973 {
2974 	const struct btf_var_secinfo *a = _a;
2975 	const struct btf_var_secinfo *b = _b;
2976 
2977 	return a->offset - b->offset;
2978 }
2979 
2980 static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
2981 			     struct btf_type *t)
2982 {
2983 	__u32 size = 0, off = 0, i, vars = btf_vlen(t);
2984 	const char *name = btf__name_by_offset(btf, t->name_off);
2985 	const struct btf_type *t_var;
2986 	struct btf_var_secinfo *vsi;
2987 	const struct btf_var *var;
2988 	int ret;
2989 
2990 	if (!name) {
2991 		pr_debug("No name found in string section for DATASEC kind.\n");
2992 		return -ENOENT;
2993 	}
2994 
2995 	/* .extern datasec size and var offsets were set correctly during
2996 	 * extern collection step, so just skip straight to sorting variables
2997 	 */
2998 	if (t->size)
2999 		goto sort_vars;
3000 
3001 	ret = find_elf_sec_sz(obj, name, &size);
3002 	if (ret || !size) {
3003 		pr_debug("Invalid size for section %s: %u bytes\n", name, size);
3004 		return -ENOENT;
3005 	}
3006 
3007 	t->size = size;
3008 
3009 	for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
3010 		t_var = btf__type_by_id(btf, vsi->type);
3011 		if (!t_var || !btf_is_var(t_var)) {
3012 			pr_debug("Non-VAR type seen in section %s\n", name);
3013 			return -EINVAL;
3014 		}
3015 
3016 		var = btf_var(t_var);
3017 		if (var->linkage == BTF_VAR_STATIC)
3018 			continue;
3019 
3020 		name = btf__name_by_offset(btf, t_var->name_off);
3021 		if (!name) {
3022 			pr_debug("No name found in string section for VAR kind\n");
3023 			return -ENOENT;
3024 		}
3025 
3026 		ret = find_elf_var_offset(obj, name, &off);
3027 		if (ret) {
3028 			pr_debug("No offset found in symbol table for VAR %s\n",
3029 				 name);
3030 			return -ENOENT;
3031 		}
3032 
3033 		vsi->offset = off;
3034 	}
3035 
3036 sort_vars:
3037 	qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
3038 	return 0;
3039 }
3040 
3041 static int btf_finalize_data(struct bpf_object *obj, struct btf *btf)
3042 {
3043 	int err = 0;
3044 	__u32 i, n = btf__type_cnt(btf);
3045 
3046 	for (i = 1; i < n; i++) {
3047 		struct btf_type *t = btf_type_by_id(btf, i);
3048 
3049 		/* Loader needs to fix up some of the things compiler
3050 		 * couldn't get its hands on while emitting BTF. This
3051 		 * is section size and global variable offset. We use
3052 		 * the info from the ELF itself for this purpose.
3053 		 */
3054 		if (btf_is_datasec(t)) {
3055 			err = btf_fixup_datasec(obj, btf, t);
3056 			if (err)
3057 				break;
3058 		}
3059 	}
3060 
3061 	return libbpf_err(err);
3062 }
3063 
3064 int btf__finalize_data(struct bpf_object *obj, struct btf *btf)
3065 {
3066 	return btf_finalize_data(obj, btf);
3067 }
3068 
3069 static int bpf_object__finalize_btf(struct bpf_object *obj)
3070 {
3071 	int err;
3072 
3073 	if (!obj->btf)
3074 		return 0;
3075 
3076 	err = btf_finalize_data(obj, obj->btf);
3077 	if (err) {
3078 		pr_warn("Error finalizing %s: %d.\n", BTF_ELF_SEC, err);
3079 		return err;
3080 	}
3081 
3082 	return 0;
3083 }
3084 
3085 static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
3086 {
3087 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
3088 	    prog->type == BPF_PROG_TYPE_LSM)
3089 		return true;
3090 
3091 	/* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
3092 	 * also need vmlinux BTF
3093 	 */
3094 	if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
3095 		return true;
3096 
3097 	return false;
3098 }
3099 
3100 static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
3101 {
3102 	struct bpf_program *prog;
3103 	int i;
3104 
3105 	/* CO-RE relocations need kernel BTF, only when btf_custom_path
3106 	 * is not specified
3107 	 */
3108 	if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
3109 		return true;
3110 
3111 	/* Support for typed ksyms needs kernel BTF */
3112 	for (i = 0; i < obj->nr_extern; i++) {
3113 		const struct extern_desc *ext;
3114 
3115 		ext = &obj->externs[i];
3116 		if (ext->type == EXT_KSYM && ext->ksym.type_id)
3117 			return true;
3118 	}
3119 
3120 	bpf_object__for_each_program(prog, obj) {
3121 		if (!prog->autoload)
3122 			continue;
3123 		if (prog_needs_vmlinux_btf(prog))
3124 			return true;
3125 	}
3126 
3127 	return false;
3128 }
3129 
3130 static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
3131 {
3132 	int err;
3133 
3134 	/* btf_vmlinux could be loaded earlier */
3135 	if (obj->btf_vmlinux || obj->gen_loader)
3136 		return 0;
3137 
3138 	if (!force && !obj_needs_vmlinux_btf(obj))
3139 		return 0;
3140 
3141 	obj->btf_vmlinux = btf__load_vmlinux_btf();
3142 	err = libbpf_get_error(obj->btf_vmlinux);
3143 	if (err) {
3144 		pr_warn("Error loading vmlinux BTF: %d\n", err);
3145 		obj->btf_vmlinux = NULL;
3146 		return err;
3147 	}
3148 	return 0;
3149 }
3150 
3151 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
3152 {
3153 	struct btf *kern_btf = obj->btf;
3154 	bool btf_mandatory, sanitize;
3155 	int i, err = 0;
3156 
3157 	if (!obj->btf)
3158 		return 0;
3159 
3160 	if (!kernel_supports(obj, FEAT_BTF)) {
3161 		if (kernel_needs_btf(obj)) {
3162 			err = -EOPNOTSUPP;
3163 			goto report;
3164 		}
3165 		pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
3166 		return 0;
3167 	}
3168 
3169 	/* Even though some subprogs are global/weak, user might prefer more
3170 	 * permissive BPF verification process that BPF verifier performs for
3171 	 * static functions, taking into account more context from the caller
3172 	 * functions. In such case, they need to mark such subprogs with
3173 	 * __attribute__((visibility("hidden"))) and libbpf will adjust
3174 	 * corresponding FUNC BTF type to be marked as static and trigger more
3175 	 * involved BPF verification process.
3176 	 */
3177 	for (i = 0; i < obj->nr_programs; i++) {
3178 		struct bpf_program *prog = &obj->programs[i];
3179 		struct btf_type *t;
3180 		const char *name;
3181 		int j, n;
3182 
3183 		if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
3184 			continue;
3185 
3186 		n = btf__type_cnt(obj->btf);
3187 		for (j = 1; j < n; j++) {
3188 			t = btf_type_by_id(obj->btf, j);
3189 			if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
3190 				continue;
3191 
3192 			name = btf__str_by_offset(obj->btf, t->name_off);
3193 			if (strcmp(name, prog->name) != 0)
3194 				continue;
3195 
3196 			t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
3197 			break;
3198 		}
3199 	}
3200 
3201 	sanitize = btf_needs_sanitization(obj);
3202 	if (sanitize) {
3203 		const void *raw_data;
3204 		__u32 sz;
3205 
3206 		/* clone BTF to sanitize a copy and leave the original intact */
3207 		raw_data = btf__raw_data(obj->btf, &sz);
3208 		kern_btf = btf__new(raw_data, sz);
3209 		err = libbpf_get_error(kern_btf);
3210 		if (err)
3211 			return err;
3212 
3213 		/* enforce 8-byte pointers for BPF-targeted BTFs */
3214 		btf__set_pointer_size(obj->btf, 8);
3215 		err = bpf_object__sanitize_btf(obj, kern_btf);
3216 		if (err)
3217 			return err;
3218 	}
3219 
3220 	if (obj->gen_loader) {
3221 		__u32 raw_size = 0;
3222 		const void *raw_data = btf__raw_data(kern_btf, &raw_size);
3223 
3224 		if (!raw_data)
3225 			return -ENOMEM;
3226 		bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
3227 		/* Pretend to have valid FD to pass various fd >= 0 checks.
3228 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
3229 		 */
3230 		btf__set_fd(kern_btf, 0);
3231 	} else {
3232 		/* currently BPF_BTF_LOAD only supports log_level 1 */
3233 		err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
3234 					   obj->log_level ? 1 : 0);
3235 	}
3236 	if (sanitize) {
3237 		if (!err) {
3238 			/* move fd to libbpf's BTF */
3239 			btf__set_fd(obj->btf, btf__fd(kern_btf));
3240 			btf__set_fd(kern_btf, -1);
3241 		}
3242 		btf__free(kern_btf);
3243 	}
3244 report:
3245 	if (err) {
3246 		btf_mandatory = kernel_needs_btf(obj);
3247 		pr_warn("Error loading .BTF into kernel: %d. %s\n", err,
3248 			btf_mandatory ? "BTF is mandatory, can't proceed."
3249 				      : "BTF is optional, ignoring.");
3250 		if (!btf_mandatory)
3251 			err = 0;
3252 	}
3253 	return err;
3254 }
3255 
3256 static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
3257 {
3258 	const char *name;
3259 
3260 	name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
3261 	if (!name) {
3262 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3263 			off, obj->path, elf_errmsg(-1));
3264 		return NULL;
3265 	}
3266 
3267 	return name;
3268 }
3269 
3270 static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
3271 {
3272 	const char *name;
3273 
3274 	name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
3275 	if (!name) {
3276 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3277 			off, obj->path, elf_errmsg(-1));
3278 		return NULL;
3279 	}
3280 
3281 	return name;
3282 }
3283 
3284 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
3285 {
3286 	Elf_Scn *scn;
3287 
3288 	scn = elf_getscn(obj->efile.elf, idx);
3289 	if (!scn) {
3290 		pr_warn("elf: failed to get section(%zu) from %s: %s\n",
3291 			idx, obj->path, elf_errmsg(-1));
3292 		return NULL;
3293 	}
3294 	return scn;
3295 }
3296 
3297 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
3298 {
3299 	Elf_Scn *scn = NULL;
3300 	Elf *elf = obj->efile.elf;
3301 	const char *sec_name;
3302 
3303 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3304 		sec_name = elf_sec_name(obj, scn);
3305 		if (!sec_name)
3306 			return NULL;
3307 
3308 		if (strcmp(sec_name, name) != 0)
3309 			continue;
3310 
3311 		return scn;
3312 	}
3313 	return NULL;
3314 }
3315 
3316 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn)
3317 {
3318 	Elf64_Shdr *shdr;
3319 
3320 	if (!scn)
3321 		return NULL;
3322 
3323 	shdr = elf64_getshdr(scn);
3324 	if (!shdr) {
3325 		pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
3326 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3327 		return NULL;
3328 	}
3329 
3330 	return shdr;
3331 }
3332 
3333 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
3334 {
3335 	const char *name;
3336 	Elf64_Shdr *sh;
3337 
3338 	if (!scn)
3339 		return NULL;
3340 
3341 	sh = elf_sec_hdr(obj, scn);
3342 	if (!sh)
3343 		return NULL;
3344 
3345 	name = elf_sec_str(obj, sh->sh_name);
3346 	if (!name) {
3347 		pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
3348 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3349 		return NULL;
3350 	}
3351 
3352 	return name;
3353 }
3354 
3355 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
3356 {
3357 	Elf_Data *data;
3358 
3359 	if (!scn)
3360 		return NULL;
3361 
3362 	data = elf_getdata(scn, 0);
3363 	if (!data) {
3364 		pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
3365 			elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
3366 			obj->path, elf_errmsg(-1));
3367 		return NULL;
3368 	}
3369 
3370 	return data;
3371 }
3372 
3373 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx)
3374 {
3375 	if (idx >= obj->efile.symbols->d_size / sizeof(Elf64_Sym))
3376 		return NULL;
3377 
3378 	return (Elf64_Sym *)obj->efile.symbols->d_buf + idx;
3379 }
3380 
3381 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx)
3382 {
3383 	if (idx >= data->d_size / sizeof(Elf64_Rel))
3384 		return NULL;
3385 
3386 	return (Elf64_Rel *)data->d_buf + idx;
3387 }
3388 
3389 static bool is_sec_name_dwarf(const char *name)
3390 {
3391 	/* approximation, but the actual list is too long */
3392 	return str_has_pfx(name, ".debug_");
3393 }
3394 
3395 static bool ignore_elf_section(Elf64_Shdr *hdr, const char *name)
3396 {
3397 	/* no special handling of .strtab */
3398 	if (hdr->sh_type == SHT_STRTAB)
3399 		return true;
3400 
3401 	/* ignore .llvm_addrsig section as well */
3402 	if (hdr->sh_type == SHT_LLVM_ADDRSIG)
3403 		return true;
3404 
3405 	/* no subprograms will lead to an empty .text section, ignore it */
3406 	if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
3407 	    strcmp(name, ".text") == 0)
3408 		return true;
3409 
3410 	/* DWARF sections */
3411 	if (is_sec_name_dwarf(name))
3412 		return true;
3413 
3414 	if (str_has_pfx(name, ".rel")) {
3415 		name += sizeof(".rel") - 1;
3416 		/* DWARF section relocations */
3417 		if (is_sec_name_dwarf(name))
3418 			return true;
3419 
3420 		/* .BTF and .BTF.ext don't need relocations */
3421 		if (strcmp(name, BTF_ELF_SEC) == 0 ||
3422 		    strcmp(name, BTF_EXT_ELF_SEC) == 0)
3423 			return true;
3424 	}
3425 
3426 	return false;
3427 }
3428 
3429 static int cmp_progs(const void *_a, const void *_b)
3430 {
3431 	const struct bpf_program *a = _a;
3432 	const struct bpf_program *b = _b;
3433 
3434 	if (a->sec_idx != b->sec_idx)
3435 		return a->sec_idx < b->sec_idx ? -1 : 1;
3436 
3437 	/* sec_insn_off can't be the same within the section */
3438 	return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
3439 }
3440 
3441 static int bpf_object__elf_collect(struct bpf_object *obj)
3442 {
3443 	struct elf_sec_desc *sec_desc;
3444 	Elf *elf = obj->efile.elf;
3445 	Elf_Data *btf_ext_data = NULL;
3446 	Elf_Data *btf_data = NULL;
3447 	int idx = 0, err = 0;
3448 	const char *name;
3449 	Elf_Data *data;
3450 	Elf_Scn *scn;
3451 	Elf64_Shdr *sh;
3452 
3453 	/* ELF section indices are 0-based, but sec #0 is special "invalid"
3454 	 * section. e_shnum does include sec #0, so e_shnum is the necessary
3455 	 * size of an array to keep all the sections.
3456 	 */
3457 	obj->efile.sec_cnt = obj->efile.ehdr->e_shnum;
3458 	obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs));
3459 	if (!obj->efile.secs)
3460 		return -ENOMEM;
3461 
3462 	/* a bunch of ELF parsing functionality depends on processing symbols,
3463 	 * so do the first pass and find the symbol table
3464 	 */
3465 	scn = NULL;
3466 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3467 		sh = elf_sec_hdr(obj, scn);
3468 		if (!sh)
3469 			return -LIBBPF_ERRNO__FORMAT;
3470 
3471 		if (sh->sh_type == SHT_SYMTAB) {
3472 			if (obj->efile.symbols) {
3473 				pr_warn("elf: multiple symbol tables in %s\n", obj->path);
3474 				return -LIBBPF_ERRNO__FORMAT;
3475 			}
3476 
3477 			data = elf_sec_data(obj, scn);
3478 			if (!data)
3479 				return -LIBBPF_ERRNO__FORMAT;
3480 
3481 			idx = elf_ndxscn(scn);
3482 
3483 			obj->efile.symbols = data;
3484 			obj->efile.symbols_shndx = idx;
3485 			obj->efile.strtabidx = sh->sh_link;
3486 		}
3487 	}
3488 
3489 	if (!obj->efile.symbols) {
3490 		pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
3491 			obj->path);
3492 		return -ENOENT;
3493 	}
3494 
3495 	scn = NULL;
3496 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3497 		idx = elf_ndxscn(scn);
3498 		sec_desc = &obj->efile.secs[idx];
3499 
3500 		sh = elf_sec_hdr(obj, scn);
3501 		if (!sh)
3502 			return -LIBBPF_ERRNO__FORMAT;
3503 
3504 		name = elf_sec_str(obj, sh->sh_name);
3505 		if (!name)
3506 			return -LIBBPF_ERRNO__FORMAT;
3507 
3508 		if (ignore_elf_section(sh, name))
3509 			continue;
3510 
3511 		data = elf_sec_data(obj, scn);
3512 		if (!data)
3513 			return -LIBBPF_ERRNO__FORMAT;
3514 
3515 		pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
3516 			 idx, name, (unsigned long)data->d_size,
3517 			 (int)sh->sh_link, (unsigned long)sh->sh_flags,
3518 			 (int)sh->sh_type);
3519 
3520 		if (strcmp(name, "license") == 0) {
3521 			err = bpf_object__init_license(obj, data->d_buf, data->d_size);
3522 			if (err)
3523 				return err;
3524 		} else if (strcmp(name, "version") == 0) {
3525 			err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
3526 			if (err)
3527 				return err;
3528 		} else if (strcmp(name, "maps") == 0) {
3529 			obj->efile.maps_shndx = idx;
3530 		} else if (strcmp(name, MAPS_ELF_SEC) == 0) {
3531 			obj->efile.btf_maps_shndx = idx;
3532 		} else if (strcmp(name, BTF_ELF_SEC) == 0) {
3533 			if (sh->sh_type != SHT_PROGBITS)
3534 				return -LIBBPF_ERRNO__FORMAT;
3535 			btf_data = data;
3536 		} else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
3537 			if (sh->sh_type != SHT_PROGBITS)
3538 				return -LIBBPF_ERRNO__FORMAT;
3539 			btf_ext_data = data;
3540 		} else if (sh->sh_type == SHT_SYMTAB) {
3541 			/* already processed during the first pass above */
3542 		} else if (sh->sh_type == SHT_PROGBITS && data->d_size > 0) {
3543 			if (sh->sh_flags & SHF_EXECINSTR) {
3544 				if (strcmp(name, ".text") == 0)
3545 					obj->efile.text_shndx = idx;
3546 				err = bpf_object__add_programs(obj, data, name, idx);
3547 				if (err)
3548 					return err;
3549 			} else if (strcmp(name, DATA_SEC) == 0 ||
3550 				   str_has_pfx(name, DATA_SEC ".")) {
3551 				sec_desc->sec_type = SEC_DATA;
3552 				sec_desc->shdr = sh;
3553 				sec_desc->data = data;
3554 			} else if (strcmp(name, RODATA_SEC) == 0 ||
3555 				   str_has_pfx(name, RODATA_SEC ".")) {
3556 				sec_desc->sec_type = SEC_RODATA;
3557 				sec_desc->shdr = sh;
3558 				sec_desc->data = data;
3559 			} else if (strcmp(name, STRUCT_OPS_SEC) == 0) {
3560 				obj->efile.st_ops_data = data;
3561 				obj->efile.st_ops_shndx = idx;
3562 			} else {
3563 				pr_info("elf: skipping unrecognized data section(%d) %s\n",
3564 					idx, name);
3565 			}
3566 		} else if (sh->sh_type == SHT_REL) {
3567 			int targ_sec_idx = sh->sh_info; /* points to other section */
3568 
3569 			if (sh->sh_entsize != sizeof(Elf64_Rel) ||
3570 			    targ_sec_idx >= obj->efile.sec_cnt)
3571 				return -LIBBPF_ERRNO__FORMAT;
3572 
3573 			/* Only do relo for section with exec instructions */
3574 			if (!section_have_execinstr(obj, targ_sec_idx) &&
3575 			    strcmp(name, ".rel" STRUCT_OPS_SEC) &&
3576 			    strcmp(name, ".rel" MAPS_ELF_SEC)) {
3577 				pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
3578 					idx, name, targ_sec_idx,
3579 					elf_sec_name(obj, elf_sec_by_idx(obj, targ_sec_idx)) ?: "<?>");
3580 				continue;
3581 			}
3582 
3583 			sec_desc->sec_type = SEC_RELO;
3584 			sec_desc->shdr = sh;
3585 			sec_desc->data = data;
3586 		} else if (sh->sh_type == SHT_NOBITS && strcmp(name, BSS_SEC) == 0) {
3587 			sec_desc->sec_type = SEC_BSS;
3588 			sec_desc->shdr = sh;
3589 			sec_desc->data = data;
3590 		} else {
3591 			pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
3592 				(size_t)sh->sh_size);
3593 		}
3594 	}
3595 
3596 	if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
3597 		pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
3598 		return -LIBBPF_ERRNO__FORMAT;
3599 	}
3600 
3601 	/* sort BPF programs by section name and in-section instruction offset
3602 	 * for faster search */
3603 	if (obj->nr_programs)
3604 		qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
3605 
3606 	return bpf_object__init_btf(obj, btf_data, btf_ext_data);
3607 }
3608 
3609 static bool sym_is_extern(const Elf64_Sym *sym)
3610 {
3611 	int bind = ELF64_ST_BIND(sym->st_info);
3612 	/* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
3613 	return sym->st_shndx == SHN_UNDEF &&
3614 	       (bind == STB_GLOBAL || bind == STB_WEAK) &&
3615 	       ELF64_ST_TYPE(sym->st_info) == STT_NOTYPE;
3616 }
3617 
3618 static bool sym_is_subprog(const Elf64_Sym *sym, int text_shndx)
3619 {
3620 	int bind = ELF64_ST_BIND(sym->st_info);
3621 	int type = ELF64_ST_TYPE(sym->st_info);
3622 
3623 	/* in .text section */
3624 	if (sym->st_shndx != text_shndx)
3625 		return false;
3626 
3627 	/* local function */
3628 	if (bind == STB_LOCAL && type == STT_SECTION)
3629 		return true;
3630 
3631 	/* global function */
3632 	return bind == STB_GLOBAL && type == STT_FUNC;
3633 }
3634 
3635 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
3636 {
3637 	const struct btf_type *t;
3638 	const char *tname;
3639 	int i, n;
3640 
3641 	if (!btf)
3642 		return -ESRCH;
3643 
3644 	n = btf__type_cnt(btf);
3645 	for (i = 1; i < n; i++) {
3646 		t = btf__type_by_id(btf, i);
3647 
3648 		if (!btf_is_var(t) && !btf_is_func(t))
3649 			continue;
3650 
3651 		tname = btf__name_by_offset(btf, t->name_off);
3652 		if (strcmp(tname, ext_name))
3653 			continue;
3654 
3655 		if (btf_is_var(t) &&
3656 		    btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
3657 			return -EINVAL;
3658 
3659 		if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
3660 			return -EINVAL;
3661 
3662 		return i;
3663 	}
3664 
3665 	return -ENOENT;
3666 }
3667 
3668 static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
3669 	const struct btf_var_secinfo *vs;
3670 	const struct btf_type *t;
3671 	int i, j, n;
3672 
3673 	if (!btf)
3674 		return -ESRCH;
3675 
3676 	n = btf__type_cnt(btf);
3677 	for (i = 1; i < n; i++) {
3678 		t = btf__type_by_id(btf, i);
3679 
3680 		if (!btf_is_datasec(t))
3681 			continue;
3682 
3683 		vs = btf_var_secinfos(t);
3684 		for (j = 0; j < btf_vlen(t); j++, vs++) {
3685 			if (vs->type == ext_btf_id)
3686 				return i;
3687 		}
3688 	}
3689 
3690 	return -ENOENT;
3691 }
3692 
3693 static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
3694 				     bool *is_signed)
3695 {
3696 	const struct btf_type *t;
3697 	const char *name;
3698 
3699 	t = skip_mods_and_typedefs(btf, id, NULL);
3700 	name = btf__name_by_offset(btf, t->name_off);
3701 
3702 	if (is_signed)
3703 		*is_signed = false;
3704 	switch (btf_kind(t)) {
3705 	case BTF_KIND_INT: {
3706 		int enc = btf_int_encoding(t);
3707 
3708 		if (enc & BTF_INT_BOOL)
3709 			return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
3710 		if (is_signed)
3711 			*is_signed = enc & BTF_INT_SIGNED;
3712 		if (t->size == 1)
3713 			return KCFG_CHAR;
3714 		if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
3715 			return KCFG_UNKNOWN;
3716 		return KCFG_INT;
3717 	}
3718 	case BTF_KIND_ENUM:
3719 		if (t->size != 4)
3720 			return KCFG_UNKNOWN;
3721 		if (strcmp(name, "libbpf_tristate"))
3722 			return KCFG_UNKNOWN;
3723 		return KCFG_TRISTATE;
3724 	case BTF_KIND_ENUM64:
3725 		if (strcmp(name, "libbpf_tristate"))
3726 			return KCFG_UNKNOWN;
3727 		return KCFG_TRISTATE;
3728 	case BTF_KIND_ARRAY:
3729 		if (btf_array(t)->nelems == 0)
3730 			return KCFG_UNKNOWN;
3731 		if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
3732 			return KCFG_UNKNOWN;
3733 		return KCFG_CHAR_ARR;
3734 	default:
3735 		return KCFG_UNKNOWN;
3736 	}
3737 }
3738 
3739 static int cmp_externs(const void *_a, const void *_b)
3740 {
3741 	const struct extern_desc *a = _a;
3742 	const struct extern_desc *b = _b;
3743 
3744 	if (a->type != b->type)
3745 		return a->type < b->type ? -1 : 1;
3746 
3747 	if (a->type == EXT_KCFG) {
3748 		/* descending order by alignment requirements */
3749 		if (a->kcfg.align != b->kcfg.align)
3750 			return a->kcfg.align > b->kcfg.align ? -1 : 1;
3751 		/* ascending order by size, within same alignment class */
3752 		if (a->kcfg.sz != b->kcfg.sz)
3753 			return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
3754 	}
3755 
3756 	/* resolve ties by name */
3757 	return strcmp(a->name, b->name);
3758 }
3759 
3760 static int find_int_btf_id(const struct btf *btf)
3761 {
3762 	const struct btf_type *t;
3763 	int i, n;
3764 
3765 	n = btf__type_cnt(btf);
3766 	for (i = 1; i < n; i++) {
3767 		t = btf__type_by_id(btf, i);
3768 
3769 		if (btf_is_int(t) && btf_int_bits(t) == 32)
3770 			return i;
3771 	}
3772 
3773 	return 0;
3774 }
3775 
3776 static int add_dummy_ksym_var(struct btf *btf)
3777 {
3778 	int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
3779 	const struct btf_var_secinfo *vs;
3780 	const struct btf_type *sec;
3781 
3782 	if (!btf)
3783 		return 0;
3784 
3785 	sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
3786 					    BTF_KIND_DATASEC);
3787 	if (sec_btf_id < 0)
3788 		return 0;
3789 
3790 	sec = btf__type_by_id(btf, sec_btf_id);
3791 	vs = btf_var_secinfos(sec);
3792 	for (i = 0; i < btf_vlen(sec); i++, vs++) {
3793 		const struct btf_type *vt;
3794 
3795 		vt = btf__type_by_id(btf, vs->type);
3796 		if (btf_is_func(vt))
3797 			break;
3798 	}
3799 
3800 	/* No func in ksyms sec.  No need to add dummy var. */
3801 	if (i == btf_vlen(sec))
3802 		return 0;
3803 
3804 	int_btf_id = find_int_btf_id(btf);
3805 	dummy_var_btf_id = btf__add_var(btf,
3806 					"dummy_ksym",
3807 					BTF_VAR_GLOBAL_ALLOCATED,
3808 					int_btf_id);
3809 	if (dummy_var_btf_id < 0)
3810 		pr_warn("cannot create a dummy_ksym var\n");
3811 
3812 	return dummy_var_btf_id;
3813 }
3814 
3815 static int bpf_object__collect_externs(struct bpf_object *obj)
3816 {
3817 	struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
3818 	const struct btf_type *t;
3819 	struct extern_desc *ext;
3820 	int i, n, off, dummy_var_btf_id;
3821 	const char *ext_name, *sec_name;
3822 	Elf_Scn *scn;
3823 	Elf64_Shdr *sh;
3824 
3825 	if (!obj->efile.symbols)
3826 		return 0;
3827 
3828 	scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
3829 	sh = elf_sec_hdr(obj, scn);
3830 	if (!sh || sh->sh_entsize != sizeof(Elf64_Sym))
3831 		return -LIBBPF_ERRNO__FORMAT;
3832 
3833 	dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
3834 	if (dummy_var_btf_id < 0)
3835 		return dummy_var_btf_id;
3836 
3837 	n = sh->sh_size / sh->sh_entsize;
3838 	pr_debug("looking for externs among %d symbols...\n", n);
3839 
3840 	for (i = 0; i < n; i++) {
3841 		Elf64_Sym *sym = elf_sym_by_idx(obj, i);
3842 
3843 		if (!sym)
3844 			return -LIBBPF_ERRNO__FORMAT;
3845 		if (!sym_is_extern(sym))
3846 			continue;
3847 		ext_name = elf_sym_str(obj, sym->st_name);
3848 		if (!ext_name || !ext_name[0])
3849 			continue;
3850 
3851 		ext = obj->externs;
3852 		ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
3853 		if (!ext)
3854 			return -ENOMEM;
3855 		obj->externs = ext;
3856 		ext = &ext[obj->nr_extern];
3857 		memset(ext, 0, sizeof(*ext));
3858 		obj->nr_extern++;
3859 
3860 		ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
3861 		if (ext->btf_id <= 0) {
3862 			pr_warn("failed to find BTF for extern '%s': %d\n",
3863 				ext_name, ext->btf_id);
3864 			return ext->btf_id;
3865 		}
3866 		t = btf__type_by_id(obj->btf, ext->btf_id);
3867 		ext->name = btf__name_by_offset(obj->btf, t->name_off);
3868 		ext->sym_idx = i;
3869 		ext->is_weak = ELF64_ST_BIND(sym->st_info) == STB_WEAK;
3870 
3871 		ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
3872 		if (ext->sec_btf_id <= 0) {
3873 			pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
3874 				ext_name, ext->btf_id, ext->sec_btf_id);
3875 			return ext->sec_btf_id;
3876 		}
3877 		sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
3878 		sec_name = btf__name_by_offset(obj->btf, sec->name_off);
3879 
3880 		if (strcmp(sec_name, KCONFIG_SEC) == 0) {
3881 			if (btf_is_func(t)) {
3882 				pr_warn("extern function %s is unsupported under %s section\n",
3883 					ext->name, KCONFIG_SEC);
3884 				return -ENOTSUP;
3885 			}
3886 			kcfg_sec = sec;
3887 			ext->type = EXT_KCFG;
3888 			ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
3889 			if (ext->kcfg.sz <= 0) {
3890 				pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
3891 					ext_name, ext->kcfg.sz);
3892 				return ext->kcfg.sz;
3893 			}
3894 			ext->kcfg.align = btf__align_of(obj->btf, t->type);
3895 			if (ext->kcfg.align <= 0) {
3896 				pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
3897 					ext_name, ext->kcfg.align);
3898 				return -EINVAL;
3899 			}
3900 			ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
3901 						        &ext->kcfg.is_signed);
3902 			if (ext->kcfg.type == KCFG_UNKNOWN) {
3903 				pr_warn("extern (kcfg) '%s' type is unsupported\n", ext_name);
3904 				return -ENOTSUP;
3905 			}
3906 		} else if (strcmp(sec_name, KSYMS_SEC) == 0) {
3907 			ksym_sec = sec;
3908 			ext->type = EXT_KSYM;
3909 			skip_mods_and_typedefs(obj->btf, t->type,
3910 					       &ext->ksym.type_id);
3911 		} else {
3912 			pr_warn("unrecognized extern section '%s'\n", sec_name);
3913 			return -ENOTSUP;
3914 		}
3915 	}
3916 	pr_debug("collected %d externs total\n", obj->nr_extern);
3917 
3918 	if (!obj->nr_extern)
3919 		return 0;
3920 
3921 	/* sort externs by type, for kcfg ones also by (align, size, name) */
3922 	qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
3923 
3924 	/* for .ksyms section, we need to turn all externs into allocated
3925 	 * variables in BTF to pass kernel verification; we do this by
3926 	 * pretending that each extern is a 8-byte variable
3927 	 */
3928 	if (ksym_sec) {
3929 		/* find existing 4-byte integer type in BTF to use for fake
3930 		 * extern variables in DATASEC
3931 		 */
3932 		int int_btf_id = find_int_btf_id(obj->btf);
3933 		/* For extern function, a dummy_var added earlier
3934 		 * will be used to replace the vs->type and
3935 		 * its name string will be used to refill
3936 		 * the missing param's name.
3937 		 */
3938 		const struct btf_type *dummy_var;
3939 
3940 		dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
3941 		for (i = 0; i < obj->nr_extern; i++) {
3942 			ext = &obj->externs[i];
3943 			if (ext->type != EXT_KSYM)
3944 				continue;
3945 			pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
3946 				 i, ext->sym_idx, ext->name);
3947 		}
3948 
3949 		sec = ksym_sec;
3950 		n = btf_vlen(sec);
3951 		for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
3952 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3953 			struct btf_type *vt;
3954 
3955 			vt = (void *)btf__type_by_id(obj->btf, vs->type);
3956 			ext_name = btf__name_by_offset(obj->btf, vt->name_off);
3957 			ext = find_extern_by_name(obj, ext_name);
3958 			if (!ext) {
3959 				pr_warn("failed to find extern definition for BTF %s '%s'\n",
3960 					btf_kind_str(vt), ext_name);
3961 				return -ESRCH;
3962 			}
3963 			if (btf_is_func(vt)) {
3964 				const struct btf_type *func_proto;
3965 				struct btf_param *param;
3966 				int j;
3967 
3968 				func_proto = btf__type_by_id(obj->btf,
3969 							     vt->type);
3970 				param = btf_params(func_proto);
3971 				/* Reuse the dummy_var string if the
3972 				 * func proto does not have param name.
3973 				 */
3974 				for (j = 0; j < btf_vlen(func_proto); j++)
3975 					if (param[j].type && !param[j].name_off)
3976 						param[j].name_off =
3977 							dummy_var->name_off;
3978 				vs->type = dummy_var_btf_id;
3979 				vt->info &= ~0xffff;
3980 				vt->info |= BTF_FUNC_GLOBAL;
3981 			} else {
3982 				btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3983 				vt->type = int_btf_id;
3984 			}
3985 			vs->offset = off;
3986 			vs->size = sizeof(int);
3987 		}
3988 		sec->size = off;
3989 	}
3990 
3991 	if (kcfg_sec) {
3992 		sec = kcfg_sec;
3993 		/* for kcfg externs calculate their offsets within a .kconfig map */
3994 		off = 0;
3995 		for (i = 0; i < obj->nr_extern; i++) {
3996 			ext = &obj->externs[i];
3997 			if (ext->type != EXT_KCFG)
3998 				continue;
3999 
4000 			ext->kcfg.data_off = roundup(off, ext->kcfg.align);
4001 			off = ext->kcfg.data_off + ext->kcfg.sz;
4002 			pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
4003 				 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
4004 		}
4005 		sec->size = off;
4006 		n = btf_vlen(sec);
4007 		for (i = 0; i < n; i++) {
4008 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4009 
4010 			t = btf__type_by_id(obj->btf, vs->type);
4011 			ext_name = btf__name_by_offset(obj->btf, t->name_off);
4012 			ext = find_extern_by_name(obj, ext_name);
4013 			if (!ext) {
4014 				pr_warn("failed to find extern definition for BTF var '%s'\n",
4015 					ext_name);
4016 				return -ESRCH;
4017 			}
4018 			btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4019 			vs->offset = ext->kcfg.data_off;
4020 		}
4021 	}
4022 	return 0;
4023 }
4024 
4025 struct bpf_program *
4026 bpf_object__find_program_by_title(const struct bpf_object *obj,
4027 				  const char *title)
4028 {
4029 	struct bpf_program *pos;
4030 
4031 	bpf_object__for_each_program(pos, obj) {
4032 		if (pos->sec_name && !strcmp(pos->sec_name, title))
4033 			return pos;
4034 	}
4035 	return errno = ENOENT, NULL;
4036 }
4037 
4038 static bool prog_is_subprog(const struct bpf_object *obj,
4039 			    const struct bpf_program *prog)
4040 {
4041 	/* For legacy reasons, libbpf supports an entry-point BPF programs
4042 	 * without SEC() attribute, i.e., those in the .text section. But if
4043 	 * there are 2 or more such programs in the .text section, they all
4044 	 * must be subprograms called from entry-point BPF programs in
4045 	 * designated SEC()'tions, otherwise there is no way to distinguish
4046 	 * which of those programs should be loaded vs which are a subprogram.
4047 	 * Similarly, if there is a function/program in .text and at least one
4048 	 * other BPF program with custom SEC() attribute, then we just assume
4049 	 * .text programs are subprograms (even if they are not called from
4050 	 * other programs), because libbpf never explicitly supported mixing
4051 	 * SEC()-designated BPF programs and .text entry-point BPF programs.
4052 	 *
4053 	 * In libbpf 1.0 strict mode, we always consider .text
4054 	 * programs to be subprograms.
4055 	 */
4056 
4057 	if (libbpf_mode & LIBBPF_STRICT_SEC_NAME)
4058 		return prog->sec_idx == obj->efile.text_shndx;
4059 
4060 	return prog->sec_idx == obj->efile.text_shndx && obj->nr_programs > 1;
4061 }
4062 
4063 struct bpf_program *
4064 bpf_object__find_program_by_name(const struct bpf_object *obj,
4065 				 const char *name)
4066 {
4067 	struct bpf_program *prog;
4068 
4069 	bpf_object__for_each_program(prog, obj) {
4070 		if (prog_is_subprog(obj, prog))
4071 			continue;
4072 		if (!strcmp(prog->name, name))
4073 			return prog;
4074 	}
4075 	return errno = ENOENT, NULL;
4076 }
4077 
4078 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
4079 				      int shndx)
4080 {
4081 	switch (obj->efile.secs[shndx].sec_type) {
4082 	case SEC_BSS:
4083 	case SEC_DATA:
4084 	case SEC_RODATA:
4085 		return true;
4086 	default:
4087 		return false;
4088 	}
4089 }
4090 
4091 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
4092 				      int shndx)
4093 {
4094 	return shndx == obj->efile.maps_shndx ||
4095 	       shndx == obj->efile.btf_maps_shndx;
4096 }
4097 
4098 static enum libbpf_map_type
4099 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
4100 {
4101 	if (shndx == obj->efile.symbols_shndx)
4102 		return LIBBPF_MAP_KCONFIG;
4103 
4104 	switch (obj->efile.secs[shndx].sec_type) {
4105 	case SEC_BSS:
4106 		return LIBBPF_MAP_BSS;
4107 	case SEC_DATA:
4108 		return LIBBPF_MAP_DATA;
4109 	case SEC_RODATA:
4110 		return LIBBPF_MAP_RODATA;
4111 	default:
4112 		return LIBBPF_MAP_UNSPEC;
4113 	}
4114 }
4115 
4116 static int bpf_program__record_reloc(struct bpf_program *prog,
4117 				     struct reloc_desc *reloc_desc,
4118 				     __u32 insn_idx, const char *sym_name,
4119 				     const Elf64_Sym *sym, const Elf64_Rel *rel)
4120 {
4121 	struct bpf_insn *insn = &prog->insns[insn_idx];
4122 	size_t map_idx, nr_maps = prog->obj->nr_maps;
4123 	struct bpf_object *obj = prog->obj;
4124 	__u32 shdr_idx = sym->st_shndx;
4125 	enum libbpf_map_type type;
4126 	const char *sym_sec_name;
4127 	struct bpf_map *map;
4128 
4129 	if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
4130 		pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n",
4131 			prog->name, sym_name, insn_idx, insn->code);
4132 		return -LIBBPF_ERRNO__RELOC;
4133 	}
4134 
4135 	if (sym_is_extern(sym)) {
4136 		int sym_idx = ELF64_R_SYM(rel->r_info);
4137 		int i, n = obj->nr_extern;
4138 		struct extern_desc *ext;
4139 
4140 		for (i = 0; i < n; i++) {
4141 			ext = &obj->externs[i];
4142 			if (ext->sym_idx == sym_idx)
4143 				break;
4144 		}
4145 		if (i >= n) {
4146 			pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
4147 				prog->name, sym_name, sym_idx);
4148 			return -LIBBPF_ERRNO__RELOC;
4149 		}
4150 		pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
4151 			 prog->name, i, ext->name, ext->sym_idx, insn_idx);
4152 		if (insn->code == (BPF_JMP | BPF_CALL))
4153 			reloc_desc->type = RELO_EXTERN_FUNC;
4154 		else
4155 			reloc_desc->type = RELO_EXTERN_VAR;
4156 		reloc_desc->insn_idx = insn_idx;
4157 		reloc_desc->sym_off = i; /* sym_off stores extern index */
4158 		return 0;
4159 	}
4160 
4161 	/* sub-program call relocation */
4162 	if (is_call_insn(insn)) {
4163 		if (insn->src_reg != BPF_PSEUDO_CALL) {
4164 			pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
4165 			return -LIBBPF_ERRNO__RELOC;
4166 		}
4167 		/* text_shndx can be 0, if no default "main" program exists */
4168 		if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
4169 			sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4170 			pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
4171 				prog->name, sym_name, sym_sec_name);
4172 			return -LIBBPF_ERRNO__RELOC;
4173 		}
4174 		if (sym->st_value % BPF_INSN_SZ) {
4175 			pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
4176 				prog->name, sym_name, (size_t)sym->st_value);
4177 			return -LIBBPF_ERRNO__RELOC;
4178 		}
4179 		reloc_desc->type = RELO_CALL;
4180 		reloc_desc->insn_idx = insn_idx;
4181 		reloc_desc->sym_off = sym->st_value;
4182 		return 0;
4183 	}
4184 
4185 	if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
4186 		pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
4187 			prog->name, sym_name, shdr_idx);
4188 		return -LIBBPF_ERRNO__RELOC;
4189 	}
4190 
4191 	/* loading subprog addresses */
4192 	if (sym_is_subprog(sym, obj->efile.text_shndx)) {
4193 		/* global_func: sym->st_value = offset in the section, insn->imm = 0.
4194 		 * local_func: sym->st_value = 0, insn->imm = offset in the section.
4195 		 */
4196 		if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
4197 			pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
4198 				prog->name, sym_name, (size_t)sym->st_value, insn->imm);
4199 			return -LIBBPF_ERRNO__RELOC;
4200 		}
4201 
4202 		reloc_desc->type = RELO_SUBPROG_ADDR;
4203 		reloc_desc->insn_idx = insn_idx;
4204 		reloc_desc->sym_off = sym->st_value;
4205 		return 0;
4206 	}
4207 
4208 	type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
4209 	sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4210 
4211 	/* generic map reference relocation */
4212 	if (type == LIBBPF_MAP_UNSPEC) {
4213 		if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
4214 			pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
4215 				prog->name, sym_name, sym_sec_name);
4216 			return -LIBBPF_ERRNO__RELOC;
4217 		}
4218 		for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4219 			map = &obj->maps[map_idx];
4220 			if (map->libbpf_type != type ||
4221 			    map->sec_idx != sym->st_shndx ||
4222 			    map->sec_offset != sym->st_value)
4223 				continue;
4224 			pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n",
4225 				 prog->name, map_idx, map->name, map->sec_idx,
4226 				 map->sec_offset, insn_idx);
4227 			break;
4228 		}
4229 		if (map_idx >= nr_maps) {
4230 			pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
4231 				prog->name, sym_sec_name, (size_t)sym->st_value);
4232 			return -LIBBPF_ERRNO__RELOC;
4233 		}
4234 		reloc_desc->type = RELO_LD64;
4235 		reloc_desc->insn_idx = insn_idx;
4236 		reloc_desc->map_idx = map_idx;
4237 		reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
4238 		return 0;
4239 	}
4240 
4241 	/* global data map relocation */
4242 	if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
4243 		pr_warn("prog '%s': bad data relo against section '%s'\n",
4244 			prog->name, sym_sec_name);
4245 		return -LIBBPF_ERRNO__RELOC;
4246 	}
4247 	for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4248 		map = &obj->maps[map_idx];
4249 		if (map->libbpf_type != type || map->sec_idx != sym->st_shndx)
4250 			continue;
4251 		pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n",
4252 			 prog->name, map_idx, map->name, map->sec_idx,
4253 			 map->sec_offset, insn_idx);
4254 		break;
4255 	}
4256 	if (map_idx >= nr_maps) {
4257 		pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
4258 			prog->name, sym_sec_name);
4259 		return -LIBBPF_ERRNO__RELOC;
4260 	}
4261 
4262 	reloc_desc->type = RELO_DATA;
4263 	reloc_desc->insn_idx = insn_idx;
4264 	reloc_desc->map_idx = map_idx;
4265 	reloc_desc->sym_off = sym->st_value;
4266 	return 0;
4267 }
4268 
4269 static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
4270 {
4271 	return insn_idx >= prog->sec_insn_off &&
4272 	       insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
4273 }
4274 
4275 static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
4276 						 size_t sec_idx, size_t insn_idx)
4277 {
4278 	int l = 0, r = obj->nr_programs - 1, m;
4279 	struct bpf_program *prog;
4280 
4281 	while (l < r) {
4282 		m = l + (r - l + 1) / 2;
4283 		prog = &obj->programs[m];
4284 
4285 		if (prog->sec_idx < sec_idx ||
4286 		    (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
4287 			l = m;
4288 		else
4289 			r = m - 1;
4290 	}
4291 	/* matching program could be at index l, but it still might be the
4292 	 * wrong one, so we need to double check conditions for the last time
4293 	 */
4294 	prog = &obj->programs[l];
4295 	if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
4296 		return prog;
4297 	return NULL;
4298 }
4299 
4300 static int
4301 bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
4302 {
4303 	const char *relo_sec_name, *sec_name;
4304 	size_t sec_idx = shdr->sh_info, sym_idx;
4305 	struct bpf_program *prog;
4306 	struct reloc_desc *relos;
4307 	int err, i, nrels;
4308 	const char *sym_name;
4309 	__u32 insn_idx;
4310 	Elf_Scn *scn;
4311 	Elf_Data *scn_data;
4312 	Elf64_Sym *sym;
4313 	Elf64_Rel *rel;
4314 
4315 	if (sec_idx >= obj->efile.sec_cnt)
4316 		return -EINVAL;
4317 
4318 	scn = elf_sec_by_idx(obj, sec_idx);
4319 	scn_data = elf_sec_data(obj, scn);
4320 
4321 	relo_sec_name = elf_sec_str(obj, shdr->sh_name);
4322 	sec_name = elf_sec_name(obj, scn);
4323 	if (!relo_sec_name || !sec_name)
4324 		return -EINVAL;
4325 
4326 	pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
4327 		 relo_sec_name, sec_idx, sec_name);
4328 	nrels = shdr->sh_size / shdr->sh_entsize;
4329 
4330 	for (i = 0; i < nrels; i++) {
4331 		rel = elf_rel_by_idx(data, i);
4332 		if (!rel) {
4333 			pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
4334 			return -LIBBPF_ERRNO__FORMAT;
4335 		}
4336 
4337 		sym_idx = ELF64_R_SYM(rel->r_info);
4338 		sym = elf_sym_by_idx(obj, sym_idx);
4339 		if (!sym) {
4340 			pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
4341 				relo_sec_name, sym_idx, i);
4342 			return -LIBBPF_ERRNO__FORMAT;
4343 		}
4344 
4345 		if (sym->st_shndx >= obj->efile.sec_cnt) {
4346 			pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
4347 				relo_sec_name, sym_idx, (size_t)sym->st_shndx, i);
4348 			return -LIBBPF_ERRNO__FORMAT;
4349 		}
4350 
4351 		if (rel->r_offset % BPF_INSN_SZ || rel->r_offset >= scn_data->d_size) {
4352 			pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
4353 				relo_sec_name, (size_t)rel->r_offset, i);
4354 			return -LIBBPF_ERRNO__FORMAT;
4355 		}
4356 
4357 		insn_idx = rel->r_offset / BPF_INSN_SZ;
4358 		/* relocations against static functions are recorded as
4359 		 * relocations against the section that contains a function;
4360 		 * in such case, symbol will be STT_SECTION and sym.st_name
4361 		 * will point to empty string (0), so fetch section name
4362 		 * instead
4363 		 */
4364 		if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
4365 			sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx));
4366 		else
4367 			sym_name = elf_sym_str(obj, sym->st_name);
4368 		sym_name = sym_name ?: "<?";
4369 
4370 		pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
4371 			 relo_sec_name, i, insn_idx, sym_name);
4372 
4373 		prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
4374 		if (!prog) {
4375 			pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
4376 				relo_sec_name, i, sec_name, insn_idx);
4377 			continue;
4378 		}
4379 
4380 		relos = libbpf_reallocarray(prog->reloc_desc,
4381 					    prog->nr_reloc + 1, sizeof(*relos));
4382 		if (!relos)
4383 			return -ENOMEM;
4384 		prog->reloc_desc = relos;
4385 
4386 		/* adjust insn_idx to local BPF program frame of reference */
4387 		insn_idx -= prog->sec_insn_off;
4388 		err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
4389 						insn_idx, sym_name, sym, rel);
4390 		if (err)
4391 			return err;
4392 
4393 		prog->nr_reloc++;
4394 	}
4395 	return 0;
4396 }
4397 
4398 static int bpf_map_find_btf_info(struct bpf_object *obj, struct bpf_map *map)
4399 {
4400 	struct bpf_map_def *def = &map->def;
4401 	__u32 key_type_id = 0, value_type_id = 0;
4402 	int ret;
4403 
4404 	if (!obj->btf)
4405 		return -ENOENT;
4406 
4407 	/* if it's BTF-defined map, we don't need to search for type IDs.
4408 	 * For struct_ops map, it does not need btf_key_type_id and
4409 	 * btf_value_type_id.
4410 	 */
4411 	if (map->sec_idx == obj->efile.btf_maps_shndx ||
4412 	    bpf_map__is_struct_ops(map))
4413 		return 0;
4414 
4415 	if (!bpf_map__is_internal(map)) {
4416 		pr_warn("Use of BPF_ANNOTATE_KV_PAIR is deprecated, use BTF-defined maps in .maps section instead\n");
4417 #pragma GCC diagnostic push
4418 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
4419 		ret = btf__get_map_kv_tids(obj->btf, map->name, def->key_size,
4420 					   def->value_size, &key_type_id,
4421 					   &value_type_id);
4422 #pragma GCC diagnostic pop
4423 	} else {
4424 		/*
4425 		 * LLVM annotates global data differently in BTF, that is,
4426 		 * only as '.data', '.bss' or '.rodata'.
4427 		 */
4428 		ret = btf__find_by_name(obj->btf, map->real_name);
4429 	}
4430 	if (ret < 0)
4431 		return ret;
4432 
4433 	map->btf_key_type_id = key_type_id;
4434 	map->btf_value_type_id = bpf_map__is_internal(map) ?
4435 				 ret : value_type_id;
4436 	return 0;
4437 }
4438 
4439 static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
4440 {
4441 	char file[PATH_MAX], buff[4096];
4442 	FILE *fp;
4443 	__u32 val;
4444 	int err;
4445 
4446 	snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
4447 	memset(info, 0, sizeof(*info));
4448 
4449 	fp = fopen(file, "r");
4450 	if (!fp) {
4451 		err = -errno;
4452 		pr_warn("failed to open %s: %d. No procfs support?\n", file,
4453 			err);
4454 		return err;
4455 	}
4456 
4457 	while (fgets(buff, sizeof(buff), fp)) {
4458 		if (sscanf(buff, "map_type:\t%u", &val) == 1)
4459 			info->type = val;
4460 		else if (sscanf(buff, "key_size:\t%u", &val) == 1)
4461 			info->key_size = val;
4462 		else if (sscanf(buff, "value_size:\t%u", &val) == 1)
4463 			info->value_size = val;
4464 		else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
4465 			info->max_entries = val;
4466 		else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
4467 			info->map_flags = val;
4468 	}
4469 
4470 	fclose(fp);
4471 
4472 	return 0;
4473 }
4474 
4475 bool bpf_map__autocreate(const struct bpf_map *map)
4476 {
4477 	return map->autocreate;
4478 }
4479 
4480 int bpf_map__set_autocreate(struct bpf_map *map, bool autocreate)
4481 {
4482 	if (map->obj->loaded)
4483 		return libbpf_err(-EBUSY);
4484 
4485 	map->autocreate = autocreate;
4486 	return 0;
4487 }
4488 
4489 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
4490 {
4491 	struct bpf_map_info info = {};
4492 	__u32 len = sizeof(info);
4493 	int new_fd, err;
4494 	char *new_name;
4495 
4496 	err = bpf_obj_get_info_by_fd(fd, &info, &len);
4497 	if (err && errno == EINVAL)
4498 		err = bpf_get_map_info_from_fdinfo(fd, &info);
4499 	if (err)
4500 		return libbpf_err(err);
4501 
4502 	new_name = strdup(info.name);
4503 	if (!new_name)
4504 		return libbpf_err(-errno);
4505 
4506 	new_fd = open("/", O_RDONLY | O_CLOEXEC);
4507 	if (new_fd < 0) {
4508 		err = -errno;
4509 		goto err_free_new_name;
4510 	}
4511 
4512 	new_fd = dup3(fd, new_fd, O_CLOEXEC);
4513 	if (new_fd < 0) {
4514 		err = -errno;
4515 		goto err_close_new_fd;
4516 	}
4517 
4518 	err = zclose(map->fd);
4519 	if (err) {
4520 		err = -errno;
4521 		goto err_close_new_fd;
4522 	}
4523 	free(map->name);
4524 
4525 	map->fd = new_fd;
4526 	map->name = new_name;
4527 	map->def.type = info.type;
4528 	map->def.key_size = info.key_size;
4529 	map->def.value_size = info.value_size;
4530 	map->def.max_entries = info.max_entries;
4531 	map->def.map_flags = info.map_flags;
4532 	map->btf_key_type_id = info.btf_key_type_id;
4533 	map->btf_value_type_id = info.btf_value_type_id;
4534 	map->reused = true;
4535 	map->map_extra = info.map_extra;
4536 
4537 	return 0;
4538 
4539 err_close_new_fd:
4540 	close(new_fd);
4541 err_free_new_name:
4542 	free(new_name);
4543 	return libbpf_err(err);
4544 }
4545 
4546 __u32 bpf_map__max_entries(const struct bpf_map *map)
4547 {
4548 	return map->def.max_entries;
4549 }
4550 
4551 struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
4552 {
4553 	if (!bpf_map_type__is_map_in_map(map->def.type))
4554 		return errno = EINVAL, NULL;
4555 
4556 	return map->inner_map;
4557 }
4558 
4559 int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
4560 {
4561 	if (map->fd >= 0)
4562 		return libbpf_err(-EBUSY);
4563 	map->def.max_entries = max_entries;
4564 	return 0;
4565 }
4566 
4567 int bpf_map__resize(struct bpf_map *map, __u32 max_entries)
4568 {
4569 	if (!map || !max_entries)
4570 		return libbpf_err(-EINVAL);
4571 
4572 	return bpf_map__set_max_entries(map, max_entries);
4573 }
4574 
4575 static int
4576 bpf_object__probe_loading(struct bpf_object *obj)
4577 {
4578 	char *cp, errmsg[STRERR_BUFSIZE];
4579 	struct bpf_insn insns[] = {
4580 		BPF_MOV64_IMM(BPF_REG_0, 0),
4581 		BPF_EXIT_INSN(),
4582 	};
4583 	int ret, insn_cnt = ARRAY_SIZE(insns);
4584 
4585 	if (obj->gen_loader)
4586 		return 0;
4587 
4588 	ret = bump_rlimit_memlock();
4589 	if (ret)
4590 		pr_warn("Failed to bump RLIMIT_MEMLOCK (err = %d), you might need to do it explicitly!\n", ret);
4591 
4592 	/* make sure basic loading works */
4593 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4594 	if (ret < 0)
4595 		ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
4596 	if (ret < 0) {
4597 		ret = errno;
4598 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4599 		pr_warn("Error in %s():%s(%d). Couldn't load trivial BPF "
4600 			"program. Make sure your kernel supports BPF "
4601 			"(CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is "
4602 			"set to big enough value.\n", __func__, cp, ret);
4603 		return -ret;
4604 	}
4605 	close(ret);
4606 
4607 	return 0;
4608 }
4609 
4610 static int probe_fd(int fd)
4611 {
4612 	if (fd >= 0)
4613 		close(fd);
4614 	return fd >= 0;
4615 }
4616 
4617 static int probe_kern_prog_name(void)
4618 {
4619 	struct bpf_insn insns[] = {
4620 		BPF_MOV64_IMM(BPF_REG_0, 0),
4621 		BPF_EXIT_INSN(),
4622 	};
4623 	int ret, insn_cnt = ARRAY_SIZE(insns);
4624 
4625 	/* make sure loading with name works */
4626 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, "test", "GPL", insns, insn_cnt, NULL);
4627 	return probe_fd(ret);
4628 }
4629 
4630 static int probe_kern_global_data(void)
4631 {
4632 	char *cp, errmsg[STRERR_BUFSIZE];
4633 	struct bpf_insn insns[] = {
4634 		BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
4635 		BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
4636 		BPF_MOV64_IMM(BPF_REG_0, 0),
4637 		BPF_EXIT_INSN(),
4638 	};
4639 	int ret, map, insn_cnt = ARRAY_SIZE(insns);
4640 
4641 	map = bpf_map_create(BPF_MAP_TYPE_ARRAY, NULL, sizeof(int), 32, 1, NULL);
4642 	if (map < 0) {
4643 		ret = -errno;
4644 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4645 		pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4646 			__func__, cp, -ret);
4647 		return ret;
4648 	}
4649 
4650 	insns[0].imm = map;
4651 
4652 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4653 	close(map);
4654 	return probe_fd(ret);
4655 }
4656 
4657 static int probe_kern_btf(void)
4658 {
4659 	static const char strs[] = "\0int";
4660 	__u32 types[] = {
4661 		/* int */
4662 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4663 	};
4664 
4665 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4666 					     strs, sizeof(strs)));
4667 }
4668 
4669 static int probe_kern_btf_func(void)
4670 {
4671 	static const char strs[] = "\0int\0x\0a";
4672 	/* void x(int a) {} */
4673 	__u32 types[] = {
4674 		/* int */
4675 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4676 		/* FUNC_PROTO */                                /* [2] */
4677 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4678 		BTF_PARAM_ENC(7, 1),
4679 		/* FUNC x */                                    /* [3] */
4680 		BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
4681 	};
4682 
4683 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4684 					     strs, sizeof(strs)));
4685 }
4686 
4687 static int probe_kern_btf_func_global(void)
4688 {
4689 	static const char strs[] = "\0int\0x\0a";
4690 	/* static void x(int a) {} */
4691 	__u32 types[] = {
4692 		/* int */
4693 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4694 		/* FUNC_PROTO */                                /* [2] */
4695 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4696 		BTF_PARAM_ENC(7, 1),
4697 		/* FUNC x BTF_FUNC_GLOBAL */                    /* [3] */
4698 		BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, BTF_FUNC_GLOBAL), 2),
4699 	};
4700 
4701 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4702 					     strs, sizeof(strs)));
4703 }
4704 
4705 static int probe_kern_btf_datasec(void)
4706 {
4707 	static const char strs[] = "\0x\0.data";
4708 	/* static int a; */
4709 	__u32 types[] = {
4710 		/* int */
4711 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4712 		/* VAR x */                                     /* [2] */
4713 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4714 		BTF_VAR_STATIC,
4715 		/* DATASEC val */                               /* [3] */
4716 		BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
4717 		BTF_VAR_SECINFO_ENC(2, 0, 4),
4718 	};
4719 
4720 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4721 					     strs, sizeof(strs)));
4722 }
4723 
4724 static int probe_kern_btf_float(void)
4725 {
4726 	static const char strs[] = "\0float";
4727 	__u32 types[] = {
4728 		/* float */
4729 		BTF_TYPE_FLOAT_ENC(1, 4),
4730 	};
4731 
4732 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4733 					     strs, sizeof(strs)));
4734 }
4735 
4736 static int probe_kern_btf_decl_tag(void)
4737 {
4738 	static const char strs[] = "\0tag";
4739 	__u32 types[] = {
4740 		/* int */
4741 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4742 		/* VAR x */                                     /* [2] */
4743 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4744 		BTF_VAR_STATIC,
4745 		/* attr */
4746 		BTF_TYPE_DECL_TAG_ENC(1, 2, -1),
4747 	};
4748 
4749 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4750 					     strs, sizeof(strs)));
4751 }
4752 
4753 static int probe_kern_btf_type_tag(void)
4754 {
4755 	static const char strs[] = "\0tag";
4756 	__u32 types[] = {
4757 		/* int */
4758 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),		/* [1] */
4759 		/* attr */
4760 		BTF_TYPE_TYPE_TAG_ENC(1, 1),				/* [2] */
4761 		/* ptr */
4762 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_PTR, 0, 0), 2),	/* [3] */
4763 	};
4764 
4765 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4766 					     strs, sizeof(strs)));
4767 }
4768 
4769 static int probe_kern_array_mmap(void)
4770 {
4771 	LIBBPF_OPTS(bpf_map_create_opts, opts, .map_flags = BPF_F_MMAPABLE);
4772 	int fd;
4773 
4774 	fd = bpf_map_create(BPF_MAP_TYPE_ARRAY, NULL, sizeof(int), sizeof(int), 1, &opts);
4775 	return probe_fd(fd);
4776 }
4777 
4778 static int probe_kern_exp_attach_type(void)
4779 {
4780 	LIBBPF_OPTS(bpf_prog_load_opts, opts, .expected_attach_type = BPF_CGROUP_INET_SOCK_CREATE);
4781 	struct bpf_insn insns[] = {
4782 		BPF_MOV64_IMM(BPF_REG_0, 0),
4783 		BPF_EXIT_INSN(),
4784 	};
4785 	int fd, insn_cnt = ARRAY_SIZE(insns);
4786 
4787 	/* use any valid combination of program type and (optional)
4788 	 * non-zero expected attach type (i.e., not a BPF_CGROUP_INET_INGRESS)
4789 	 * to see if kernel supports expected_attach_type field for
4790 	 * BPF_PROG_LOAD command
4791 	 */
4792 	fd = bpf_prog_load(BPF_PROG_TYPE_CGROUP_SOCK, NULL, "GPL", insns, insn_cnt, &opts);
4793 	return probe_fd(fd);
4794 }
4795 
4796 static int probe_kern_probe_read_kernel(void)
4797 {
4798 	struct bpf_insn insns[] = {
4799 		BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),	/* r1 = r10 (fp) */
4800 		BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -8),	/* r1 += -8 */
4801 		BPF_MOV64_IMM(BPF_REG_2, 8),		/* r2 = 8 */
4802 		BPF_MOV64_IMM(BPF_REG_3, 0),		/* r3 = 0 */
4803 		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_probe_read_kernel),
4804 		BPF_EXIT_INSN(),
4805 	};
4806 	int fd, insn_cnt = ARRAY_SIZE(insns);
4807 
4808 	fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
4809 	return probe_fd(fd);
4810 }
4811 
4812 static int probe_prog_bind_map(void)
4813 {
4814 	char *cp, errmsg[STRERR_BUFSIZE];
4815 	struct bpf_insn insns[] = {
4816 		BPF_MOV64_IMM(BPF_REG_0, 0),
4817 		BPF_EXIT_INSN(),
4818 	};
4819 	int ret, map, prog, insn_cnt = ARRAY_SIZE(insns);
4820 
4821 	map = bpf_map_create(BPF_MAP_TYPE_ARRAY, NULL, sizeof(int), 32, 1, NULL);
4822 	if (map < 0) {
4823 		ret = -errno;
4824 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4825 		pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4826 			__func__, cp, -ret);
4827 		return ret;
4828 	}
4829 
4830 	prog = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4831 	if (prog < 0) {
4832 		close(map);
4833 		return 0;
4834 	}
4835 
4836 	ret = bpf_prog_bind_map(prog, map, NULL);
4837 
4838 	close(map);
4839 	close(prog);
4840 
4841 	return ret >= 0;
4842 }
4843 
4844 static int probe_module_btf(void)
4845 {
4846 	static const char strs[] = "\0int";
4847 	__u32 types[] = {
4848 		/* int */
4849 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4850 	};
4851 	struct bpf_btf_info info;
4852 	__u32 len = sizeof(info);
4853 	char name[16];
4854 	int fd, err;
4855 
4856 	fd = libbpf__load_raw_btf((char *)types, sizeof(types), strs, sizeof(strs));
4857 	if (fd < 0)
4858 		return 0; /* BTF not supported at all */
4859 
4860 	memset(&info, 0, sizeof(info));
4861 	info.name = ptr_to_u64(name);
4862 	info.name_len = sizeof(name);
4863 
4864 	/* check that BPF_OBJ_GET_INFO_BY_FD supports specifying name pointer;
4865 	 * kernel's module BTF support coincides with support for
4866 	 * name/name_len fields in struct bpf_btf_info.
4867 	 */
4868 	err = bpf_obj_get_info_by_fd(fd, &info, &len);
4869 	close(fd);
4870 	return !err;
4871 }
4872 
4873 static int probe_perf_link(void)
4874 {
4875 	struct bpf_insn insns[] = {
4876 		BPF_MOV64_IMM(BPF_REG_0, 0),
4877 		BPF_EXIT_INSN(),
4878 	};
4879 	int prog_fd, link_fd, err;
4880 
4881 	prog_fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL",
4882 				insns, ARRAY_SIZE(insns), NULL);
4883 	if (prog_fd < 0)
4884 		return -errno;
4885 
4886 	/* use invalid perf_event FD to get EBADF, if link is supported;
4887 	 * otherwise EINVAL should be returned
4888 	 */
4889 	link_fd = bpf_link_create(prog_fd, -1, BPF_PERF_EVENT, NULL);
4890 	err = -errno; /* close() can clobber errno */
4891 
4892 	if (link_fd >= 0)
4893 		close(link_fd);
4894 	close(prog_fd);
4895 
4896 	return link_fd < 0 && err == -EBADF;
4897 }
4898 
4899 static int probe_kern_bpf_cookie(void)
4900 {
4901 	struct bpf_insn insns[] = {
4902 		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_get_attach_cookie),
4903 		BPF_EXIT_INSN(),
4904 	};
4905 	int ret, insn_cnt = ARRAY_SIZE(insns);
4906 
4907 	ret = bpf_prog_load(BPF_PROG_TYPE_KPROBE, NULL, "GPL", insns, insn_cnt, NULL);
4908 	return probe_fd(ret);
4909 }
4910 
4911 static int probe_kern_btf_enum64(void)
4912 {
4913 	static const char strs[] = "\0enum64";
4914 	__u32 types[] = {
4915 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_ENUM64, 0, 0), 8),
4916 	};
4917 
4918 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4919 					     strs, sizeof(strs)));
4920 }
4921 
4922 enum kern_feature_result {
4923 	FEAT_UNKNOWN = 0,
4924 	FEAT_SUPPORTED = 1,
4925 	FEAT_MISSING = 2,
4926 };
4927 
4928 typedef int (*feature_probe_fn)(void);
4929 
4930 static struct kern_feature_desc {
4931 	const char *desc;
4932 	feature_probe_fn probe;
4933 	enum kern_feature_result res;
4934 } feature_probes[__FEAT_CNT] = {
4935 	[FEAT_PROG_NAME] = {
4936 		"BPF program name", probe_kern_prog_name,
4937 	},
4938 	[FEAT_GLOBAL_DATA] = {
4939 		"global variables", probe_kern_global_data,
4940 	},
4941 	[FEAT_BTF] = {
4942 		"minimal BTF", probe_kern_btf,
4943 	},
4944 	[FEAT_BTF_FUNC] = {
4945 		"BTF functions", probe_kern_btf_func,
4946 	},
4947 	[FEAT_BTF_GLOBAL_FUNC] = {
4948 		"BTF global function", probe_kern_btf_func_global,
4949 	},
4950 	[FEAT_BTF_DATASEC] = {
4951 		"BTF data section and variable", probe_kern_btf_datasec,
4952 	},
4953 	[FEAT_ARRAY_MMAP] = {
4954 		"ARRAY map mmap()", probe_kern_array_mmap,
4955 	},
4956 	[FEAT_EXP_ATTACH_TYPE] = {
4957 		"BPF_PROG_LOAD expected_attach_type attribute",
4958 		probe_kern_exp_attach_type,
4959 	},
4960 	[FEAT_PROBE_READ_KERN] = {
4961 		"bpf_probe_read_kernel() helper", probe_kern_probe_read_kernel,
4962 	},
4963 	[FEAT_PROG_BIND_MAP] = {
4964 		"BPF_PROG_BIND_MAP support", probe_prog_bind_map,
4965 	},
4966 	[FEAT_MODULE_BTF] = {
4967 		"module BTF support", probe_module_btf,
4968 	},
4969 	[FEAT_BTF_FLOAT] = {
4970 		"BTF_KIND_FLOAT support", probe_kern_btf_float,
4971 	},
4972 	[FEAT_PERF_LINK] = {
4973 		"BPF perf link support", probe_perf_link,
4974 	},
4975 	[FEAT_BTF_DECL_TAG] = {
4976 		"BTF_KIND_DECL_TAG support", probe_kern_btf_decl_tag,
4977 	},
4978 	[FEAT_BTF_TYPE_TAG] = {
4979 		"BTF_KIND_TYPE_TAG support", probe_kern_btf_type_tag,
4980 	},
4981 	[FEAT_MEMCG_ACCOUNT] = {
4982 		"memcg-based memory accounting", probe_memcg_account,
4983 	},
4984 	[FEAT_BPF_COOKIE] = {
4985 		"BPF cookie support", probe_kern_bpf_cookie,
4986 	},
4987 	[FEAT_BTF_ENUM64] = {
4988 		"BTF_KIND_ENUM64 support", probe_kern_btf_enum64,
4989 	},
4990 };
4991 
4992 bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
4993 {
4994 	struct kern_feature_desc *feat = &feature_probes[feat_id];
4995 	int ret;
4996 
4997 	if (obj && obj->gen_loader)
4998 		/* To generate loader program assume the latest kernel
4999 		 * to avoid doing extra prog_load, map_create syscalls.
5000 		 */
5001 		return true;
5002 
5003 	if (READ_ONCE(feat->res) == FEAT_UNKNOWN) {
5004 		ret = feat->probe();
5005 		if (ret > 0) {
5006 			WRITE_ONCE(feat->res, FEAT_SUPPORTED);
5007 		} else if (ret == 0) {
5008 			WRITE_ONCE(feat->res, FEAT_MISSING);
5009 		} else {
5010 			pr_warn("Detection of kernel %s support failed: %d\n", feat->desc, ret);
5011 			WRITE_ONCE(feat->res, FEAT_MISSING);
5012 		}
5013 	}
5014 
5015 	return READ_ONCE(feat->res) == FEAT_SUPPORTED;
5016 }
5017 
5018 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
5019 {
5020 	struct bpf_map_info map_info = {};
5021 	char msg[STRERR_BUFSIZE];
5022 	__u32 map_info_len;
5023 	int err;
5024 
5025 	map_info_len = sizeof(map_info);
5026 
5027 	err = bpf_obj_get_info_by_fd(map_fd, &map_info, &map_info_len);
5028 	if (err && errno == EINVAL)
5029 		err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
5030 	if (err) {
5031 		pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
5032 			libbpf_strerror_r(errno, msg, sizeof(msg)));
5033 		return false;
5034 	}
5035 
5036 	return (map_info.type == map->def.type &&
5037 		map_info.key_size == map->def.key_size &&
5038 		map_info.value_size == map->def.value_size &&
5039 		map_info.max_entries == map->def.max_entries &&
5040 		map_info.map_flags == map->def.map_flags &&
5041 		map_info.map_extra == map->map_extra);
5042 }
5043 
5044 static int
5045 bpf_object__reuse_map(struct bpf_map *map)
5046 {
5047 	char *cp, errmsg[STRERR_BUFSIZE];
5048 	int err, pin_fd;
5049 
5050 	pin_fd = bpf_obj_get(map->pin_path);
5051 	if (pin_fd < 0) {
5052 		err = -errno;
5053 		if (err == -ENOENT) {
5054 			pr_debug("found no pinned map to reuse at '%s'\n",
5055 				 map->pin_path);
5056 			return 0;
5057 		}
5058 
5059 		cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
5060 		pr_warn("couldn't retrieve pinned map '%s': %s\n",
5061 			map->pin_path, cp);
5062 		return err;
5063 	}
5064 
5065 	if (!map_is_reuse_compat(map, pin_fd)) {
5066 		pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
5067 			map->pin_path);
5068 		close(pin_fd);
5069 		return -EINVAL;
5070 	}
5071 
5072 	err = bpf_map__reuse_fd(map, pin_fd);
5073 	close(pin_fd);
5074 	if (err) {
5075 		return err;
5076 	}
5077 	map->pinned = true;
5078 	pr_debug("reused pinned map at '%s'\n", map->pin_path);
5079 
5080 	return 0;
5081 }
5082 
5083 static int
5084 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
5085 {
5086 	enum libbpf_map_type map_type = map->libbpf_type;
5087 	char *cp, errmsg[STRERR_BUFSIZE];
5088 	int err, zero = 0;
5089 
5090 	if (obj->gen_loader) {
5091 		bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
5092 					 map->mmaped, map->def.value_size);
5093 		if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
5094 			bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
5095 		return 0;
5096 	}
5097 	err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
5098 	if (err) {
5099 		err = -errno;
5100 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5101 		pr_warn("Error setting initial map(%s) contents: %s\n",
5102 			map->name, cp);
5103 		return err;
5104 	}
5105 
5106 	/* Freeze .rodata and .kconfig map as read-only from syscall side. */
5107 	if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
5108 		err = bpf_map_freeze(map->fd);
5109 		if (err) {
5110 			err = -errno;
5111 			cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5112 			pr_warn("Error freezing map(%s) as read-only: %s\n",
5113 				map->name, cp);
5114 			return err;
5115 		}
5116 	}
5117 	return 0;
5118 }
5119 
5120 static void bpf_map__destroy(struct bpf_map *map);
5121 
5122 static size_t adjust_ringbuf_sz(size_t sz)
5123 {
5124 	__u32 page_sz = sysconf(_SC_PAGE_SIZE);
5125 	__u32 mul;
5126 
5127 	/* if user forgot to set any size, make sure they see error */
5128 	if (sz == 0)
5129 		return 0;
5130 	/* Kernel expects BPF_MAP_TYPE_RINGBUF's max_entries to be
5131 	 * a power-of-2 multiple of kernel's page size. If user diligently
5132 	 * satisified these conditions, pass the size through.
5133 	 */
5134 	if ((sz % page_sz) == 0 && is_pow_of_2(sz / page_sz))
5135 		return sz;
5136 
5137 	/* Otherwise find closest (page_sz * power_of_2) product bigger than
5138 	 * user-set size to satisfy both user size request and kernel
5139 	 * requirements and substitute correct max_entries for map creation.
5140 	 */
5141 	for (mul = 1; mul <= UINT_MAX / page_sz; mul <<= 1) {
5142 		if (mul * page_sz > sz)
5143 			return mul * page_sz;
5144 	}
5145 
5146 	/* if it's impossible to satisfy the conditions (i.e., user size is
5147 	 * very close to UINT_MAX but is not a power-of-2 multiple of
5148 	 * page_size) then just return original size and let kernel reject it
5149 	 */
5150 	return sz;
5151 }
5152 
5153 static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
5154 {
5155 	LIBBPF_OPTS(bpf_map_create_opts, create_attr);
5156 	struct bpf_map_def *def = &map->def;
5157 	const char *map_name = NULL;
5158 	int err = 0;
5159 
5160 	if (kernel_supports(obj, FEAT_PROG_NAME))
5161 		map_name = map->name;
5162 	create_attr.map_ifindex = map->map_ifindex;
5163 	create_attr.map_flags = def->map_flags;
5164 	create_attr.numa_node = map->numa_node;
5165 	create_attr.map_extra = map->map_extra;
5166 
5167 	if (bpf_map__is_struct_ops(map))
5168 		create_attr.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
5169 
5170 	if (obj->btf && btf__fd(obj->btf) >= 0) {
5171 		create_attr.btf_fd = btf__fd(obj->btf);
5172 		create_attr.btf_key_type_id = map->btf_key_type_id;
5173 		create_attr.btf_value_type_id = map->btf_value_type_id;
5174 	}
5175 
5176 	if (bpf_map_type__is_map_in_map(def->type)) {
5177 		if (map->inner_map) {
5178 			err = bpf_object__create_map(obj, map->inner_map, true);
5179 			if (err) {
5180 				pr_warn("map '%s': failed to create inner map: %d\n",
5181 					map->name, err);
5182 				return err;
5183 			}
5184 			map->inner_map_fd = bpf_map__fd(map->inner_map);
5185 		}
5186 		if (map->inner_map_fd >= 0)
5187 			create_attr.inner_map_fd = map->inner_map_fd;
5188 	}
5189 
5190 	switch (def->type) {
5191 	case BPF_MAP_TYPE_RINGBUF:
5192 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
5193 		/* fallthrough */
5194 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5195 	case BPF_MAP_TYPE_CGROUP_ARRAY:
5196 	case BPF_MAP_TYPE_STACK_TRACE:
5197 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5198 	case BPF_MAP_TYPE_HASH_OF_MAPS:
5199 	case BPF_MAP_TYPE_DEVMAP:
5200 	case BPF_MAP_TYPE_DEVMAP_HASH:
5201 	case BPF_MAP_TYPE_CPUMAP:
5202 	case BPF_MAP_TYPE_XSKMAP:
5203 	case BPF_MAP_TYPE_SOCKMAP:
5204 	case BPF_MAP_TYPE_SOCKHASH:
5205 	case BPF_MAP_TYPE_QUEUE:
5206 	case BPF_MAP_TYPE_STACK:
5207 		create_attr.btf_fd = 0;
5208 		create_attr.btf_key_type_id = 0;
5209 		create_attr.btf_value_type_id = 0;
5210 		map->btf_key_type_id = 0;
5211 		map->btf_value_type_id = 0;
5212 	default:
5213 		break;
5214 	}
5215 
5216 	if (obj->gen_loader) {
5217 		bpf_gen__map_create(obj->gen_loader, def->type, map_name,
5218 				    def->key_size, def->value_size, def->max_entries,
5219 				    &create_attr, is_inner ? -1 : map - obj->maps);
5220 		/* Pretend to have valid FD to pass various fd >= 0 checks.
5221 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
5222 		 */
5223 		map->fd = 0;
5224 	} else {
5225 		map->fd = bpf_map_create(def->type, map_name,
5226 					 def->key_size, def->value_size,
5227 					 def->max_entries, &create_attr);
5228 	}
5229 	if (map->fd < 0 && (create_attr.btf_key_type_id ||
5230 			    create_attr.btf_value_type_id)) {
5231 		char *cp, errmsg[STRERR_BUFSIZE];
5232 
5233 		err = -errno;
5234 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5235 		pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
5236 			map->name, cp, err);
5237 		create_attr.btf_fd = 0;
5238 		create_attr.btf_key_type_id = 0;
5239 		create_attr.btf_value_type_id = 0;
5240 		map->btf_key_type_id = 0;
5241 		map->btf_value_type_id = 0;
5242 		map->fd = bpf_map_create(def->type, map_name,
5243 					 def->key_size, def->value_size,
5244 					 def->max_entries, &create_attr);
5245 	}
5246 
5247 	err = map->fd < 0 ? -errno : 0;
5248 
5249 	if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
5250 		if (obj->gen_loader)
5251 			map->inner_map->fd = -1;
5252 		bpf_map__destroy(map->inner_map);
5253 		zfree(&map->inner_map);
5254 	}
5255 
5256 	return err;
5257 }
5258 
5259 static int init_map_in_map_slots(struct bpf_object *obj, struct bpf_map *map)
5260 {
5261 	const struct bpf_map *targ_map;
5262 	unsigned int i;
5263 	int fd, err = 0;
5264 
5265 	for (i = 0; i < map->init_slots_sz; i++) {
5266 		if (!map->init_slots[i])
5267 			continue;
5268 
5269 		targ_map = map->init_slots[i];
5270 		fd = bpf_map__fd(targ_map);
5271 
5272 		if (obj->gen_loader) {
5273 			bpf_gen__populate_outer_map(obj->gen_loader,
5274 						    map - obj->maps, i,
5275 						    targ_map - obj->maps);
5276 		} else {
5277 			err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5278 		}
5279 		if (err) {
5280 			err = -errno;
5281 			pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %d\n",
5282 				map->name, i, targ_map->name, fd, err);
5283 			return err;
5284 		}
5285 		pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
5286 			 map->name, i, targ_map->name, fd);
5287 	}
5288 
5289 	zfree(&map->init_slots);
5290 	map->init_slots_sz = 0;
5291 
5292 	return 0;
5293 }
5294 
5295 static int init_prog_array_slots(struct bpf_object *obj, struct bpf_map *map)
5296 {
5297 	const struct bpf_program *targ_prog;
5298 	unsigned int i;
5299 	int fd, err;
5300 
5301 	if (obj->gen_loader)
5302 		return -ENOTSUP;
5303 
5304 	for (i = 0; i < map->init_slots_sz; i++) {
5305 		if (!map->init_slots[i])
5306 			continue;
5307 
5308 		targ_prog = map->init_slots[i];
5309 		fd = bpf_program__fd(targ_prog);
5310 
5311 		err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5312 		if (err) {
5313 			err = -errno;
5314 			pr_warn("map '%s': failed to initialize slot [%d] to prog '%s' fd=%d: %d\n",
5315 				map->name, i, targ_prog->name, fd, err);
5316 			return err;
5317 		}
5318 		pr_debug("map '%s': slot [%d] set to prog '%s' fd=%d\n",
5319 			 map->name, i, targ_prog->name, fd);
5320 	}
5321 
5322 	zfree(&map->init_slots);
5323 	map->init_slots_sz = 0;
5324 
5325 	return 0;
5326 }
5327 
5328 static int bpf_object_init_prog_arrays(struct bpf_object *obj)
5329 {
5330 	struct bpf_map *map;
5331 	int i, err;
5332 
5333 	for (i = 0; i < obj->nr_maps; i++) {
5334 		map = &obj->maps[i];
5335 
5336 		if (!map->init_slots_sz || map->def.type != BPF_MAP_TYPE_PROG_ARRAY)
5337 			continue;
5338 
5339 		err = init_prog_array_slots(obj, map);
5340 		if (err < 0) {
5341 			zclose(map->fd);
5342 			return err;
5343 		}
5344 	}
5345 	return 0;
5346 }
5347 
5348 static int map_set_def_max_entries(struct bpf_map *map)
5349 {
5350 	if (map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !map->def.max_entries) {
5351 		int nr_cpus;
5352 
5353 		nr_cpus = libbpf_num_possible_cpus();
5354 		if (nr_cpus < 0) {
5355 			pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
5356 				map->name, nr_cpus);
5357 			return nr_cpus;
5358 		}
5359 		pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
5360 		map->def.max_entries = nr_cpus;
5361 	}
5362 
5363 	return 0;
5364 }
5365 
5366 static int
5367 bpf_object__create_maps(struct bpf_object *obj)
5368 {
5369 	struct bpf_map *map;
5370 	char *cp, errmsg[STRERR_BUFSIZE];
5371 	unsigned int i, j;
5372 	int err;
5373 	bool retried;
5374 
5375 	for (i = 0; i < obj->nr_maps; i++) {
5376 		map = &obj->maps[i];
5377 
5378 		/* To support old kernels, we skip creating global data maps
5379 		 * (.rodata, .data, .kconfig, etc); later on, during program
5380 		 * loading, if we detect that at least one of the to-be-loaded
5381 		 * programs is referencing any global data map, we'll error
5382 		 * out with program name and relocation index logged.
5383 		 * This approach allows to accommodate Clang emitting
5384 		 * unnecessary .rodata.str1.1 sections for string literals,
5385 		 * but also it allows to have CO-RE applications that use
5386 		 * global variables in some of BPF programs, but not others.
5387 		 * If those global variable-using programs are not loaded at
5388 		 * runtime due to bpf_program__set_autoload(prog, false),
5389 		 * bpf_object loading will succeed just fine even on old
5390 		 * kernels.
5391 		 */
5392 		if (bpf_map__is_internal(map) && !kernel_supports(obj, FEAT_GLOBAL_DATA))
5393 			map->autocreate = false;
5394 
5395 		if (!map->autocreate) {
5396 			pr_debug("map '%s': skipped auto-creating...\n", map->name);
5397 			continue;
5398 		}
5399 
5400 		err = map_set_def_max_entries(map);
5401 		if (err)
5402 			goto err_out;
5403 
5404 		retried = false;
5405 retry:
5406 		if (map->pin_path) {
5407 			err = bpf_object__reuse_map(map);
5408 			if (err) {
5409 				pr_warn("map '%s': error reusing pinned map\n",
5410 					map->name);
5411 				goto err_out;
5412 			}
5413 			if (retried && map->fd < 0) {
5414 				pr_warn("map '%s': cannot find pinned map\n",
5415 					map->name);
5416 				err = -ENOENT;
5417 				goto err_out;
5418 			}
5419 		}
5420 
5421 		if (map->fd >= 0) {
5422 			pr_debug("map '%s': skipping creation (preset fd=%d)\n",
5423 				 map->name, map->fd);
5424 		} else {
5425 			err = bpf_object__create_map(obj, map, false);
5426 			if (err)
5427 				goto err_out;
5428 
5429 			pr_debug("map '%s': created successfully, fd=%d\n",
5430 				 map->name, map->fd);
5431 
5432 			if (bpf_map__is_internal(map)) {
5433 				err = bpf_object__populate_internal_map(obj, map);
5434 				if (err < 0) {
5435 					zclose(map->fd);
5436 					goto err_out;
5437 				}
5438 			}
5439 
5440 			if (map->init_slots_sz && map->def.type != BPF_MAP_TYPE_PROG_ARRAY) {
5441 				err = init_map_in_map_slots(obj, map);
5442 				if (err < 0) {
5443 					zclose(map->fd);
5444 					goto err_out;
5445 				}
5446 			}
5447 		}
5448 
5449 		if (map->pin_path && !map->pinned) {
5450 			err = bpf_map__pin(map, NULL);
5451 			if (err) {
5452 				zclose(map->fd);
5453 				if (!retried && err == -EEXIST) {
5454 					retried = true;
5455 					goto retry;
5456 				}
5457 				pr_warn("map '%s': failed to auto-pin at '%s': %d\n",
5458 					map->name, map->pin_path, err);
5459 				goto err_out;
5460 			}
5461 		}
5462 	}
5463 
5464 	return 0;
5465 
5466 err_out:
5467 	cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5468 	pr_warn("map '%s': failed to create: %s(%d)\n", map->name, cp, err);
5469 	pr_perm_msg(err);
5470 	for (j = 0; j < i; j++)
5471 		zclose(obj->maps[j].fd);
5472 	return err;
5473 }
5474 
5475 static bool bpf_core_is_flavor_sep(const char *s)
5476 {
5477 	/* check X___Y name pattern, where X and Y are not underscores */
5478 	return s[0] != '_' &&				      /* X */
5479 	       s[1] == '_' && s[2] == '_' && s[3] == '_' &&   /* ___ */
5480 	       s[4] != '_';				      /* Y */
5481 }
5482 
5483 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
5484  * before last triple underscore. Struct name part after last triple
5485  * underscore is ignored by BPF CO-RE relocation during relocation matching.
5486  */
5487 size_t bpf_core_essential_name_len(const char *name)
5488 {
5489 	size_t n = strlen(name);
5490 	int i;
5491 
5492 	for (i = n - 5; i >= 0; i--) {
5493 		if (bpf_core_is_flavor_sep(name + i))
5494 			return i + 1;
5495 	}
5496 	return n;
5497 }
5498 
5499 void bpf_core_free_cands(struct bpf_core_cand_list *cands)
5500 {
5501 	if (!cands)
5502 		return;
5503 
5504 	free(cands->cands);
5505 	free(cands);
5506 }
5507 
5508 int bpf_core_add_cands(struct bpf_core_cand *local_cand,
5509 		       size_t local_essent_len,
5510 		       const struct btf *targ_btf,
5511 		       const char *targ_btf_name,
5512 		       int targ_start_id,
5513 		       struct bpf_core_cand_list *cands)
5514 {
5515 	struct bpf_core_cand *new_cands, *cand;
5516 	const struct btf_type *t, *local_t;
5517 	const char *targ_name, *local_name;
5518 	size_t targ_essent_len;
5519 	int n, i;
5520 
5521 	local_t = btf__type_by_id(local_cand->btf, local_cand->id);
5522 	local_name = btf__str_by_offset(local_cand->btf, local_t->name_off);
5523 
5524 	n = btf__type_cnt(targ_btf);
5525 	for (i = targ_start_id; i < n; i++) {
5526 		t = btf__type_by_id(targ_btf, i);
5527 		if (!btf_kind_core_compat(t, local_t))
5528 			continue;
5529 
5530 		targ_name = btf__name_by_offset(targ_btf, t->name_off);
5531 		if (str_is_empty(targ_name))
5532 			continue;
5533 
5534 		targ_essent_len = bpf_core_essential_name_len(targ_name);
5535 		if (targ_essent_len != local_essent_len)
5536 			continue;
5537 
5538 		if (strncmp(local_name, targ_name, local_essent_len) != 0)
5539 			continue;
5540 
5541 		pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s in [%s]\n",
5542 			 local_cand->id, btf_kind_str(local_t),
5543 			 local_name, i, btf_kind_str(t), targ_name,
5544 			 targ_btf_name);
5545 		new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
5546 					      sizeof(*cands->cands));
5547 		if (!new_cands)
5548 			return -ENOMEM;
5549 
5550 		cand = &new_cands[cands->len];
5551 		cand->btf = targ_btf;
5552 		cand->id = i;
5553 
5554 		cands->cands = new_cands;
5555 		cands->len++;
5556 	}
5557 	return 0;
5558 }
5559 
5560 static int load_module_btfs(struct bpf_object *obj)
5561 {
5562 	struct bpf_btf_info info;
5563 	struct module_btf *mod_btf;
5564 	struct btf *btf;
5565 	char name[64];
5566 	__u32 id = 0, len;
5567 	int err, fd;
5568 
5569 	if (obj->btf_modules_loaded)
5570 		return 0;
5571 
5572 	if (obj->gen_loader)
5573 		return 0;
5574 
5575 	/* don't do this again, even if we find no module BTFs */
5576 	obj->btf_modules_loaded = true;
5577 
5578 	/* kernel too old to support module BTFs */
5579 	if (!kernel_supports(obj, FEAT_MODULE_BTF))
5580 		return 0;
5581 
5582 	while (true) {
5583 		err = bpf_btf_get_next_id(id, &id);
5584 		if (err && errno == ENOENT)
5585 			return 0;
5586 		if (err) {
5587 			err = -errno;
5588 			pr_warn("failed to iterate BTF objects: %d\n", err);
5589 			return err;
5590 		}
5591 
5592 		fd = bpf_btf_get_fd_by_id(id);
5593 		if (fd < 0) {
5594 			if (errno == ENOENT)
5595 				continue; /* expected race: BTF was unloaded */
5596 			err = -errno;
5597 			pr_warn("failed to get BTF object #%d FD: %d\n", id, err);
5598 			return err;
5599 		}
5600 
5601 		len = sizeof(info);
5602 		memset(&info, 0, sizeof(info));
5603 		info.name = ptr_to_u64(name);
5604 		info.name_len = sizeof(name);
5605 
5606 		err = bpf_obj_get_info_by_fd(fd, &info, &len);
5607 		if (err) {
5608 			err = -errno;
5609 			pr_warn("failed to get BTF object #%d info: %d\n", id, err);
5610 			goto err_out;
5611 		}
5612 
5613 		/* ignore non-module BTFs */
5614 		if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
5615 			close(fd);
5616 			continue;
5617 		}
5618 
5619 		btf = btf_get_from_fd(fd, obj->btf_vmlinux);
5620 		err = libbpf_get_error(btf);
5621 		if (err) {
5622 			pr_warn("failed to load module [%s]'s BTF object #%d: %d\n",
5623 				name, id, err);
5624 			goto err_out;
5625 		}
5626 
5627 		err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
5628 				        sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
5629 		if (err)
5630 			goto err_out;
5631 
5632 		mod_btf = &obj->btf_modules[obj->btf_module_cnt++];
5633 
5634 		mod_btf->btf = btf;
5635 		mod_btf->id = id;
5636 		mod_btf->fd = fd;
5637 		mod_btf->name = strdup(name);
5638 		if (!mod_btf->name) {
5639 			err = -ENOMEM;
5640 			goto err_out;
5641 		}
5642 		continue;
5643 
5644 err_out:
5645 		close(fd);
5646 		return err;
5647 	}
5648 
5649 	return 0;
5650 }
5651 
5652 static struct bpf_core_cand_list *
5653 bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
5654 {
5655 	struct bpf_core_cand local_cand = {};
5656 	struct bpf_core_cand_list *cands;
5657 	const struct btf *main_btf;
5658 	const struct btf_type *local_t;
5659 	const char *local_name;
5660 	size_t local_essent_len;
5661 	int err, i;
5662 
5663 	local_cand.btf = local_btf;
5664 	local_cand.id = local_type_id;
5665 	local_t = btf__type_by_id(local_btf, local_type_id);
5666 	if (!local_t)
5667 		return ERR_PTR(-EINVAL);
5668 
5669 	local_name = btf__name_by_offset(local_btf, local_t->name_off);
5670 	if (str_is_empty(local_name))
5671 		return ERR_PTR(-EINVAL);
5672 	local_essent_len = bpf_core_essential_name_len(local_name);
5673 
5674 	cands = calloc(1, sizeof(*cands));
5675 	if (!cands)
5676 		return ERR_PTR(-ENOMEM);
5677 
5678 	/* Attempt to find target candidates in vmlinux BTF first */
5679 	main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
5680 	err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
5681 	if (err)
5682 		goto err_out;
5683 
5684 	/* if vmlinux BTF has any candidate, don't got for module BTFs */
5685 	if (cands->len)
5686 		return cands;
5687 
5688 	/* if vmlinux BTF was overridden, don't attempt to load module BTFs */
5689 	if (obj->btf_vmlinux_override)
5690 		return cands;
5691 
5692 	/* now look through module BTFs, trying to still find candidates */
5693 	err = load_module_btfs(obj);
5694 	if (err)
5695 		goto err_out;
5696 
5697 	for (i = 0; i < obj->btf_module_cnt; i++) {
5698 		err = bpf_core_add_cands(&local_cand, local_essent_len,
5699 					 obj->btf_modules[i].btf,
5700 					 obj->btf_modules[i].name,
5701 					 btf__type_cnt(obj->btf_vmlinux),
5702 					 cands);
5703 		if (err)
5704 			goto err_out;
5705 	}
5706 
5707 	return cands;
5708 err_out:
5709 	bpf_core_free_cands(cands);
5710 	return ERR_PTR(err);
5711 }
5712 
5713 /* Check local and target types for compatibility. This check is used for
5714  * type-based CO-RE relocations and follow slightly different rules than
5715  * field-based relocations. This function assumes that root types were already
5716  * checked for name match. Beyond that initial root-level name check, names
5717  * are completely ignored. Compatibility rules are as follows:
5718  *   - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
5719  *     kind should match for local and target types (i.e., STRUCT is not
5720  *     compatible with UNION);
5721  *   - for ENUMs, the size is ignored;
5722  *   - for INT, size and signedness are ignored;
5723  *   - for ARRAY, dimensionality is ignored, element types are checked for
5724  *     compatibility recursively;
5725  *   - CONST/VOLATILE/RESTRICT modifiers are ignored;
5726  *   - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
5727  *   - FUNC_PROTOs are compatible if they have compatible signature: same
5728  *     number of input args and compatible return and argument types.
5729  * These rules are not set in stone and probably will be adjusted as we get
5730  * more experience with using BPF CO-RE relocations.
5731  */
5732 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
5733 			      const struct btf *targ_btf, __u32 targ_id)
5734 {
5735 	const struct btf_type *local_type, *targ_type;
5736 	int depth = 32; /* max recursion depth */
5737 
5738 	/* caller made sure that names match (ignoring flavor suffix) */
5739 	local_type = btf__type_by_id(local_btf, local_id);
5740 	targ_type = btf__type_by_id(targ_btf, targ_id);
5741 	if (!btf_kind_core_compat(local_type, targ_type))
5742 		return 0;
5743 
5744 recur:
5745 	depth--;
5746 	if (depth < 0)
5747 		return -EINVAL;
5748 
5749 	local_type = skip_mods_and_typedefs(local_btf, local_id, &local_id);
5750 	targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
5751 	if (!local_type || !targ_type)
5752 		return -EINVAL;
5753 
5754 	if (!btf_kind_core_compat(local_type, targ_type))
5755 		return 0;
5756 
5757 	switch (btf_kind(local_type)) {
5758 	case BTF_KIND_UNKN:
5759 	case BTF_KIND_STRUCT:
5760 	case BTF_KIND_UNION:
5761 	case BTF_KIND_ENUM:
5762 	case BTF_KIND_ENUM64:
5763 	case BTF_KIND_FWD:
5764 		return 1;
5765 	case BTF_KIND_INT:
5766 		/* just reject deprecated bitfield-like integers; all other
5767 		 * integers are by default compatible between each other
5768 		 */
5769 		return btf_int_offset(local_type) == 0 && btf_int_offset(targ_type) == 0;
5770 	case BTF_KIND_PTR:
5771 		local_id = local_type->type;
5772 		targ_id = targ_type->type;
5773 		goto recur;
5774 	case BTF_KIND_ARRAY:
5775 		local_id = btf_array(local_type)->type;
5776 		targ_id = btf_array(targ_type)->type;
5777 		goto recur;
5778 	case BTF_KIND_FUNC_PROTO: {
5779 		struct btf_param *local_p = btf_params(local_type);
5780 		struct btf_param *targ_p = btf_params(targ_type);
5781 		__u16 local_vlen = btf_vlen(local_type);
5782 		__u16 targ_vlen = btf_vlen(targ_type);
5783 		int i, err;
5784 
5785 		if (local_vlen != targ_vlen)
5786 			return 0;
5787 
5788 		for (i = 0; i < local_vlen; i++, local_p++, targ_p++) {
5789 			skip_mods_and_typedefs(local_btf, local_p->type, &local_id);
5790 			skip_mods_and_typedefs(targ_btf, targ_p->type, &targ_id);
5791 			err = bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id);
5792 			if (err <= 0)
5793 				return err;
5794 		}
5795 
5796 		/* tail recurse for return type check */
5797 		skip_mods_and_typedefs(local_btf, local_type->type, &local_id);
5798 		skip_mods_and_typedefs(targ_btf, targ_type->type, &targ_id);
5799 		goto recur;
5800 	}
5801 	default:
5802 		pr_warn("unexpected kind %s relocated, local [%d], target [%d]\n",
5803 			btf_kind_str(local_type), local_id, targ_id);
5804 		return 0;
5805 	}
5806 }
5807 
5808 static size_t bpf_core_hash_fn(const void *key, void *ctx)
5809 {
5810 	return (size_t)key;
5811 }
5812 
5813 static bool bpf_core_equal_fn(const void *k1, const void *k2, void *ctx)
5814 {
5815 	return k1 == k2;
5816 }
5817 
5818 static void *u32_as_hash_key(__u32 x)
5819 {
5820 	return (void *)(uintptr_t)x;
5821 }
5822 
5823 static int record_relo_core(struct bpf_program *prog,
5824 			    const struct bpf_core_relo *core_relo, int insn_idx)
5825 {
5826 	struct reloc_desc *relos, *relo;
5827 
5828 	relos = libbpf_reallocarray(prog->reloc_desc,
5829 				    prog->nr_reloc + 1, sizeof(*relos));
5830 	if (!relos)
5831 		return -ENOMEM;
5832 	relo = &relos[prog->nr_reloc];
5833 	relo->type = RELO_CORE;
5834 	relo->insn_idx = insn_idx;
5835 	relo->core_relo = core_relo;
5836 	prog->reloc_desc = relos;
5837 	prog->nr_reloc++;
5838 	return 0;
5839 }
5840 
5841 static const struct bpf_core_relo *find_relo_core(struct bpf_program *prog, int insn_idx)
5842 {
5843 	struct reloc_desc *relo;
5844 	int i;
5845 
5846 	for (i = 0; i < prog->nr_reloc; i++) {
5847 		relo = &prog->reloc_desc[i];
5848 		if (relo->type != RELO_CORE || relo->insn_idx != insn_idx)
5849 			continue;
5850 
5851 		return relo->core_relo;
5852 	}
5853 
5854 	return NULL;
5855 }
5856 
5857 static int bpf_core_resolve_relo(struct bpf_program *prog,
5858 				 const struct bpf_core_relo *relo,
5859 				 int relo_idx,
5860 				 const struct btf *local_btf,
5861 				 struct hashmap *cand_cache,
5862 				 struct bpf_core_relo_res *targ_res)
5863 {
5864 	struct bpf_core_spec specs_scratch[3] = {};
5865 	const void *type_key = u32_as_hash_key(relo->type_id);
5866 	struct bpf_core_cand_list *cands = NULL;
5867 	const char *prog_name = prog->name;
5868 	const struct btf_type *local_type;
5869 	const char *local_name;
5870 	__u32 local_id = relo->type_id;
5871 	int err;
5872 
5873 	local_type = btf__type_by_id(local_btf, local_id);
5874 	if (!local_type)
5875 		return -EINVAL;
5876 
5877 	local_name = btf__name_by_offset(local_btf, local_type->name_off);
5878 	if (!local_name)
5879 		return -EINVAL;
5880 
5881 	if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
5882 	    !hashmap__find(cand_cache, type_key, (void **)&cands)) {
5883 		cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
5884 		if (IS_ERR(cands)) {
5885 			pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n",
5886 				prog_name, relo_idx, local_id, btf_kind_str(local_type),
5887 				local_name, PTR_ERR(cands));
5888 			return PTR_ERR(cands);
5889 		}
5890 		err = hashmap__set(cand_cache, type_key, cands, NULL, NULL);
5891 		if (err) {
5892 			bpf_core_free_cands(cands);
5893 			return err;
5894 		}
5895 	}
5896 
5897 	return bpf_core_calc_relo_insn(prog_name, relo, relo_idx, local_btf, cands, specs_scratch,
5898 				       targ_res);
5899 }
5900 
5901 static int
5902 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
5903 {
5904 	const struct btf_ext_info_sec *sec;
5905 	struct bpf_core_relo_res targ_res;
5906 	const struct bpf_core_relo *rec;
5907 	const struct btf_ext_info *seg;
5908 	struct hashmap_entry *entry;
5909 	struct hashmap *cand_cache = NULL;
5910 	struct bpf_program *prog;
5911 	struct bpf_insn *insn;
5912 	const char *sec_name;
5913 	int i, err = 0, insn_idx, sec_idx, sec_num;
5914 
5915 	if (obj->btf_ext->core_relo_info.len == 0)
5916 		return 0;
5917 
5918 	if (targ_btf_path) {
5919 		obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
5920 		err = libbpf_get_error(obj->btf_vmlinux_override);
5921 		if (err) {
5922 			pr_warn("failed to parse target BTF: %d\n", err);
5923 			return err;
5924 		}
5925 	}
5926 
5927 	cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
5928 	if (IS_ERR(cand_cache)) {
5929 		err = PTR_ERR(cand_cache);
5930 		goto out;
5931 	}
5932 
5933 	seg = &obj->btf_ext->core_relo_info;
5934 	sec_num = 0;
5935 	for_each_btf_ext_sec(seg, sec) {
5936 		sec_idx = seg->sec_idxs[sec_num];
5937 		sec_num++;
5938 
5939 		sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
5940 		if (str_is_empty(sec_name)) {
5941 			err = -EINVAL;
5942 			goto out;
5943 		}
5944 
5945 		pr_debug("sec '%s': found %d CO-RE relocations\n", sec_name, sec->num_info);
5946 
5947 		for_each_btf_ext_rec(seg, sec, i, rec) {
5948 			if (rec->insn_off % BPF_INSN_SZ)
5949 				return -EINVAL;
5950 			insn_idx = rec->insn_off / BPF_INSN_SZ;
5951 			prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
5952 			if (!prog) {
5953 				/* When __weak subprog is "overridden" by another instance
5954 				 * of the subprog from a different object file, linker still
5955 				 * appends all the .BTF.ext info that used to belong to that
5956 				 * eliminated subprogram.
5957 				 * This is similar to what x86-64 linker does for relocations.
5958 				 * So just ignore such relocations just like we ignore
5959 				 * subprog instructions when discovering subprograms.
5960 				 */
5961 				pr_debug("sec '%s': skipping CO-RE relocation #%d for insn #%d belonging to eliminated weak subprogram\n",
5962 					 sec_name, i, insn_idx);
5963 				continue;
5964 			}
5965 			/* no need to apply CO-RE relocation if the program is
5966 			 * not going to be loaded
5967 			 */
5968 			if (!prog->autoload)
5969 				continue;
5970 
5971 			/* adjust insn_idx from section frame of reference to the local
5972 			 * program's frame of reference; (sub-)program code is not yet
5973 			 * relocated, so it's enough to just subtract in-section offset
5974 			 */
5975 			insn_idx = insn_idx - prog->sec_insn_off;
5976 			if (insn_idx >= prog->insns_cnt)
5977 				return -EINVAL;
5978 			insn = &prog->insns[insn_idx];
5979 
5980 			err = record_relo_core(prog, rec, insn_idx);
5981 			if (err) {
5982 				pr_warn("prog '%s': relo #%d: failed to record relocation: %d\n",
5983 					prog->name, i, err);
5984 				goto out;
5985 			}
5986 
5987 			if (prog->obj->gen_loader)
5988 				continue;
5989 
5990 			err = bpf_core_resolve_relo(prog, rec, i, obj->btf, cand_cache, &targ_res);
5991 			if (err) {
5992 				pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
5993 					prog->name, i, err);
5994 				goto out;
5995 			}
5996 
5997 			err = bpf_core_patch_insn(prog->name, insn, insn_idx, rec, i, &targ_res);
5998 			if (err) {
5999 				pr_warn("prog '%s': relo #%d: failed to patch insn #%u: %d\n",
6000 					prog->name, i, insn_idx, err);
6001 				goto out;
6002 			}
6003 		}
6004 	}
6005 
6006 out:
6007 	/* obj->btf_vmlinux and module BTFs are freed after object load */
6008 	btf__free(obj->btf_vmlinux_override);
6009 	obj->btf_vmlinux_override = NULL;
6010 
6011 	if (!IS_ERR_OR_NULL(cand_cache)) {
6012 		hashmap__for_each_entry(cand_cache, entry, i) {
6013 			bpf_core_free_cands(entry->value);
6014 		}
6015 		hashmap__free(cand_cache);
6016 	}
6017 	return err;
6018 }
6019 
6020 /* base map load ldimm64 special constant, used also for log fixup logic */
6021 #define MAP_LDIMM64_POISON_BASE 2001000000
6022 #define MAP_LDIMM64_POISON_PFX "200100"
6023 
6024 static void poison_map_ldimm64(struct bpf_program *prog, int relo_idx,
6025 			       int insn_idx, struct bpf_insn *insn,
6026 			       int map_idx, const struct bpf_map *map)
6027 {
6028 	int i;
6029 
6030 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that loads map #%d '%s'\n",
6031 		 prog->name, relo_idx, insn_idx, map_idx, map->name);
6032 
6033 	/* we turn single ldimm64 into two identical invalid calls */
6034 	for (i = 0; i < 2; i++) {
6035 		insn->code = BPF_JMP | BPF_CALL;
6036 		insn->dst_reg = 0;
6037 		insn->src_reg = 0;
6038 		insn->off = 0;
6039 		/* if this instruction is reachable (not a dead code),
6040 		 * verifier will complain with something like:
6041 		 * invalid func unknown#2001000123
6042 		 * where lower 123 is map index into obj->maps[] array
6043 		 */
6044 		insn->imm = MAP_LDIMM64_POISON_BASE + map_idx;
6045 
6046 		insn++;
6047 	}
6048 }
6049 
6050 /* Relocate data references within program code:
6051  *  - map references;
6052  *  - global variable references;
6053  *  - extern references.
6054  */
6055 static int
6056 bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
6057 {
6058 	int i;
6059 
6060 	for (i = 0; i < prog->nr_reloc; i++) {
6061 		struct reloc_desc *relo = &prog->reloc_desc[i];
6062 		struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6063 		const struct bpf_map *map;
6064 		struct extern_desc *ext;
6065 
6066 		switch (relo->type) {
6067 		case RELO_LD64:
6068 			map = &obj->maps[relo->map_idx];
6069 			if (obj->gen_loader) {
6070 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
6071 				insn[0].imm = relo->map_idx;
6072 			} else if (map->autocreate) {
6073 				insn[0].src_reg = BPF_PSEUDO_MAP_FD;
6074 				insn[0].imm = map->fd;
6075 			} else {
6076 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6077 						   relo->map_idx, map);
6078 			}
6079 			break;
6080 		case RELO_DATA:
6081 			map = &obj->maps[relo->map_idx];
6082 			insn[1].imm = insn[0].imm + relo->sym_off;
6083 			if (obj->gen_loader) {
6084 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6085 				insn[0].imm = relo->map_idx;
6086 			} else if (map->autocreate) {
6087 				insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6088 				insn[0].imm = map->fd;
6089 			} else {
6090 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6091 						   relo->map_idx, map);
6092 			}
6093 			break;
6094 		case RELO_EXTERN_VAR:
6095 			ext = &obj->externs[relo->sym_off];
6096 			if (ext->type == EXT_KCFG) {
6097 				if (obj->gen_loader) {
6098 					insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6099 					insn[0].imm = obj->kconfig_map_idx;
6100 				} else {
6101 					insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6102 					insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
6103 				}
6104 				insn[1].imm = ext->kcfg.data_off;
6105 			} else /* EXT_KSYM */ {
6106 				if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
6107 					insn[0].src_reg = BPF_PSEUDO_BTF_ID;
6108 					insn[0].imm = ext->ksym.kernel_btf_id;
6109 					insn[1].imm = ext->ksym.kernel_btf_obj_fd;
6110 				} else { /* typeless ksyms or unresolved typed ksyms */
6111 					insn[0].imm = (__u32)ext->ksym.addr;
6112 					insn[1].imm = ext->ksym.addr >> 32;
6113 				}
6114 			}
6115 			break;
6116 		case RELO_EXTERN_FUNC:
6117 			ext = &obj->externs[relo->sym_off];
6118 			insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
6119 			if (ext->is_set) {
6120 				insn[0].imm = ext->ksym.kernel_btf_id;
6121 				insn[0].off = ext->ksym.btf_fd_idx;
6122 			} else { /* unresolved weak kfunc */
6123 				insn[0].imm = 0;
6124 				insn[0].off = 0;
6125 			}
6126 			break;
6127 		case RELO_SUBPROG_ADDR:
6128 			if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
6129 				pr_warn("prog '%s': relo #%d: bad insn\n",
6130 					prog->name, i);
6131 				return -EINVAL;
6132 			}
6133 			/* handled already */
6134 			break;
6135 		case RELO_CALL:
6136 			/* handled already */
6137 			break;
6138 		case RELO_CORE:
6139 			/* will be handled by bpf_program_record_relos() */
6140 			break;
6141 		default:
6142 			pr_warn("prog '%s': relo #%d: bad relo type %d\n",
6143 				prog->name, i, relo->type);
6144 			return -EINVAL;
6145 		}
6146 	}
6147 
6148 	return 0;
6149 }
6150 
6151 static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
6152 				    const struct bpf_program *prog,
6153 				    const struct btf_ext_info *ext_info,
6154 				    void **prog_info, __u32 *prog_rec_cnt,
6155 				    __u32 *prog_rec_sz)
6156 {
6157 	void *copy_start = NULL, *copy_end = NULL;
6158 	void *rec, *rec_end, *new_prog_info;
6159 	const struct btf_ext_info_sec *sec;
6160 	size_t old_sz, new_sz;
6161 	int i, sec_num, sec_idx, off_adj;
6162 
6163 	sec_num = 0;
6164 	for_each_btf_ext_sec(ext_info, sec) {
6165 		sec_idx = ext_info->sec_idxs[sec_num];
6166 		sec_num++;
6167 		if (prog->sec_idx != sec_idx)
6168 			continue;
6169 
6170 		for_each_btf_ext_rec(ext_info, sec, i, rec) {
6171 			__u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
6172 
6173 			if (insn_off < prog->sec_insn_off)
6174 				continue;
6175 			if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
6176 				break;
6177 
6178 			if (!copy_start)
6179 				copy_start = rec;
6180 			copy_end = rec + ext_info->rec_size;
6181 		}
6182 
6183 		if (!copy_start)
6184 			return -ENOENT;
6185 
6186 		/* append func/line info of a given (sub-)program to the main
6187 		 * program func/line info
6188 		 */
6189 		old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
6190 		new_sz = old_sz + (copy_end - copy_start);
6191 		new_prog_info = realloc(*prog_info, new_sz);
6192 		if (!new_prog_info)
6193 			return -ENOMEM;
6194 		*prog_info = new_prog_info;
6195 		*prog_rec_cnt = new_sz / ext_info->rec_size;
6196 		memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
6197 
6198 		/* Kernel instruction offsets are in units of 8-byte
6199 		 * instructions, while .BTF.ext instruction offsets generated
6200 		 * by Clang are in units of bytes. So convert Clang offsets
6201 		 * into kernel offsets and adjust offset according to program
6202 		 * relocated position.
6203 		 */
6204 		off_adj = prog->sub_insn_off - prog->sec_insn_off;
6205 		rec = new_prog_info + old_sz;
6206 		rec_end = new_prog_info + new_sz;
6207 		for (; rec < rec_end; rec += ext_info->rec_size) {
6208 			__u32 *insn_off = rec;
6209 
6210 			*insn_off = *insn_off / BPF_INSN_SZ + off_adj;
6211 		}
6212 		*prog_rec_sz = ext_info->rec_size;
6213 		return 0;
6214 	}
6215 
6216 	return -ENOENT;
6217 }
6218 
6219 static int
6220 reloc_prog_func_and_line_info(const struct bpf_object *obj,
6221 			      struct bpf_program *main_prog,
6222 			      const struct bpf_program *prog)
6223 {
6224 	int err;
6225 
6226 	/* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
6227 	 * supprot func/line info
6228 	 */
6229 	if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
6230 		return 0;
6231 
6232 	/* only attempt func info relocation if main program's func_info
6233 	 * relocation was successful
6234 	 */
6235 	if (main_prog != prog && !main_prog->func_info)
6236 		goto line_info;
6237 
6238 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
6239 				       &main_prog->func_info,
6240 				       &main_prog->func_info_cnt,
6241 				       &main_prog->func_info_rec_size);
6242 	if (err) {
6243 		if (err != -ENOENT) {
6244 			pr_warn("prog '%s': error relocating .BTF.ext function info: %d\n",
6245 				prog->name, err);
6246 			return err;
6247 		}
6248 		if (main_prog->func_info) {
6249 			/*
6250 			 * Some info has already been found but has problem
6251 			 * in the last btf_ext reloc. Must have to error out.
6252 			 */
6253 			pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
6254 			return err;
6255 		}
6256 		/* Have problem loading the very first info. Ignore the rest. */
6257 		pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
6258 			prog->name);
6259 	}
6260 
6261 line_info:
6262 	/* don't relocate line info if main program's relocation failed */
6263 	if (main_prog != prog && !main_prog->line_info)
6264 		return 0;
6265 
6266 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
6267 				       &main_prog->line_info,
6268 				       &main_prog->line_info_cnt,
6269 				       &main_prog->line_info_rec_size);
6270 	if (err) {
6271 		if (err != -ENOENT) {
6272 			pr_warn("prog '%s': error relocating .BTF.ext line info: %d\n",
6273 				prog->name, err);
6274 			return err;
6275 		}
6276 		if (main_prog->line_info) {
6277 			/*
6278 			 * Some info has already been found but has problem
6279 			 * in the last btf_ext reloc. Must have to error out.
6280 			 */
6281 			pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
6282 			return err;
6283 		}
6284 		/* Have problem loading the very first info. Ignore the rest. */
6285 		pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
6286 			prog->name);
6287 	}
6288 	return 0;
6289 }
6290 
6291 static int cmp_relo_by_insn_idx(const void *key, const void *elem)
6292 {
6293 	size_t insn_idx = *(const size_t *)key;
6294 	const struct reloc_desc *relo = elem;
6295 
6296 	if (insn_idx == relo->insn_idx)
6297 		return 0;
6298 	return insn_idx < relo->insn_idx ? -1 : 1;
6299 }
6300 
6301 static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
6302 {
6303 	if (!prog->nr_reloc)
6304 		return NULL;
6305 	return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
6306 		       sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
6307 }
6308 
6309 static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
6310 {
6311 	int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
6312 	struct reloc_desc *relos;
6313 	int i;
6314 
6315 	if (main_prog == subprog)
6316 		return 0;
6317 	relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
6318 	if (!relos)
6319 		return -ENOMEM;
6320 	if (subprog->nr_reloc)
6321 		memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
6322 		       sizeof(*relos) * subprog->nr_reloc);
6323 
6324 	for (i = main_prog->nr_reloc; i < new_cnt; i++)
6325 		relos[i].insn_idx += subprog->sub_insn_off;
6326 	/* After insn_idx adjustment the 'relos' array is still sorted
6327 	 * by insn_idx and doesn't break bsearch.
6328 	 */
6329 	main_prog->reloc_desc = relos;
6330 	main_prog->nr_reloc = new_cnt;
6331 	return 0;
6332 }
6333 
6334 static int
6335 bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
6336 		       struct bpf_program *prog)
6337 {
6338 	size_t sub_insn_idx, insn_idx, new_cnt;
6339 	struct bpf_program *subprog;
6340 	struct bpf_insn *insns, *insn;
6341 	struct reloc_desc *relo;
6342 	int err;
6343 
6344 	err = reloc_prog_func_and_line_info(obj, main_prog, prog);
6345 	if (err)
6346 		return err;
6347 
6348 	for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
6349 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6350 		if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
6351 			continue;
6352 
6353 		relo = find_prog_insn_relo(prog, insn_idx);
6354 		if (relo && relo->type == RELO_EXTERN_FUNC)
6355 			/* kfunc relocations will be handled later
6356 			 * in bpf_object__relocate_data()
6357 			 */
6358 			continue;
6359 		if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
6360 			pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
6361 				prog->name, insn_idx, relo->type);
6362 			return -LIBBPF_ERRNO__RELOC;
6363 		}
6364 		if (relo) {
6365 			/* sub-program instruction index is a combination of
6366 			 * an offset of a symbol pointed to by relocation and
6367 			 * call instruction's imm field; for global functions,
6368 			 * call always has imm = -1, but for static functions
6369 			 * relocation is against STT_SECTION and insn->imm
6370 			 * points to a start of a static function
6371 			 *
6372 			 * for subprog addr relocation, the relo->sym_off + insn->imm is
6373 			 * the byte offset in the corresponding section.
6374 			 */
6375 			if (relo->type == RELO_CALL)
6376 				sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
6377 			else
6378 				sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
6379 		} else if (insn_is_pseudo_func(insn)) {
6380 			/*
6381 			 * RELO_SUBPROG_ADDR relo is always emitted even if both
6382 			 * functions are in the same section, so it shouldn't reach here.
6383 			 */
6384 			pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
6385 				prog->name, insn_idx);
6386 			return -LIBBPF_ERRNO__RELOC;
6387 		} else {
6388 			/* if subprogram call is to a static function within
6389 			 * the same ELF section, there won't be any relocation
6390 			 * emitted, but it also means there is no additional
6391 			 * offset necessary, insns->imm is relative to
6392 			 * instruction's original position within the section
6393 			 */
6394 			sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
6395 		}
6396 
6397 		/* we enforce that sub-programs should be in .text section */
6398 		subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
6399 		if (!subprog) {
6400 			pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
6401 				prog->name);
6402 			return -LIBBPF_ERRNO__RELOC;
6403 		}
6404 
6405 		/* if it's the first call instruction calling into this
6406 		 * subprogram (meaning this subprog hasn't been processed
6407 		 * yet) within the context of current main program:
6408 		 *   - append it at the end of main program's instructions blog;
6409 		 *   - process is recursively, while current program is put on hold;
6410 		 *   - if that subprogram calls some other not yet processes
6411 		 *   subprogram, same thing will happen recursively until
6412 		 *   there are no more unprocesses subprograms left to append
6413 		 *   and relocate.
6414 		 */
6415 		if (subprog->sub_insn_off == 0) {
6416 			subprog->sub_insn_off = main_prog->insns_cnt;
6417 
6418 			new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
6419 			insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
6420 			if (!insns) {
6421 				pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
6422 				return -ENOMEM;
6423 			}
6424 			main_prog->insns = insns;
6425 			main_prog->insns_cnt = new_cnt;
6426 
6427 			memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
6428 			       subprog->insns_cnt * sizeof(*insns));
6429 
6430 			pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
6431 				 main_prog->name, subprog->insns_cnt, subprog->name);
6432 
6433 			/* The subprog insns are now appended. Append its relos too. */
6434 			err = append_subprog_relos(main_prog, subprog);
6435 			if (err)
6436 				return err;
6437 			err = bpf_object__reloc_code(obj, main_prog, subprog);
6438 			if (err)
6439 				return err;
6440 		}
6441 
6442 		/* main_prog->insns memory could have been re-allocated, so
6443 		 * calculate pointer again
6444 		 */
6445 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6446 		/* calculate correct instruction position within current main
6447 		 * prog; each main prog can have a different set of
6448 		 * subprograms appended (potentially in different order as
6449 		 * well), so position of any subprog can be different for
6450 		 * different main programs */
6451 		insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
6452 
6453 		pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
6454 			 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
6455 	}
6456 
6457 	return 0;
6458 }
6459 
6460 /*
6461  * Relocate sub-program calls.
6462  *
6463  * Algorithm operates as follows. Each entry-point BPF program (referred to as
6464  * main prog) is processed separately. For each subprog (non-entry functions,
6465  * that can be called from either entry progs or other subprogs) gets their
6466  * sub_insn_off reset to zero. This serves as indicator that this subprogram
6467  * hasn't been yet appended and relocated within current main prog. Once its
6468  * relocated, sub_insn_off will point at the position within current main prog
6469  * where given subprog was appended. This will further be used to relocate all
6470  * the call instructions jumping into this subprog.
6471  *
6472  * We start with main program and process all call instructions. If the call
6473  * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
6474  * is zero), subprog instructions are appended at the end of main program's
6475  * instruction array. Then main program is "put on hold" while we recursively
6476  * process newly appended subprogram. If that subprogram calls into another
6477  * subprogram that hasn't been appended, new subprogram is appended again to
6478  * the *main* prog's instructions (subprog's instructions are always left
6479  * untouched, as they need to be in unmodified state for subsequent main progs
6480  * and subprog instructions are always sent only as part of a main prog) and
6481  * the process continues recursively. Once all the subprogs called from a main
6482  * prog or any of its subprogs are appended (and relocated), all their
6483  * positions within finalized instructions array are known, so it's easy to
6484  * rewrite call instructions with correct relative offsets, corresponding to
6485  * desired target subprog.
6486  *
6487  * Its important to realize that some subprogs might not be called from some
6488  * main prog and any of its called/used subprogs. Those will keep their
6489  * subprog->sub_insn_off as zero at all times and won't be appended to current
6490  * main prog and won't be relocated within the context of current main prog.
6491  * They might still be used from other main progs later.
6492  *
6493  * Visually this process can be shown as below. Suppose we have two main
6494  * programs mainA and mainB and BPF object contains three subprogs: subA,
6495  * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
6496  * subC both call subB:
6497  *
6498  *        +--------+ +-------+
6499  *        |        v v       |
6500  *     +--+---+ +--+-+-+ +---+--+
6501  *     | subA | | subB | | subC |
6502  *     +--+---+ +------+ +---+--+
6503  *        ^                  ^
6504  *        |                  |
6505  *    +---+-------+   +------+----+
6506  *    |   mainA   |   |   mainB   |
6507  *    +-----------+   +-----------+
6508  *
6509  * We'll start relocating mainA, will find subA, append it and start
6510  * processing sub A recursively:
6511  *
6512  *    +-----------+------+
6513  *    |   mainA   | subA |
6514  *    +-----------+------+
6515  *
6516  * At this point we notice that subB is used from subA, so we append it and
6517  * relocate (there are no further subcalls from subB):
6518  *
6519  *    +-----------+------+------+
6520  *    |   mainA   | subA | subB |
6521  *    +-----------+------+------+
6522  *
6523  * At this point, we relocate subA calls, then go one level up and finish with
6524  * relocatin mainA calls. mainA is done.
6525  *
6526  * For mainB process is similar but results in different order. We start with
6527  * mainB and skip subA and subB, as mainB never calls them (at least
6528  * directly), but we see subC is needed, so we append and start processing it:
6529  *
6530  *    +-----------+------+
6531  *    |   mainB   | subC |
6532  *    +-----------+------+
6533  * Now we see subC needs subB, so we go back to it, append and relocate it:
6534  *
6535  *    +-----------+------+------+
6536  *    |   mainB   | subC | subB |
6537  *    +-----------+------+------+
6538  *
6539  * At this point we unwind recursion, relocate calls in subC, then in mainB.
6540  */
6541 static int
6542 bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
6543 {
6544 	struct bpf_program *subprog;
6545 	int i, err;
6546 
6547 	/* mark all subprogs as not relocated (yet) within the context of
6548 	 * current main program
6549 	 */
6550 	for (i = 0; i < obj->nr_programs; i++) {
6551 		subprog = &obj->programs[i];
6552 		if (!prog_is_subprog(obj, subprog))
6553 			continue;
6554 
6555 		subprog->sub_insn_off = 0;
6556 	}
6557 
6558 	err = bpf_object__reloc_code(obj, prog, prog);
6559 	if (err)
6560 		return err;
6561 
6562 	return 0;
6563 }
6564 
6565 static void
6566 bpf_object__free_relocs(struct bpf_object *obj)
6567 {
6568 	struct bpf_program *prog;
6569 	int i;
6570 
6571 	/* free up relocation descriptors */
6572 	for (i = 0; i < obj->nr_programs; i++) {
6573 		prog = &obj->programs[i];
6574 		zfree(&prog->reloc_desc);
6575 		prog->nr_reloc = 0;
6576 	}
6577 }
6578 
6579 static int cmp_relocs(const void *_a, const void *_b)
6580 {
6581 	const struct reloc_desc *a = _a;
6582 	const struct reloc_desc *b = _b;
6583 
6584 	if (a->insn_idx != b->insn_idx)
6585 		return a->insn_idx < b->insn_idx ? -1 : 1;
6586 
6587 	/* no two relocations should have the same insn_idx, but ... */
6588 	if (a->type != b->type)
6589 		return a->type < b->type ? -1 : 1;
6590 
6591 	return 0;
6592 }
6593 
6594 static void bpf_object__sort_relos(struct bpf_object *obj)
6595 {
6596 	int i;
6597 
6598 	for (i = 0; i < obj->nr_programs; i++) {
6599 		struct bpf_program *p = &obj->programs[i];
6600 
6601 		if (!p->nr_reloc)
6602 			continue;
6603 
6604 		qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
6605 	}
6606 }
6607 
6608 static int
6609 bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
6610 {
6611 	struct bpf_program *prog;
6612 	size_t i, j;
6613 	int err;
6614 
6615 	if (obj->btf_ext) {
6616 		err = bpf_object__relocate_core(obj, targ_btf_path);
6617 		if (err) {
6618 			pr_warn("failed to perform CO-RE relocations: %d\n",
6619 				err);
6620 			return err;
6621 		}
6622 		bpf_object__sort_relos(obj);
6623 	}
6624 
6625 	/* Before relocating calls pre-process relocations and mark
6626 	 * few ld_imm64 instructions that points to subprogs.
6627 	 * Otherwise bpf_object__reloc_code() later would have to consider
6628 	 * all ld_imm64 insns as relocation candidates. That would
6629 	 * reduce relocation speed, since amount of find_prog_insn_relo()
6630 	 * would increase and most of them will fail to find a relo.
6631 	 */
6632 	for (i = 0; i < obj->nr_programs; i++) {
6633 		prog = &obj->programs[i];
6634 		for (j = 0; j < prog->nr_reloc; j++) {
6635 			struct reloc_desc *relo = &prog->reloc_desc[j];
6636 			struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6637 
6638 			/* mark the insn, so it's recognized by insn_is_pseudo_func() */
6639 			if (relo->type == RELO_SUBPROG_ADDR)
6640 				insn[0].src_reg = BPF_PSEUDO_FUNC;
6641 		}
6642 	}
6643 
6644 	/* relocate subprogram calls and append used subprograms to main
6645 	 * programs; each copy of subprogram code needs to be relocated
6646 	 * differently for each main program, because its code location might
6647 	 * have changed.
6648 	 * Append subprog relos to main programs to allow data relos to be
6649 	 * processed after text is completely relocated.
6650 	 */
6651 	for (i = 0; i < obj->nr_programs; i++) {
6652 		prog = &obj->programs[i];
6653 		/* sub-program's sub-calls are relocated within the context of
6654 		 * its main program only
6655 		 */
6656 		if (prog_is_subprog(obj, prog))
6657 			continue;
6658 		if (!prog->autoload)
6659 			continue;
6660 
6661 		err = bpf_object__relocate_calls(obj, prog);
6662 		if (err) {
6663 			pr_warn("prog '%s': failed to relocate calls: %d\n",
6664 				prog->name, err);
6665 			return err;
6666 		}
6667 	}
6668 	/* Process data relos for main programs */
6669 	for (i = 0; i < obj->nr_programs; i++) {
6670 		prog = &obj->programs[i];
6671 		if (prog_is_subprog(obj, prog))
6672 			continue;
6673 		if (!prog->autoload)
6674 			continue;
6675 		err = bpf_object__relocate_data(obj, prog);
6676 		if (err) {
6677 			pr_warn("prog '%s': failed to relocate data references: %d\n",
6678 				prog->name, err);
6679 			return err;
6680 		}
6681 	}
6682 
6683 	return 0;
6684 }
6685 
6686 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
6687 					    Elf64_Shdr *shdr, Elf_Data *data);
6688 
6689 static int bpf_object__collect_map_relos(struct bpf_object *obj,
6690 					 Elf64_Shdr *shdr, Elf_Data *data)
6691 {
6692 	const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
6693 	int i, j, nrels, new_sz;
6694 	const struct btf_var_secinfo *vi = NULL;
6695 	const struct btf_type *sec, *var, *def;
6696 	struct bpf_map *map = NULL, *targ_map = NULL;
6697 	struct bpf_program *targ_prog = NULL;
6698 	bool is_prog_array, is_map_in_map;
6699 	const struct btf_member *member;
6700 	const char *name, *mname, *type;
6701 	unsigned int moff;
6702 	Elf64_Sym *sym;
6703 	Elf64_Rel *rel;
6704 	void *tmp;
6705 
6706 	if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
6707 		return -EINVAL;
6708 	sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
6709 	if (!sec)
6710 		return -EINVAL;
6711 
6712 	nrels = shdr->sh_size / shdr->sh_entsize;
6713 	for (i = 0; i < nrels; i++) {
6714 		rel = elf_rel_by_idx(data, i);
6715 		if (!rel) {
6716 			pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
6717 			return -LIBBPF_ERRNO__FORMAT;
6718 		}
6719 
6720 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
6721 		if (!sym) {
6722 			pr_warn(".maps relo #%d: symbol %zx not found\n",
6723 				i, (size_t)ELF64_R_SYM(rel->r_info));
6724 			return -LIBBPF_ERRNO__FORMAT;
6725 		}
6726 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
6727 
6728 		pr_debug(".maps relo #%d: for %zd value %zd rel->r_offset %zu name %d ('%s')\n",
6729 			 i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
6730 			 (size_t)rel->r_offset, sym->st_name, name);
6731 
6732 		for (j = 0; j < obj->nr_maps; j++) {
6733 			map = &obj->maps[j];
6734 			if (map->sec_idx != obj->efile.btf_maps_shndx)
6735 				continue;
6736 
6737 			vi = btf_var_secinfos(sec) + map->btf_var_idx;
6738 			if (vi->offset <= rel->r_offset &&
6739 			    rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size)
6740 				break;
6741 		}
6742 		if (j == obj->nr_maps) {
6743 			pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
6744 				i, name, (size_t)rel->r_offset);
6745 			return -EINVAL;
6746 		}
6747 
6748 		is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
6749 		is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
6750 		type = is_map_in_map ? "map" : "prog";
6751 		if (is_map_in_map) {
6752 			if (sym->st_shndx != obj->efile.btf_maps_shndx) {
6753 				pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
6754 					i, name);
6755 				return -LIBBPF_ERRNO__RELOC;
6756 			}
6757 			if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
6758 			    map->def.key_size != sizeof(int)) {
6759 				pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
6760 					i, map->name, sizeof(int));
6761 				return -EINVAL;
6762 			}
6763 			targ_map = bpf_object__find_map_by_name(obj, name);
6764 			if (!targ_map) {
6765 				pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
6766 					i, name);
6767 				return -ESRCH;
6768 			}
6769 		} else if (is_prog_array) {
6770 			targ_prog = bpf_object__find_program_by_name(obj, name);
6771 			if (!targ_prog) {
6772 				pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
6773 					i, name);
6774 				return -ESRCH;
6775 			}
6776 			if (targ_prog->sec_idx != sym->st_shndx ||
6777 			    targ_prog->sec_insn_off * 8 != sym->st_value ||
6778 			    prog_is_subprog(obj, targ_prog)) {
6779 				pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
6780 					i, name);
6781 				return -LIBBPF_ERRNO__RELOC;
6782 			}
6783 		} else {
6784 			return -EINVAL;
6785 		}
6786 
6787 		var = btf__type_by_id(obj->btf, vi->type);
6788 		def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
6789 		if (btf_vlen(def) == 0)
6790 			return -EINVAL;
6791 		member = btf_members(def) + btf_vlen(def) - 1;
6792 		mname = btf__name_by_offset(obj->btf, member->name_off);
6793 		if (strcmp(mname, "values"))
6794 			return -EINVAL;
6795 
6796 		moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
6797 		if (rel->r_offset - vi->offset < moff)
6798 			return -EINVAL;
6799 
6800 		moff = rel->r_offset - vi->offset - moff;
6801 		/* here we use BPF pointer size, which is always 64 bit, as we
6802 		 * are parsing ELF that was built for BPF target
6803 		 */
6804 		if (moff % bpf_ptr_sz)
6805 			return -EINVAL;
6806 		moff /= bpf_ptr_sz;
6807 		if (moff >= map->init_slots_sz) {
6808 			new_sz = moff + 1;
6809 			tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
6810 			if (!tmp)
6811 				return -ENOMEM;
6812 			map->init_slots = tmp;
6813 			memset(map->init_slots + map->init_slots_sz, 0,
6814 			       (new_sz - map->init_slots_sz) * host_ptr_sz);
6815 			map->init_slots_sz = new_sz;
6816 		}
6817 		map->init_slots[moff] = is_map_in_map ? (void *)targ_map : (void *)targ_prog;
6818 
6819 		pr_debug(".maps relo #%d: map '%s' slot [%d] points to %s '%s'\n",
6820 			 i, map->name, moff, type, name);
6821 	}
6822 
6823 	return 0;
6824 }
6825 
6826 static int bpf_object__collect_relos(struct bpf_object *obj)
6827 {
6828 	int i, err;
6829 
6830 	for (i = 0; i < obj->efile.sec_cnt; i++) {
6831 		struct elf_sec_desc *sec_desc = &obj->efile.secs[i];
6832 		Elf64_Shdr *shdr;
6833 		Elf_Data *data;
6834 		int idx;
6835 
6836 		if (sec_desc->sec_type != SEC_RELO)
6837 			continue;
6838 
6839 		shdr = sec_desc->shdr;
6840 		data = sec_desc->data;
6841 		idx = shdr->sh_info;
6842 
6843 		if (shdr->sh_type != SHT_REL) {
6844 			pr_warn("internal error at %d\n", __LINE__);
6845 			return -LIBBPF_ERRNO__INTERNAL;
6846 		}
6847 
6848 		if (idx == obj->efile.st_ops_shndx)
6849 			err = bpf_object__collect_st_ops_relos(obj, shdr, data);
6850 		else if (idx == obj->efile.btf_maps_shndx)
6851 			err = bpf_object__collect_map_relos(obj, shdr, data);
6852 		else
6853 			err = bpf_object__collect_prog_relos(obj, shdr, data);
6854 		if (err)
6855 			return err;
6856 	}
6857 
6858 	bpf_object__sort_relos(obj);
6859 	return 0;
6860 }
6861 
6862 static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
6863 {
6864 	if (BPF_CLASS(insn->code) == BPF_JMP &&
6865 	    BPF_OP(insn->code) == BPF_CALL &&
6866 	    BPF_SRC(insn->code) == BPF_K &&
6867 	    insn->src_reg == 0 &&
6868 	    insn->dst_reg == 0) {
6869 		    *func_id = insn->imm;
6870 		    return true;
6871 	}
6872 	return false;
6873 }
6874 
6875 static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
6876 {
6877 	struct bpf_insn *insn = prog->insns;
6878 	enum bpf_func_id func_id;
6879 	int i;
6880 
6881 	if (obj->gen_loader)
6882 		return 0;
6883 
6884 	for (i = 0; i < prog->insns_cnt; i++, insn++) {
6885 		if (!insn_is_helper_call(insn, &func_id))
6886 			continue;
6887 
6888 		/* on kernels that don't yet support
6889 		 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
6890 		 * to bpf_probe_read() which works well for old kernels
6891 		 */
6892 		switch (func_id) {
6893 		case BPF_FUNC_probe_read_kernel:
6894 		case BPF_FUNC_probe_read_user:
6895 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6896 				insn->imm = BPF_FUNC_probe_read;
6897 			break;
6898 		case BPF_FUNC_probe_read_kernel_str:
6899 		case BPF_FUNC_probe_read_user_str:
6900 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6901 				insn->imm = BPF_FUNC_probe_read_str;
6902 			break;
6903 		default:
6904 			break;
6905 		}
6906 	}
6907 	return 0;
6908 }
6909 
6910 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
6911 				     int *btf_obj_fd, int *btf_type_id);
6912 
6913 /* this is called as prog->sec_def->prog_prepare_load_fn for libbpf-supported sec_defs */
6914 static int libbpf_prepare_prog_load(struct bpf_program *prog,
6915 				    struct bpf_prog_load_opts *opts, long cookie)
6916 {
6917 	enum sec_def_flags def = cookie;
6918 
6919 	/* old kernels might not support specifying expected_attach_type */
6920 	if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
6921 		opts->expected_attach_type = 0;
6922 
6923 	if (def & SEC_SLEEPABLE)
6924 		opts->prog_flags |= BPF_F_SLEEPABLE;
6925 
6926 	if (prog->type == BPF_PROG_TYPE_XDP && (def & SEC_XDP_FRAGS))
6927 		opts->prog_flags |= BPF_F_XDP_HAS_FRAGS;
6928 
6929 	if (def & SEC_DEPRECATED) {
6930 		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",
6931 			prog->sec_name);
6932 	}
6933 
6934 	if ((def & SEC_ATTACH_BTF) && !prog->attach_btf_id) {
6935 		int btf_obj_fd = 0, btf_type_id = 0, err;
6936 		const char *attach_name;
6937 
6938 		attach_name = strchr(prog->sec_name, '/');
6939 		if (!attach_name) {
6940 			/* if BPF program is annotated with just SEC("fentry")
6941 			 * (or similar) without declaratively specifying
6942 			 * target, then it is expected that target will be
6943 			 * specified with bpf_program__set_attach_target() at
6944 			 * runtime before BPF object load step. If not, then
6945 			 * there is nothing to load into the kernel as BPF
6946 			 * verifier won't be able to validate BPF program
6947 			 * correctness anyways.
6948 			 */
6949 			pr_warn("prog '%s': no BTF-based attach target is specified, use bpf_program__set_attach_target()\n",
6950 				prog->name);
6951 			return -EINVAL;
6952 		}
6953 		attach_name++; /* skip over / */
6954 
6955 		err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
6956 		if (err)
6957 			return err;
6958 
6959 		/* cache resolved BTF FD and BTF type ID in the prog */
6960 		prog->attach_btf_obj_fd = btf_obj_fd;
6961 		prog->attach_btf_id = btf_type_id;
6962 
6963 		/* but by now libbpf common logic is not utilizing
6964 		 * prog->atach_btf_obj_fd/prog->attach_btf_id anymore because
6965 		 * this callback is called after opts were populated by
6966 		 * libbpf, so this callback has to update opts explicitly here
6967 		 */
6968 		opts->attach_btf_obj_fd = btf_obj_fd;
6969 		opts->attach_btf_id = btf_type_id;
6970 	}
6971 	return 0;
6972 }
6973 
6974 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz);
6975 
6976 static int bpf_object_load_prog_instance(struct bpf_object *obj, struct bpf_program *prog,
6977 					 struct bpf_insn *insns, int insns_cnt,
6978 					 const char *license, __u32 kern_version,
6979 					 int *prog_fd)
6980 {
6981 	LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
6982 	const char *prog_name = NULL;
6983 	char *cp, errmsg[STRERR_BUFSIZE];
6984 	size_t log_buf_size = 0;
6985 	char *log_buf = NULL, *tmp;
6986 	int btf_fd, ret, err;
6987 	bool own_log_buf = true;
6988 	__u32 log_level = prog->log_level;
6989 
6990 	if (prog->type == BPF_PROG_TYPE_UNSPEC) {
6991 		/*
6992 		 * The program type must be set.  Most likely we couldn't find a proper
6993 		 * section definition at load time, and thus we didn't infer the type.
6994 		 */
6995 		pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
6996 			prog->name, prog->sec_name);
6997 		return -EINVAL;
6998 	}
6999 
7000 	if (!insns || !insns_cnt)
7001 		return -EINVAL;
7002 
7003 	load_attr.expected_attach_type = prog->expected_attach_type;
7004 	if (kernel_supports(obj, FEAT_PROG_NAME))
7005 		prog_name = prog->name;
7006 	load_attr.attach_prog_fd = prog->attach_prog_fd;
7007 	load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
7008 	load_attr.attach_btf_id = prog->attach_btf_id;
7009 	load_attr.kern_version = kern_version;
7010 	load_attr.prog_ifindex = prog->prog_ifindex;
7011 
7012 	/* specify func_info/line_info only if kernel supports them */
7013 	btf_fd = bpf_object__btf_fd(obj);
7014 	if (btf_fd >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
7015 		load_attr.prog_btf_fd = btf_fd;
7016 		load_attr.func_info = prog->func_info;
7017 		load_attr.func_info_rec_size = prog->func_info_rec_size;
7018 		load_attr.func_info_cnt = prog->func_info_cnt;
7019 		load_attr.line_info = prog->line_info;
7020 		load_attr.line_info_rec_size = prog->line_info_rec_size;
7021 		load_attr.line_info_cnt = prog->line_info_cnt;
7022 	}
7023 	load_attr.log_level = log_level;
7024 	load_attr.prog_flags = prog->prog_flags;
7025 	load_attr.fd_array = obj->fd_array;
7026 
7027 	/* adjust load_attr if sec_def provides custom preload callback */
7028 	if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
7029 		err = prog->sec_def->prog_prepare_load_fn(prog, &load_attr, prog->sec_def->cookie);
7030 		if (err < 0) {
7031 			pr_warn("prog '%s': failed to prepare load attributes: %d\n",
7032 				prog->name, err);
7033 			return err;
7034 		}
7035 		insns = prog->insns;
7036 		insns_cnt = prog->insns_cnt;
7037 	}
7038 
7039 	if (obj->gen_loader) {
7040 		bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
7041 				   license, insns, insns_cnt, &load_attr,
7042 				   prog - obj->programs);
7043 		*prog_fd = -1;
7044 		return 0;
7045 	}
7046 
7047 retry_load:
7048 	/* if log_level is zero, we don't request logs initially even if
7049 	 * custom log_buf is specified; if the program load fails, then we'll
7050 	 * bump log_level to 1 and use either custom log_buf or we'll allocate
7051 	 * our own and retry the load to get details on what failed
7052 	 */
7053 	if (log_level) {
7054 		if (prog->log_buf) {
7055 			log_buf = prog->log_buf;
7056 			log_buf_size = prog->log_size;
7057 			own_log_buf = false;
7058 		} else if (obj->log_buf) {
7059 			log_buf = obj->log_buf;
7060 			log_buf_size = obj->log_size;
7061 			own_log_buf = false;
7062 		} else {
7063 			log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
7064 			tmp = realloc(log_buf, log_buf_size);
7065 			if (!tmp) {
7066 				ret = -ENOMEM;
7067 				goto out;
7068 			}
7069 			log_buf = tmp;
7070 			log_buf[0] = '\0';
7071 			own_log_buf = true;
7072 		}
7073 	}
7074 
7075 	load_attr.log_buf = log_buf;
7076 	load_attr.log_size = log_buf_size;
7077 	load_attr.log_level = log_level;
7078 
7079 	ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
7080 	if (ret >= 0) {
7081 		if (log_level && own_log_buf) {
7082 			pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
7083 				 prog->name, log_buf);
7084 		}
7085 
7086 		if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
7087 			struct bpf_map *map;
7088 			int i;
7089 
7090 			for (i = 0; i < obj->nr_maps; i++) {
7091 				map = &prog->obj->maps[i];
7092 				if (map->libbpf_type != LIBBPF_MAP_RODATA)
7093 					continue;
7094 
7095 				if (bpf_prog_bind_map(ret, bpf_map__fd(map), NULL)) {
7096 					cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
7097 					pr_warn("prog '%s': failed to bind map '%s': %s\n",
7098 						prog->name, map->real_name, cp);
7099 					/* Don't fail hard if can't bind rodata. */
7100 				}
7101 			}
7102 		}
7103 
7104 		*prog_fd = ret;
7105 		ret = 0;
7106 		goto out;
7107 	}
7108 
7109 	if (log_level == 0) {
7110 		log_level = 1;
7111 		goto retry_load;
7112 	}
7113 	/* On ENOSPC, increase log buffer size and retry, unless custom
7114 	 * log_buf is specified.
7115 	 * Be careful to not overflow u32, though. Kernel's log buf size limit
7116 	 * isn't part of UAPI so it can always be bumped to full 4GB. So don't
7117 	 * multiply by 2 unless we are sure we'll fit within 32 bits.
7118 	 * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
7119 	 */
7120 	if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
7121 		goto retry_load;
7122 
7123 	ret = -errno;
7124 
7125 	/* post-process verifier log to improve error descriptions */
7126 	fixup_verifier_log(prog, log_buf, log_buf_size);
7127 
7128 	cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
7129 	pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, cp);
7130 	pr_perm_msg(ret);
7131 
7132 	if (own_log_buf && log_buf && log_buf[0] != '\0') {
7133 		pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
7134 			prog->name, log_buf);
7135 	}
7136 
7137 out:
7138 	if (own_log_buf)
7139 		free(log_buf);
7140 	return ret;
7141 }
7142 
7143 static char *find_prev_line(char *buf, char *cur)
7144 {
7145 	char *p;
7146 
7147 	if (cur == buf) /* end of a log buf */
7148 		return NULL;
7149 
7150 	p = cur - 1;
7151 	while (p - 1 >= buf && *(p - 1) != '\n')
7152 		p--;
7153 
7154 	return p;
7155 }
7156 
7157 static void patch_log(char *buf, size_t buf_sz, size_t log_sz,
7158 		      char *orig, size_t orig_sz, const char *patch)
7159 {
7160 	/* size of the remaining log content to the right from the to-be-replaced part */
7161 	size_t rem_sz = (buf + log_sz) - (orig + orig_sz);
7162 	size_t patch_sz = strlen(patch);
7163 
7164 	if (patch_sz != orig_sz) {
7165 		/* If patch line(s) are longer than original piece of verifier log,
7166 		 * shift log contents by (patch_sz - orig_sz) bytes to the right
7167 		 * starting from after to-be-replaced part of the log.
7168 		 *
7169 		 * If patch line(s) are shorter than original piece of verifier log,
7170 		 * shift log contents by (orig_sz - patch_sz) bytes to the left
7171 		 * starting from after to-be-replaced part of the log
7172 		 *
7173 		 * We need to be careful about not overflowing available
7174 		 * buf_sz capacity. If that's the case, we'll truncate the end
7175 		 * of the original log, as necessary.
7176 		 */
7177 		if (patch_sz > orig_sz) {
7178 			if (orig + patch_sz >= buf + buf_sz) {
7179 				/* patch is big enough to cover remaining space completely */
7180 				patch_sz -= (orig + patch_sz) - (buf + buf_sz) + 1;
7181 				rem_sz = 0;
7182 			} else if (patch_sz - orig_sz > buf_sz - log_sz) {
7183 				/* patch causes part of remaining log to be truncated */
7184 				rem_sz -= (patch_sz - orig_sz) - (buf_sz - log_sz);
7185 			}
7186 		}
7187 		/* shift remaining log to the right by calculated amount */
7188 		memmove(orig + patch_sz, orig + orig_sz, rem_sz);
7189 	}
7190 
7191 	memcpy(orig, patch, patch_sz);
7192 }
7193 
7194 static void fixup_log_failed_core_relo(struct bpf_program *prog,
7195 				       char *buf, size_t buf_sz, size_t log_sz,
7196 				       char *line1, char *line2, char *line3)
7197 {
7198 	/* Expected log for failed and not properly guarded CO-RE relocation:
7199 	 * line1 -> 123: (85) call unknown#195896080
7200 	 * line2 -> invalid func unknown#195896080
7201 	 * line3 -> <anything else or end of buffer>
7202 	 *
7203 	 * "123" is the index of the instruction that was poisoned. We extract
7204 	 * instruction index to find corresponding CO-RE relocation and
7205 	 * replace this part of the log with more relevant information about
7206 	 * failed CO-RE relocation.
7207 	 */
7208 	const struct bpf_core_relo *relo;
7209 	struct bpf_core_spec spec;
7210 	char patch[512], spec_buf[256];
7211 	int insn_idx, err, spec_len;
7212 
7213 	if (sscanf(line1, "%d: (%*d) call unknown#195896080\n", &insn_idx) != 1)
7214 		return;
7215 
7216 	relo = find_relo_core(prog, insn_idx);
7217 	if (!relo)
7218 		return;
7219 
7220 	err = bpf_core_parse_spec(prog->name, prog->obj->btf, relo, &spec);
7221 	if (err)
7222 		return;
7223 
7224 	spec_len = bpf_core_format_spec(spec_buf, sizeof(spec_buf), &spec);
7225 	snprintf(patch, sizeof(patch),
7226 		 "%d: <invalid CO-RE relocation>\n"
7227 		 "failed to resolve CO-RE relocation %s%s\n",
7228 		 insn_idx, spec_buf, spec_len >= sizeof(spec_buf) ? "..." : "");
7229 
7230 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7231 }
7232 
7233 static void fixup_log_missing_map_load(struct bpf_program *prog,
7234 				       char *buf, size_t buf_sz, size_t log_sz,
7235 				       char *line1, char *line2, char *line3)
7236 {
7237 	/* Expected log for failed and not properly guarded CO-RE relocation:
7238 	 * line1 -> 123: (85) call unknown#2001000345
7239 	 * line2 -> invalid func unknown#2001000345
7240 	 * line3 -> <anything else or end of buffer>
7241 	 *
7242 	 * "123" is the index of the instruction that was poisoned.
7243 	 * "345" in "2001000345" are map index in obj->maps to fetch map name.
7244 	 */
7245 	struct bpf_object *obj = prog->obj;
7246 	const struct bpf_map *map;
7247 	int insn_idx, map_idx;
7248 	char patch[128];
7249 
7250 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &map_idx) != 2)
7251 		return;
7252 
7253 	map_idx -= MAP_LDIMM64_POISON_BASE;
7254 	if (map_idx < 0 || map_idx >= obj->nr_maps)
7255 		return;
7256 	map = &obj->maps[map_idx];
7257 
7258 	snprintf(patch, sizeof(patch),
7259 		 "%d: <invalid BPF map reference>\n"
7260 		 "BPF map '%s' is referenced but wasn't created\n",
7261 		 insn_idx, map->name);
7262 
7263 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7264 }
7265 
7266 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz)
7267 {
7268 	/* look for familiar error patterns in last N lines of the log */
7269 	const size_t max_last_line_cnt = 10;
7270 	char *prev_line, *cur_line, *next_line;
7271 	size_t log_sz;
7272 	int i;
7273 
7274 	if (!buf)
7275 		return;
7276 
7277 	log_sz = strlen(buf) + 1;
7278 	next_line = buf + log_sz - 1;
7279 
7280 	for (i = 0; i < max_last_line_cnt; i++, next_line = cur_line) {
7281 		cur_line = find_prev_line(buf, next_line);
7282 		if (!cur_line)
7283 			return;
7284 
7285 		/* failed CO-RE relocation case */
7286 		if (str_has_pfx(cur_line, "invalid func unknown#195896080\n")) {
7287 			prev_line = find_prev_line(buf, cur_line);
7288 			if (!prev_line)
7289 				continue;
7290 
7291 			fixup_log_failed_core_relo(prog, buf, buf_sz, log_sz,
7292 						   prev_line, cur_line, next_line);
7293 			return;
7294 		} else if (str_has_pfx(cur_line, "invalid func unknown#"MAP_LDIMM64_POISON_PFX)) {
7295 			prev_line = find_prev_line(buf, cur_line);
7296 			if (!prev_line)
7297 				continue;
7298 
7299 			fixup_log_missing_map_load(prog, buf, buf_sz, log_sz,
7300 						   prev_line, cur_line, next_line);
7301 			return;
7302 		}
7303 	}
7304 }
7305 
7306 static int bpf_program_record_relos(struct bpf_program *prog)
7307 {
7308 	struct bpf_object *obj = prog->obj;
7309 	int i;
7310 
7311 	for (i = 0; i < prog->nr_reloc; i++) {
7312 		struct reloc_desc *relo = &prog->reloc_desc[i];
7313 		struct extern_desc *ext = &obj->externs[relo->sym_off];
7314 
7315 		switch (relo->type) {
7316 		case RELO_EXTERN_VAR:
7317 			if (ext->type != EXT_KSYM)
7318 				continue;
7319 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7320 					       ext->is_weak, !ext->ksym.type_id,
7321 					       BTF_KIND_VAR, relo->insn_idx);
7322 			break;
7323 		case RELO_EXTERN_FUNC:
7324 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7325 					       ext->is_weak, false, BTF_KIND_FUNC,
7326 					       relo->insn_idx);
7327 			break;
7328 		case RELO_CORE: {
7329 			struct bpf_core_relo cr = {
7330 				.insn_off = relo->insn_idx * 8,
7331 				.type_id = relo->core_relo->type_id,
7332 				.access_str_off = relo->core_relo->access_str_off,
7333 				.kind = relo->core_relo->kind,
7334 			};
7335 
7336 			bpf_gen__record_relo_core(obj->gen_loader, &cr);
7337 			break;
7338 		}
7339 		default:
7340 			continue;
7341 		}
7342 	}
7343 	return 0;
7344 }
7345 
7346 static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
7347 				const char *license, __u32 kern_ver)
7348 {
7349 	int err = 0, fd, i;
7350 
7351 	if (obj->loaded) {
7352 		pr_warn("prog '%s': can't load after object was loaded\n", prog->name);
7353 		return libbpf_err(-EINVAL);
7354 	}
7355 
7356 	if (prog->instances.nr < 0 || !prog->instances.fds) {
7357 		if (prog->preprocessor) {
7358 			pr_warn("Internal error: can't load program '%s'\n",
7359 				prog->name);
7360 			return libbpf_err(-LIBBPF_ERRNO__INTERNAL);
7361 		}
7362 
7363 		prog->instances.fds = malloc(sizeof(int));
7364 		if (!prog->instances.fds) {
7365 			pr_warn("Not enough memory for BPF fds\n");
7366 			return libbpf_err(-ENOMEM);
7367 		}
7368 		prog->instances.nr = 1;
7369 		prog->instances.fds[0] = -1;
7370 	}
7371 
7372 	if (!prog->preprocessor) {
7373 		if (prog->instances.nr != 1) {
7374 			pr_warn("prog '%s': inconsistent nr(%d) != 1\n",
7375 				prog->name, prog->instances.nr);
7376 		}
7377 		if (obj->gen_loader)
7378 			bpf_program_record_relos(prog);
7379 		err = bpf_object_load_prog_instance(obj, prog,
7380 						    prog->insns, prog->insns_cnt,
7381 						    license, kern_ver, &fd);
7382 		if (!err)
7383 			prog->instances.fds[0] = fd;
7384 		goto out;
7385 	}
7386 
7387 	for (i = 0; i < prog->instances.nr; i++) {
7388 		struct bpf_prog_prep_result result;
7389 		bpf_program_prep_t preprocessor = prog->preprocessor;
7390 
7391 		memset(&result, 0, sizeof(result));
7392 		err = preprocessor(prog, i, prog->insns,
7393 				   prog->insns_cnt, &result);
7394 		if (err) {
7395 			pr_warn("Preprocessing the %dth instance of program '%s' failed\n",
7396 				i, prog->name);
7397 			goto out;
7398 		}
7399 
7400 		if (!result.new_insn_ptr || !result.new_insn_cnt) {
7401 			pr_debug("Skip loading the %dth instance of program '%s'\n",
7402 				 i, prog->name);
7403 			prog->instances.fds[i] = -1;
7404 			if (result.pfd)
7405 				*result.pfd = -1;
7406 			continue;
7407 		}
7408 
7409 		err = bpf_object_load_prog_instance(obj, prog,
7410 						    result.new_insn_ptr, result.new_insn_cnt,
7411 						    license, kern_ver, &fd);
7412 		if (err) {
7413 			pr_warn("Loading the %dth instance of program '%s' failed\n",
7414 				i, prog->name);
7415 			goto out;
7416 		}
7417 
7418 		if (result.pfd)
7419 			*result.pfd = fd;
7420 		prog->instances.fds[i] = fd;
7421 	}
7422 out:
7423 	if (err)
7424 		pr_warn("failed to load program '%s'\n", prog->name);
7425 	return libbpf_err(err);
7426 }
7427 
7428 int bpf_program__load(struct bpf_program *prog, const char *license, __u32 kern_ver)
7429 {
7430 	return bpf_object_load_prog(prog->obj, prog, license, kern_ver);
7431 }
7432 
7433 static int
7434 bpf_object__load_progs(struct bpf_object *obj, int log_level)
7435 {
7436 	struct bpf_program *prog;
7437 	size_t i;
7438 	int err;
7439 
7440 	for (i = 0; i < obj->nr_programs; i++) {
7441 		prog = &obj->programs[i];
7442 		err = bpf_object__sanitize_prog(obj, prog);
7443 		if (err)
7444 			return err;
7445 	}
7446 
7447 	for (i = 0; i < obj->nr_programs; i++) {
7448 		prog = &obj->programs[i];
7449 		if (prog_is_subprog(obj, prog))
7450 			continue;
7451 		if (!prog->autoload) {
7452 			pr_debug("prog '%s': skipped loading\n", prog->name);
7453 			continue;
7454 		}
7455 		prog->log_level |= log_level;
7456 		err = bpf_object_load_prog(obj, prog, obj->license, obj->kern_version);
7457 		if (err)
7458 			return err;
7459 	}
7460 
7461 	bpf_object__free_relocs(obj);
7462 	return 0;
7463 }
7464 
7465 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
7466 
7467 static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
7468 {
7469 	struct bpf_program *prog;
7470 	int err;
7471 
7472 	bpf_object__for_each_program(prog, obj) {
7473 		prog->sec_def = find_sec_def(prog->sec_name);
7474 		if (!prog->sec_def) {
7475 			/* couldn't guess, but user might manually specify */
7476 			pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
7477 				prog->name, prog->sec_name);
7478 			continue;
7479 		}
7480 
7481 		prog->type = prog->sec_def->prog_type;
7482 		prog->expected_attach_type = prog->sec_def->expected_attach_type;
7483 
7484 #pragma GCC diagnostic push
7485 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
7486 		if (prog->sec_def->prog_type == BPF_PROG_TYPE_TRACING ||
7487 		    prog->sec_def->prog_type == BPF_PROG_TYPE_EXT)
7488 			prog->attach_prog_fd = OPTS_GET(opts, attach_prog_fd, 0);
7489 #pragma GCC diagnostic pop
7490 
7491 		/* sec_def can have custom callback which should be called
7492 		 * after bpf_program is initialized to adjust its properties
7493 		 */
7494 		if (prog->sec_def->prog_setup_fn) {
7495 			err = prog->sec_def->prog_setup_fn(prog, prog->sec_def->cookie);
7496 			if (err < 0) {
7497 				pr_warn("prog '%s': failed to initialize: %d\n",
7498 					prog->name, err);
7499 				return err;
7500 			}
7501 		}
7502 	}
7503 
7504 	return 0;
7505 }
7506 
7507 static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
7508 					  const struct bpf_object_open_opts *opts)
7509 {
7510 	const char *obj_name, *kconfig, *btf_tmp_path;
7511 	struct bpf_object *obj;
7512 	char tmp_name[64];
7513 	int err;
7514 	char *log_buf;
7515 	size_t log_size;
7516 	__u32 log_level;
7517 
7518 	if (elf_version(EV_CURRENT) == EV_NONE) {
7519 		pr_warn("failed to init libelf for %s\n",
7520 			path ? : "(mem buf)");
7521 		return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
7522 	}
7523 
7524 	if (!OPTS_VALID(opts, bpf_object_open_opts))
7525 		return ERR_PTR(-EINVAL);
7526 
7527 	obj_name = OPTS_GET(opts, object_name, NULL);
7528 	if (obj_buf) {
7529 		if (!obj_name) {
7530 			snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
7531 				 (unsigned long)obj_buf,
7532 				 (unsigned long)obj_buf_sz);
7533 			obj_name = tmp_name;
7534 		}
7535 		path = obj_name;
7536 		pr_debug("loading object '%s' from buffer\n", obj_name);
7537 	}
7538 
7539 	log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
7540 	log_size = OPTS_GET(opts, kernel_log_size, 0);
7541 	log_level = OPTS_GET(opts, kernel_log_level, 0);
7542 	if (log_size > UINT_MAX)
7543 		return ERR_PTR(-EINVAL);
7544 	if (log_size && !log_buf)
7545 		return ERR_PTR(-EINVAL);
7546 
7547 	obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
7548 	if (IS_ERR(obj))
7549 		return obj;
7550 
7551 	obj->log_buf = log_buf;
7552 	obj->log_size = log_size;
7553 	obj->log_level = log_level;
7554 
7555 	btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
7556 	if (btf_tmp_path) {
7557 		if (strlen(btf_tmp_path) >= PATH_MAX) {
7558 			err = -ENAMETOOLONG;
7559 			goto out;
7560 		}
7561 		obj->btf_custom_path = strdup(btf_tmp_path);
7562 		if (!obj->btf_custom_path) {
7563 			err = -ENOMEM;
7564 			goto out;
7565 		}
7566 	}
7567 
7568 	kconfig = OPTS_GET(opts, kconfig, NULL);
7569 	if (kconfig) {
7570 		obj->kconfig = strdup(kconfig);
7571 		if (!obj->kconfig) {
7572 			err = -ENOMEM;
7573 			goto out;
7574 		}
7575 	}
7576 
7577 	err = bpf_object__elf_init(obj);
7578 	err = err ? : bpf_object__check_endianness(obj);
7579 	err = err ? : bpf_object__elf_collect(obj);
7580 	err = err ? : bpf_object__collect_externs(obj);
7581 	err = err ? : bpf_object__finalize_btf(obj);
7582 	err = err ? : bpf_object__init_maps(obj, opts);
7583 	err = err ? : bpf_object_init_progs(obj, opts);
7584 	err = err ? : bpf_object__collect_relos(obj);
7585 	if (err)
7586 		goto out;
7587 
7588 	bpf_object__elf_finish(obj);
7589 
7590 	return obj;
7591 out:
7592 	bpf_object__close(obj);
7593 	return ERR_PTR(err);
7594 }
7595 
7596 static struct bpf_object *
7597 __bpf_object__open_xattr(struct bpf_object_open_attr *attr, int flags)
7598 {
7599 	DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
7600 		.relaxed_maps = flags & MAPS_RELAX_COMPAT,
7601 	);
7602 
7603 	/* param validation */
7604 	if (!attr->file)
7605 		return NULL;
7606 
7607 	pr_debug("loading %s\n", attr->file);
7608 	return bpf_object_open(attr->file, NULL, 0, &opts);
7609 }
7610 
7611 struct bpf_object *bpf_object__open_xattr(struct bpf_object_open_attr *attr)
7612 {
7613 	return libbpf_ptr(__bpf_object__open_xattr(attr, 0));
7614 }
7615 
7616 struct bpf_object *bpf_object__open(const char *path)
7617 {
7618 	struct bpf_object_open_attr attr = {
7619 		.file		= path,
7620 		.prog_type	= BPF_PROG_TYPE_UNSPEC,
7621 	};
7622 
7623 	return libbpf_ptr(__bpf_object__open_xattr(&attr, 0));
7624 }
7625 
7626 struct bpf_object *
7627 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
7628 {
7629 	if (!path)
7630 		return libbpf_err_ptr(-EINVAL);
7631 
7632 	pr_debug("loading %s\n", path);
7633 
7634 	return libbpf_ptr(bpf_object_open(path, NULL, 0, opts));
7635 }
7636 
7637 struct bpf_object *
7638 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
7639 		     const struct bpf_object_open_opts *opts)
7640 {
7641 	if (!obj_buf || obj_buf_sz == 0)
7642 		return libbpf_err_ptr(-EINVAL);
7643 
7644 	return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, opts));
7645 }
7646 
7647 struct bpf_object *
7648 bpf_object__open_buffer(const void *obj_buf, size_t obj_buf_sz,
7649 			const char *name)
7650 {
7651 	DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
7652 		.object_name = name,
7653 		/* wrong default, but backwards-compatible */
7654 		.relaxed_maps = true,
7655 	);
7656 
7657 	/* returning NULL is wrong, but backwards-compatible */
7658 	if (!obj_buf || obj_buf_sz == 0)
7659 		return errno = EINVAL, NULL;
7660 
7661 	return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, &opts));
7662 }
7663 
7664 static int bpf_object_unload(struct bpf_object *obj)
7665 {
7666 	size_t i;
7667 
7668 	if (!obj)
7669 		return libbpf_err(-EINVAL);
7670 
7671 	for (i = 0; i < obj->nr_maps; i++) {
7672 		zclose(obj->maps[i].fd);
7673 		if (obj->maps[i].st_ops)
7674 			zfree(&obj->maps[i].st_ops->kern_vdata);
7675 	}
7676 
7677 	for (i = 0; i < obj->nr_programs; i++)
7678 		bpf_program__unload(&obj->programs[i]);
7679 
7680 	return 0;
7681 }
7682 
7683 int bpf_object__unload(struct bpf_object *obj) __attribute__((alias("bpf_object_unload")));
7684 
7685 static int bpf_object__sanitize_maps(struct bpf_object *obj)
7686 {
7687 	struct bpf_map *m;
7688 
7689 	bpf_object__for_each_map(m, obj) {
7690 		if (!bpf_map__is_internal(m))
7691 			continue;
7692 		if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
7693 			m->def.map_flags ^= BPF_F_MMAPABLE;
7694 	}
7695 
7696 	return 0;
7697 }
7698 
7699 int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
7700 {
7701 	char sym_type, sym_name[500];
7702 	unsigned long long sym_addr;
7703 	int ret, err = 0;
7704 	FILE *f;
7705 
7706 	f = fopen("/proc/kallsyms", "r");
7707 	if (!f) {
7708 		err = -errno;
7709 		pr_warn("failed to open /proc/kallsyms: %d\n", err);
7710 		return err;
7711 	}
7712 
7713 	while (true) {
7714 		ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
7715 			     &sym_addr, &sym_type, sym_name);
7716 		if (ret == EOF && feof(f))
7717 			break;
7718 		if (ret != 3) {
7719 			pr_warn("failed to read kallsyms entry: %d\n", ret);
7720 			err = -EINVAL;
7721 			break;
7722 		}
7723 
7724 		err = cb(sym_addr, sym_type, sym_name, ctx);
7725 		if (err)
7726 			break;
7727 	}
7728 
7729 	fclose(f);
7730 	return err;
7731 }
7732 
7733 static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
7734 		       const char *sym_name, void *ctx)
7735 {
7736 	struct bpf_object *obj = ctx;
7737 	const struct btf_type *t;
7738 	struct extern_desc *ext;
7739 
7740 	ext = find_extern_by_name(obj, sym_name);
7741 	if (!ext || ext->type != EXT_KSYM)
7742 		return 0;
7743 
7744 	t = btf__type_by_id(obj->btf, ext->btf_id);
7745 	if (!btf_is_var(t))
7746 		return 0;
7747 
7748 	if (ext->is_set && ext->ksym.addr != sym_addr) {
7749 		pr_warn("extern (ksym) '%s' resolution is ambiguous: 0x%llx or 0x%llx\n",
7750 			sym_name, ext->ksym.addr, sym_addr);
7751 		return -EINVAL;
7752 	}
7753 	if (!ext->is_set) {
7754 		ext->is_set = true;
7755 		ext->ksym.addr = sym_addr;
7756 		pr_debug("extern (ksym) %s=0x%llx\n", sym_name, sym_addr);
7757 	}
7758 	return 0;
7759 }
7760 
7761 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
7762 {
7763 	return libbpf_kallsyms_parse(kallsyms_cb, obj);
7764 }
7765 
7766 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
7767 			    __u16 kind, struct btf **res_btf,
7768 			    struct module_btf **res_mod_btf)
7769 {
7770 	struct module_btf *mod_btf;
7771 	struct btf *btf;
7772 	int i, id, err;
7773 
7774 	btf = obj->btf_vmlinux;
7775 	mod_btf = NULL;
7776 	id = btf__find_by_name_kind(btf, ksym_name, kind);
7777 
7778 	if (id == -ENOENT) {
7779 		err = load_module_btfs(obj);
7780 		if (err)
7781 			return err;
7782 
7783 		for (i = 0; i < obj->btf_module_cnt; i++) {
7784 			/* we assume module_btf's BTF FD is always >0 */
7785 			mod_btf = &obj->btf_modules[i];
7786 			btf = mod_btf->btf;
7787 			id = btf__find_by_name_kind_own(btf, ksym_name, kind);
7788 			if (id != -ENOENT)
7789 				break;
7790 		}
7791 	}
7792 	if (id <= 0)
7793 		return -ESRCH;
7794 
7795 	*res_btf = btf;
7796 	*res_mod_btf = mod_btf;
7797 	return id;
7798 }
7799 
7800 static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
7801 					       struct extern_desc *ext)
7802 {
7803 	const struct btf_type *targ_var, *targ_type;
7804 	__u32 targ_type_id, local_type_id;
7805 	struct module_btf *mod_btf = NULL;
7806 	const char *targ_var_name;
7807 	struct btf *btf = NULL;
7808 	int id, err;
7809 
7810 	id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
7811 	if (id < 0) {
7812 		if (id == -ESRCH && ext->is_weak)
7813 			return 0;
7814 		pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
7815 			ext->name);
7816 		return id;
7817 	}
7818 
7819 	/* find local type_id */
7820 	local_type_id = ext->ksym.type_id;
7821 
7822 	/* find target type_id */
7823 	targ_var = btf__type_by_id(btf, id);
7824 	targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
7825 	targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
7826 
7827 	err = bpf_core_types_are_compat(obj->btf, local_type_id,
7828 					btf, targ_type_id);
7829 	if (err <= 0) {
7830 		const struct btf_type *local_type;
7831 		const char *targ_name, *local_name;
7832 
7833 		local_type = btf__type_by_id(obj->btf, local_type_id);
7834 		local_name = btf__name_by_offset(obj->btf, local_type->name_off);
7835 		targ_name = btf__name_by_offset(btf, targ_type->name_off);
7836 
7837 		pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
7838 			ext->name, local_type_id,
7839 			btf_kind_str(local_type), local_name, targ_type_id,
7840 			btf_kind_str(targ_type), targ_name);
7841 		return -EINVAL;
7842 	}
7843 
7844 	ext->is_set = true;
7845 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
7846 	ext->ksym.kernel_btf_id = id;
7847 	pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
7848 		 ext->name, id, btf_kind_str(targ_var), targ_var_name);
7849 
7850 	return 0;
7851 }
7852 
7853 static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
7854 						struct extern_desc *ext)
7855 {
7856 	int local_func_proto_id, kfunc_proto_id, kfunc_id;
7857 	struct module_btf *mod_btf = NULL;
7858 	const struct btf_type *kern_func;
7859 	struct btf *kern_btf = NULL;
7860 	int ret;
7861 
7862 	local_func_proto_id = ext->ksym.type_id;
7863 
7864 	kfunc_id = find_ksym_btf_id(obj, ext->name, BTF_KIND_FUNC, &kern_btf, &mod_btf);
7865 	if (kfunc_id < 0) {
7866 		if (kfunc_id == -ESRCH && ext->is_weak)
7867 			return 0;
7868 		pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
7869 			ext->name);
7870 		return kfunc_id;
7871 	}
7872 
7873 	kern_func = btf__type_by_id(kern_btf, kfunc_id);
7874 	kfunc_proto_id = kern_func->type;
7875 
7876 	ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
7877 					kern_btf, kfunc_proto_id);
7878 	if (ret <= 0) {
7879 		pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with kernel [%d]\n",
7880 			ext->name, local_func_proto_id, kfunc_proto_id);
7881 		return -EINVAL;
7882 	}
7883 
7884 	/* set index for module BTF fd in fd_array, if unset */
7885 	if (mod_btf && !mod_btf->fd_array_idx) {
7886 		/* insn->off is s16 */
7887 		if (obj->fd_array_cnt == INT16_MAX) {
7888 			pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
7889 				ext->name, mod_btf->fd_array_idx);
7890 			return -E2BIG;
7891 		}
7892 		/* Cannot use index 0 for module BTF fd */
7893 		if (!obj->fd_array_cnt)
7894 			obj->fd_array_cnt = 1;
7895 
7896 		ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
7897 					obj->fd_array_cnt + 1);
7898 		if (ret)
7899 			return ret;
7900 		mod_btf->fd_array_idx = obj->fd_array_cnt;
7901 		/* we assume module BTF FD is always >0 */
7902 		obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
7903 	}
7904 
7905 	ext->is_set = true;
7906 	ext->ksym.kernel_btf_id = kfunc_id;
7907 	ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
7908 	pr_debug("extern (func ksym) '%s': resolved to kernel [%d]\n",
7909 		 ext->name, kfunc_id);
7910 
7911 	return 0;
7912 }
7913 
7914 static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
7915 {
7916 	const struct btf_type *t;
7917 	struct extern_desc *ext;
7918 	int i, err;
7919 
7920 	for (i = 0; i < obj->nr_extern; i++) {
7921 		ext = &obj->externs[i];
7922 		if (ext->type != EXT_KSYM || !ext->ksym.type_id)
7923 			continue;
7924 
7925 		if (obj->gen_loader) {
7926 			ext->is_set = true;
7927 			ext->ksym.kernel_btf_obj_fd = 0;
7928 			ext->ksym.kernel_btf_id = 0;
7929 			continue;
7930 		}
7931 		t = btf__type_by_id(obj->btf, ext->btf_id);
7932 		if (btf_is_var(t))
7933 			err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
7934 		else
7935 			err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
7936 		if (err)
7937 			return err;
7938 	}
7939 	return 0;
7940 }
7941 
7942 static int bpf_object__resolve_externs(struct bpf_object *obj,
7943 				       const char *extra_kconfig)
7944 {
7945 	bool need_config = false, need_kallsyms = false;
7946 	bool need_vmlinux_btf = false;
7947 	struct extern_desc *ext;
7948 	void *kcfg_data = NULL;
7949 	int err, i;
7950 
7951 	if (obj->nr_extern == 0)
7952 		return 0;
7953 
7954 	if (obj->kconfig_map_idx >= 0)
7955 		kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
7956 
7957 	for (i = 0; i < obj->nr_extern; i++) {
7958 		ext = &obj->externs[i];
7959 
7960 		if (ext->type == EXT_KCFG &&
7961 		    strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
7962 			void *ext_val = kcfg_data + ext->kcfg.data_off;
7963 			__u32 kver = get_kernel_version();
7964 
7965 			if (!kver) {
7966 				pr_warn("failed to get kernel version\n");
7967 				return -EINVAL;
7968 			}
7969 			err = set_kcfg_value_num(ext, ext_val, kver);
7970 			if (err)
7971 				return err;
7972 			pr_debug("extern (kcfg) %s=0x%x\n", ext->name, kver);
7973 		} else if (ext->type == EXT_KCFG && str_has_pfx(ext->name, "CONFIG_")) {
7974 			need_config = true;
7975 		} else if (ext->type == EXT_KSYM) {
7976 			if (ext->ksym.type_id)
7977 				need_vmlinux_btf = true;
7978 			else
7979 				need_kallsyms = true;
7980 		} else {
7981 			pr_warn("unrecognized extern '%s'\n", ext->name);
7982 			return -EINVAL;
7983 		}
7984 	}
7985 	if (need_config && extra_kconfig) {
7986 		err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
7987 		if (err)
7988 			return -EINVAL;
7989 		need_config = false;
7990 		for (i = 0; i < obj->nr_extern; i++) {
7991 			ext = &obj->externs[i];
7992 			if (ext->type == EXT_KCFG && !ext->is_set) {
7993 				need_config = true;
7994 				break;
7995 			}
7996 		}
7997 	}
7998 	if (need_config) {
7999 		err = bpf_object__read_kconfig_file(obj, kcfg_data);
8000 		if (err)
8001 			return -EINVAL;
8002 	}
8003 	if (need_kallsyms) {
8004 		err = bpf_object__read_kallsyms_file(obj);
8005 		if (err)
8006 			return -EINVAL;
8007 	}
8008 	if (need_vmlinux_btf) {
8009 		err = bpf_object__resolve_ksyms_btf_id(obj);
8010 		if (err)
8011 			return -EINVAL;
8012 	}
8013 	for (i = 0; i < obj->nr_extern; i++) {
8014 		ext = &obj->externs[i];
8015 
8016 		if (!ext->is_set && !ext->is_weak) {
8017 			pr_warn("extern %s (strong) not resolved\n", ext->name);
8018 			return -ESRCH;
8019 		} else if (!ext->is_set) {
8020 			pr_debug("extern %s (weak) not resolved, defaulting to zero\n",
8021 				 ext->name);
8022 		}
8023 	}
8024 
8025 	return 0;
8026 }
8027 
8028 static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
8029 {
8030 	int err, i;
8031 
8032 	if (!obj)
8033 		return libbpf_err(-EINVAL);
8034 
8035 	if (obj->loaded) {
8036 		pr_warn("object '%s': load can't be attempted twice\n", obj->name);
8037 		return libbpf_err(-EINVAL);
8038 	}
8039 
8040 	if (obj->gen_loader)
8041 		bpf_gen__init(obj->gen_loader, extra_log_level, obj->nr_programs, obj->nr_maps);
8042 
8043 	err = bpf_object__probe_loading(obj);
8044 	err = err ? : bpf_object__load_vmlinux_btf(obj, false);
8045 	err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
8046 	err = err ? : bpf_object__sanitize_and_load_btf(obj);
8047 	err = err ? : bpf_object__sanitize_maps(obj);
8048 	err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
8049 	err = err ? : bpf_object__create_maps(obj);
8050 	err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
8051 	err = err ? : bpf_object__load_progs(obj, extra_log_level);
8052 	err = err ? : bpf_object_init_prog_arrays(obj);
8053 
8054 	if (obj->gen_loader) {
8055 		/* reset FDs */
8056 		if (obj->btf)
8057 			btf__set_fd(obj->btf, -1);
8058 		for (i = 0; i < obj->nr_maps; i++)
8059 			obj->maps[i].fd = -1;
8060 		if (!err)
8061 			err = bpf_gen__finish(obj->gen_loader, obj->nr_programs, obj->nr_maps);
8062 	}
8063 
8064 	/* clean up fd_array */
8065 	zfree(&obj->fd_array);
8066 
8067 	/* clean up module BTFs */
8068 	for (i = 0; i < obj->btf_module_cnt; i++) {
8069 		close(obj->btf_modules[i].fd);
8070 		btf__free(obj->btf_modules[i].btf);
8071 		free(obj->btf_modules[i].name);
8072 	}
8073 	free(obj->btf_modules);
8074 
8075 	/* clean up vmlinux BTF */
8076 	btf__free(obj->btf_vmlinux);
8077 	obj->btf_vmlinux = NULL;
8078 
8079 	obj->loaded = true; /* doesn't matter if successfully or not */
8080 
8081 	if (err)
8082 		goto out;
8083 
8084 	return 0;
8085 out:
8086 	/* unpin any maps that were auto-pinned during load */
8087 	for (i = 0; i < obj->nr_maps; i++)
8088 		if (obj->maps[i].pinned && !obj->maps[i].reused)
8089 			bpf_map__unpin(&obj->maps[i], NULL);
8090 
8091 	bpf_object_unload(obj);
8092 	pr_warn("failed to load object '%s'\n", obj->path);
8093 	return libbpf_err(err);
8094 }
8095 
8096 int bpf_object__load_xattr(struct bpf_object_load_attr *attr)
8097 {
8098 	return bpf_object_load(attr->obj, attr->log_level, attr->target_btf_path);
8099 }
8100 
8101 int bpf_object__load(struct bpf_object *obj)
8102 {
8103 	return bpf_object_load(obj, 0, NULL);
8104 }
8105 
8106 static int make_parent_dir(const char *path)
8107 {
8108 	char *cp, errmsg[STRERR_BUFSIZE];
8109 	char *dname, *dir;
8110 	int err = 0;
8111 
8112 	dname = strdup(path);
8113 	if (dname == NULL)
8114 		return -ENOMEM;
8115 
8116 	dir = dirname(dname);
8117 	if (mkdir(dir, 0700) && errno != EEXIST)
8118 		err = -errno;
8119 
8120 	free(dname);
8121 	if (err) {
8122 		cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
8123 		pr_warn("failed to mkdir %s: %s\n", path, cp);
8124 	}
8125 	return err;
8126 }
8127 
8128 static int check_path(const char *path)
8129 {
8130 	char *cp, errmsg[STRERR_BUFSIZE];
8131 	struct statfs st_fs;
8132 	char *dname, *dir;
8133 	int err = 0;
8134 
8135 	if (path == NULL)
8136 		return -EINVAL;
8137 
8138 	dname = strdup(path);
8139 	if (dname == NULL)
8140 		return -ENOMEM;
8141 
8142 	dir = dirname(dname);
8143 	if (statfs(dir, &st_fs)) {
8144 		cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
8145 		pr_warn("failed to statfs %s: %s\n", dir, cp);
8146 		err = -errno;
8147 	}
8148 	free(dname);
8149 
8150 	if (!err && st_fs.f_type != BPF_FS_MAGIC) {
8151 		pr_warn("specified path %s is not on BPF FS\n", path);
8152 		err = -EINVAL;
8153 	}
8154 
8155 	return err;
8156 }
8157 
8158 static int bpf_program_pin_instance(struct bpf_program *prog, const char *path, int instance)
8159 {
8160 	char *cp, errmsg[STRERR_BUFSIZE];
8161 	int err;
8162 
8163 	err = make_parent_dir(path);
8164 	if (err)
8165 		return libbpf_err(err);
8166 
8167 	err = check_path(path);
8168 	if (err)
8169 		return libbpf_err(err);
8170 
8171 	if (prog == NULL) {
8172 		pr_warn("invalid program pointer\n");
8173 		return libbpf_err(-EINVAL);
8174 	}
8175 
8176 	if (instance < 0 || instance >= prog->instances.nr) {
8177 		pr_warn("invalid prog instance %d of prog %s (max %d)\n",
8178 			instance, prog->name, prog->instances.nr);
8179 		return libbpf_err(-EINVAL);
8180 	}
8181 
8182 	if (bpf_obj_pin(prog->instances.fds[instance], path)) {
8183 		err = -errno;
8184 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
8185 		pr_warn("failed to pin program: %s\n", cp);
8186 		return libbpf_err(err);
8187 	}
8188 	pr_debug("pinned program '%s'\n", path);
8189 
8190 	return 0;
8191 }
8192 
8193 static int bpf_program_unpin_instance(struct bpf_program *prog, const char *path, int instance)
8194 {
8195 	int err;
8196 
8197 	err = check_path(path);
8198 	if (err)
8199 		return libbpf_err(err);
8200 
8201 	if (prog == NULL) {
8202 		pr_warn("invalid program pointer\n");
8203 		return libbpf_err(-EINVAL);
8204 	}
8205 
8206 	if (instance < 0 || instance >= prog->instances.nr) {
8207 		pr_warn("invalid prog instance %d of prog %s (max %d)\n",
8208 			instance, prog->name, prog->instances.nr);
8209 		return libbpf_err(-EINVAL);
8210 	}
8211 
8212 	err = unlink(path);
8213 	if (err != 0)
8214 		return libbpf_err(-errno);
8215 
8216 	pr_debug("unpinned program '%s'\n", path);
8217 
8218 	return 0;
8219 }
8220 
8221 __attribute__((alias("bpf_program_pin_instance")))
8222 int bpf_object__pin_instance(struct bpf_program *prog, const char *path, int instance);
8223 
8224 __attribute__((alias("bpf_program_unpin_instance")))
8225 int bpf_program__unpin_instance(struct bpf_program *prog, const char *path, int instance);
8226 
8227 int bpf_program__pin(struct bpf_program *prog, const char *path)
8228 {
8229 	int i, err;
8230 
8231 	err = make_parent_dir(path);
8232 	if (err)
8233 		return libbpf_err(err);
8234 
8235 	err = check_path(path);
8236 	if (err)
8237 		return libbpf_err(err);
8238 
8239 	if (prog == NULL) {
8240 		pr_warn("invalid program pointer\n");
8241 		return libbpf_err(-EINVAL);
8242 	}
8243 
8244 	if (prog->instances.nr <= 0) {
8245 		pr_warn("no instances of prog %s to pin\n", prog->name);
8246 		return libbpf_err(-EINVAL);
8247 	}
8248 
8249 	if (prog->instances.nr == 1) {
8250 		/* don't create subdirs when pinning single instance */
8251 		return bpf_program_pin_instance(prog, path, 0);
8252 	}
8253 
8254 	for (i = 0; i < prog->instances.nr; i++) {
8255 		char buf[PATH_MAX];
8256 		int len;
8257 
8258 		len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
8259 		if (len < 0) {
8260 			err = -EINVAL;
8261 			goto err_unpin;
8262 		} else if (len >= PATH_MAX) {
8263 			err = -ENAMETOOLONG;
8264 			goto err_unpin;
8265 		}
8266 
8267 		err = bpf_program_pin_instance(prog, buf, i);
8268 		if (err)
8269 			goto err_unpin;
8270 	}
8271 
8272 	return 0;
8273 
8274 err_unpin:
8275 	for (i = i - 1; i >= 0; i--) {
8276 		char buf[PATH_MAX];
8277 		int len;
8278 
8279 		len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
8280 		if (len < 0)
8281 			continue;
8282 		else if (len >= PATH_MAX)
8283 			continue;
8284 
8285 		bpf_program_unpin_instance(prog, buf, i);
8286 	}
8287 
8288 	rmdir(path);
8289 
8290 	return libbpf_err(err);
8291 }
8292 
8293 int bpf_program__unpin(struct bpf_program *prog, const char *path)
8294 {
8295 	int i, err;
8296 
8297 	err = check_path(path);
8298 	if (err)
8299 		return libbpf_err(err);
8300 
8301 	if (prog == NULL) {
8302 		pr_warn("invalid program pointer\n");
8303 		return libbpf_err(-EINVAL);
8304 	}
8305 
8306 	if (prog->instances.nr <= 0) {
8307 		pr_warn("no instances of prog %s to pin\n", prog->name);
8308 		return libbpf_err(-EINVAL);
8309 	}
8310 
8311 	if (prog->instances.nr == 1) {
8312 		/* don't create subdirs when pinning single instance */
8313 		return bpf_program_unpin_instance(prog, path, 0);
8314 	}
8315 
8316 	for (i = 0; i < prog->instances.nr; i++) {
8317 		char buf[PATH_MAX];
8318 		int len;
8319 
8320 		len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
8321 		if (len < 0)
8322 			return libbpf_err(-EINVAL);
8323 		else if (len >= PATH_MAX)
8324 			return libbpf_err(-ENAMETOOLONG);
8325 
8326 		err = bpf_program_unpin_instance(prog, buf, i);
8327 		if (err)
8328 			return err;
8329 	}
8330 
8331 	err = rmdir(path);
8332 	if (err)
8333 		return libbpf_err(-errno);
8334 
8335 	return 0;
8336 }
8337 
8338 int bpf_map__pin(struct bpf_map *map, const char *path)
8339 {
8340 	char *cp, errmsg[STRERR_BUFSIZE];
8341 	int err;
8342 
8343 	if (map == NULL) {
8344 		pr_warn("invalid map pointer\n");
8345 		return libbpf_err(-EINVAL);
8346 	}
8347 
8348 	if (map->pin_path) {
8349 		if (path && strcmp(path, map->pin_path)) {
8350 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8351 				bpf_map__name(map), map->pin_path, path);
8352 			return libbpf_err(-EINVAL);
8353 		} else if (map->pinned) {
8354 			pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
8355 				 bpf_map__name(map), map->pin_path);
8356 			return 0;
8357 		}
8358 	} else {
8359 		if (!path) {
8360 			pr_warn("missing a path to pin map '%s' at\n",
8361 				bpf_map__name(map));
8362 			return libbpf_err(-EINVAL);
8363 		} else if (map->pinned) {
8364 			pr_warn("map '%s' already pinned\n", bpf_map__name(map));
8365 			return libbpf_err(-EEXIST);
8366 		}
8367 
8368 		map->pin_path = strdup(path);
8369 		if (!map->pin_path) {
8370 			err = -errno;
8371 			goto out_err;
8372 		}
8373 	}
8374 
8375 	err = make_parent_dir(map->pin_path);
8376 	if (err)
8377 		return libbpf_err(err);
8378 
8379 	err = check_path(map->pin_path);
8380 	if (err)
8381 		return libbpf_err(err);
8382 
8383 	if (bpf_obj_pin(map->fd, map->pin_path)) {
8384 		err = -errno;
8385 		goto out_err;
8386 	}
8387 
8388 	map->pinned = true;
8389 	pr_debug("pinned map '%s'\n", map->pin_path);
8390 
8391 	return 0;
8392 
8393 out_err:
8394 	cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
8395 	pr_warn("failed to pin map: %s\n", cp);
8396 	return libbpf_err(err);
8397 }
8398 
8399 int bpf_map__unpin(struct bpf_map *map, const char *path)
8400 {
8401 	int err;
8402 
8403 	if (map == NULL) {
8404 		pr_warn("invalid map pointer\n");
8405 		return libbpf_err(-EINVAL);
8406 	}
8407 
8408 	if (map->pin_path) {
8409 		if (path && strcmp(path, map->pin_path)) {
8410 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8411 				bpf_map__name(map), map->pin_path, path);
8412 			return libbpf_err(-EINVAL);
8413 		}
8414 		path = map->pin_path;
8415 	} else if (!path) {
8416 		pr_warn("no path to unpin map '%s' from\n",
8417 			bpf_map__name(map));
8418 		return libbpf_err(-EINVAL);
8419 	}
8420 
8421 	err = check_path(path);
8422 	if (err)
8423 		return libbpf_err(err);
8424 
8425 	err = unlink(path);
8426 	if (err != 0)
8427 		return libbpf_err(-errno);
8428 
8429 	map->pinned = false;
8430 	pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
8431 
8432 	return 0;
8433 }
8434 
8435 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
8436 {
8437 	char *new = NULL;
8438 
8439 	if (path) {
8440 		new = strdup(path);
8441 		if (!new)
8442 			return libbpf_err(-errno);
8443 	}
8444 
8445 	free(map->pin_path);
8446 	map->pin_path = new;
8447 	return 0;
8448 }
8449 
8450 __alias(bpf_map__pin_path)
8451 const char *bpf_map__get_pin_path(const struct bpf_map *map);
8452 
8453 const char *bpf_map__pin_path(const struct bpf_map *map)
8454 {
8455 	return map->pin_path;
8456 }
8457 
8458 bool bpf_map__is_pinned(const struct bpf_map *map)
8459 {
8460 	return map->pinned;
8461 }
8462 
8463 static void sanitize_pin_path(char *s)
8464 {
8465 	/* bpffs disallows periods in path names */
8466 	while (*s) {
8467 		if (*s == '.')
8468 			*s = '_';
8469 		s++;
8470 	}
8471 }
8472 
8473 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
8474 {
8475 	struct bpf_map *map;
8476 	int err;
8477 
8478 	if (!obj)
8479 		return libbpf_err(-ENOENT);
8480 
8481 	if (!obj->loaded) {
8482 		pr_warn("object not yet loaded; load it first\n");
8483 		return libbpf_err(-ENOENT);
8484 	}
8485 
8486 	bpf_object__for_each_map(map, obj) {
8487 		char *pin_path = NULL;
8488 		char buf[PATH_MAX];
8489 
8490 		if (!map->autocreate)
8491 			continue;
8492 
8493 		if (path) {
8494 			int len;
8495 
8496 			len = snprintf(buf, PATH_MAX, "%s/%s", path,
8497 				       bpf_map__name(map));
8498 			if (len < 0) {
8499 				err = -EINVAL;
8500 				goto err_unpin_maps;
8501 			} else if (len >= PATH_MAX) {
8502 				err = -ENAMETOOLONG;
8503 				goto err_unpin_maps;
8504 			}
8505 			sanitize_pin_path(buf);
8506 			pin_path = buf;
8507 		} else if (!map->pin_path) {
8508 			continue;
8509 		}
8510 
8511 		err = bpf_map__pin(map, pin_path);
8512 		if (err)
8513 			goto err_unpin_maps;
8514 	}
8515 
8516 	return 0;
8517 
8518 err_unpin_maps:
8519 	while ((map = bpf_object__prev_map(obj, map))) {
8520 		if (!map->pin_path)
8521 			continue;
8522 
8523 		bpf_map__unpin(map, NULL);
8524 	}
8525 
8526 	return libbpf_err(err);
8527 }
8528 
8529 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
8530 {
8531 	struct bpf_map *map;
8532 	int err;
8533 
8534 	if (!obj)
8535 		return libbpf_err(-ENOENT);
8536 
8537 	bpf_object__for_each_map(map, obj) {
8538 		char *pin_path = NULL;
8539 		char buf[PATH_MAX];
8540 
8541 		if (path) {
8542 			int len;
8543 
8544 			len = snprintf(buf, PATH_MAX, "%s/%s", path,
8545 				       bpf_map__name(map));
8546 			if (len < 0)
8547 				return libbpf_err(-EINVAL);
8548 			else if (len >= PATH_MAX)
8549 				return libbpf_err(-ENAMETOOLONG);
8550 			sanitize_pin_path(buf);
8551 			pin_path = buf;
8552 		} else if (!map->pin_path) {
8553 			continue;
8554 		}
8555 
8556 		err = bpf_map__unpin(map, pin_path);
8557 		if (err)
8558 			return libbpf_err(err);
8559 	}
8560 
8561 	return 0;
8562 }
8563 
8564 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
8565 {
8566 	struct bpf_program *prog;
8567 	int err;
8568 
8569 	if (!obj)
8570 		return libbpf_err(-ENOENT);
8571 
8572 	if (!obj->loaded) {
8573 		pr_warn("object not yet loaded; load it first\n");
8574 		return libbpf_err(-ENOENT);
8575 	}
8576 
8577 	bpf_object__for_each_program(prog, obj) {
8578 		char buf[PATH_MAX];
8579 		int len;
8580 
8581 		len = snprintf(buf, PATH_MAX, "%s/%s", path,
8582 			       prog->pin_name);
8583 		if (len < 0) {
8584 			err = -EINVAL;
8585 			goto err_unpin_programs;
8586 		} else if (len >= PATH_MAX) {
8587 			err = -ENAMETOOLONG;
8588 			goto err_unpin_programs;
8589 		}
8590 
8591 		err = bpf_program__pin(prog, buf);
8592 		if (err)
8593 			goto err_unpin_programs;
8594 	}
8595 
8596 	return 0;
8597 
8598 err_unpin_programs:
8599 	while ((prog = bpf_object__prev_program(obj, prog))) {
8600 		char buf[PATH_MAX];
8601 		int len;
8602 
8603 		len = snprintf(buf, PATH_MAX, "%s/%s", path,
8604 			       prog->pin_name);
8605 		if (len < 0)
8606 			continue;
8607 		else if (len >= PATH_MAX)
8608 			continue;
8609 
8610 		bpf_program__unpin(prog, buf);
8611 	}
8612 
8613 	return libbpf_err(err);
8614 }
8615 
8616 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
8617 {
8618 	struct bpf_program *prog;
8619 	int err;
8620 
8621 	if (!obj)
8622 		return libbpf_err(-ENOENT);
8623 
8624 	bpf_object__for_each_program(prog, obj) {
8625 		char buf[PATH_MAX];
8626 		int len;
8627 
8628 		len = snprintf(buf, PATH_MAX, "%s/%s", path,
8629 			       prog->pin_name);
8630 		if (len < 0)
8631 			return libbpf_err(-EINVAL);
8632 		else if (len >= PATH_MAX)
8633 			return libbpf_err(-ENAMETOOLONG);
8634 
8635 		err = bpf_program__unpin(prog, buf);
8636 		if (err)
8637 			return libbpf_err(err);
8638 	}
8639 
8640 	return 0;
8641 }
8642 
8643 int bpf_object__pin(struct bpf_object *obj, const char *path)
8644 {
8645 	int err;
8646 
8647 	err = bpf_object__pin_maps(obj, path);
8648 	if (err)
8649 		return libbpf_err(err);
8650 
8651 	err = bpf_object__pin_programs(obj, path);
8652 	if (err) {
8653 		bpf_object__unpin_maps(obj, path);
8654 		return libbpf_err(err);
8655 	}
8656 
8657 	return 0;
8658 }
8659 
8660 static void bpf_map__destroy(struct bpf_map *map)
8661 {
8662 	if (map->clear_priv)
8663 		map->clear_priv(map, map->priv);
8664 	map->priv = NULL;
8665 	map->clear_priv = NULL;
8666 
8667 	if (map->inner_map) {
8668 		bpf_map__destroy(map->inner_map);
8669 		zfree(&map->inner_map);
8670 	}
8671 
8672 	zfree(&map->init_slots);
8673 	map->init_slots_sz = 0;
8674 
8675 	if (map->mmaped) {
8676 		munmap(map->mmaped, bpf_map_mmap_sz(map));
8677 		map->mmaped = NULL;
8678 	}
8679 
8680 	if (map->st_ops) {
8681 		zfree(&map->st_ops->data);
8682 		zfree(&map->st_ops->progs);
8683 		zfree(&map->st_ops->kern_func_off);
8684 		zfree(&map->st_ops);
8685 	}
8686 
8687 	zfree(&map->name);
8688 	zfree(&map->real_name);
8689 	zfree(&map->pin_path);
8690 
8691 	if (map->fd >= 0)
8692 		zclose(map->fd);
8693 }
8694 
8695 void bpf_object__close(struct bpf_object *obj)
8696 {
8697 	size_t i;
8698 
8699 	if (IS_ERR_OR_NULL(obj))
8700 		return;
8701 
8702 	if (obj->clear_priv)
8703 		obj->clear_priv(obj, obj->priv);
8704 
8705 	usdt_manager_free(obj->usdt_man);
8706 	obj->usdt_man = NULL;
8707 
8708 	bpf_gen__free(obj->gen_loader);
8709 	bpf_object__elf_finish(obj);
8710 	bpf_object_unload(obj);
8711 	btf__free(obj->btf);
8712 	btf_ext__free(obj->btf_ext);
8713 
8714 	for (i = 0; i < obj->nr_maps; i++)
8715 		bpf_map__destroy(&obj->maps[i]);
8716 
8717 	zfree(&obj->btf_custom_path);
8718 	zfree(&obj->kconfig);
8719 	zfree(&obj->externs);
8720 	obj->nr_extern = 0;
8721 
8722 	zfree(&obj->maps);
8723 	obj->nr_maps = 0;
8724 
8725 	if (obj->programs && obj->nr_programs) {
8726 		for (i = 0; i < obj->nr_programs; i++)
8727 			bpf_program__exit(&obj->programs[i]);
8728 	}
8729 	zfree(&obj->programs);
8730 
8731 	list_del(&obj->list);
8732 	free(obj);
8733 }
8734 
8735 struct bpf_object *
8736 bpf_object__next(struct bpf_object *prev)
8737 {
8738 	struct bpf_object *next;
8739 	bool strict = (libbpf_mode & LIBBPF_STRICT_NO_OBJECT_LIST);
8740 
8741 	if (strict)
8742 		return NULL;
8743 
8744 	if (!prev)
8745 		next = list_first_entry(&bpf_objects_list,
8746 					struct bpf_object,
8747 					list);
8748 	else
8749 		next = list_next_entry(prev, list);
8750 
8751 	/* Empty list is noticed here so don't need checking on entry. */
8752 	if (&next->list == &bpf_objects_list)
8753 		return NULL;
8754 
8755 	return next;
8756 }
8757 
8758 const char *bpf_object__name(const struct bpf_object *obj)
8759 {
8760 	return obj ? obj->name : libbpf_err_ptr(-EINVAL);
8761 }
8762 
8763 unsigned int bpf_object__kversion(const struct bpf_object *obj)
8764 {
8765 	return obj ? obj->kern_version : 0;
8766 }
8767 
8768 struct btf *bpf_object__btf(const struct bpf_object *obj)
8769 {
8770 	return obj ? obj->btf : NULL;
8771 }
8772 
8773 int bpf_object__btf_fd(const struct bpf_object *obj)
8774 {
8775 	return obj->btf ? btf__fd(obj->btf) : -1;
8776 }
8777 
8778 int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
8779 {
8780 	if (obj->loaded)
8781 		return libbpf_err(-EINVAL);
8782 
8783 	obj->kern_version = kern_version;
8784 
8785 	return 0;
8786 }
8787 
8788 int bpf_object__set_priv(struct bpf_object *obj, void *priv,
8789 			 bpf_object_clear_priv_t clear_priv)
8790 {
8791 	if (obj->priv && obj->clear_priv)
8792 		obj->clear_priv(obj, obj->priv);
8793 
8794 	obj->priv = priv;
8795 	obj->clear_priv = clear_priv;
8796 	return 0;
8797 }
8798 
8799 void *bpf_object__priv(const struct bpf_object *obj)
8800 {
8801 	return obj ? obj->priv : libbpf_err_ptr(-EINVAL);
8802 }
8803 
8804 int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
8805 {
8806 	struct bpf_gen *gen;
8807 
8808 	if (!opts)
8809 		return -EFAULT;
8810 	if (!OPTS_VALID(opts, gen_loader_opts))
8811 		return -EINVAL;
8812 	gen = calloc(sizeof(*gen), 1);
8813 	if (!gen)
8814 		return -ENOMEM;
8815 	gen->opts = opts;
8816 	obj->gen_loader = gen;
8817 	return 0;
8818 }
8819 
8820 static struct bpf_program *
8821 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
8822 		    bool forward)
8823 {
8824 	size_t nr_programs = obj->nr_programs;
8825 	ssize_t idx;
8826 
8827 	if (!nr_programs)
8828 		return NULL;
8829 
8830 	if (!p)
8831 		/* Iter from the beginning */
8832 		return forward ? &obj->programs[0] :
8833 			&obj->programs[nr_programs - 1];
8834 
8835 	if (p->obj != obj) {
8836 		pr_warn("error: program handler doesn't match object\n");
8837 		return errno = EINVAL, NULL;
8838 	}
8839 
8840 	idx = (p - obj->programs) + (forward ? 1 : -1);
8841 	if (idx >= obj->nr_programs || idx < 0)
8842 		return NULL;
8843 	return &obj->programs[idx];
8844 }
8845 
8846 struct bpf_program *
8847 bpf_program__next(struct bpf_program *prev, const struct bpf_object *obj)
8848 {
8849 	return bpf_object__next_program(obj, prev);
8850 }
8851 
8852 struct bpf_program *
8853 bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
8854 {
8855 	struct bpf_program *prog = prev;
8856 
8857 	do {
8858 		prog = __bpf_program__iter(prog, obj, true);
8859 	} while (prog && prog_is_subprog(obj, prog));
8860 
8861 	return prog;
8862 }
8863 
8864 struct bpf_program *
8865 bpf_program__prev(struct bpf_program *next, const struct bpf_object *obj)
8866 {
8867 	return bpf_object__prev_program(obj, next);
8868 }
8869 
8870 struct bpf_program *
8871 bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
8872 {
8873 	struct bpf_program *prog = next;
8874 
8875 	do {
8876 		prog = __bpf_program__iter(prog, obj, false);
8877 	} while (prog && prog_is_subprog(obj, prog));
8878 
8879 	return prog;
8880 }
8881 
8882 int bpf_program__set_priv(struct bpf_program *prog, void *priv,
8883 			  bpf_program_clear_priv_t clear_priv)
8884 {
8885 	if (prog->priv && prog->clear_priv)
8886 		prog->clear_priv(prog, prog->priv);
8887 
8888 	prog->priv = priv;
8889 	prog->clear_priv = clear_priv;
8890 	return 0;
8891 }
8892 
8893 void *bpf_program__priv(const struct bpf_program *prog)
8894 {
8895 	return prog ? prog->priv : libbpf_err_ptr(-EINVAL);
8896 }
8897 
8898 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
8899 {
8900 	prog->prog_ifindex = ifindex;
8901 }
8902 
8903 const char *bpf_program__name(const struct bpf_program *prog)
8904 {
8905 	return prog->name;
8906 }
8907 
8908 const char *bpf_program__section_name(const struct bpf_program *prog)
8909 {
8910 	return prog->sec_name;
8911 }
8912 
8913 const char *bpf_program__title(const struct bpf_program *prog, bool needs_copy)
8914 {
8915 	const char *title;
8916 
8917 	title = prog->sec_name;
8918 	if (needs_copy) {
8919 		title = strdup(title);
8920 		if (!title) {
8921 			pr_warn("failed to strdup program title\n");
8922 			return libbpf_err_ptr(-ENOMEM);
8923 		}
8924 	}
8925 
8926 	return title;
8927 }
8928 
8929 bool bpf_program__autoload(const struct bpf_program *prog)
8930 {
8931 	return prog->autoload;
8932 }
8933 
8934 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
8935 {
8936 	if (prog->obj->loaded)
8937 		return libbpf_err(-EINVAL);
8938 
8939 	prog->autoload = autoload;
8940 	return 0;
8941 }
8942 
8943 static int bpf_program_nth_fd(const struct bpf_program *prog, int n);
8944 
8945 int bpf_program__fd(const struct bpf_program *prog)
8946 {
8947 	return bpf_program_nth_fd(prog, 0);
8948 }
8949 
8950 size_t bpf_program__size(const struct bpf_program *prog)
8951 {
8952 	return prog->insns_cnt * BPF_INSN_SZ;
8953 }
8954 
8955 const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
8956 {
8957 	return prog->insns;
8958 }
8959 
8960 size_t bpf_program__insn_cnt(const struct bpf_program *prog)
8961 {
8962 	return prog->insns_cnt;
8963 }
8964 
8965 int bpf_program__set_insns(struct bpf_program *prog,
8966 			   struct bpf_insn *new_insns, size_t new_insn_cnt)
8967 {
8968 	struct bpf_insn *insns;
8969 
8970 	if (prog->obj->loaded)
8971 		return -EBUSY;
8972 
8973 	insns = libbpf_reallocarray(prog->insns, new_insn_cnt, sizeof(*insns));
8974 	if (!insns) {
8975 		pr_warn("prog '%s': failed to realloc prog code\n", prog->name);
8976 		return -ENOMEM;
8977 	}
8978 	memcpy(insns, new_insns, new_insn_cnt * sizeof(*insns));
8979 
8980 	prog->insns = insns;
8981 	prog->insns_cnt = new_insn_cnt;
8982 	return 0;
8983 }
8984 
8985 int bpf_program__set_prep(struct bpf_program *prog, int nr_instances,
8986 			  bpf_program_prep_t prep)
8987 {
8988 	int *instances_fds;
8989 
8990 	if (nr_instances <= 0 || !prep)
8991 		return libbpf_err(-EINVAL);
8992 
8993 	if (prog->instances.nr > 0 || prog->instances.fds) {
8994 		pr_warn("Can't set pre-processor after loading\n");
8995 		return libbpf_err(-EINVAL);
8996 	}
8997 
8998 	instances_fds = malloc(sizeof(int) * nr_instances);
8999 	if (!instances_fds) {
9000 		pr_warn("alloc memory failed for fds\n");
9001 		return libbpf_err(-ENOMEM);
9002 	}
9003 
9004 	/* fill all fd with -1 */
9005 	memset(instances_fds, -1, sizeof(int) * nr_instances);
9006 
9007 	prog->instances.nr = nr_instances;
9008 	prog->instances.fds = instances_fds;
9009 	prog->preprocessor = prep;
9010 	return 0;
9011 }
9012 
9013 __attribute__((alias("bpf_program_nth_fd")))
9014 int bpf_program__nth_fd(const struct bpf_program *prog, int n);
9015 
9016 static int bpf_program_nth_fd(const struct bpf_program *prog, int n)
9017 {
9018 	int fd;
9019 
9020 	if (!prog)
9021 		return libbpf_err(-EINVAL);
9022 
9023 	if (n >= prog->instances.nr || n < 0) {
9024 		pr_warn("Can't get the %dth fd from program %s: only %d instances\n",
9025 			n, prog->name, prog->instances.nr);
9026 		return libbpf_err(-EINVAL);
9027 	}
9028 
9029 	fd = prog->instances.fds[n];
9030 	if (fd < 0) {
9031 		pr_warn("%dth instance of program '%s' is invalid\n",
9032 			n, prog->name);
9033 		return libbpf_err(-ENOENT);
9034 	}
9035 
9036 	return fd;
9037 }
9038 
9039 __alias(bpf_program__type)
9040 enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog);
9041 
9042 enum bpf_prog_type bpf_program__type(const struct bpf_program *prog)
9043 {
9044 	return prog->type;
9045 }
9046 
9047 int bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
9048 {
9049 	if (prog->obj->loaded)
9050 		return libbpf_err(-EBUSY);
9051 
9052 	prog->type = type;
9053 	return 0;
9054 }
9055 
9056 static bool bpf_program__is_type(const struct bpf_program *prog,
9057 				 enum bpf_prog_type type)
9058 {
9059 	return prog ? (prog->type == type) : false;
9060 }
9061 
9062 #define BPF_PROG_TYPE_FNS(NAME, TYPE)				\
9063 int bpf_program__set_##NAME(struct bpf_program *prog)		\
9064 {								\
9065 	if (!prog)						\
9066 		return libbpf_err(-EINVAL);			\
9067 	return bpf_program__set_type(prog, TYPE);			\
9068 }								\
9069 								\
9070 bool bpf_program__is_##NAME(const struct bpf_program *prog)	\
9071 {								\
9072 	return bpf_program__is_type(prog, TYPE);		\
9073 }								\
9074 
9075 BPF_PROG_TYPE_FNS(socket_filter, BPF_PROG_TYPE_SOCKET_FILTER);
9076 BPF_PROG_TYPE_FNS(lsm, BPF_PROG_TYPE_LSM);
9077 BPF_PROG_TYPE_FNS(kprobe, BPF_PROG_TYPE_KPROBE);
9078 BPF_PROG_TYPE_FNS(sched_cls, BPF_PROG_TYPE_SCHED_CLS);
9079 BPF_PROG_TYPE_FNS(sched_act, BPF_PROG_TYPE_SCHED_ACT);
9080 BPF_PROG_TYPE_FNS(tracepoint, BPF_PROG_TYPE_TRACEPOINT);
9081 BPF_PROG_TYPE_FNS(raw_tracepoint, BPF_PROG_TYPE_RAW_TRACEPOINT);
9082 BPF_PROG_TYPE_FNS(xdp, BPF_PROG_TYPE_XDP);
9083 BPF_PROG_TYPE_FNS(perf_event, BPF_PROG_TYPE_PERF_EVENT);
9084 BPF_PROG_TYPE_FNS(tracing, BPF_PROG_TYPE_TRACING);
9085 BPF_PROG_TYPE_FNS(struct_ops, BPF_PROG_TYPE_STRUCT_OPS);
9086 BPF_PROG_TYPE_FNS(extension, BPF_PROG_TYPE_EXT);
9087 BPF_PROG_TYPE_FNS(sk_lookup, BPF_PROG_TYPE_SK_LOOKUP);
9088 
9089 __alias(bpf_program__expected_attach_type)
9090 enum bpf_attach_type bpf_program__get_expected_attach_type(const struct bpf_program *prog);
9091 
9092 enum bpf_attach_type bpf_program__expected_attach_type(const struct bpf_program *prog)
9093 {
9094 	return prog->expected_attach_type;
9095 }
9096 
9097 int bpf_program__set_expected_attach_type(struct bpf_program *prog,
9098 					   enum bpf_attach_type type)
9099 {
9100 	if (prog->obj->loaded)
9101 		return libbpf_err(-EBUSY);
9102 
9103 	prog->expected_attach_type = type;
9104 	return 0;
9105 }
9106 
9107 __u32 bpf_program__flags(const struct bpf_program *prog)
9108 {
9109 	return prog->prog_flags;
9110 }
9111 
9112 int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
9113 {
9114 	if (prog->obj->loaded)
9115 		return libbpf_err(-EBUSY);
9116 
9117 	prog->prog_flags = flags;
9118 	return 0;
9119 }
9120 
9121 __u32 bpf_program__log_level(const struct bpf_program *prog)
9122 {
9123 	return prog->log_level;
9124 }
9125 
9126 int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
9127 {
9128 	if (prog->obj->loaded)
9129 		return libbpf_err(-EBUSY);
9130 
9131 	prog->log_level = log_level;
9132 	return 0;
9133 }
9134 
9135 const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
9136 {
9137 	*log_size = prog->log_size;
9138 	return prog->log_buf;
9139 }
9140 
9141 int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
9142 {
9143 	if (log_size && !log_buf)
9144 		return -EINVAL;
9145 	if (prog->log_size > UINT_MAX)
9146 		return -EINVAL;
9147 	if (prog->obj->loaded)
9148 		return -EBUSY;
9149 
9150 	prog->log_buf = log_buf;
9151 	prog->log_size = log_size;
9152 	return 0;
9153 }
9154 
9155 #define SEC_DEF(sec_pfx, ptype, atype, flags, ...) {			    \
9156 	.sec = (char *)sec_pfx,						    \
9157 	.prog_type = BPF_PROG_TYPE_##ptype,				    \
9158 	.expected_attach_type = atype,					    \
9159 	.cookie = (long)(flags),					    \
9160 	.prog_prepare_load_fn = libbpf_prepare_prog_load,		    \
9161 	__VA_ARGS__							    \
9162 }
9163 
9164 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9165 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9166 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9167 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9168 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9169 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9170 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9171 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9172 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9173 
9174 static const struct bpf_sec_def section_defs[] = {
9175 	SEC_DEF("socket",		SOCKET_FILTER, 0, SEC_NONE | SEC_SLOPPY_PFX),
9176 	SEC_DEF("sk_reuseport/migrate",	SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9177 	SEC_DEF("sk_reuseport",		SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9178 	SEC_DEF("kprobe+",		KPROBE,	0, SEC_NONE, attach_kprobe),
9179 	SEC_DEF("uprobe+",		KPROBE,	0, SEC_NONE, attach_uprobe),
9180 	SEC_DEF("uprobe.s+",		KPROBE,	0, SEC_SLEEPABLE, attach_uprobe),
9181 	SEC_DEF("kretprobe+",		KPROBE, 0, SEC_NONE, attach_kprobe),
9182 	SEC_DEF("uretprobe+",		KPROBE, 0, SEC_NONE, attach_uprobe),
9183 	SEC_DEF("uretprobe.s+",		KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
9184 	SEC_DEF("kprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
9185 	SEC_DEF("kretprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
9186 	SEC_DEF("usdt+",		KPROBE,	0, SEC_NONE, attach_usdt),
9187 	SEC_DEF("tc",			SCHED_CLS, 0, SEC_NONE),
9188 	SEC_DEF("classifier",		SCHED_CLS, 0, SEC_NONE | SEC_SLOPPY_PFX | SEC_DEPRECATED),
9189 	SEC_DEF("action",		SCHED_ACT, 0, SEC_NONE | SEC_SLOPPY_PFX),
9190 	SEC_DEF("tracepoint+",		TRACEPOINT, 0, SEC_NONE, attach_tp),
9191 	SEC_DEF("tp+",			TRACEPOINT, 0, SEC_NONE, attach_tp),
9192 	SEC_DEF("raw_tracepoint+",	RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
9193 	SEC_DEF("raw_tp+",		RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
9194 	SEC_DEF("raw_tracepoint.w+",	RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
9195 	SEC_DEF("raw_tp.w+",		RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
9196 	SEC_DEF("tp_btf+",		TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
9197 	SEC_DEF("fentry+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
9198 	SEC_DEF("fmod_ret+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
9199 	SEC_DEF("fexit+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
9200 	SEC_DEF("fentry.s+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
9201 	SEC_DEF("fmod_ret.s+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
9202 	SEC_DEF("fexit.s+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
9203 	SEC_DEF("freplace+",		EXT, 0, SEC_ATTACH_BTF, attach_trace),
9204 	SEC_DEF("lsm+",			LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
9205 	SEC_DEF("lsm.s+",		LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
9206 	SEC_DEF("iter+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
9207 	SEC_DEF("iter.s+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_iter),
9208 	SEC_DEF("syscall",		SYSCALL, 0, SEC_SLEEPABLE),
9209 	SEC_DEF("xdp.frags/devmap",	XDP, BPF_XDP_DEVMAP, SEC_XDP_FRAGS),
9210 	SEC_DEF("xdp/devmap",		XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
9211 	SEC_DEF("xdp_devmap/",		XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE | SEC_DEPRECATED),
9212 	SEC_DEF("xdp.frags/cpumap",	XDP, BPF_XDP_CPUMAP, SEC_XDP_FRAGS),
9213 	SEC_DEF("xdp/cpumap",		XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
9214 	SEC_DEF("xdp_cpumap/",		XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE | SEC_DEPRECATED),
9215 	SEC_DEF("xdp.frags",		XDP, BPF_XDP, SEC_XDP_FRAGS),
9216 	SEC_DEF("xdp",			XDP, BPF_XDP, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
9217 	SEC_DEF("perf_event",		PERF_EVENT, 0, SEC_NONE | SEC_SLOPPY_PFX),
9218 	SEC_DEF("lwt_in",		LWT_IN, 0, SEC_NONE | SEC_SLOPPY_PFX),
9219 	SEC_DEF("lwt_out",		LWT_OUT, 0, SEC_NONE | SEC_SLOPPY_PFX),
9220 	SEC_DEF("lwt_xmit",		LWT_XMIT, 0, SEC_NONE | SEC_SLOPPY_PFX),
9221 	SEC_DEF("lwt_seg6local",	LWT_SEG6LOCAL, 0, SEC_NONE | SEC_SLOPPY_PFX),
9222 	SEC_DEF("cgroup_skb/ingress",	CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
9223 	SEC_DEF("cgroup_skb/egress",	CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
9224 	SEC_DEF("cgroup/skb",		CGROUP_SKB, 0, SEC_NONE | SEC_SLOPPY_PFX),
9225 	SEC_DEF("cgroup/sock_create",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9226 	SEC_DEF("cgroup/sock_release",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9227 	SEC_DEF("cgroup/sock",		CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
9228 	SEC_DEF("cgroup/post_bind4",	CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9229 	SEC_DEF("cgroup/post_bind6",	CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9230 	SEC_DEF("cgroup/dev",		CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
9231 	SEC_DEF("sockops",		SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
9232 	SEC_DEF("sk_skb/stream_parser",	SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
9233 	SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
9234 	SEC_DEF("sk_skb",		SK_SKB, 0, SEC_NONE | SEC_SLOPPY_PFX),
9235 	SEC_DEF("sk_msg",		SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
9236 	SEC_DEF("lirc_mode2",		LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
9237 	SEC_DEF("flow_dissector",	FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
9238 	SEC_DEF("cgroup/bind4",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9239 	SEC_DEF("cgroup/bind6",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9240 	SEC_DEF("cgroup/connect4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9241 	SEC_DEF("cgroup/connect6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9242 	SEC_DEF("cgroup/sendmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9243 	SEC_DEF("cgroup/sendmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9244 	SEC_DEF("cgroup/recvmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9245 	SEC_DEF("cgroup/recvmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9246 	SEC_DEF("cgroup/getpeername4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9247 	SEC_DEF("cgroup/getpeername6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9248 	SEC_DEF("cgroup/getsockname4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9249 	SEC_DEF("cgroup/getsockname6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9250 	SEC_DEF("cgroup/sysctl",	CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9251 	SEC_DEF("cgroup/getsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9252 	SEC_DEF("cgroup/setsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9253 	SEC_DEF("struct_ops+",		STRUCT_OPS, 0, SEC_NONE),
9254 	SEC_DEF("sk_lookup",		SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9255 };
9256 
9257 static size_t custom_sec_def_cnt;
9258 static struct bpf_sec_def *custom_sec_defs;
9259 static struct bpf_sec_def custom_fallback_def;
9260 static bool has_custom_fallback_def;
9261 
9262 static int last_custom_sec_def_handler_id;
9263 
9264 int libbpf_register_prog_handler(const char *sec,
9265 				 enum bpf_prog_type prog_type,
9266 				 enum bpf_attach_type exp_attach_type,
9267 				 const struct libbpf_prog_handler_opts *opts)
9268 {
9269 	struct bpf_sec_def *sec_def;
9270 
9271 	if (!OPTS_VALID(opts, libbpf_prog_handler_opts))
9272 		return libbpf_err(-EINVAL);
9273 
9274 	if (last_custom_sec_def_handler_id == INT_MAX) /* prevent overflow */
9275 		return libbpf_err(-E2BIG);
9276 
9277 	if (sec) {
9278 		sec_def = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt + 1,
9279 					      sizeof(*sec_def));
9280 		if (!sec_def)
9281 			return libbpf_err(-ENOMEM);
9282 
9283 		custom_sec_defs = sec_def;
9284 		sec_def = &custom_sec_defs[custom_sec_def_cnt];
9285 	} else {
9286 		if (has_custom_fallback_def)
9287 			return libbpf_err(-EBUSY);
9288 
9289 		sec_def = &custom_fallback_def;
9290 	}
9291 
9292 	sec_def->sec = sec ? strdup(sec) : NULL;
9293 	if (sec && !sec_def->sec)
9294 		return libbpf_err(-ENOMEM);
9295 
9296 	sec_def->prog_type = prog_type;
9297 	sec_def->expected_attach_type = exp_attach_type;
9298 	sec_def->cookie = OPTS_GET(opts, cookie, 0);
9299 
9300 	sec_def->prog_setup_fn = OPTS_GET(opts, prog_setup_fn, NULL);
9301 	sec_def->prog_prepare_load_fn = OPTS_GET(opts, prog_prepare_load_fn, NULL);
9302 	sec_def->prog_attach_fn = OPTS_GET(opts, prog_attach_fn, NULL);
9303 
9304 	sec_def->handler_id = ++last_custom_sec_def_handler_id;
9305 
9306 	if (sec)
9307 		custom_sec_def_cnt++;
9308 	else
9309 		has_custom_fallback_def = true;
9310 
9311 	return sec_def->handler_id;
9312 }
9313 
9314 int libbpf_unregister_prog_handler(int handler_id)
9315 {
9316 	struct bpf_sec_def *sec_defs;
9317 	int i;
9318 
9319 	if (handler_id <= 0)
9320 		return libbpf_err(-EINVAL);
9321 
9322 	if (has_custom_fallback_def && custom_fallback_def.handler_id == handler_id) {
9323 		memset(&custom_fallback_def, 0, sizeof(custom_fallback_def));
9324 		has_custom_fallback_def = false;
9325 		return 0;
9326 	}
9327 
9328 	for (i = 0; i < custom_sec_def_cnt; i++) {
9329 		if (custom_sec_defs[i].handler_id == handler_id)
9330 			break;
9331 	}
9332 
9333 	if (i == custom_sec_def_cnt)
9334 		return libbpf_err(-ENOENT);
9335 
9336 	free(custom_sec_defs[i].sec);
9337 	for (i = i + 1; i < custom_sec_def_cnt; i++)
9338 		custom_sec_defs[i - 1] = custom_sec_defs[i];
9339 	custom_sec_def_cnt--;
9340 
9341 	/* try to shrink the array, but it's ok if we couldn't */
9342 	sec_defs = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt, sizeof(*sec_defs));
9343 	if (sec_defs)
9344 		custom_sec_defs = sec_defs;
9345 
9346 	return 0;
9347 }
9348 
9349 static bool sec_def_matches(const struct bpf_sec_def *sec_def, const char *sec_name,
9350 			    bool allow_sloppy)
9351 {
9352 	size_t len = strlen(sec_def->sec);
9353 
9354 	/* "type/" always has to have proper SEC("type/extras") form */
9355 	if (sec_def->sec[len - 1] == '/') {
9356 		if (str_has_pfx(sec_name, sec_def->sec))
9357 			return true;
9358 		return false;
9359 	}
9360 
9361 	/* "type+" means it can be either exact SEC("type") or
9362 	 * well-formed SEC("type/extras") with proper '/' separator
9363 	 */
9364 	if (sec_def->sec[len - 1] == '+') {
9365 		len--;
9366 		/* not even a prefix */
9367 		if (strncmp(sec_name, sec_def->sec, len) != 0)
9368 			return false;
9369 		/* exact match or has '/' separator */
9370 		if (sec_name[len] == '\0' || sec_name[len] == '/')
9371 			return true;
9372 		return false;
9373 	}
9374 
9375 	/* SEC_SLOPPY_PFX definitions are allowed to be just prefix
9376 	 * matches, unless strict section name mode
9377 	 * (LIBBPF_STRICT_SEC_NAME) is enabled, in which case the
9378 	 * match has to be exact.
9379 	 */
9380 	if (allow_sloppy && str_has_pfx(sec_name, sec_def->sec))
9381 		return true;
9382 
9383 	/* Definitions not marked SEC_SLOPPY_PFX (e.g.,
9384 	 * SEC("syscall")) are exact matches in both modes.
9385 	 */
9386 	return strcmp(sec_name, sec_def->sec) == 0;
9387 }
9388 
9389 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
9390 {
9391 	const struct bpf_sec_def *sec_def;
9392 	int i, n;
9393 	bool strict = libbpf_mode & LIBBPF_STRICT_SEC_NAME, allow_sloppy;
9394 
9395 	n = custom_sec_def_cnt;
9396 	for (i = 0; i < n; i++) {
9397 		sec_def = &custom_sec_defs[i];
9398 		if (sec_def_matches(sec_def, sec_name, false))
9399 			return sec_def;
9400 	}
9401 
9402 	n = ARRAY_SIZE(section_defs);
9403 	for (i = 0; i < n; i++) {
9404 		sec_def = &section_defs[i];
9405 		allow_sloppy = (sec_def->cookie & SEC_SLOPPY_PFX) && !strict;
9406 		if (sec_def_matches(sec_def, sec_name, allow_sloppy))
9407 			return sec_def;
9408 	}
9409 
9410 	if (has_custom_fallback_def)
9411 		return &custom_fallback_def;
9412 
9413 	return NULL;
9414 }
9415 
9416 #define MAX_TYPE_NAME_SIZE 32
9417 
9418 static char *libbpf_get_type_names(bool attach_type)
9419 {
9420 	int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
9421 	char *buf;
9422 
9423 	buf = malloc(len);
9424 	if (!buf)
9425 		return NULL;
9426 
9427 	buf[0] = '\0';
9428 	/* Forge string buf with all available names */
9429 	for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
9430 		const struct bpf_sec_def *sec_def = &section_defs[i];
9431 
9432 		if (attach_type) {
9433 			if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
9434 				continue;
9435 
9436 			if (!(sec_def->cookie & SEC_ATTACHABLE))
9437 				continue;
9438 		}
9439 
9440 		if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
9441 			free(buf);
9442 			return NULL;
9443 		}
9444 		strcat(buf, " ");
9445 		strcat(buf, section_defs[i].sec);
9446 	}
9447 
9448 	return buf;
9449 }
9450 
9451 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
9452 			     enum bpf_attach_type *expected_attach_type)
9453 {
9454 	const struct bpf_sec_def *sec_def;
9455 	char *type_names;
9456 
9457 	if (!name)
9458 		return libbpf_err(-EINVAL);
9459 
9460 	sec_def = find_sec_def(name);
9461 	if (sec_def) {
9462 		*prog_type = sec_def->prog_type;
9463 		*expected_attach_type = sec_def->expected_attach_type;
9464 		return 0;
9465 	}
9466 
9467 	pr_debug("failed to guess program type from ELF section '%s'\n", name);
9468 	type_names = libbpf_get_type_names(false);
9469 	if (type_names != NULL) {
9470 		pr_debug("supported section(type) names are:%s\n", type_names);
9471 		free(type_names);
9472 	}
9473 
9474 	return libbpf_err(-ESRCH);
9475 }
9476 
9477 const char *libbpf_bpf_attach_type_str(enum bpf_attach_type t)
9478 {
9479 	if (t < 0 || t >= ARRAY_SIZE(attach_type_name))
9480 		return NULL;
9481 
9482 	return attach_type_name[t];
9483 }
9484 
9485 const char *libbpf_bpf_link_type_str(enum bpf_link_type t)
9486 {
9487 	if (t < 0 || t >= ARRAY_SIZE(link_type_name))
9488 		return NULL;
9489 
9490 	return link_type_name[t];
9491 }
9492 
9493 const char *libbpf_bpf_map_type_str(enum bpf_map_type t)
9494 {
9495 	if (t < 0 || t >= ARRAY_SIZE(map_type_name))
9496 		return NULL;
9497 
9498 	return map_type_name[t];
9499 }
9500 
9501 const char *libbpf_bpf_prog_type_str(enum bpf_prog_type t)
9502 {
9503 	if (t < 0 || t >= ARRAY_SIZE(prog_type_name))
9504 		return NULL;
9505 
9506 	return prog_type_name[t];
9507 }
9508 
9509 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
9510 						     size_t offset)
9511 {
9512 	struct bpf_map *map;
9513 	size_t i;
9514 
9515 	for (i = 0; i < obj->nr_maps; i++) {
9516 		map = &obj->maps[i];
9517 		if (!bpf_map__is_struct_ops(map))
9518 			continue;
9519 		if (map->sec_offset <= offset &&
9520 		    offset - map->sec_offset < map->def.value_size)
9521 			return map;
9522 	}
9523 
9524 	return NULL;
9525 }
9526 
9527 /* Collect the reloc from ELF and populate the st_ops->progs[] */
9528 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
9529 					    Elf64_Shdr *shdr, Elf_Data *data)
9530 {
9531 	const struct btf_member *member;
9532 	struct bpf_struct_ops *st_ops;
9533 	struct bpf_program *prog;
9534 	unsigned int shdr_idx;
9535 	const struct btf *btf;
9536 	struct bpf_map *map;
9537 	unsigned int moff, insn_idx;
9538 	const char *name;
9539 	__u32 member_idx;
9540 	Elf64_Sym *sym;
9541 	Elf64_Rel *rel;
9542 	int i, nrels;
9543 
9544 	btf = obj->btf;
9545 	nrels = shdr->sh_size / shdr->sh_entsize;
9546 	for (i = 0; i < nrels; i++) {
9547 		rel = elf_rel_by_idx(data, i);
9548 		if (!rel) {
9549 			pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
9550 			return -LIBBPF_ERRNO__FORMAT;
9551 		}
9552 
9553 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
9554 		if (!sym) {
9555 			pr_warn("struct_ops reloc: symbol %zx not found\n",
9556 				(size_t)ELF64_R_SYM(rel->r_info));
9557 			return -LIBBPF_ERRNO__FORMAT;
9558 		}
9559 
9560 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
9561 		map = find_struct_ops_map_by_offset(obj, rel->r_offset);
9562 		if (!map) {
9563 			pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
9564 				(size_t)rel->r_offset);
9565 			return -EINVAL;
9566 		}
9567 
9568 		moff = rel->r_offset - map->sec_offset;
9569 		shdr_idx = sym->st_shndx;
9570 		st_ops = map->st_ops;
9571 		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",
9572 			 map->name,
9573 			 (long long)(rel->r_info >> 32),
9574 			 (long long)sym->st_value,
9575 			 shdr_idx, (size_t)rel->r_offset,
9576 			 map->sec_offset, sym->st_name, name);
9577 
9578 		if (shdr_idx >= SHN_LORESERVE) {
9579 			pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
9580 				map->name, (size_t)rel->r_offset, shdr_idx);
9581 			return -LIBBPF_ERRNO__RELOC;
9582 		}
9583 		if (sym->st_value % BPF_INSN_SZ) {
9584 			pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
9585 				map->name, (unsigned long long)sym->st_value);
9586 			return -LIBBPF_ERRNO__FORMAT;
9587 		}
9588 		insn_idx = sym->st_value / BPF_INSN_SZ;
9589 
9590 		member = find_member_by_offset(st_ops->type, moff * 8);
9591 		if (!member) {
9592 			pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
9593 				map->name, moff);
9594 			return -EINVAL;
9595 		}
9596 		member_idx = member - btf_members(st_ops->type);
9597 		name = btf__name_by_offset(btf, member->name_off);
9598 
9599 		if (!resolve_func_ptr(btf, member->type, NULL)) {
9600 			pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
9601 				map->name, name);
9602 			return -EINVAL;
9603 		}
9604 
9605 		prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
9606 		if (!prog) {
9607 			pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
9608 				map->name, shdr_idx, name);
9609 			return -EINVAL;
9610 		}
9611 
9612 		/* prevent the use of BPF prog with invalid type */
9613 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
9614 			pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
9615 				map->name, prog->name);
9616 			return -EINVAL;
9617 		}
9618 
9619 		/* if we haven't yet processed this BPF program, record proper
9620 		 * attach_btf_id and member_idx
9621 		 */
9622 		if (!prog->attach_btf_id) {
9623 			prog->attach_btf_id = st_ops->type_id;
9624 			prog->expected_attach_type = member_idx;
9625 		}
9626 
9627 		/* struct_ops BPF prog can be re-used between multiple
9628 		 * .struct_ops as long as it's the same struct_ops struct
9629 		 * definition and the same function pointer field
9630 		 */
9631 		if (prog->attach_btf_id != st_ops->type_id ||
9632 		    prog->expected_attach_type != member_idx) {
9633 			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",
9634 				map->name, prog->name, prog->sec_name, prog->type,
9635 				prog->attach_btf_id, prog->expected_attach_type, name);
9636 			return -EINVAL;
9637 		}
9638 
9639 		st_ops->progs[member_idx] = prog;
9640 	}
9641 
9642 	return 0;
9643 }
9644 
9645 #define BTF_TRACE_PREFIX "btf_trace_"
9646 #define BTF_LSM_PREFIX "bpf_lsm_"
9647 #define BTF_ITER_PREFIX "bpf_iter_"
9648 #define BTF_MAX_NAME_SIZE 128
9649 
9650 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
9651 				const char **prefix, int *kind)
9652 {
9653 	switch (attach_type) {
9654 	case BPF_TRACE_RAW_TP:
9655 		*prefix = BTF_TRACE_PREFIX;
9656 		*kind = BTF_KIND_TYPEDEF;
9657 		break;
9658 	case BPF_LSM_MAC:
9659 		*prefix = BTF_LSM_PREFIX;
9660 		*kind = BTF_KIND_FUNC;
9661 		break;
9662 	case BPF_TRACE_ITER:
9663 		*prefix = BTF_ITER_PREFIX;
9664 		*kind = BTF_KIND_FUNC;
9665 		break;
9666 	default:
9667 		*prefix = "";
9668 		*kind = BTF_KIND_FUNC;
9669 	}
9670 }
9671 
9672 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
9673 				   const char *name, __u32 kind)
9674 {
9675 	char btf_type_name[BTF_MAX_NAME_SIZE];
9676 	int ret;
9677 
9678 	ret = snprintf(btf_type_name, sizeof(btf_type_name),
9679 		       "%s%s", prefix, name);
9680 	/* snprintf returns the number of characters written excluding the
9681 	 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
9682 	 * indicates truncation.
9683 	 */
9684 	if (ret < 0 || ret >= sizeof(btf_type_name))
9685 		return -ENAMETOOLONG;
9686 	return btf__find_by_name_kind(btf, btf_type_name, kind);
9687 }
9688 
9689 static inline int find_attach_btf_id(struct btf *btf, const char *name,
9690 				     enum bpf_attach_type attach_type)
9691 {
9692 	const char *prefix;
9693 	int kind;
9694 
9695 	btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
9696 	return find_btf_by_prefix_kind(btf, prefix, name, kind);
9697 }
9698 
9699 int libbpf_find_vmlinux_btf_id(const char *name,
9700 			       enum bpf_attach_type attach_type)
9701 {
9702 	struct btf *btf;
9703 	int err;
9704 
9705 	btf = btf__load_vmlinux_btf();
9706 	err = libbpf_get_error(btf);
9707 	if (err) {
9708 		pr_warn("vmlinux BTF is not found\n");
9709 		return libbpf_err(err);
9710 	}
9711 
9712 	err = find_attach_btf_id(btf, name, attach_type);
9713 	if (err <= 0)
9714 		pr_warn("%s is not found in vmlinux BTF\n", name);
9715 
9716 	btf__free(btf);
9717 	return libbpf_err(err);
9718 }
9719 
9720 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
9721 {
9722 	struct bpf_prog_info info = {};
9723 	__u32 info_len = sizeof(info);
9724 	struct btf *btf;
9725 	int err;
9726 
9727 	err = bpf_obj_get_info_by_fd(attach_prog_fd, &info, &info_len);
9728 	if (err) {
9729 		pr_warn("failed bpf_obj_get_info_by_fd for FD %d: %d\n",
9730 			attach_prog_fd, err);
9731 		return err;
9732 	}
9733 
9734 	err = -EINVAL;
9735 	if (!info.btf_id) {
9736 		pr_warn("The target program doesn't have BTF\n");
9737 		goto out;
9738 	}
9739 	btf = btf__load_from_kernel_by_id(info.btf_id);
9740 	err = libbpf_get_error(btf);
9741 	if (err) {
9742 		pr_warn("Failed to get BTF %d of the program: %d\n", info.btf_id, err);
9743 		goto out;
9744 	}
9745 	err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
9746 	btf__free(btf);
9747 	if (err <= 0) {
9748 		pr_warn("%s is not found in prog's BTF\n", name);
9749 		goto out;
9750 	}
9751 out:
9752 	return err;
9753 }
9754 
9755 static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
9756 			      enum bpf_attach_type attach_type,
9757 			      int *btf_obj_fd, int *btf_type_id)
9758 {
9759 	int ret, i;
9760 
9761 	ret = find_attach_btf_id(obj->btf_vmlinux, attach_name, attach_type);
9762 	if (ret > 0) {
9763 		*btf_obj_fd = 0; /* vmlinux BTF */
9764 		*btf_type_id = ret;
9765 		return 0;
9766 	}
9767 	if (ret != -ENOENT)
9768 		return ret;
9769 
9770 	ret = load_module_btfs(obj);
9771 	if (ret)
9772 		return ret;
9773 
9774 	for (i = 0; i < obj->btf_module_cnt; i++) {
9775 		const struct module_btf *mod = &obj->btf_modules[i];
9776 
9777 		ret = find_attach_btf_id(mod->btf, attach_name, attach_type);
9778 		if (ret > 0) {
9779 			*btf_obj_fd = mod->fd;
9780 			*btf_type_id = ret;
9781 			return 0;
9782 		}
9783 		if (ret == -ENOENT)
9784 			continue;
9785 
9786 		return ret;
9787 	}
9788 
9789 	return -ESRCH;
9790 }
9791 
9792 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
9793 				     int *btf_obj_fd, int *btf_type_id)
9794 {
9795 	enum bpf_attach_type attach_type = prog->expected_attach_type;
9796 	__u32 attach_prog_fd = prog->attach_prog_fd;
9797 	int err = 0;
9798 
9799 	/* BPF program's BTF ID */
9800 	if (attach_prog_fd) {
9801 		err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd);
9802 		if (err < 0) {
9803 			pr_warn("failed to find BPF program (FD %d) BTF ID for '%s': %d\n",
9804 				 attach_prog_fd, attach_name, err);
9805 			return err;
9806 		}
9807 		*btf_obj_fd = 0;
9808 		*btf_type_id = err;
9809 		return 0;
9810 	}
9811 
9812 	/* kernel/module BTF ID */
9813 	if (prog->obj->gen_loader) {
9814 		bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
9815 		*btf_obj_fd = 0;
9816 		*btf_type_id = 1;
9817 	} else {
9818 		err = find_kernel_btf_id(prog->obj, attach_name, attach_type, btf_obj_fd, btf_type_id);
9819 	}
9820 	if (err) {
9821 		pr_warn("failed to find kernel BTF type ID of '%s': %d\n", attach_name, err);
9822 		return err;
9823 	}
9824 	return 0;
9825 }
9826 
9827 int libbpf_attach_type_by_name(const char *name,
9828 			       enum bpf_attach_type *attach_type)
9829 {
9830 	char *type_names;
9831 	const struct bpf_sec_def *sec_def;
9832 
9833 	if (!name)
9834 		return libbpf_err(-EINVAL);
9835 
9836 	sec_def = find_sec_def(name);
9837 	if (!sec_def) {
9838 		pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
9839 		type_names = libbpf_get_type_names(true);
9840 		if (type_names != NULL) {
9841 			pr_debug("attachable section(type) names are:%s\n", type_names);
9842 			free(type_names);
9843 		}
9844 
9845 		return libbpf_err(-EINVAL);
9846 	}
9847 
9848 	if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
9849 		return libbpf_err(-EINVAL);
9850 	if (!(sec_def->cookie & SEC_ATTACHABLE))
9851 		return libbpf_err(-EINVAL);
9852 
9853 	*attach_type = sec_def->expected_attach_type;
9854 	return 0;
9855 }
9856 
9857 int bpf_map__fd(const struct bpf_map *map)
9858 {
9859 	return map ? map->fd : libbpf_err(-EINVAL);
9860 }
9861 
9862 const struct bpf_map_def *bpf_map__def(const struct bpf_map *map)
9863 {
9864 	return map ? &map->def : libbpf_err_ptr(-EINVAL);
9865 }
9866 
9867 static bool map_uses_real_name(const struct bpf_map *map)
9868 {
9869 	/* Since libbpf started to support custom .data.* and .rodata.* maps,
9870 	 * their user-visible name differs from kernel-visible name. Users see
9871 	 * such map's corresponding ELF section name as a map name.
9872 	 * This check distinguishes .data/.rodata from .data.* and .rodata.*
9873 	 * maps to know which name has to be returned to the user.
9874 	 */
9875 	if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
9876 		return true;
9877 	if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
9878 		return true;
9879 	return false;
9880 }
9881 
9882 const char *bpf_map__name(const struct bpf_map *map)
9883 {
9884 	if (!map)
9885 		return NULL;
9886 
9887 	if (map_uses_real_name(map))
9888 		return map->real_name;
9889 
9890 	return map->name;
9891 }
9892 
9893 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
9894 {
9895 	return map->def.type;
9896 }
9897 
9898 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
9899 {
9900 	if (map->fd >= 0)
9901 		return libbpf_err(-EBUSY);
9902 	map->def.type = type;
9903 	return 0;
9904 }
9905 
9906 __u32 bpf_map__map_flags(const struct bpf_map *map)
9907 {
9908 	return map->def.map_flags;
9909 }
9910 
9911 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
9912 {
9913 	if (map->fd >= 0)
9914 		return libbpf_err(-EBUSY);
9915 	map->def.map_flags = flags;
9916 	return 0;
9917 }
9918 
9919 __u64 bpf_map__map_extra(const struct bpf_map *map)
9920 {
9921 	return map->map_extra;
9922 }
9923 
9924 int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
9925 {
9926 	if (map->fd >= 0)
9927 		return libbpf_err(-EBUSY);
9928 	map->map_extra = map_extra;
9929 	return 0;
9930 }
9931 
9932 __u32 bpf_map__numa_node(const struct bpf_map *map)
9933 {
9934 	return map->numa_node;
9935 }
9936 
9937 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
9938 {
9939 	if (map->fd >= 0)
9940 		return libbpf_err(-EBUSY);
9941 	map->numa_node = numa_node;
9942 	return 0;
9943 }
9944 
9945 __u32 bpf_map__key_size(const struct bpf_map *map)
9946 {
9947 	return map->def.key_size;
9948 }
9949 
9950 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
9951 {
9952 	if (map->fd >= 0)
9953 		return libbpf_err(-EBUSY);
9954 	map->def.key_size = size;
9955 	return 0;
9956 }
9957 
9958 __u32 bpf_map__value_size(const struct bpf_map *map)
9959 {
9960 	return map->def.value_size;
9961 }
9962 
9963 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
9964 {
9965 	if (map->fd >= 0)
9966 		return libbpf_err(-EBUSY);
9967 	map->def.value_size = size;
9968 	return 0;
9969 }
9970 
9971 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
9972 {
9973 	return map ? map->btf_key_type_id : 0;
9974 }
9975 
9976 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
9977 {
9978 	return map ? map->btf_value_type_id : 0;
9979 }
9980 
9981 int bpf_map__set_priv(struct bpf_map *map, void *priv,
9982 		     bpf_map_clear_priv_t clear_priv)
9983 {
9984 	if (!map)
9985 		return libbpf_err(-EINVAL);
9986 
9987 	if (map->priv) {
9988 		if (map->clear_priv)
9989 			map->clear_priv(map, map->priv);
9990 	}
9991 
9992 	map->priv = priv;
9993 	map->clear_priv = clear_priv;
9994 	return 0;
9995 }
9996 
9997 void *bpf_map__priv(const struct bpf_map *map)
9998 {
9999 	return map ? map->priv : libbpf_err_ptr(-EINVAL);
10000 }
10001 
10002 int bpf_map__set_initial_value(struct bpf_map *map,
10003 			       const void *data, size_t size)
10004 {
10005 	if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG ||
10006 	    size != map->def.value_size || map->fd >= 0)
10007 		return libbpf_err(-EINVAL);
10008 
10009 	memcpy(map->mmaped, data, size);
10010 	return 0;
10011 }
10012 
10013 const void *bpf_map__initial_value(struct bpf_map *map, size_t *psize)
10014 {
10015 	if (!map->mmaped)
10016 		return NULL;
10017 	*psize = map->def.value_size;
10018 	return map->mmaped;
10019 }
10020 
10021 bool bpf_map__is_offload_neutral(const struct bpf_map *map)
10022 {
10023 	return map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY;
10024 }
10025 
10026 bool bpf_map__is_internal(const struct bpf_map *map)
10027 {
10028 	return map->libbpf_type != LIBBPF_MAP_UNSPEC;
10029 }
10030 
10031 __u32 bpf_map__ifindex(const struct bpf_map *map)
10032 {
10033 	return map->map_ifindex;
10034 }
10035 
10036 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
10037 {
10038 	if (map->fd >= 0)
10039 		return libbpf_err(-EBUSY);
10040 	map->map_ifindex = ifindex;
10041 	return 0;
10042 }
10043 
10044 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
10045 {
10046 	if (!bpf_map_type__is_map_in_map(map->def.type)) {
10047 		pr_warn("error: unsupported map type\n");
10048 		return libbpf_err(-EINVAL);
10049 	}
10050 	if (map->inner_map_fd != -1) {
10051 		pr_warn("error: inner_map_fd already specified\n");
10052 		return libbpf_err(-EINVAL);
10053 	}
10054 	if (map->inner_map) {
10055 		bpf_map__destroy(map->inner_map);
10056 		zfree(&map->inner_map);
10057 	}
10058 	map->inner_map_fd = fd;
10059 	return 0;
10060 }
10061 
10062 static struct bpf_map *
10063 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
10064 {
10065 	ssize_t idx;
10066 	struct bpf_map *s, *e;
10067 
10068 	if (!obj || !obj->maps)
10069 		return errno = EINVAL, NULL;
10070 
10071 	s = obj->maps;
10072 	e = obj->maps + obj->nr_maps;
10073 
10074 	if ((m < s) || (m >= e)) {
10075 		pr_warn("error in %s: map handler doesn't belong to object\n",
10076 			 __func__);
10077 		return errno = EINVAL, NULL;
10078 	}
10079 
10080 	idx = (m - obj->maps) + i;
10081 	if (idx >= obj->nr_maps || idx < 0)
10082 		return NULL;
10083 	return &obj->maps[idx];
10084 }
10085 
10086 struct bpf_map *
10087 bpf_map__next(const struct bpf_map *prev, const struct bpf_object *obj)
10088 {
10089 	return bpf_object__next_map(obj, prev);
10090 }
10091 
10092 struct bpf_map *
10093 bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
10094 {
10095 	if (prev == NULL)
10096 		return obj->maps;
10097 
10098 	return __bpf_map__iter(prev, obj, 1);
10099 }
10100 
10101 struct bpf_map *
10102 bpf_map__prev(const struct bpf_map *next, const struct bpf_object *obj)
10103 {
10104 	return bpf_object__prev_map(obj, next);
10105 }
10106 
10107 struct bpf_map *
10108 bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
10109 {
10110 	if (next == NULL) {
10111 		if (!obj->nr_maps)
10112 			return NULL;
10113 		return obj->maps + obj->nr_maps - 1;
10114 	}
10115 
10116 	return __bpf_map__iter(next, obj, -1);
10117 }
10118 
10119 struct bpf_map *
10120 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
10121 {
10122 	struct bpf_map *pos;
10123 
10124 	bpf_object__for_each_map(pos, obj) {
10125 		/* if it's a special internal map name (which always starts
10126 		 * with dot) then check if that special name matches the
10127 		 * real map name (ELF section name)
10128 		 */
10129 		if (name[0] == '.') {
10130 			if (pos->real_name && strcmp(pos->real_name, name) == 0)
10131 				return pos;
10132 			continue;
10133 		}
10134 		/* otherwise map name has to be an exact match */
10135 		if (map_uses_real_name(pos)) {
10136 			if (strcmp(pos->real_name, name) == 0)
10137 				return pos;
10138 			continue;
10139 		}
10140 		if (strcmp(pos->name, name) == 0)
10141 			return pos;
10142 	}
10143 	return errno = ENOENT, NULL;
10144 }
10145 
10146 int
10147 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
10148 {
10149 	return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
10150 }
10151 
10152 struct bpf_map *
10153 bpf_object__find_map_by_offset(struct bpf_object *obj, size_t offset)
10154 {
10155 	return libbpf_err_ptr(-ENOTSUP);
10156 }
10157 
10158 static int validate_map_op(const struct bpf_map *map, size_t key_sz,
10159 			   size_t value_sz, bool check_value_sz)
10160 {
10161 	if (map->fd <= 0)
10162 		return -ENOENT;
10163 
10164 	if (map->def.key_size != key_sz) {
10165 		pr_warn("map '%s': unexpected key size %zu provided, expected %u\n",
10166 			map->name, key_sz, map->def.key_size);
10167 		return -EINVAL;
10168 	}
10169 
10170 	if (!check_value_sz)
10171 		return 0;
10172 
10173 	switch (map->def.type) {
10174 	case BPF_MAP_TYPE_PERCPU_ARRAY:
10175 	case BPF_MAP_TYPE_PERCPU_HASH:
10176 	case BPF_MAP_TYPE_LRU_PERCPU_HASH:
10177 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: {
10178 		int num_cpu = libbpf_num_possible_cpus();
10179 		size_t elem_sz = roundup(map->def.value_size, 8);
10180 
10181 		if (value_sz != num_cpu * elem_sz) {
10182 			pr_warn("map '%s': unexpected value size %zu provided for per-CPU map, expected %d * %zu = %zd\n",
10183 				map->name, value_sz, num_cpu, elem_sz, num_cpu * elem_sz);
10184 			return -EINVAL;
10185 		}
10186 		break;
10187 	}
10188 	default:
10189 		if (map->def.value_size != value_sz) {
10190 			pr_warn("map '%s': unexpected value size %zu provided, expected %u\n",
10191 				map->name, value_sz, map->def.value_size);
10192 			return -EINVAL;
10193 		}
10194 		break;
10195 	}
10196 	return 0;
10197 }
10198 
10199 int bpf_map__lookup_elem(const struct bpf_map *map,
10200 			 const void *key, size_t key_sz,
10201 			 void *value, size_t value_sz, __u64 flags)
10202 {
10203 	int err;
10204 
10205 	err = validate_map_op(map, key_sz, value_sz, true);
10206 	if (err)
10207 		return libbpf_err(err);
10208 
10209 	return bpf_map_lookup_elem_flags(map->fd, key, value, flags);
10210 }
10211 
10212 int bpf_map__update_elem(const struct bpf_map *map,
10213 			 const void *key, size_t key_sz,
10214 			 const void *value, size_t value_sz, __u64 flags)
10215 {
10216 	int err;
10217 
10218 	err = validate_map_op(map, key_sz, value_sz, true);
10219 	if (err)
10220 		return libbpf_err(err);
10221 
10222 	return bpf_map_update_elem(map->fd, key, value, flags);
10223 }
10224 
10225 int bpf_map__delete_elem(const struct bpf_map *map,
10226 			 const void *key, size_t key_sz, __u64 flags)
10227 {
10228 	int err;
10229 
10230 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
10231 	if (err)
10232 		return libbpf_err(err);
10233 
10234 	return bpf_map_delete_elem_flags(map->fd, key, flags);
10235 }
10236 
10237 int bpf_map__lookup_and_delete_elem(const struct bpf_map *map,
10238 				    const void *key, size_t key_sz,
10239 				    void *value, size_t value_sz, __u64 flags)
10240 {
10241 	int err;
10242 
10243 	err = validate_map_op(map, key_sz, value_sz, true);
10244 	if (err)
10245 		return libbpf_err(err);
10246 
10247 	return bpf_map_lookup_and_delete_elem_flags(map->fd, key, value, flags);
10248 }
10249 
10250 int bpf_map__get_next_key(const struct bpf_map *map,
10251 			  const void *cur_key, void *next_key, size_t key_sz)
10252 {
10253 	int err;
10254 
10255 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
10256 	if (err)
10257 		return libbpf_err(err);
10258 
10259 	return bpf_map_get_next_key(map->fd, cur_key, next_key);
10260 }
10261 
10262 long libbpf_get_error(const void *ptr)
10263 {
10264 	if (!IS_ERR_OR_NULL(ptr))
10265 		return 0;
10266 
10267 	if (IS_ERR(ptr))
10268 		errno = -PTR_ERR(ptr);
10269 
10270 	/* If ptr == NULL, then errno should be already set by the failing
10271 	 * API, because libbpf never returns NULL on success and it now always
10272 	 * sets errno on error. So no extra errno handling for ptr == NULL
10273 	 * case.
10274 	 */
10275 	return -errno;
10276 }
10277 
10278 __attribute__((alias("bpf_prog_load_xattr2")))
10279 int bpf_prog_load_xattr(const struct bpf_prog_load_attr *attr,
10280 			struct bpf_object **pobj, int *prog_fd);
10281 
10282 static int bpf_prog_load_xattr2(const struct bpf_prog_load_attr *attr,
10283 				struct bpf_object **pobj, int *prog_fd)
10284 {
10285 	struct bpf_object_open_attr open_attr = {};
10286 	struct bpf_program *prog, *first_prog = NULL;
10287 	struct bpf_object *obj;
10288 	struct bpf_map *map;
10289 	int err;
10290 
10291 	if (!attr)
10292 		return libbpf_err(-EINVAL);
10293 	if (!attr->file)
10294 		return libbpf_err(-EINVAL);
10295 
10296 	open_attr.file = attr->file;
10297 	open_attr.prog_type = attr->prog_type;
10298 
10299 	obj = __bpf_object__open_xattr(&open_attr, 0);
10300 	err = libbpf_get_error(obj);
10301 	if (err)
10302 		return libbpf_err(-ENOENT);
10303 
10304 	bpf_object__for_each_program(prog, obj) {
10305 		enum bpf_attach_type attach_type = attr->expected_attach_type;
10306 		/*
10307 		 * to preserve backwards compatibility, bpf_prog_load treats
10308 		 * attr->prog_type, if specified, as an override to whatever
10309 		 * bpf_object__open guessed
10310 		 */
10311 		if (attr->prog_type != BPF_PROG_TYPE_UNSPEC) {
10312 			prog->type = attr->prog_type;
10313 			prog->expected_attach_type = attach_type;
10314 		}
10315 		if (bpf_program__type(prog) == BPF_PROG_TYPE_UNSPEC) {
10316 			/*
10317 			 * we haven't guessed from section name and user
10318 			 * didn't provide a fallback type, too bad...
10319 			 */
10320 			bpf_object__close(obj);
10321 			return libbpf_err(-EINVAL);
10322 		}
10323 
10324 		prog->prog_ifindex = attr->ifindex;
10325 		prog->log_level = attr->log_level;
10326 		prog->prog_flags |= attr->prog_flags;
10327 		if (!first_prog)
10328 			first_prog = prog;
10329 	}
10330 
10331 	bpf_object__for_each_map(map, obj) {
10332 		if (map->def.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
10333 			map->map_ifindex = attr->ifindex;
10334 	}
10335 
10336 	if (!first_prog) {
10337 		pr_warn("object file doesn't contain bpf program\n");
10338 		bpf_object__close(obj);
10339 		return libbpf_err(-ENOENT);
10340 	}
10341 
10342 	err = bpf_object__load(obj);
10343 	if (err) {
10344 		bpf_object__close(obj);
10345 		return libbpf_err(err);
10346 	}
10347 
10348 	*pobj = obj;
10349 	*prog_fd = bpf_program__fd(first_prog);
10350 	return 0;
10351 }
10352 
10353 COMPAT_VERSION(bpf_prog_load_deprecated, bpf_prog_load, LIBBPF_0.0.1)
10354 int bpf_prog_load_deprecated(const char *file, enum bpf_prog_type type,
10355 			     struct bpf_object **pobj, int *prog_fd)
10356 {
10357 	struct bpf_prog_load_attr attr;
10358 
10359 	memset(&attr, 0, sizeof(struct bpf_prog_load_attr));
10360 	attr.file = file;
10361 	attr.prog_type = type;
10362 	attr.expected_attach_type = 0;
10363 
10364 	return bpf_prog_load_xattr2(&attr, pobj, prog_fd);
10365 }
10366 
10367 /* Replace link's underlying BPF program with the new one */
10368 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
10369 {
10370 	int ret;
10371 
10372 	ret = bpf_link_update(bpf_link__fd(link), bpf_program__fd(prog), NULL);
10373 	return libbpf_err_errno(ret);
10374 }
10375 
10376 /* Release "ownership" of underlying BPF resource (typically, BPF program
10377  * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
10378  * link, when destructed through bpf_link__destroy() call won't attempt to
10379  * detach/unregisted that BPF resource. This is useful in situations where,
10380  * say, attached BPF program has to outlive userspace program that attached it
10381  * in the system. Depending on type of BPF program, though, there might be
10382  * additional steps (like pinning BPF program in BPF FS) necessary to ensure
10383  * exit of userspace program doesn't trigger automatic detachment and clean up
10384  * inside the kernel.
10385  */
10386 void bpf_link__disconnect(struct bpf_link *link)
10387 {
10388 	link->disconnected = true;
10389 }
10390 
10391 int bpf_link__destroy(struct bpf_link *link)
10392 {
10393 	int err = 0;
10394 
10395 	if (IS_ERR_OR_NULL(link))
10396 		return 0;
10397 
10398 	if (!link->disconnected && link->detach)
10399 		err = link->detach(link);
10400 	if (link->pin_path)
10401 		free(link->pin_path);
10402 	if (link->dealloc)
10403 		link->dealloc(link);
10404 	else
10405 		free(link);
10406 
10407 	return libbpf_err(err);
10408 }
10409 
10410 int bpf_link__fd(const struct bpf_link *link)
10411 {
10412 	return link->fd;
10413 }
10414 
10415 const char *bpf_link__pin_path(const struct bpf_link *link)
10416 {
10417 	return link->pin_path;
10418 }
10419 
10420 static int bpf_link__detach_fd(struct bpf_link *link)
10421 {
10422 	return libbpf_err_errno(close(link->fd));
10423 }
10424 
10425 struct bpf_link *bpf_link__open(const char *path)
10426 {
10427 	struct bpf_link *link;
10428 	int fd;
10429 
10430 	fd = bpf_obj_get(path);
10431 	if (fd < 0) {
10432 		fd = -errno;
10433 		pr_warn("failed to open link at %s: %d\n", path, fd);
10434 		return libbpf_err_ptr(fd);
10435 	}
10436 
10437 	link = calloc(1, sizeof(*link));
10438 	if (!link) {
10439 		close(fd);
10440 		return libbpf_err_ptr(-ENOMEM);
10441 	}
10442 	link->detach = &bpf_link__detach_fd;
10443 	link->fd = fd;
10444 
10445 	link->pin_path = strdup(path);
10446 	if (!link->pin_path) {
10447 		bpf_link__destroy(link);
10448 		return libbpf_err_ptr(-ENOMEM);
10449 	}
10450 
10451 	return link;
10452 }
10453 
10454 int bpf_link__detach(struct bpf_link *link)
10455 {
10456 	return bpf_link_detach(link->fd) ? -errno : 0;
10457 }
10458 
10459 int bpf_link__pin(struct bpf_link *link, const char *path)
10460 {
10461 	int err;
10462 
10463 	if (link->pin_path)
10464 		return libbpf_err(-EBUSY);
10465 	err = make_parent_dir(path);
10466 	if (err)
10467 		return libbpf_err(err);
10468 	err = check_path(path);
10469 	if (err)
10470 		return libbpf_err(err);
10471 
10472 	link->pin_path = strdup(path);
10473 	if (!link->pin_path)
10474 		return libbpf_err(-ENOMEM);
10475 
10476 	if (bpf_obj_pin(link->fd, link->pin_path)) {
10477 		err = -errno;
10478 		zfree(&link->pin_path);
10479 		return libbpf_err(err);
10480 	}
10481 
10482 	pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
10483 	return 0;
10484 }
10485 
10486 int bpf_link__unpin(struct bpf_link *link)
10487 {
10488 	int err;
10489 
10490 	if (!link->pin_path)
10491 		return libbpf_err(-EINVAL);
10492 
10493 	err = unlink(link->pin_path);
10494 	if (err != 0)
10495 		return -errno;
10496 
10497 	pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
10498 	zfree(&link->pin_path);
10499 	return 0;
10500 }
10501 
10502 struct bpf_link_perf {
10503 	struct bpf_link link;
10504 	int perf_event_fd;
10505 	/* legacy kprobe support: keep track of probe identifier and type */
10506 	char *legacy_probe_name;
10507 	bool legacy_is_kprobe;
10508 	bool legacy_is_retprobe;
10509 };
10510 
10511 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
10512 static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
10513 
10514 static int bpf_link_perf_detach(struct bpf_link *link)
10515 {
10516 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10517 	int err = 0;
10518 
10519 	if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
10520 		err = -errno;
10521 
10522 	if (perf_link->perf_event_fd != link->fd)
10523 		close(perf_link->perf_event_fd);
10524 	close(link->fd);
10525 
10526 	/* legacy uprobe/kprobe needs to be removed after perf event fd closure */
10527 	if (perf_link->legacy_probe_name) {
10528 		if (perf_link->legacy_is_kprobe) {
10529 			err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
10530 							 perf_link->legacy_is_retprobe);
10531 		} else {
10532 			err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
10533 							 perf_link->legacy_is_retprobe);
10534 		}
10535 	}
10536 
10537 	return err;
10538 }
10539 
10540 static void bpf_link_perf_dealloc(struct bpf_link *link)
10541 {
10542 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10543 
10544 	free(perf_link->legacy_probe_name);
10545 	free(perf_link);
10546 }
10547 
10548 struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
10549 						     const struct bpf_perf_event_opts *opts)
10550 {
10551 	char errmsg[STRERR_BUFSIZE];
10552 	struct bpf_link_perf *link;
10553 	int prog_fd, link_fd = -1, err;
10554 
10555 	if (!OPTS_VALID(opts, bpf_perf_event_opts))
10556 		return libbpf_err_ptr(-EINVAL);
10557 
10558 	if (pfd < 0) {
10559 		pr_warn("prog '%s': invalid perf event FD %d\n",
10560 			prog->name, pfd);
10561 		return libbpf_err_ptr(-EINVAL);
10562 	}
10563 	prog_fd = bpf_program__fd(prog);
10564 	if (prog_fd < 0) {
10565 		pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
10566 			prog->name);
10567 		return libbpf_err_ptr(-EINVAL);
10568 	}
10569 
10570 	link = calloc(1, sizeof(*link));
10571 	if (!link)
10572 		return libbpf_err_ptr(-ENOMEM);
10573 	link->link.detach = &bpf_link_perf_detach;
10574 	link->link.dealloc = &bpf_link_perf_dealloc;
10575 	link->perf_event_fd = pfd;
10576 
10577 	if (kernel_supports(prog->obj, FEAT_PERF_LINK)) {
10578 		DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
10579 			.perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
10580 
10581 		link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
10582 		if (link_fd < 0) {
10583 			err = -errno;
10584 			pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %d (%s)\n",
10585 				prog->name, pfd,
10586 				err, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10587 			goto err_out;
10588 		}
10589 		link->link.fd = link_fd;
10590 	} else {
10591 		if (OPTS_GET(opts, bpf_cookie, 0)) {
10592 			pr_warn("prog '%s': user context value is not supported\n", prog->name);
10593 			err = -EOPNOTSUPP;
10594 			goto err_out;
10595 		}
10596 
10597 		if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
10598 			err = -errno;
10599 			pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
10600 				prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10601 			if (err == -EPROTO)
10602 				pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
10603 					prog->name, pfd);
10604 			goto err_out;
10605 		}
10606 		link->link.fd = pfd;
10607 	}
10608 	if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
10609 		err = -errno;
10610 		pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
10611 			prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10612 		goto err_out;
10613 	}
10614 
10615 	return &link->link;
10616 err_out:
10617 	if (link_fd >= 0)
10618 		close(link_fd);
10619 	free(link);
10620 	return libbpf_err_ptr(err);
10621 }
10622 
10623 struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
10624 {
10625 	return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
10626 }
10627 
10628 /*
10629  * this function is expected to parse integer in the range of [0, 2^31-1] from
10630  * given file using scanf format string fmt. If actual parsed value is
10631  * negative, the result might be indistinguishable from error
10632  */
10633 static int parse_uint_from_file(const char *file, const char *fmt)
10634 {
10635 	char buf[STRERR_BUFSIZE];
10636 	int err, ret;
10637 	FILE *f;
10638 
10639 	f = fopen(file, "r");
10640 	if (!f) {
10641 		err = -errno;
10642 		pr_debug("failed to open '%s': %s\n", file,
10643 			 libbpf_strerror_r(err, buf, sizeof(buf)));
10644 		return err;
10645 	}
10646 	err = fscanf(f, fmt, &ret);
10647 	if (err != 1) {
10648 		err = err == EOF ? -EIO : -errno;
10649 		pr_debug("failed to parse '%s': %s\n", file,
10650 			libbpf_strerror_r(err, buf, sizeof(buf)));
10651 		fclose(f);
10652 		return err;
10653 	}
10654 	fclose(f);
10655 	return ret;
10656 }
10657 
10658 static int determine_kprobe_perf_type(void)
10659 {
10660 	const char *file = "/sys/bus/event_source/devices/kprobe/type";
10661 
10662 	return parse_uint_from_file(file, "%d\n");
10663 }
10664 
10665 static int determine_uprobe_perf_type(void)
10666 {
10667 	const char *file = "/sys/bus/event_source/devices/uprobe/type";
10668 
10669 	return parse_uint_from_file(file, "%d\n");
10670 }
10671 
10672 static int determine_kprobe_retprobe_bit(void)
10673 {
10674 	const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
10675 
10676 	return parse_uint_from_file(file, "config:%d\n");
10677 }
10678 
10679 static int determine_uprobe_retprobe_bit(void)
10680 {
10681 	const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
10682 
10683 	return parse_uint_from_file(file, "config:%d\n");
10684 }
10685 
10686 #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
10687 #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
10688 
10689 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
10690 				 uint64_t offset, int pid, size_t ref_ctr_off)
10691 {
10692 	struct perf_event_attr attr = {};
10693 	char errmsg[STRERR_BUFSIZE];
10694 	int type, pfd, err;
10695 
10696 	if (ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
10697 		return -EINVAL;
10698 
10699 	type = uprobe ? determine_uprobe_perf_type()
10700 		      : determine_kprobe_perf_type();
10701 	if (type < 0) {
10702 		pr_warn("failed to determine %s perf type: %s\n",
10703 			uprobe ? "uprobe" : "kprobe",
10704 			libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
10705 		return type;
10706 	}
10707 	if (retprobe) {
10708 		int bit = uprobe ? determine_uprobe_retprobe_bit()
10709 				 : determine_kprobe_retprobe_bit();
10710 
10711 		if (bit < 0) {
10712 			pr_warn("failed to determine %s retprobe bit: %s\n",
10713 				uprobe ? "uprobe" : "kprobe",
10714 				libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
10715 			return bit;
10716 		}
10717 		attr.config |= 1 << bit;
10718 	}
10719 	attr.size = sizeof(attr);
10720 	attr.type = type;
10721 	attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
10722 	attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
10723 	attr.config2 = offset;		 /* kprobe_addr or probe_offset */
10724 
10725 	/* pid filter is meaningful only for uprobes */
10726 	pfd = syscall(__NR_perf_event_open, &attr,
10727 		      pid < 0 ? -1 : pid /* pid */,
10728 		      pid == -1 ? 0 : -1 /* cpu */,
10729 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
10730 	if (pfd < 0) {
10731 		err = -errno;
10732 		pr_warn("%s perf_event_open() failed: %s\n",
10733 			uprobe ? "uprobe" : "kprobe",
10734 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10735 		return err;
10736 	}
10737 	return pfd;
10738 }
10739 
10740 static int append_to_file(const char *file, const char *fmt, ...)
10741 {
10742 	int fd, n, err = 0;
10743 	va_list ap;
10744 
10745 	fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
10746 	if (fd < 0)
10747 		return -errno;
10748 
10749 	va_start(ap, fmt);
10750 	n = vdprintf(fd, fmt, ap);
10751 	va_end(ap);
10752 
10753 	if (n < 0)
10754 		err = -errno;
10755 
10756 	close(fd);
10757 	return err;
10758 }
10759 
10760 static void gen_kprobe_legacy_event_name(char *buf, size_t buf_sz,
10761 					 const char *kfunc_name, size_t offset)
10762 {
10763 	static int index = 0;
10764 
10765 	snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx_%d", getpid(), kfunc_name, offset,
10766 		 __sync_fetch_and_add(&index, 1));
10767 }
10768 
10769 static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
10770 				   const char *kfunc_name, size_t offset)
10771 {
10772 	const char *file = "/sys/kernel/debug/tracing/kprobe_events";
10773 
10774 	return append_to_file(file, "%c:%s/%s %s+0x%zx",
10775 			      retprobe ? 'r' : 'p',
10776 			      retprobe ? "kretprobes" : "kprobes",
10777 			      probe_name, kfunc_name, offset);
10778 }
10779 
10780 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
10781 {
10782 	const char *file = "/sys/kernel/debug/tracing/kprobe_events";
10783 
10784 	return append_to_file(file, "-:%s/%s", retprobe ? "kretprobes" : "kprobes", probe_name);
10785 }
10786 
10787 static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
10788 {
10789 	char file[256];
10790 
10791 	snprintf(file, sizeof(file),
10792 		 "/sys/kernel/debug/tracing/events/%s/%s/id",
10793 		 retprobe ? "kretprobes" : "kprobes", probe_name);
10794 
10795 	return parse_uint_from_file(file, "%d\n");
10796 }
10797 
10798 static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
10799 					 const char *kfunc_name, size_t offset, int pid)
10800 {
10801 	struct perf_event_attr attr = {};
10802 	char errmsg[STRERR_BUFSIZE];
10803 	int type, pfd, err;
10804 
10805 	err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
10806 	if (err < 0) {
10807 		pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
10808 			kfunc_name, offset,
10809 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10810 		return err;
10811 	}
10812 	type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
10813 	if (type < 0) {
10814 		pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
10815 			kfunc_name, offset,
10816 			libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
10817 		return type;
10818 	}
10819 	attr.size = sizeof(attr);
10820 	attr.config = type;
10821 	attr.type = PERF_TYPE_TRACEPOINT;
10822 
10823 	pfd = syscall(__NR_perf_event_open, &attr,
10824 		      pid < 0 ? -1 : pid, /* pid */
10825 		      pid == -1 ? 0 : -1, /* cpu */
10826 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
10827 	if (pfd < 0) {
10828 		err = -errno;
10829 		pr_warn("legacy kprobe perf_event_open() failed: %s\n",
10830 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10831 		return err;
10832 	}
10833 	return pfd;
10834 }
10835 
10836 struct bpf_link *
10837 bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
10838 				const char *func_name,
10839 				const struct bpf_kprobe_opts *opts)
10840 {
10841 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
10842 	char errmsg[STRERR_BUFSIZE];
10843 	char *legacy_probe = NULL;
10844 	struct bpf_link *link;
10845 	size_t offset;
10846 	bool retprobe, legacy;
10847 	int pfd, err;
10848 
10849 	if (!OPTS_VALID(opts, bpf_kprobe_opts))
10850 		return libbpf_err_ptr(-EINVAL);
10851 
10852 	retprobe = OPTS_GET(opts, retprobe, false);
10853 	offset = OPTS_GET(opts, offset, 0);
10854 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10855 
10856 	legacy = determine_kprobe_perf_type() < 0;
10857 	if (!legacy) {
10858 		pfd = perf_event_open_probe(false /* uprobe */, retprobe,
10859 					    func_name, offset,
10860 					    -1 /* pid */, 0 /* ref_ctr_off */);
10861 	} else {
10862 		char probe_name[256];
10863 
10864 		gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name),
10865 					     func_name, offset);
10866 
10867 		legacy_probe = strdup(probe_name);
10868 		if (!legacy_probe)
10869 			return libbpf_err_ptr(-ENOMEM);
10870 
10871 		pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
10872 						    offset, -1 /* pid */);
10873 	}
10874 	if (pfd < 0) {
10875 		err = -errno;
10876 		pr_warn("prog '%s': failed to create %s '%s+0x%zx' perf event: %s\n",
10877 			prog->name, retprobe ? "kretprobe" : "kprobe",
10878 			func_name, offset,
10879 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10880 		goto err_out;
10881 	}
10882 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
10883 	err = libbpf_get_error(link);
10884 	if (err) {
10885 		close(pfd);
10886 		pr_warn("prog '%s': failed to attach to %s '%s+0x%zx': %s\n",
10887 			prog->name, retprobe ? "kretprobe" : "kprobe",
10888 			func_name, offset,
10889 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10890 		goto err_out;
10891 	}
10892 	if (legacy) {
10893 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10894 
10895 		perf_link->legacy_probe_name = legacy_probe;
10896 		perf_link->legacy_is_kprobe = true;
10897 		perf_link->legacy_is_retprobe = retprobe;
10898 	}
10899 
10900 	return link;
10901 err_out:
10902 	free(legacy_probe);
10903 	return libbpf_err_ptr(err);
10904 }
10905 
10906 struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
10907 					    bool retprobe,
10908 					    const char *func_name)
10909 {
10910 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
10911 		.retprobe = retprobe,
10912 	);
10913 
10914 	return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
10915 }
10916 
10917 /* Adapted from perf/util/string.c */
10918 static bool glob_match(const char *str, const char *pat)
10919 {
10920 	while (*str && *pat && *pat != '*') {
10921 		if (*pat == '?') {      /* Matches any single character */
10922 			str++;
10923 			pat++;
10924 			continue;
10925 		}
10926 		if (*str != *pat)
10927 			return false;
10928 		str++;
10929 		pat++;
10930 	}
10931 	/* Check wild card */
10932 	if (*pat == '*') {
10933 		while (*pat == '*')
10934 			pat++;
10935 		if (!*pat) /* Tail wild card matches all */
10936 			return true;
10937 		while (*str)
10938 			if (glob_match(str++, pat))
10939 				return true;
10940 	}
10941 	return !*str && !*pat;
10942 }
10943 
10944 struct kprobe_multi_resolve {
10945 	const char *pattern;
10946 	unsigned long *addrs;
10947 	size_t cap;
10948 	size_t cnt;
10949 };
10950 
10951 static int
10952 resolve_kprobe_multi_cb(unsigned long long sym_addr, char sym_type,
10953 			const char *sym_name, void *ctx)
10954 {
10955 	struct kprobe_multi_resolve *res = ctx;
10956 	int err;
10957 
10958 	if (!glob_match(sym_name, res->pattern))
10959 		return 0;
10960 
10961 	err = libbpf_ensure_mem((void **) &res->addrs, &res->cap, sizeof(unsigned long),
10962 				res->cnt + 1);
10963 	if (err)
10964 		return err;
10965 
10966 	res->addrs[res->cnt++] = (unsigned long) sym_addr;
10967 	return 0;
10968 }
10969 
10970 struct bpf_link *
10971 bpf_program__attach_kprobe_multi_opts(const struct bpf_program *prog,
10972 				      const char *pattern,
10973 				      const struct bpf_kprobe_multi_opts *opts)
10974 {
10975 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
10976 	struct kprobe_multi_resolve res = {
10977 		.pattern = pattern,
10978 	};
10979 	struct bpf_link *link = NULL;
10980 	char errmsg[STRERR_BUFSIZE];
10981 	const unsigned long *addrs;
10982 	int err, link_fd, prog_fd;
10983 	const __u64 *cookies;
10984 	const char **syms;
10985 	bool retprobe;
10986 	size_t cnt;
10987 
10988 	if (!OPTS_VALID(opts, bpf_kprobe_multi_opts))
10989 		return libbpf_err_ptr(-EINVAL);
10990 
10991 	syms    = OPTS_GET(opts, syms, false);
10992 	addrs   = OPTS_GET(opts, addrs, false);
10993 	cnt     = OPTS_GET(opts, cnt, false);
10994 	cookies = OPTS_GET(opts, cookies, false);
10995 
10996 	if (!pattern && !addrs && !syms)
10997 		return libbpf_err_ptr(-EINVAL);
10998 	if (pattern && (addrs || syms || cookies || cnt))
10999 		return libbpf_err_ptr(-EINVAL);
11000 	if (!pattern && !cnt)
11001 		return libbpf_err_ptr(-EINVAL);
11002 	if (addrs && syms)
11003 		return libbpf_err_ptr(-EINVAL);
11004 
11005 	if (pattern) {
11006 		err = libbpf_kallsyms_parse(resolve_kprobe_multi_cb, &res);
11007 		if (err)
11008 			goto error;
11009 		if (!res.cnt) {
11010 			err = -ENOENT;
11011 			goto error;
11012 		}
11013 		addrs = res.addrs;
11014 		cnt = res.cnt;
11015 	}
11016 
11017 	retprobe = OPTS_GET(opts, retprobe, false);
11018 
11019 	lopts.kprobe_multi.syms = syms;
11020 	lopts.kprobe_multi.addrs = addrs;
11021 	lopts.kprobe_multi.cookies = cookies;
11022 	lopts.kprobe_multi.cnt = cnt;
11023 	lopts.kprobe_multi.flags = retprobe ? BPF_F_KPROBE_MULTI_RETURN : 0;
11024 
11025 	link = calloc(1, sizeof(*link));
11026 	if (!link) {
11027 		err = -ENOMEM;
11028 		goto error;
11029 	}
11030 	link->detach = &bpf_link__detach_fd;
11031 
11032 	prog_fd = bpf_program__fd(prog);
11033 	link_fd = bpf_link_create(prog_fd, 0, BPF_TRACE_KPROBE_MULTI, &lopts);
11034 	if (link_fd < 0) {
11035 		err = -errno;
11036 		pr_warn("prog '%s': failed to attach: %s\n",
11037 			prog->name, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11038 		goto error;
11039 	}
11040 	link->fd = link_fd;
11041 	free(res.addrs);
11042 	return link;
11043 
11044 error:
11045 	free(link);
11046 	free(res.addrs);
11047 	return libbpf_err_ptr(err);
11048 }
11049 
11050 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11051 {
11052 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
11053 	unsigned long offset = 0;
11054 	const char *func_name;
11055 	char *func;
11056 	int n;
11057 
11058 	*link = NULL;
11059 
11060 	/* no auto-attach for SEC("kprobe") and SEC("kretprobe") */
11061 	if (strcmp(prog->sec_name, "kprobe") == 0 || strcmp(prog->sec_name, "kretprobe") == 0)
11062 		return 0;
11063 
11064 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
11065 	if (opts.retprobe)
11066 		func_name = prog->sec_name + sizeof("kretprobe/") - 1;
11067 	else
11068 		func_name = prog->sec_name + sizeof("kprobe/") - 1;
11069 
11070 	n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
11071 	if (n < 1) {
11072 		pr_warn("kprobe name is invalid: %s\n", func_name);
11073 		return -EINVAL;
11074 	}
11075 	if (opts.retprobe && offset != 0) {
11076 		free(func);
11077 		pr_warn("kretprobes do not support offset specification\n");
11078 		return -EINVAL;
11079 	}
11080 
11081 	opts.offset = offset;
11082 	*link = bpf_program__attach_kprobe_opts(prog, func, &opts);
11083 	free(func);
11084 	return libbpf_get_error(*link);
11085 }
11086 
11087 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11088 {
11089 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts);
11090 	const char *spec;
11091 	char *pattern;
11092 	int n;
11093 
11094 	*link = NULL;
11095 
11096 	/* no auto-attach for SEC("kprobe.multi") and SEC("kretprobe.multi") */
11097 	if (strcmp(prog->sec_name, "kprobe.multi") == 0 ||
11098 	    strcmp(prog->sec_name, "kretprobe.multi") == 0)
11099 		return 0;
11100 
11101 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe.multi/");
11102 	if (opts.retprobe)
11103 		spec = prog->sec_name + sizeof("kretprobe.multi/") - 1;
11104 	else
11105 		spec = prog->sec_name + sizeof("kprobe.multi/") - 1;
11106 
11107 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
11108 	if (n < 1) {
11109 		pr_warn("kprobe multi pattern is invalid: %s\n", pattern);
11110 		return -EINVAL;
11111 	}
11112 
11113 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
11114 	free(pattern);
11115 	return libbpf_get_error(*link);
11116 }
11117 
11118 static void gen_uprobe_legacy_event_name(char *buf, size_t buf_sz,
11119 					 const char *binary_path, uint64_t offset)
11120 {
11121 	int i;
11122 
11123 	snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx", getpid(), binary_path, (size_t)offset);
11124 
11125 	/* sanitize binary_path in the probe name */
11126 	for (i = 0; buf[i]; i++) {
11127 		if (!isalnum(buf[i]))
11128 			buf[i] = '_';
11129 	}
11130 }
11131 
11132 static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
11133 					  const char *binary_path, size_t offset)
11134 {
11135 	const char *file = "/sys/kernel/debug/tracing/uprobe_events";
11136 
11137 	return append_to_file(file, "%c:%s/%s %s:0x%zx",
11138 			      retprobe ? 'r' : 'p',
11139 			      retprobe ? "uretprobes" : "uprobes",
11140 			      probe_name, binary_path, offset);
11141 }
11142 
11143 static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
11144 {
11145 	const char *file = "/sys/kernel/debug/tracing/uprobe_events";
11146 
11147 	return append_to_file(file, "-:%s/%s", retprobe ? "uretprobes" : "uprobes", probe_name);
11148 }
11149 
11150 static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
11151 {
11152 	char file[512];
11153 
11154 	snprintf(file, sizeof(file),
11155 		 "/sys/kernel/debug/tracing/events/%s/%s/id",
11156 		 retprobe ? "uretprobes" : "uprobes", probe_name);
11157 
11158 	return parse_uint_from_file(file, "%d\n");
11159 }
11160 
11161 static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
11162 					 const char *binary_path, size_t offset, int pid)
11163 {
11164 	struct perf_event_attr attr;
11165 	int type, pfd, err;
11166 
11167 	err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
11168 	if (err < 0) {
11169 		pr_warn("failed to add legacy uprobe event for %s:0x%zx: %d\n",
11170 			binary_path, (size_t)offset, err);
11171 		return err;
11172 	}
11173 	type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
11174 	if (type < 0) {
11175 		pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %d\n",
11176 			binary_path, offset, err);
11177 		return type;
11178 	}
11179 
11180 	memset(&attr, 0, sizeof(attr));
11181 	attr.size = sizeof(attr);
11182 	attr.config = type;
11183 	attr.type = PERF_TYPE_TRACEPOINT;
11184 
11185 	pfd = syscall(__NR_perf_event_open, &attr,
11186 		      pid < 0 ? -1 : pid, /* pid */
11187 		      pid == -1 ? 0 : -1, /* cpu */
11188 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
11189 	if (pfd < 0) {
11190 		err = -errno;
11191 		pr_warn("legacy uprobe perf_event_open() failed: %d\n", err);
11192 		return err;
11193 	}
11194 	return pfd;
11195 }
11196 
11197 /* Return next ELF section of sh_type after scn, or first of that type if scn is NULL. */
11198 static Elf_Scn *elf_find_next_scn_by_type(Elf *elf, int sh_type, Elf_Scn *scn)
11199 {
11200 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
11201 		GElf_Shdr sh;
11202 
11203 		if (!gelf_getshdr(scn, &sh))
11204 			continue;
11205 		if (sh.sh_type == sh_type)
11206 			return scn;
11207 	}
11208 	return NULL;
11209 }
11210 
11211 /* Find offset of function name in object specified by path.  "name" matches
11212  * symbol name or name@@LIB for library functions.
11213  */
11214 static long elf_find_func_offset(const char *binary_path, const char *name)
11215 {
11216 	int fd, i, sh_types[2] = { SHT_DYNSYM, SHT_SYMTAB };
11217 	bool is_shared_lib, is_name_qualified;
11218 	char errmsg[STRERR_BUFSIZE];
11219 	long ret = -ENOENT;
11220 	size_t name_len;
11221 	GElf_Ehdr ehdr;
11222 	Elf *elf;
11223 
11224 	fd = open(binary_path, O_RDONLY | O_CLOEXEC);
11225 	if (fd < 0) {
11226 		ret = -errno;
11227 		pr_warn("failed to open %s: %s\n", binary_path,
11228 			libbpf_strerror_r(ret, errmsg, sizeof(errmsg)));
11229 		return ret;
11230 	}
11231 	elf = elf_begin(fd, ELF_C_READ_MMAP, NULL);
11232 	if (!elf) {
11233 		pr_warn("elf: could not read elf from %s: %s\n", binary_path, elf_errmsg(-1));
11234 		close(fd);
11235 		return -LIBBPF_ERRNO__FORMAT;
11236 	}
11237 	if (!gelf_getehdr(elf, &ehdr)) {
11238 		pr_warn("elf: failed to get ehdr from %s: %s\n", binary_path, elf_errmsg(-1));
11239 		ret = -LIBBPF_ERRNO__FORMAT;
11240 		goto out;
11241 	}
11242 	/* for shared lib case, we do not need to calculate relative offset */
11243 	is_shared_lib = ehdr.e_type == ET_DYN;
11244 
11245 	name_len = strlen(name);
11246 	/* Does name specify "@@LIB"? */
11247 	is_name_qualified = strstr(name, "@@") != NULL;
11248 
11249 	/* Search SHT_DYNSYM, SHT_SYMTAB for symbol.  This search order is used because if
11250 	 * a binary is stripped, it may only have SHT_DYNSYM, and a fully-statically
11251 	 * linked binary may not have SHT_DYMSYM, so absence of a section should not be
11252 	 * reported as a warning/error.
11253 	 */
11254 	for (i = 0; i < ARRAY_SIZE(sh_types); i++) {
11255 		size_t nr_syms, strtabidx, idx;
11256 		Elf_Data *symbols = NULL;
11257 		Elf_Scn *scn = NULL;
11258 		int last_bind = -1;
11259 		const char *sname;
11260 		GElf_Shdr sh;
11261 
11262 		scn = elf_find_next_scn_by_type(elf, sh_types[i], NULL);
11263 		if (!scn) {
11264 			pr_debug("elf: failed to find symbol table ELF sections in '%s'\n",
11265 				 binary_path);
11266 			continue;
11267 		}
11268 		if (!gelf_getshdr(scn, &sh))
11269 			continue;
11270 		strtabidx = sh.sh_link;
11271 		symbols = elf_getdata(scn, 0);
11272 		if (!symbols) {
11273 			pr_warn("elf: failed to get symbols for symtab section in '%s': %s\n",
11274 				binary_path, elf_errmsg(-1));
11275 			ret = -LIBBPF_ERRNO__FORMAT;
11276 			goto out;
11277 		}
11278 		nr_syms = symbols->d_size / sh.sh_entsize;
11279 
11280 		for (idx = 0; idx < nr_syms; idx++) {
11281 			int curr_bind;
11282 			GElf_Sym sym;
11283 			Elf_Scn *sym_scn;
11284 			GElf_Shdr sym_sh;
11285 
11286 			if (!gelf_getsym(symbols, idx, &sym))
11287 				continue;
11288 
11289 			if (GELF_ST_TYPE(sym.st_info) != STT_FUNC)
11290 				continue;
11291 
11292 			sname = elf_strptr(elf, strtabidx, sym.st_name);
11293 			if (!sname)
11294 				continue;
11295 
11296 			curr_bind = GELF_ST_BIND(sym.st_info);
11297 
11298 			/* User can specify func, func@@LIB or func@@LIB_VERSION. */
11299 			if (strncmp(sname, name, name_len) != 0)
11300 				continue;
11301 			/* ...but we don't want a search for "foo" to match 'foo2" also, so any
11302 			 * additional characters in sname should be of the form "@@LIB".
11303 			 */
11304 			if (!is_name_qualified && sname[name_len] != '\0' && sname[name_len] != '@')
11305 				continue;
11306 
11307 			if (ret >= 0) {
11308 				/* handle multiple matches */
11309 				if (last_bind != STB_WEAK && curr_bind != STB_WEAK) {
11310 					/* Only accept one non-weak bind. */
11311 					pr_warn("elf: ambiguous match for '%s', '%s' in '%s'\n",
11312 						sname, name, binary_path);
11313 					ret = -LIBBPF_ERRNO__FORMAT;
11314 					goto out;
11315 				} else if (curr_bind == STB_WEAK) {
11316 					/* already have a non-weak bind, and
11317 					 * this is a weak bind, so ignore.
11318 					 */
11319 					continue;
11320 				}
11321 			}
11322 
11323 			/* Transform symbol's virtual address (absolute for
11324 			 * binaries and relative for shared libs) into file
11325 			 * offset, which is what kernel is expecting for
11326 			 * uprobe/uretprobe attachment.
11327 			 * See Documentation/trace/uprobetracer.rst for more
11328 			 * details.
11329 			 * This is done by looking up symbol's containing
11330 			 * section's header and using it's virtual address
11331 			 * (sh_addr) and corresponding file offset (sh_offset)
11332 			 * to transform sym.st_value (virtual address) into
11333 			 * desired final file offset.
11334 			 */
11335 			sym_scn = elf_getscn(elf, sym.st_shndx);
11336 			if (!sym_scn)
11337 				continue;
11338 			if (!gelf_getshdr(sym_scn, &sym_sh))
11339 				continue;
11340 
11341 			ret = sym.st_value - sym_sh.sh_addr + sym_sh.sh_offset;
11342 			last_bind = curr_bind;
11343 		}
11344 		if (ret > 0)
11345 			break;
11346 	}
11347 
11348 	if (ret > 0) {
11349 		pr_debug("elf: symbol address match for '%s' in '%s': 0x%lx\n", name, binary_path,
11350 			 ret);
11351 	} else {
11352 		if (ret == 0) {
11353 			pr_warn("elf: '%s' is 0 in symtab for '%s': %s\n", name, binary_path,
11354 				is_shared_lib ? "should not be 0 in a shared library" :
11355 						"try using shared library path instead");
11356 			ret = -ENOENT;
11357 		} else {
11358 			pr_warn("elf: failed to find symbol '%s' in '%s'\n", name, binary_path);
11359 		}
11360 	}
11361 out:
11362 	elf_end(elf);
11363 	close(fd);
11364 	return ret;
11365 }
11366 
11367 static const char *arch_specific_lib_paths(void)
11368 {
11369 	/*
11370 	 * Based on https://packages.debian.org/sid/libc6.
11371 	 *
11372 	 * Assume that the traced program is built for the same architecture
11373 	 * as libbpf, which should cover the vast majority of cases.
11374 	 */
11375 #if defined(__x86_64__)
11376 	return "/lib/x86_64-linux-gnu";
11377 #elif defined(__i386__)
11378 	return "/lib/i386-linux-gnu";
11379 #elif defined(__s390x__)
11380 	return "/lib/s390x-linux-gnu";
11381 #elif defined(__s390__)
11382 	return "/lib/s390-linux-gnu";
11383 #elif defined(__arm__) && defined(__SOFTFP__)
11384 	return "/lib/arm-linux-gnueabi";
11385 #elif defined(__arm__) && !defined(__SOFTFP__)
11386 	return "/lib/arm-linux-gnueabihf";
11387 #elif defined(__aarch64__)
11388 	return "/lib/aarch64-linux-gnu";
11389 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 64
11390 	return "/lib/mips64el-linux-gnuabi64";
11391 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 32
11392 	return "/lib/mipsel-linux-gnu";
11393 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
11394 	return "/lib/powerpc64le-linux-gnu";
11395 #elif defined(__sparc__) && defined(__arch64__)
11396 	return "/lib/sparc64-linux-gnu";
11397 #elif defined(__riscv) && __riscv_xlen == 64
11398 	return "/lib/riscv64-linux-gnu";
11399 #else
11400 	return NULL;
11401 #endif
11402 }
11403 
11404 /* Get full path to program/shared library. */
11405 static int resolve_full_path(const char *file, char *result, size_t result_sz)
11406 {
11407 	const char *search_paths[3] = {};
11408 	int i;
11409 
11410 	if (str_has_sfx(file, ".so") || strstr(file, ".so.")) {
11411 		search_paths[0] = getenv("LD_LIBRARY_PATH");
11412 		search_paths[1] = "/usr/lib64:/usr/lib";
11413 		search_paths[2] = arch_specific_lib_paths();
11414 	} else {
11415 		search_paths[0] = getenv("PATH");
11416 		search_paths[1] = "/usr/bin:/usr/sbin";
11417 	}
11418 
11419 	for (i = 0; i < ARRAY_SIZE(search_paths); i++) {
11420 		const char *s;
11421 
11422 		if (!search_paths[i])
11423 			continue;
11424 		for (s = search_paths[i]; s != NULL; s = strchr(s, ':')) {
11425 			char *next_path;
11426 			int seg_len;
11427 
11428 			if (s[0] == ':')
11429 				s++;
11430 			next_path = strchr(s, ':');
11431 			seg_len = next_path ? next_path - s : strlen(s);
11432 			if (!seg_len)
11433 				continue;
11434 			snprintf(result, result_sz, "%.*s/%s", seg_len, s, file);
11435 			/* ensure it is an executable file/link */
11436 			if (access(result, R_OK | X_OK) < 0)
11437 				continue;
11438 			pr_debug("resolved '%s' to '%s'\n", file, result);
11439 			return 0;
11440 		}
11441 	}
11442 	return -ENOENT;
11443 }
11444 
11445 LIBBPF_API struct bpf_link *
11446 bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
11447 				const char *binary_path, size_t func_offset,
11448 				const struct bpf_uprobe_opts *opts)
11449 {
11450 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11451 	char errmsg[STRERR_BUFSIZE], *legacy_probe = NULL;
11452 	char full_binary_path[PATH_MAX];
11453 	struct bpf_link *link;
11454 	size_t ref_ctr_off;
11455 	int pfd, err;
11456 	bool retprobe, legacy;
11457 	const char *func_name;
11458 
11459 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
11460 		return libbpf_err_ptr(-EINVAL);
11461 
11462 	retprobe = OPTS_GET(opts, retprobe, false);
11463 	ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
11464 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11465 
11466 	if (binary_path && !strchr(binary_path, '/')) {
11467 		err = resolve_full_path(binary_path, full_binary_path,
11468 					sizeof(full_binary_path));
11469 		if (err) {
11470 			pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11471 				prog->name, binary_path, err);
11472 			return libbpf_err_ptr(err);
11473 		}
11474 		binary_path = full_binary_path;
11475 	}
11476 	func_name = OPTS_GET(opts, func_name, NULL);
11477 	if (func_name) {
11478 		long sym_off;
11479 
11480 		if (!binary_path) {
11481 			pr_warn("prog '%s': name-based attach requires binary_path\n",
11482 				prog->name);
11483 			return libbpf_err_ptr(-EINVAL);
11484 		}
11485 		sym_off = elf_find_func_offset(binary_path, func_name);
11486 		if (sym_off < 0)
11487 			return libbpf_err_ptr(sym_off);
11488 		func_offset += sym_off;
11489 	}
11490 
11491 	legacy = determine_uprobe_perf_type() < 0;
11492 	if (!legacy) {
11493 		pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
11494 					    func_offset, pid, ref_ctr_off);
11495 	} else {
11496 		char probe_name[PATH_MAX + 64];
11497 
11498 		if (ref_ctr_off)
11499 			return libbpf_err_ptr(-EINVAL);
11500 
11501 		gen_uprobe_legacy_event_name(probe_name, sizeof(probe_name),
11502 					     binary_path, func_offset);
11503 
11504 		legacy_probe = strdup(probe_name);
11505 		if (!legacy_probe)
11506 			return libbpf_err_ptr(-ENOMEM);
11507 
11508 		pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
11509 						    binary_path, func_offset, pid);
11510 	}
11511 	if (pfd < 0) {
11512 		err = -errno;
11513 		pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
11514 			prog->name, retprobe ? "uretprobe" : "uprobe",
11515 			binary_path, func_offset,
11516 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11517 		goto err_out;
11518 	}
11519 
11520 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11521 	err = libbpf_get_error(link);
11522 	if (err) {
11523 		close(pfd);
11524 		pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
11525 			prog->name, retprobe ? "uretprobe" : "uprobe",
11526 			binary_path, func_offset,
11527 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11528 		goto err_out;
11529 	}
11530 	if (legacy) {
11531 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
11532 
11533 		perf_link->legacy_probe_name = legacy_probe;
11534 		perf_link->legacy_is_kprobe = false;
11535 		perf_link->legacy_is_retprobe = retprobe;
11536 	}
11537 	return link;
11538 err_out:
11539 	free(legacy_probe);
11540 	return libbpf_err_ptr(err);
11541 
11542 }
11543 
11544 /* Format of u[ret]probe section definition supporting auto-attach:
11545  * u[ret]probe/binary:function[+offset]
11546  *
11547  * binary can be an absolute/relative path or a filename; the latter is resolved to a
11548  * full binary path via bpf_program__attach_uprobe_opts.
11549  *
11550  * Specifying uprobe+ ensures we carry out strict matching; either "uprobe" must be
11551  * specified (and auto-attach is not possible) or the above format is specified for
11552  * auto-attach.
11553  */
11554 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11555 {
11556 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts);
11557 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
11558 	int n, ret = -EINVAL;
11559 	long offset = 0;
11560 
11561 	*link = NULL;
11562 
11563 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[a-zA-Z0-9_.]+%li",
11564 		   &probe_type, &binary_path, &func_name, &offset);
11565 	switch (n) {
11566 	case 1:
11567 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
11568 		ret = 0;
11569 		break;
11570 	case 2:
11571 		pr_warn("prog '%s': section '%s' missing ':function[+offset]' specification\n",
11572 			prog->name, prog->sec_name);
11573 		break;
11574 	case 3:
11575 	case 4:
11576 		opts.retprobe = strcmp(probe_type, "uretprobe") == 0 ||
11577 				strcmp(probe_type, "uretprobe.s") == 0;
11578 		if (opts.retprobe && offset != 0) {
11579 			pr_warn("prog '%s': uretprobes do not support offset specification\n",
11580 				prog->name);
11581 			break;
11582 		}
11583 		opts.func_name = func_name;
11584 		*link = bpf_program__attach_uprobe_opts(prog, -1, binary_path, offset, &opts);
11585 		ret = libbpf_get_error(*link);
11586 		break;
11587 	default:
11588 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
11589 			prog->sec_name);
11590 		break;
11591 	}
11592 	free(probe_type);
11593 	free(binary_path);
11594 	free(func_name);
11595 
11596 	return ret;
11597 }
11598 
11599 struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
11600 					    bool retprobe, pid_t pid,
11601 					    const char *binary_path,
11602 					    size_t func_offset)
11603 {
11604 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
11605 
11606 	return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
11607 }
11608 
11609 struct bpf_link *bpf_program__attach_usdt(const struct bpf_program *prog,
11610 					  pid_t pid, const char *binary_path,
11611 					  const char *usdt_provider, const char *usdt_name,
11612 					  const struct bpf_usdt_opts *opts)
11613 {
11614 	char resolved_path[512];
11615 	struct bpf_object *obj = prog->obj;
11616 	struct bpf_link *link;
11617 	__u64 usdt_cookie;
11618 	int err;
11619 
11620 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
11621 		return libbpf_err_ptr(-EINVAL);
11622 
11623 	if (bpf_program__fd(prog) < 0) {
11624 		pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
11625 			prog->name);
11626 		return libbpf_err_ptr(-EINVAL);
11627 	}
11628 
11629 	if (!strchr(binary_path, '/')) {
11630 		err = resolve_full_path(binary_path, resolved_path, sizeof(resolved_path));
11631 		if (err) {
11632 			pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11633 				prog->name, binary_path, err);
11634 			return libbpf_err_ptr(err);
11635 		}
11636 		binary_path = resolved_path;
11637 	}
11638 
11639 	/* USDT manager is instantiated lazily on first USDT attach. It will
11640 	 * be destroyed together with BPF object in bpf_object__close().
11641 	 */
11642 	if (IS_ERR(obj->usdt_man))
11643 		return libbpf_ptr(obj->usdt_man);
11644 	if (!obj->usdt_man) {
11645 		obj->usdt_man = usdt_manager_new(obj);
11646 		if (IS_ERR(obj->usdt_man))
11647 			return libbpf_ptr(obj->usdt_man);
11648 	}
11649 
11650 	usdt_cookie = OPTS_GET(opts, usdt_cookie, 0);
11651 	link = usdt_manager_attach_usdt(obj->usdt_man, prog, pid, binary_path,
11652 				        usdt_provider, usdt_name, usdt_cookie);
11653 	err = libbpf_get_error(link);
11654 	if (err)
11655 		return libbpf_err_ptr(err);
11656 	return link;
11657 }
11658 
11659 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11660 {
11661 	char *path = NULL, *provider = NULL, *name = NULL;
11662 	const char *sec_name;
11663 	int n, err;
11664 
11665 	sec_name = bpf_program__section_name(prog);
11666 	if (strcmp(sec_name, "usdt") == 0) {
11667 		/* no auto-attach for just SEC("usdt") */
11668 		*link = NULL;
11669 		return 0;
11670 	}
11671 
11672 	n = sscanf(sec_name, "usdt/%m[^:]:%m[^:]:%m[^:]", &path, &provider, &name);
11673 	if (n != 3) {
11674 		pr_warn("invalid section '%s', expected SEC(\"usdt/<path>:<provider>:<name>\")\n",
11675 			sec_name);
11676 		err = -EINVAL;
11677 	} else {
11678 		*link = bpf_program__attach_usdt(prog, -1 /* any process */, path,
11679 						 provider, name, NULL);
11680 		err = libbpf_get_error(*link);
11681 	}
11682 	free(path);
11683 	free(provider);
11684 	free(name);
11685 	return err;
11686 }
11687 
11688 static int determine_tracepoint_id(const char *tp_category,
11689 				   const char *tp_name)
11690 {
11691 	char file[PATH_MAX];
11692 	int ret;
11693 
11694 	ret = snprintf(file, sizeof(file),
11695 		       "/sys/kernel/debug/tracing/events/%s/%s/id",
11696 		       tp_category, tp_name);
11697 	if (ret < 0)
11698 		return -errno;
11699 	if (ret >= sizeof(file)) {
11700 		pr_debug("tracepoint %s/%s path is too long\n",
11701 			 tp_category, tp_name);
11702 		return -E2BIG;
11703 	}
11704 	return parse_uint_from_file(file, "%d\n");
11705 }
11706 
11707 static int perf_event_open_tracepoint(const char *tp_category,
11708 				      const char *tp_name)
11709 {
11710 	struct perf_event_attr attr = {};
11711 	char errmsg[STRERR_BUFSIZE];
11712 	int tp_id, pfd, err;
11713 
11714 	tp_id = determine_tracepoint_id(tp_category, tp_name);
11715 	if (tp_id < 0) {
11716 		pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
11717 			tp_category, tp_name,
11718 			libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
11719 		return tp_id;
11720 	}
11721 
11722 	attr.type = PERF_TYPE_TRACEPOINT;
11723 	attr.size = sizeof(attr);
11724 	attr.config = tp_id;
11725 
11726 	pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
11727 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
11728 	if (pfd < 0) {
11729 		err = -errno;
11730 		pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
11731 			tp_category, tp_name,
11732 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11733 		return err;
11734 	}
11735 	return pfd;
11736 }
11737 
11738 struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
11739 						     const char *tp_category,
11740 						     const char *tp_name,
11741 						     const struct bpf_tracepoint_opts *opts)
11742 {
11743 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11744 	char errmsg[STRERR_BUFSIZE];
11745 	struct bpf_link *link;
11746 	int pfd, err;
11747 
11748 	if (!OPTS_VALID(opts, bpf_tracepoint_opts))
11749 		return libbpf_err_ptr(-EINVAL);
11750 
11751 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11752 
11753 	pfd = perf_event_open_tracepoint(tp_category, tp_name);
11754 	if (pfd < 0) {
11755 		pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
11756 			prog->name, tp_category, tp_name,
11757 			libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11758 		return libbpf_err_ptr(pfd);
11759 	}
11760 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11761 	err = libbpf_get_error(link);
11762 	if (err) {
11763 		close(pfd);
11764 		pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
11765 			prog->name, tp_category, tp_name,
11766 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11767 		return libbpf_err_ptr(err);
11768 	}
11769 	return link;
11770 }
11771 
11772 struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
11773 						const char *tp_category,
11774 						const char *tp_name)
11775 {
11776 	return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
11777 }
11778 
11779 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11780 {
11781 	char *sec_name, *tp_cat, *tp_name;
11782 
11783 	*link = NULL;
11784 
11785 	/* no auto-attach for SEC("tp") or SEC("tracepoint") */
11786 	if (strcmp(prog->sec_name, "tp") == 0 || strcmp(prog->sec_name, "tracepoint") == 0)
11787 		return 0;
11788 
11789 	sec_name = strdup(prog->sec_name);
11790 	if (!sec_name)
11791 		return -ENOMEM;
11792 
11793 	/* extract "tp/<category>/<name>" or "tracepoint/<category>/<name>" */
11794 	if (str_has_pfx(prog->sec_name, "tp/"))
11795 		tp_cat = sec_name + sizeof("tp/") - 1;
11796 	else
11797 		tp_cat = sec_name + sizeof("tracepoint/") - 1;
11798 	tp_name = strchr(tp_cat, '/');
11799 	if (!tp_name) {
11800 		free(sec_name);
11801 		return -EINVAL;
11802 	}
11803 	*tp_name = '\0';
11804 	tp_name++;
11805 
11806 	*link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
11807 	free(sec_name);
11808 	return libbpf_get_error(*link);
11809 }
11810 
11811 struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
11812 						    const char *tp_name)
11813 {
11814 	char errmsg[STRERR_BUFSIZE];
11815 	struct bpf_link *link;
11816 	int prog_fd, pfd;
11817 
11818 	prog_fd = bpf_program__fd(prog);
11819 	if (prog_fd < 0) {
11820 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11821 		return libbpf_err_ptr(-EINVAL);
11822 	}
11823 
11824 	link = calloc(1, sizeof(*link));
11825 	if (!link)
11826 		return libbpf_err_ptr(-ENOMEM);
11827 	link->detach = &bpf_link__detach_fd;
11828 
11829 	pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
11830 	if (pfd < 0) {
11831 		pfd = -errno;
11832 		free(link);
11833 		pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
11834 			prog->name, tp_name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11835 		return libbpf_err_ptr(pfd);
11836 	}
11837 	link->fd = pfd;
11838 	return link;
11839 }
11840 
11841 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11842 {
11843 	static const char *const prefixes[] = {
11844 		"raw_tp",
11845 		"raw_tracepoint",
11846 		"raw_tp.w",
11847 		"raw_tracepoint.w",
11848 	};
11849 	size_t i;
11850 	const char *tp_name = NULL;
11851 
11852 	*link = NULL;
11853 
11854 	for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
11855 		size_t pfx_len;
11856 
11857 		if (!str_has_pfx(prog->sec_name, prefixes[i]))
11858 			continue;
11859 
11860 		pfx_len = strlen(prefixes[i]);
11861 		/* no auto-attach case of, e.g., SEC("raw_tp") */
11862 		if (prog->sec_name[pfx_len] == '\0')
11863 			return 0;
11864 
11865 		if (prog->sec_name[pfx_len] != '/')
11866 			continue;
11867 
11868 		tp_name = prog->sec_name + pfx_len + 1;
11869 		break;
11870 	}
11871 
11872 	if (!tp_name) {
11873 		pr_warn("prog '%s': invalid section name '%s'\n",
11874 			prog->name, prog->sec_name);
11875 		return -EINVAL;
11876 	}
11877 
11878 	*link = bpf_program__attach_raw_tracepoint(prog, tp_name);
11879 	return libbpf_get_error(link);
11880 }
11881 
11882 /* Common logic for all BPF program types that attach to a btf_id */
11883 static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog,
11884 						   const struct bpf_trace_opts *opts)
11885 {
11886 	LIBBPF_OPTS(bpf_link_create_opts, link_opts);
11887 	char errmsg[STRERR_BUFSIZE];
11888 	struct bpf_link *link;
11889 	int prog_fd, pfd;
11890 
11891 	if (!OPTS_VALID(opts, bpf_trace_opts))
11892 		return libbpf_err_ptr(-EINVAL);
11893 
11894 	prog_fd = bpf_program__fd(prog);
11895 	if (prog_fd < 0) {
11896 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11897 		return libbpf_err_ptr(-EINVAL);
11898 	}
11899 
11900 	link = calloc(1, sizeof(*link));
11901 	if (!link)
11902 		return libbpf_err_ptr(-ENOMEM);
11903 	link->detach = &bpf_link__detach_fd;
11904 
11905 	/* libbpf is smart enough to redirect to BPF_RAW_TRACEPOINT_OPEN on old kernels */
11906 	link_opts.tracing.cookie = OPTS_GET(opts, cookie, 0);
11907 	pfd = bpf_link_create(prog_fd, 0, bpf_program__expected_attach_type(prog), &link_opts);
11908 	if (pfd < 0) {
11909 		pfd = -errno;
11910 		free(link);
11911 		pr_warn("prog '%s': failed to attach: %s\n",
11912 			prog->name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11913 		return libbpf_err_ptr(pfd);
11914 	}
11915 	link->fd = pfd;
11916 	return link;
11917 }
11918 
11919 struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
11920 {
11921 	return bpf_program__attach_btf_id(prog, NULL);
11922 }
11923 
11924 struct bpf_link *bpf_program__attach_trace_opts(const struct bpf_program *prog,
11925 						const struct bpf_trace_opts *opts)
11926 {
11927 	return bpf_program__attach_btf_id(prog, opts);
11928 }
11929 
11930 struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
11931 {
11932 	return bpf_program__attach_btf_id(prog, NULL);
11933 }
11934 
11935 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11936 {
11937 	*link = bpf_program__attach_trace(prog);
11938 	return libbpf_get_error(*link);
11939 }
11940 
11941 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11942 {
11943 	*link = bpf_program__attach_lsm(prog);
11944 	return libbpf_get_error(*link);
11945 }
11946 
11947 static struct bpf_link *
11948 bpf_program__attach_fd(const struct bpf_program *prog, int target_fd, int btf_id,
11949 		       const char *target_name)
11950 {
11951 	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, opts,
11952 			    .target_btf_id = btf_id);
11953 	enum bpf_attach_type attach_type;
11954 	char errmsg[STRERR_BUFSIZE];
11955 	struct bpf_link *link;
11956 	int prog_fd, link_fd;
11957 
11958 	prog_fd = bpf_program__fd(prog);
11959 	if (prog_fd < 0) {
11960 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11961 		return libbpf_err_ptr(-EINVAL);
11962 	}
11963 
11964 	link = calloc(1, sizeof(*link));
11965 	if (!link)
11966 		return libbpf_err_ptr(-ENOMEM);
11967 	link->detach = &bpf_link__detach_fd;
11968 
11969 	attach_type = bpf_program__expected_attach_type(prog);
11970 	link_fd = bpf_link_create(prog_fd, target_fd, attach_type, &opts);
11971 	if (link_fd < 0) {
11972 		link_fd = -errno;
11973 		free(link);
11974 		pr_warn("prog '%s': failed to attach to %s: %s\n",
11975 			prog->name, target_name,
11976 			libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
11977 		return libbpf_err_ptr(link_fd);
11978 	}
11979 	link->fd = link_fd;
11980 	return link;
11981 }
11982 
11983 struct bpf_link *
11984 bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
11985 {
11986 	return bpf_program__attach_fd(prog, cgroup_fd, 0, "cgroup");
11987 }
11988 
11989 struct bpf_link *
11990 bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
11991 {
11992 	return bpf_program__attach_fd(prog, netns_fd, 0, "netns");
11993 }
11994 
11995 struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
11996 {
11997 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
11998 	return bpf_program__attach_fd(prog, ifindex, 0, "xdp");
11999 }
12000 
12001 struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
12002 					      int target_fd,
12003 					      const char *attach_func_name)
12004 {
12005 	int btf_id;
12006 
12007 	if (!!target_fd != !!attach_func_name) {
12008 		pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
12009 			prog->name);
12010 		return libbpf_err_ptr(-EINVAL);
12011 	}
12012 
12013 	if (prog->type != BPF_PROG_TYPE_EXT) {
12014 		pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace",
12015 			prog->name);
12016 		return libbpf_err_ptr(-EINVAL);
12017 	}
12018 
12019 	if (target_fd) {
12020 		btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd);
12021 		if (btf_id < 0)
12022 			return libbpf_err_ptr(btf_id);
12023 
12024 		return bpf_program__attach_fd(prog, target_fd, btf_id, "freplace");
12025 	} else {
12026 		/* no target, so use raw_tracepoint_open for compatibility
12027 		 * with old kernels
12028 		 */
12029 		return bpf_program__attach_trace(prog);
12030 	}
12031 }
12032 
12033 struct bpf_link *
12034 bpf_program__attach_iter(const struct bpf_program *prog,
12035 			 const struct bpf_iter_attach_opts *opts)
12036 {
12037 	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12038 	char errmsg[STRERR_BUFSIZE];
12039 	struct bpf_link *link;
12040 	int prog_fd, link_fd;
12041 	__u32 target_fd = 0;
12042 
12043 	if (!OPTS_VALID(opts, bpf_iter_attach_opts))
12044 		return libbpf_err_ptr(-EINVAL);
12045 
12046 	link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
12047 	link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
12048 
12049 	prog_fd = bpf_program__fd(prog);
12050 	if (prog_fd < 0) {
12051 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12052 		return libbpf_err_ptr(-EINVAL);
12053 	}
12054 
12055 	link = calloc(1, sizeof(*link));
12056 	if (!link)
12057 		return libbpf_err_ptr(-ENOMEM);
12058 	link->detach = &bpf_link__detach_fd;
12059 
12060 	link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
12061 				  &link_create_opts);
12062 	if (link_fd < 0) {
12063 		link_fd = -errno;
12064 		free(link);
12065 		pr_warn("prog '%s': failed to attach to iterator: %s\n",
12066 			prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
12067 		return libbpf_err_ptr(link_fd);
12068 	}
12069 	link->fd = link_fd;
12070 	return link;
12071 }
12072 
12073 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12074 {
12075 	*link = bpf_program__attach_iter(prog, NULL);
12076 	return libbpf_get_error(*link);
12077 }
12078 
12079 struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
12080 {
12081 	struct bpf_link *link = NULL;
12082 	int err;
12083 
12084 	if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
12085 		return libbpf_err_ptr(-EOPNOTSUPP);
12086 
12087 	err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, &link);
12088 	if (err)
12089 		return libbpf_err_ptr(err);
12090 
12091 	/* When calling bpf_program__attach() explicitly, auto-attach support
12092 	 * is expected to work, so NULL returned link is considered an error.
12093 	 * This is different for skeleton's attach, see comment in
12094 	 * bpf_object__attach_skeleton().
12095 	 */
12096 	if (!link)
12097 		return libbpf_err_ptr(-EOPNOTSUPP);
12098 
12099 	return link;
12100 }
12101 
12102 static int bpf_link__detach_struct_ops(struct bpf_link *link)
12103 {
12104 	__u32 zero = 0;
12105 
12106 	if (bpf_map_delete_elem(link->fd, &zero))
12107 		return -errno;
12108 
12109 	return 0;
12110 }
12111 
12112 struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
12113 {
12114 	struct bpf_struct_ops *st_ops;
12115 	struct bpf_link *link;
12116 	__u32 i, zero = 0;
12117 	int err;
12118 
12119 	if (!bpf_map__is_struct_ops(map) || map->fd == -1)
12120 		return libbpf_err_ptr(-EINVAL);
12121 
12122 	link = calloc(1, sizeof(*link));
12123 	if (!link)
12124 		return libbpf_err_ptr(-EINVAL);
12125 
12126 	st_ops = map->st_ops;
12127 	for (i = 0; i < btf_vlen(st_ops->type); i++) {
12128 		struct bpf_program *prog = st_ops->progs[i];
12129 		void *kern_data;
12130 		int prog_fd;
12131 
12132 		if (!prog)
12133 			continue;
12134 
12135 		prog_fd = bpf_program__fd(prog);
12136 		kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
12137 		*(unsigned long *)kern_data = prog_fd;
12138 	}
12139 
12140 	err = bpf_map_update_elem(map->fd, &zero, st_ops->kern_vdata, 0);
12141 	if (err) {
12142 		err = -errno;
12143 		free(link);
12144 		return libbpf_err_ptr(err);
12145 	}
12146 
12147 	link->detach = bpf_link__detach_struct_ops;
12148 	link->fd = map->fd;
12149 
12150 	return link;
12151 }
12152 
12153 static enum bpf_perf_event_ret
12154 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_event_mmap_page *header = mmap_mem;
12159 	__u64 data_head = ring_buffer_read_head(header);
12160 	__u64 data_tail = header->data_tail;
12161 	void *base = ((__u8 *)header) + page_size;
12162 	int ret = LIBBPF_PERF_EVENT_CONT;
12163 	struct perf_event_header *ehdr;
12164 	size_t ehdr_size;
12165 
12166 	while (data_head != data_tail) {
12167 		ehdr = base + (data_tail & (mmap_size - 1));
12168 		ehdr_size = ehdr->size;
12169 
12170 		if (((void *)ehdr) + ehdr_size > base + mmap_size) {
12171 			void *copy_start = ehdr;
12172 			size_t len_first = base + mmap_size - copy_start;
12173 			size_t len_secnd = ehdr_size - len_first;
12174 
12175 			if (*copy_size < ehdr_size) {
12176 				free(*copy_mem);
12177 				*copy_mem = malloc(ehdr_size);
12178 				if (!*copy_mem) {
12179 					*copy_size = 0;
12180 					ret = LIBBPF_PERF_EVENT_ERROR;
12181 					break;
12182 				}
12183 				*copy_size = ehdr_size;
12184 			}
12185 
12186 			memcpy(*copy_mem, copy_start, len_first);
12187 			memcpy(*copy_mem + len_first, base, len_secnd);
12188 			ehdr = *copy_mem;
12189 		}
12190 
12191 		ret = fn(ehdr, private_data);
12192 		data_tail += ehdr_size;
12193 		if (ret != LIBBPF_PERF_EVENT_CONT)
12194 			break;
12195 	}
12196 
12197 	ring_buffer_write_tail(header, data_tail);
12198 	return libbpf_err(ret);
12199 }
12200 
12201 __attribute__((alias("perf_event_read_simple")))
12202 enum bpf_perf_event_ret
12203 bpf_perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
12204 			   void **copy_mem, size_t *copy_size,
12205 			   bpf_perf_event_print_t fn, void *private_data);
12206 
12207 struct perf_buffer;
12208 
12209 struct perf_buffer_params {
12210 	struct perf_event_attr *attr;
12211 	/* if event_cb is specified, it takes precendence */
12212 	perf_buffer_event_fn event_cb;
12213 	/* sample_cb and lost_cb are higher-level common-case callbacks */
12214 	perf_buffer_sample_fn sample_cb;
12215 	perf_buffer_lost_fn lost_cb;
12216 	void *ctx;
12217 	int cpu_cnt;
12218 	int *cpus;
12219 	int *map_keys;
12220 };
12221 
12222 struct perf_cpu_buf {
12223 	struct perf_buffer *pb;
12224 	void *base; /* mmap()'ed memory */
12225 	void *buf; /* for reconstructing segmented data */
12226 	size_t buf_size;
12227 	int fd;
12228 	int cpu;
12229 	int map_key;
12230 };
12231 
12232 struct perf_buffer {
12233 	perf_buffer_event_fn event_cb;
12234 	perf_buffer_sample_fn sample_cb;
12235 	perf_buffer_lost_fn lost_cb;
12236 	void *ctx; /* passed into callbacks */
12237 
12238 	size_t page_size;
12239 	size_t mmap_size;
12240 	struct perf_cpu_buf **cpu_bufs;
12241 	struct epoll_event *events;
12242 	int cpu_cnt; /* number of allocated CPU buffers */
12243 	int epoll_fd; /* perf event FD */
12244 	int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
12245 };
12246 
12247 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
12248 				      struct perf_cpu_buf *cpu_buf)
12249 {
12250 	if (!cpu_buf)
12251 		return;
12252 	if (cpu_buf->base &&
12253 	    munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
12254 		pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
12255 	if (cpu_buf->fd >= 0) {
12256 		ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
12257 		close(cpu_buf->fd);
12258 	}
12259 	free(cpu_buf->buf);
12260 	free(cpu_buf);
12261 }
12262 
12263 void perf_buffer__free(struct perf_buffer *pb)
12264 {
12265 	int i;
12266 
12267 	if (IS_ERR_OR_NULL(pb))
12268 		return;
12269 	if (pb->cpu_bufs) {
12270 		for (i = 0; i < pb->cpu_cnt; i++) {
12271 			struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
12272 
12273 			if (!cpu_buf)
12274 				continue;
12275 
12276 			bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
12277 			perf_buffer__free_cpu_buf(pb, cpu_buf);
12278 		}
12279 		free(pb->cpu_bufs);
12280 	}
12281 	if (pb->epoll_fd >= 0)
12282 		close(pb->epoll_fd);
12283 	free(pb->events);
12284 	free(pb);
12285 }
12286 
12287 static struct perf_cpu_buf *
12288 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
12289 			  int cpu, int map_key)
12290 {
12291 	struct perf_cpu_buf *cpu_buf;
12292 	char msg[STRERR_BUFSIZE];
12293 	int err;
12294 
12295 	cpu_buf = calloc(1, sizeof(*cpu_buf));
12296 	if (!cpu_buf)
12297 		return ERR_PTR(-ENOMEM);
12298 
12299 	cpu_buf->pb = pb;
12300 	cpu_buf->cpu = cpu;
12301 	cpu_buf->map_key = map_key;
12302 
12303 	cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
12304 			      -1, PERF_FLAG_FD_CLOEXEC);
12305 	if (cpu_buf->fd < 0) {
12306 		err = -errno;
12307 		pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
12308 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
12309 		goto error;
12310 	}
12311 
12312 	cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
12313 			     PROT_READ | PROT_WRITE, MAP_SHARED,
12314 			     cpu_buf->fd, 0);
12315 	if (cpu_buf->base == MAP_FAILED) {
12316 		cpu_buf->base = NULL;
12317 		err = -errno;
12318 		pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
12319 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
12320 		goto error;
12321 	}
12322 
12323 	if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
12324 		err = -errno;
12325 		pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
12326 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
12327 		goto error;
12328 	}
12329 
12330 	return cpu_buf;
12331 
12332 error:
12333 	perf_buffer__free_cpu_buf(pb, cpu_buf);
12334 	return (struct perf_cpu_buf *)ERR_PTR(err);
12335 }
12336 
12337 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
12338 					      struct perf_buffer_params *p);
12339 
12340 DEFAULT_VERSION(perf_buffer__new_v0_6_0, perf_buffer__new, LIBBPF_0.6.0)
12341 struct perf_buffer *perf_buffer__new_v0_6_0(int map_fd, size_t page_cnt,
12342 					    perf_buffer_sample_fn sample_cb,
12343 					    perf_buffer_lost_fn lost_cb,
12344 					    void *ctx,
12345 					    const struct perf_buffer_opts *opts)
12346 {
12347 	struct perf_buffer_params p = {};
12348 	struct perf_event_attr attr = {};
12349 
12350 	if (!OPTS_VALID(opts, perf_buffer_opts))
12351 		return libbpf_err_ptr(-EINVAL);
12352 
12353 	attr.config = PERF_COUNT_SW_BPF_OUTPUT;
12354 	attr.type = PERF_TYPE_SOFTWARE;
12355 	attr.sample_type = PERF_SAMPLE_RAW;
12356 	attr.sample_period = 1;
12357 	attr.wakeup_events = 1;
12358 
12359 	p.attr = &attr;
12360 	p.sample_cb = sample_cb;
12361 	p.lost_cb = lost_cb;
12362 	p.ctx = ctx;
12363 
12364 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
12365 }
12366 
12367 COMPAT_VERSION(perf_buffer__new_deprecated, perf_buffer__new, LIBBPF_0.0.4)
12368 struct perf_buffer *perf_buffer__new_deprecated(int map_fd, size_t page_cnt,
12369 						const struct perf_buffer_opts *opts)
12370 {
12371 	return perf_buffer__new_v0_6_0(map_fd, page_cnt,
12372 				       opts ? opts->sample_cb : NULL,
12373 				       opts ? opts->lost_cb : NULL,
12374 				       opts ? opts->ctx : NULL,
12375 				       NULL);
12376 }
12377 
12378 DEFAULT_VERSION(perf_buffer__new_raw_v0_6_0, perf_buffer__new_raw, LIBBPF_0.6.0)
12379 struct perf_buffer *perf_buffer__new_raw_v0_6_0(int map_fd, size_t page_cnt,
12380 						struct perf_event_attr *attr,
12381 						perf_buffer_event_fn event_cb, void *ctx,
12382 						const struct perf_buffer_raw_opts *opts)
12383 {
12384 	struct perf_buffer_params p = {};
12385 
12386 	if (!attr)
12387 		return libbpf_err_ptr(-EINVAL);
12388 
12389 	if (!OPTS_VALID(opts, perf_buffer_raw_opts))
12390 		return libbpf_err_ptr(-EINVAL);
12391 
12392 	p.attr = attr;
12393 	p.event_cb = event_cb;
12394 	p.ctx = ctx;
12395 	p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
12396 	p.cpus = OPTS_GET(opts, cpus, NULL);
12397 	p.map_keys = OPTS_GET(opts, map_keys, NULL);
12398 
12399 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
12400 }
12401 
12402 COMPAT_VERSION(perf_buffer__new_raw_deprecated, perf_buffer__new_raw, LIBBPF_0.0.4)
12403 struct perf_buffer *perf_buffer__new_raw_deprecated(int map_fd, size_t page_cnt,
12404 						    const struct perf_buffer_raw_opts *opts)
12405 {
12406 	LIBBPF_OPTS(perf_buffer_raw_opts, inner_opts,
12407 		.cpu_cnt = opts->cpu_cnt,
12408 		.cpus = opts->cpus,
12409 		.map_keys = opts->map_keys,
12410 	);
12411 
12412 	return perf_buffer__new_raw_v0_6_0(map_fd, page_cnt, opts->attr,
12413 					   opts->event_cb, opts->ctx, &inner_opts);
12414 }
12415 
12416 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
12417 					      struct perf_buffer_params *p)
12418 {
12419 	const char *online_cpus_file = "/sys/devices/system/cpu/online";
12420 	struct bpf_map_info map;
12421 	char msg[STRERR_BUFSIZE];
12422 	struct perf_buffer *pb;
12423 	bool *online = NULL;
12424 	__u32 map_info_len;
12425 	int err, i, j, n;
12426 
12427 	if (page_cnt == 0 || (page_cnt & (page_cnt - 1))) {
12428 		pr_warn("page count should be power of two, but is %zu\n",
12429 			page_cnt);
12430 		return ERR_PTR(-EINVAL);
12431 	}
12432 
12433 	/* best-effort sanity checks */
12434 	memset(&map, 0, sizeof(map));
12435 	map_info_len = sizeof(map);
12436 	err = bpf_obj_get_info_by_fd(map_fd, &map, &map_info_len);
12437 	if (err) {
12438 		err = -errno;
12439 		/* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
12440 		 * -EBADFD, -EFAULT, or -E2BIG on real error
12441 		 */
12442 		if (err != -EINVAL) {
12443 			pr_warn("failed to get map info for map FD %d: %s\n",
12444 				map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
12445 			return ERR_PTR(err);
12446 		}
12447 		pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
12448 			 map_fd);
12449 	} else {
12450 		if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
12451 			pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
12452 				map.name);
12453 			return ERR_PTR(-EINVAL);
12454 		}
12455 	}
12456 
12457 	pb = calloc(1, sizeof(*pb));
12458 	if (!pb)
12459 		return ERR_PTR(-ENOMEM);
12460 
12461 	pb->event_cb = p->event_cb;
12462 	pb->sample_cb = p->sample_cb;
12463 	pb->lost_cb = p->lost_cb;
12464 	pb->ctx = p->ctx;
12465 
12466 	pb->page_size = getpagesize();
12467 	pb->mmap_size = pb->page_size * page_cnt;
12468 	pb->map_fd = map_fd;
12469 
12470 	pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
12471 	if (pb->epoll_fd < 0) {
12472 		err = -errno;
12473 		pr_warn("failed to create epoll instance: %s\n",
12474 			libbpf_strerror_r(err, msg, sizeof(msg)));
12475 		goto error;
12476 	}
12477 
12478 	if (p->cpu_cnt > 0) {
12479 		pb->cpu_cnt = p->cpu_cnt;
12480 	} else {
12481 		pb->cpu_cnt = libbpf_num_possible_cpus();
12482 		if (pb->cpu_cnt < 0) {
12483 			err = pb->cpu_cnt;
12484 			goto error;
12485 		}
12486 		if (map.max_entries && map.max_entries < pb->cpu_cnt)
12487 			pb->cpu_cnt = map.max_entries;
12488 	}
12489 
12490 	pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
12491 	if (!pb->events) {
12492 		err = -ENOMEM;
12493 		pr_warn("failed to allocate events: out of memory\n");
12494 		goto error;
12495 	}
12496 	pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
12497 	if (!pb->cpu_bufs) {
12498 		err = -ENOMEM;
12499 		pr_warn("failed to allocate buffers: out of memory\n");
12500 		goto error;
12501 	}
12502 
12503 	err = parse_cpu_mask_file(online_cpus_file, &online, &n);
12504 	if (err) {
12505 		pr_warn("failed to get online CPU mask: %d\n", err);
12506 		goto error;
12507 	}
12508 
12509 	for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
12510 		struct perf_cpu_buf *cpu_buf;
12511 		int cpu, map_key;
12512 
12513 		cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
12514 		map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
12515 
12516 		/* in case user didn't explicitly requested particular CPUs to
12517 		 * be attached to, skip offline/not present CPUs
12518 		 */
12519 		if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
12520 			continue;
12521 
12522 		cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
12523 		if (IS_ERR(cpu_buf)) {
12524 			err = PTR_ERR(cpu_buf);
12525 			goto error;
12526 		}
12527 
12528 		pb->cpu_bufs[j] = cpu_buf;
12529 
12530 		err = bpf_map_update_elem(pb->map_fd, &map_key,
12531 					  &cpu_buf->fd, 0);
12532 		if (err) {
12533 			err = -errno;
12534 			pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
12535 				cpu, map_key, cpu_buf->fd,
12536 				libbpf_strerror_r(err, msg, sizeof(msg)));
12537 			goto error;
12538 		}
12539 
12540 		pb->events[j].events = EPOLLIN;
12541 		pb->events[j].data.ptr = cpu_buf;
12542 		if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
12543 			      &pb->events[j]) < 0) {
12544 			err = -errno;
12545 			pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
12546 				cpu, cpu_buf->fd,
12547 				libbpf_strerror_r(err, msg, sizeof(msg)));
12548 			goto error;
12549 		}
12550 		j++;
12551 	}
12552 	pb->cpu_cnt = j;
12553 	free(online);
12554 
12555 	return pb;
12556 
12557 error:
12558 	free(online);
12559 	if (pb)
12560 		perf_buffer__free(pb);
12561 	return ERR_PTR(err);
12562 }
12563 
12564 struct perf_sample_raw {
12565 	struct perf_event_header header;
12566 	uint32_t size;
12567 	char data[];
12568 };
12569 
12570 struct perf_sample_lost {
12571 	struct perf_event_header header;
12572 	uint64_t id;
12573 	uint64_t lost;
12574 	uint64_t sample_id;
12575 };
12576 
12577 static enum bpf_perf_event_ret
12578 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
12579 {
12580 	struct perf_cpu_buf *cpu_buf = ctx;
12581 	struct perf_buffer *pb = cpu_buf->pb;
12582 	void *data = e;
12583 
12584 	/* user wants full control over parsing perf event */
12585 	if (pb->event_cb)
12586 		return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
12587 
12588 	switch (e->type) {
12589 	case PERF_RECORD_SAMPLE: {
12590 		struct perf_sample_raw *s = data;
12591 
12592 		if (pb->sample_cb)
12593 			pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
12594 		break;
12595 	}
12596 	case PERF_RECORD_LOST: {
12597 		struct perf_sample_lost *s = data;
12598 
12599 		if (pb->lost_cb)
12600 			pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
12601 		break;
12602 	}
12603 	default:
12604 		pr_warn("unknown perf sample type %d\n", e->type);
12605 		return LIBBPF_PERF_EVENT_ERROR;
12606 	}
12607 	return LIBBPF_PERF_EVENT_CONT;
12608 }
12609 
12610 static int perf_buffer__process_records(struct perf_buffer *pb,
12611 					struct perf_cpu_buf *cpu_buf)
12612 {
12613 	enum bpf_perf_event_ret ret;
12614 
12615 	ret = perf_event_read_simple(cpu_buf->base, pb->mmap_size,
12616 				     pb->page_size, &cpu_buf->buf,
12617 				     &cpu_buf->buf_size,
12618 				     perf_buffer__process_record, cpu_buf);
12619 	if (ret != LIBBPF_PERF_EVENT_CONT)
12620 		return ret;
12621 	return 0;
12622 }
12623 
12624 int perf_buffer__epoll_fd(const struct perf_buffer *pb)
12625 {
12626 	return pb->epoll_fd;
12627 }
12628 
12629 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
12630 {
12631 	int i, cnt, err;
12632 
12633 	cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
12634 	if (cnt < 0)
12635 		return -errno;
12636 
12637 	for (i = 0; i < cnt; i++) {
12638 		struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
12639 
12640 		err = perf_buffer__process_records(pb, cpu_buf);
12641 		if (err) {
12642 			pr_warn("error while processing records: %d\n", err);
12643 			return libbpf_err(err);
12644 		}
12645 	}
12646 	return cnt;
12647 }
12648 
12649 /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
12650  * manager.
12651  */
12652 size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
12653 {
12654 	return pb->cpu_cnt;
12655 }
12656 
12657 /*
12658  * Return perf_event FD of a ring buffer in *buf_idx* slot of
12659  * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
12660  * select()/poll()/epoll() Linux syscalls.
12661  */
12662 int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
12663 {
12664 	struct perf_cpu_buf *cpu_buf;
12665 
12666 	if (buf_idx >= pb->cpu_cnt)
12667 		return libbpf_err(-EINVAL);
12668 
12669 	cpu_buf = pb->cpu_bufs[buf_idx];
12670 	if (!cpu_buf)
12671 		return libbpf_err(-ENOENT);
12672 
12673 	return cpu_buf->fd;
12674 }
12675 
12676 /*
12677  * Consume data from perf ring buffer corresponding to slot *buf_idx* in
12678  * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
12679  * consume, do nothing and return success.
12680  * Returns:
12681  *   - 0 on success;
12682  *   - <0 on failure.
12683  */
12684 int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
12685 {
12686 	struct perf_cpu_buf *cpu_buf;
12687 
12688 	if (buf_idx >= pb->cpu_cnt)
12689 		return libbpf_err(-EINVAL);
12690 
12691 	cpu_buf = pb->cpu_bufs[buf_idx];
12692 	if (!cpu_buf)
12693 		return libbpf_err(-ENOENT);
12694 
12695 	return perf_buffer__process_records(pb, cpu_buf);
12696 }
12697 
12698 int perf_buffer__consume(struct perf_buffer *pb)
12699 {
12700 	int i, err;
12701 
12702 	for (i = 0; i < pb->cpu_cnt; i++) {
12703 		struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
12704 
12705 		if (!cpu_buf)
12706 			continue;
12707 
12708 		err = perf_buffer__process_records(pb, cpu_buf);
12709 		if (err) {
12710 			pr_warn("perf_buffer: failed to process records in buffer #%d: %d\n", i, err);
12711 			return libbpf_err(err);
12712 		}
12713 	}
12714 	return 0;
12715 }
12716 
12717 struct bpf_prog_info_array_desc {
12718 	int	array_offset;	/* e.g. offset of jited_prog_insns */
12719 	int	count_offset;	/* e.g. offset of jited_prog_len */
12720 	int	size_offset;	/* > 0: offset of rec size,
12721 				 * < 0: fix size of -size_offset
12722 				 */
12723 };
12724 
12725 static struct bpf_prog_info_array_desc bpf_prog_info_array_desc[] = {
12726 	[BPF_PROG_INFO_JITED_INSNS] = {
12727 		offsetof(struct bpf_prog_info, jited_prog_insns),
12728 		offsetof(struct bpf_prog_info, jited_prog_len),
12729 		-1,
12730 	},
12731 	[BPF_PROG_INFO_XLATED_INSNS] = {
12732 		offsetof(struct bpf_prog_info, xlated_prog_insns),
12733 		offsetof(struct bpf_prog_info, xlated_prog_len),
12734 		-1,
12735 	},
12736 	[BPF_PROG_INFO_MAP_IDS] = {
12737 		offsetof(struct bpf_prog_info, map_ids),
12738 		offsetof(struct bpf_prog_info, nr_map_ids),
12739 		-(int)sizeof(__u32),
12740 	},
12741 	[BPF_PROG_INFO_JITED_KSYMS] = {
12742 		offsetof(struct bpf_prog_info, jited_ksyms),
12743 		offsetof(struct bpf_prog_info, nr_jited_ksyms),
12744 		-(int)sizeof(__u64),
12745 	},
12746 	[BPF_PROG_INFO_JITED_FUNC_LENS] = {
12747 		offsetof(struct bpf_prog_info, jited_func_lens),
12748 		offsetof(struct bpf_prog_info, nr_jited_func_lens),
12749 		-(int)sizeof(__u32),
12750 	},
12751 	[BPF_PROG_INFO_FUNC_INFO] = {
12752 		offsetof(struct bpf_prog_info, func_info),
12753 		offsetof(struct bpf_prog_info, nr_func_info),
12754 		offsetof(struct bpf_prog_info, func_info_rec_size),
12755 	},
12756 	[BPF_PROG_INFO_LINE_INFO] = {
12757 		offsetof(struct bpf_prog_info, line_info),
12758 		offsetof(struct bpf_prog_info, nr_line_info),
12759 		offsetof(struct bpf_prog_info, line_info_rec_size),
12760 	},
12761 	[BPF_PROG_INFO_JITED_LINE_INFO] = {
12762 		offsetof(struct bpf_prog_info, jited_line_info),
12763 		offsetof(struct bpf_prog_info, nr_jited_line_info),
12764 		offsetof(struct bpf_prog_info, jited_line_info_rec_size),
12765 	},
12766 	[BPF_PROG_INFO_PROG_TAGS] = {
12767 		offsetof(struct bpf_prog_info, prog_tags),
12768 		offsetof(struct bpf_prog_info, nr_prog_tags),
12769 		-(int)sizeof(__u8) * BPF_TAG_SIZE,
12770 	},
12771 
12772 };
12773 
12774 static __u32 bpf_prog_info_read_offset_u32(struct bpf_prog_info *info,
12775 					   int offset)
12776 {
12777 	__u32 *array = (__u32 *)info;
12778 
12779 	if (offset >= 0)
12780 		return array[offset / sizeof(__u32)];
12781 	return -(int)offset;
12782 }
12783 
12784 static __u64 bpf_prog_info_read_offset_u64(struct bpf_prog_info *info,
12785 					   int offset)
12786 {
12787 	__u64 *array = (__u64 *)info;
12788 
12789 	if (offset >= 0)
12790 		return array[offset / sizeof(__u64)];
12791 	return -(int)offset;
12792 }
12793 
12794 static void bpf_prog_info_set_offset_u32(struct bpf_prog_info *info, int offset,
12795 					 __u32 val)
12796 {
12797 	__u32 *array = (__u32 *)info;
12798 
12799 	if (offset >= 0)
12800 		array[offset / sizeof(__u32)] = val;
12801 }
12802 
12803 static void bpf_prog_info_set_offset_u64(struct bpf_prog_info *info, int offset,
12804 					 __u64 val)
12805 {
12806 	__u64 *array = (__u64 *)info;
12807 
12808 	if (offset >= 0)
12809 		array[offset / sizeof(__u64)] = val;
12810 }
12811 
12812 struct bpf_prog_info_linear *
12813 bpf_program__get_prog_info_linear(int fd, __u64 arrays)
12814 {
12815 	struct bpf_prog_info_linear *info_linear;
12816 	struct bpf_prog_info info = {};
12817 	__u32 info_len = sizeof(info);
12818 	__u32 data_len = 0;
12819 	int i, err;
12820 	void *ptr;
12821 
12822 	if (arrays >> BPF_PROG_INFO_LAST_ARRAY)
12823 		return libbpf_err_ptr(-EINVAL);
12824 
12825 	/* step 1: get array dimensions */
12826 	err = bpf_obj_get_info_by_fd(fd, &info, &info_len);
12827 	if (err) {
12828 		pr_debug("can't get prog info: %s", strerror(errno));
12829 		return libbpf_err_ptr(-EFAULT);
12830 	}
12831 
12832 	/* step 2: calculate total size of all arrays */
12833 	for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
12834 		bool include_array = (arrays & (1UL << i)) > 0;
12835 		struct bpf_prog_info_array_desc *desc;
12836 		__u32 count, size;
12837 
12838 		desc = bpf_prog_info_array_desc + i;
12839 
12840 		/* kernel is too old to support this field */
12841 		if (info_len < desc->array_offset + sizeof(__u32) ||
12842 		    info_len < desc->count_offset + sizeof(__u32) ||
12843 		    (desc->size_offset > 0 && info_len < desc->size_offset))
12844 			include_array = false;
12845 
12846 		if (!include_array) {
12847 			arrays &= ~(1UL << i);	/* clear the bit */
12848 			continue;
12849 		}
12850 
12851 		count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
12852 		size  = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
12853 
12854 		data_len += count * size;
12855 	}
12856 
12857 	/* step 3: allocate continuous memory */
12858 	data_len = roundup(data_len, sizeof(__u64));
12859 	info_linear = malloc(sizeof(struct bpf_prog_info_linear) + data_len);
12860 	if (!info_linear)
12861 		return libbpf_err_ptr(-ENOMEM);
12862 
12863 	/* step 4: fill data to info_linear->info */
12864 	info_linear->arrays = arrays;
12865 	memset(&info_linear->info, 0, sizeof(info));
12866 	ptr = info_linear->data;
12867 
12868 	for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
12869 		struct bpf_prog_info_array_desc *desc;
12870 		__u32 count, size;
12871 
12872 		if ((arrays & (1UL << i)) == 0)
12873 			continue;
12874 
12875 		desc  = bpf_prog_info_array_desc + i;
12876 		count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
12877 		size  = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
12878 		bpf_prog_info_set_offset_u32(&info_linear->info,
12879 					     desc->count_offset, count);
12880 		bpf_prog_info_set_offset_u32(&info_linear->info,
12881 					     desc->size_offset, size);
12882 		bpf_prog_info_set_offset_u64(&info_linear->info,
12883 					     desc->array_offset,
12884 					     ptr_to_u64(ptr));
12885 		ptr += count * size;
12886 	}
12887 
12888 	/* step 5: call syscall again to get required arrays */
12889 	err = bpf_obj_get_info_by_fd(fd, &info_linear->info, &info_len);
12890 	if (err) {
12891 		pr_debug("can't get prog info: %s", strerror(errno));
12892 		free(info_linear);
12893 		return libbpf_err_ptr(-EFAULT);
12894 	}
12895 
12896 	/* step 6: verify the data */
12897 	for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
12898 		struct bpf_prog_info_array_desc *desc;
12899 		__u32 v1, v2;
12900 
12901 		if ((arrays & (1UL << i)) == 0)
12902 			continue;
12903 
12904 		desc = bpf_prog_info_array_desc + i;
12905 		v1 = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
12906 		v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
12907 						   desc->count_offset);
12908 		if (v1 != v2)
12909 			pr_warn("%s: mismatch in element count\n", __func__);
12910 
12911 		v1 = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
12912 		v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
12913 						   desc->size_offset);
12914 		if (v1 != v2)
12915 			pr_warn("%s: mismatch in rec size\n", __func__);
12916 	}
12917 
12918 	/* step 7: update info_len and data_len */
12919 	info_linear->info_len = sizeof(struct bpf_prog_info);
12920 	info_linear->data_len = data_len;
12921 
12922 	return info_linear;
12923 }
12924 
12925 void bpf_program__bpil_addr_to_offs(struct bpf_prog_info_linear *info_linear)
12926 {
12927 	int i;
12928 
12929 	for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
12930 		struct bpf_prog_info_array_desc *desc;
12931 		__u64 addr, offs;
12932 
12933 		if ((info_linear->arrays & (1UL << i)) == 0)
12934 			continue;
12935 
12936 		desc = bpf_prog_info_array_desc + i;
12937 		addr = bpf_prog_info_read_offset_u64(&info_linear->info,
12938 						     desc->array_offset);
12939 		offs = addr - ptr_to_u64(info_linear->data);
12940 		bpf_prog_info_set_offset_u64(&info_linear->info,
12941 					     desc->array_offset, offs);
12942 	}
12943 }
12944 
12945 void bpf_program__bpil_offs_to_addr(struct bpf_prog_info_linear *info_linear)
12946 {
12947 	int i;
12948 
12949 	for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
12950 		struct bpf_prog_info_array_desc *desc;
12951 		__u64 addr, offs;
12952 
12953 		if ((info_linear->arrays & (1UL << i)) == 0)
12954 			continue;
12955 
12956 		desc = bpf_prog_info_array_desc + i;
12957 		offs = bpf_prog_info_read_offset_u64(&info_linear->info,
12958 						     desc->array_offset);
12959 		addr = offs + ptr_to_u64(info_linear->data);
12960 		bpf_prog_info_set_offset_u64(&info_linear->info,
12961 					     desc->array_offset, addr);
12962 	}
12963 }
12964 
12965 int bpf_program__set_attach_target(struct bpf_program *prog,
12966 				   int attach_prog_fd,
12967 				   const char *attach_func_name)
12968 {
12969 	int btf_obj_fd = 0, btf_id = 0, err;
12970 
12971 	if (!prog || attach_prog_fd < 0)
12972 		return libbpf_err(-EINVAL);
12973 
12974 	if (prog->obj->loaded)
12975 		return libbpf_err(-EINVAL);
12976 
12977 	if (attach_prog_fd && !attach_func_name) {
12978 		/* remember attach_prog_fd and let bpf_program__load() find
12979 		 * BTF ID during the program load
12980 		 */
12981 		prog->attach_prog_fd = attach_prog_fd;
12982 		return 0;
12983 	}
12984 
12985 	if (attach_prog_fd) {
12986 		btf_id = libbpf_find_prog_btf_id(attach_func_name,
12987 						 attach_prog_fd);
12988 		if (btf_id < 0)
12989 			return libbpf_err(btf_id);
12990 	} else {
12991 		if (!attach_func_name)
12992 			return libbpf_err(-EINVAL);
12993 
12994 		/* load btf_vmlinux, if not yet */
12995 		err = bpf_object__load_vmlinux_btf(prog->obj, true);
12996 		if (err)
12997 			return libbpf_err(err);
12998 		err = find_kernel_btf_id(prog->obj, attach_func_name,
12999 					 prog->expected_attach_type,
13000 					 &btf_obj_fd, &btf_id);
13001 		if (err)
13002 			return libbpf_err(err);
13003 	}
13004 
13005 	prog->attach_btf_id = btf_id;
13006 	prog->attach_btf_obj_fd = btf_obj_fd;
13007 	prog->attach_prog_fd = attach_prog_fd;
13008 	return 0;
13009 }
13010 
13011 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
13012 {
13013 	int err = 0, n, len, start, end = -1;
13014 	bool *tmp;
13015 
13016 	*mask = NULL;
13017 	*mask_sz = 0;
13018 
13019 	/* Each sub string separated by ',' has format \d+-\d+ or \d+ */
13020 	while (*s) {
13021 		if (*s == ',' || *s == '\n') {
13022 			s++;
13023 			continue;
13024 		}
13025 		n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
13026 		if (n <= 0 || n > 2) {
13027 			pr_warn("Failed to get CPU range %s: %d\n", s, n);
13028 			err = -EINVAL;
13029 			goto cleanup;
13030 		} else if (n == 1) {
13031 			end = start;
13032 		}
13033 		if (start < 0 || start > end) {
13034 			pr_warn("Invalid CPU range [%d,%d] in %s\n",
13035 				start, end, s);
13036 			err = -EINVAL;
13037 			goto cleanup;
13038 		}
13039 		tmp = realloc(*mask, end + 1);
13040 		if (!tmp) {
13041 			err = -ENOMEM;
13042 			goto cleanup;
13043 		}
13044 		*mask = tmp;
13045 		memset(tmp + *mask_sz, 0, start - *mask_sz);
13046 		memset(tmp + start, 1, end - start + 1);
13047 		*mask_sz = end + 1;
13048 		s += len;
13049 	}
13050 	if (!*mask_sz) {
13051 		pr_warn("Empty CPU range\n");
13052 		return -EINVAL;
13053 	}
13054 	return 0;
13055 cleanup:
13056 	free(*mask);
13057 	*mask = NULL;
13058 	return err;
13059 }
13060 
13061 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
13062 {
13063 	int fd, err = 0, len;
13064 	char buf[128];
13065 
13066 	fd = open(fcpu, O_RDONLY | O_CLOEXEC);
13067 	if (fd < 0) {
13068 		err = -errno;
13069 		pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
13070 		return err;
13071 	}
13072 	len = read(fd, buf, sizeof(buf));
13073 	close(fd);
13074 	if (len <= 0) {
13075 		err = len ? -errno : -EINVAL;
13076 		pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
13077 		return err;
13078 	}
13079 	if (len >= sizeof(buf)) {
13080 		pr_warn("CPU mask is too big in file %s\n", fcpu);
13081 		return -E2BIG;
13082 	}
13083 	buf[len] = '\0';
13084 
13085 	return parse_cpu_mask_str(buf, mask, mask_sz);
13086 }
13087 
13088 int libbpf_num_possible_cpus(void)
13089 {
13090 	static const char *fcpu = "/sys/devices/system/cpu/possible";
13091 	static int cpus;
13092 	int err, n, i, tmp_cpus;
13093 	bool *mask;
13094 
13095 	tmp_cpus = READ_ONCE(cpus);
13096 	if (tmp_cpus > 0)
13097 		return tmp_cpus;
13098 
13099 	err = parse_cpu_mask_file(fcpu, &mask, &n);
13100 	if (err)
13101 		return libbpf_err(err);
13102 
13103 	tmp_cpus = 0;
13104 	for (i = 0; i < n; i++) {
13105 		if (mask[i])
13106 			tmp_cpus++;
13107 	}
13108 	free(mask);
13109 
13110 	WRITE_ONCE(cpus, tmp_cpus);
13111 	return tmp_cpus;
13112 }
13113 
13114 static int populate_skeleton_maps(const struct bpf_object *obj,
13115 				  struct bpf_map_skeleton *maps,
13116 				  size_t map_cnt)
13117 {
13118 	int i;
13119 
13120 	for (i = 0; i < map_cnt; i++) {
13121 		struct bpf_map **map = maps[i].map;
13122 		const char *name = maps[i].name;
13123 		void **mmaped = maps[i].mmaped;
13124 
13125 		*map = bpf_object__find_map_by_name(obj, name);
13126 		if (!*map) {
13127 			pr_warn("failed to find skeleton map '%s'\n", name);
13128 			return -ESRCH;
13129 		}
13130 
13131 		/* externs shouldn't be pre-setup from user code */
13132 		if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
13133 			*mmaped = (*map)->mmaped;
13134 	}
13135 	return 0;
13136 }
13137 
13138 static int populate_skeleton_progs(const struct bpf_object *obj,
13139 				   struct bpf_prog_skeleton *progs,
13140 				   size_t prog_cnt)
13141 {
13142 	int i;
13143 
13144 	for (i = 0; i < prog_cnt; i++) {
13145 		struct bpf_program **prog = progs[i].prog;
13146 		const char *name = progs[i].name;
13147 
13148 		*prog = bpf_object__find_program_by_name(obj, name);
13149 		if (!*prog) {
13150 			pr_warn("failed to find skeleton program '%s'\n", name);
13151 			return -ESRCH;
13152 		}
13153 	}
13154 	return 0;
13155 }
13156 
13157 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
13158 			      const struct bpf_object_open_opts *opts)
13159 {
13160 	DECLARE_LIBBPF_OPTS(bpf_object_open_opts, skel_opts,
13161 		.object_name = s->name,
13162 	);
13163 	struct bpf_object *obj;
13164 	int err;
13165 
13166 	/* Attempt to preserve opts->object_name, unless overriden by user
13167 	 * explicitly. Overwriting object name for skeletons is discouraged,
13168 	 * as it breaks global data maps, because they contain object name
13169 	 * prefix as their own map name prefix. When skeleton is generated,
13170 	 * bpftool is making an assumption that this name will stay the same.
13171 	 */
13172 	if (opts) {
13173 		memcpy(&skel_opts, opts, sizeof(*opts));
13174 		if (!opts->object_name)
13175 			skel_opts.object_name = s->name;
13176 	}
13177 
13178 	obj = bpf_object__open_mem(s->data, s->data_sz, &skel_opts);
13179 	err = libbpf_get_error(obj);
13180 	if (err) {
13181 		pr_warn("failed to initialize skeleton BPF object '%s': %d\n",
13182 			s->name, err);
13183 		return libbpf_err(err);
13184 	}
13185 
13186 	*s->obj = obj;
13187 	err = populate_skeleton_maps(obj, s->maps, s->map_cnt);
13188 	if (err) {
13189 		pr_warn("failed to populate skeleton maps for '%s': %d\n", s->name, err);
13190 		return libbpf_err(err);
13191 	}
13192 
13193 	err = populate_skeleton_progs(obj, s->progs, s->prog_cnt);
13194 	if (err) {
13195 		pr_warn("failed to populate skeleton progs for '%s': %d\n", s->name, err);
13196 		return libbpf_err(err);
13197 	}
13198 
13199 	return 0;
13200 }
13201 
13202 int bpf_object__open_subskeleton(struct bpf_object_subskeleton *s)
13203 {
13204 	int err, len, var_idx, i;
13205 	const char *var_name;
13206 	const struct bpf_map *map;
13207 	struct btf *btf;
13208 	__u32 map_type_id;
13209 	const struct btf_type *map_type, *var_type;
13210 	const struct bpf_var_skeleton *var_skel;
13211 	struct btf_var_secinfo *var;
13212 
13213 	if (!s->obj)
13214 		return libbpf_err(-EINVAL);
13215 
13216 	btf = bpf_object__btf(s->obj);
13217 	if (!btf) {
13218 		pr_warn("subskeletons require BTF at runtime (object %s)\n",
13219 		        bpf_object__name(s->obj));
13220 		return libbpf_err(-errno);
13221 	}
13222 
13223 	err = populate_skeleton_maps(s->obj, s->maps, s->map_cnt);
13224 	if (err) {
13225 		pr_warn("failed to populate subskeleton maps: %d\n", err);
13226 		return libbpf_err(err);
13227 	}
13228 
13229 	err = populate_skeleton_progs(s->obj, s->progs, s->prog_cnt);
13230 	if (err) {
13231 		pr_warn("failed to populate subskeleton maps: %d\n", err);
13232 		return libbpf_err(err);
13233 	}
13234 
13235 	for (var_idx = 0; var_idx < s->var_cnt; var_idx++) {
13236 		var_skel = &s->vars[var_idx];
13237 		map = *var_skel->map;
13238 		map_type_id = bpf_map__btf_value_type_id(map);
13239 		map_type = btf__type_by_id(btf, map_type_id);
13240 
13241 		if (!btf_is_datasec(map_type)) {
13242 			pr_warn("type for map '%1$s' is not a datasec: %2$s",
13243 				bpf_map__name(map),
13244 				__btf_kind_str(btf_kind(map_type)));
13245 			return libbpf_err(-EINVAL);
13246 		}
13247 
13248 		len = btf_vlen(map_type);
13249 		var = btf_var_secinfos(map_type);
13250 		for (i = 0; i < len; i++, var++) {
13251 			var_type = btf__type_by_id(btf, var->type);
13252 			var_name = btf__name_by_offset(btf, var_type->name_off);
13253 			if (strcmp(var_name, var_skel->name) == 0) {
13254 				*var_skel->addr = map->mmaped + var->offset;
13255 				break;
13256 			}
13257 		}
13258 	}
13259 	return 0;
13260 }
13261 
13262 void bpf_object__destroy_subskeleton(struct bpf_object_subskeleton *s)
13263 {
13264 	if (!s)
13265 		return;
13266 	free(s->maps);
13267 	free(s->progs);
13268 	free(s->vars);
13269 	free(s);
13270 }
13271 
13272 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
13273 {
13274 	int i, err;
13275 
13276 	err = bpf_object__load(*s->obj);
13277 	if (err) {
13278 		pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
13279 		return libbpf_err(err);
13280 	}
13281 
13282 	for (i = 0; i < s->map_cnt; i++) {
13283 		struct bpf_map *map = *s->maps[i].map;
13284 		size_t mmap_sz = bpf_map_mmap_sz(map);
13285 		int prot, map_fd = bpf_map__fd(map);
13286 		void **mmaped = s->maps[i].mmaped;
13287 
13288 		if (!mmaped)
13289 			continue;
13290 
13291 		if (!(map->def.map_flags & BPF_F_MMAPABLE)) {
13292 			*mmaped = NULL;
13293 			continue;
13294 		}
13295 
13296 		if (map->def.map_flags & BPF_F_RDONLY_PROG)
13297 			prot = PROT_READ;
13298 		else
13299 			prot = PROT_READ | PROT_WRITE;
13300 
13301 		/* Remap anonymous mmap()-ed "map initialization image" as
13302 		 * a BPF map-backed mmap()-ed memory, but preserving the same
13303 		 * memory address. This will cause kernel to change process'
13304 		 * page table to point to a different piece of kernel memory,
13305 		 * but from userspace point of view memory address (and its
13306 		 * contents, being identical at this point) will stay the
13307 		 * same. This mapping will be released by bpf_object__close()
13308 		 * as per normal clean up procedure, so we don't need to worry
13309 		 * about it from skeleton's clean up perspective.
13310 		 */
13311 		*mmaped = mmap(map->mmaped, mmap_sz, prot,
13312 				MAP_SHARED | MAP_FIXED, map_fd, 0);
13313 		if (*mmaped == MAP_FAILED) {
13314 			err = -errno;
13315 			*mmaped = NULL;
13316 			pr_warn("failed to re-mmap() map '%s': %d\n",
13317 				 bpf_map__name(map), err);
13318 			return libbpf_err(err);
13319 		}
13320 	}
13321 
13322 	return 0;
13323 }
13324 
13325 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
13326 {
13327 	int i, err;
13328 
13329 	for (i = 0; i < s->prog_cnt; i++) {
13330 		struct bpf_program *prog = *s->progs[i].prog;
13331 		struct bpf_link **link = s->progs[i].link;
13332 
13333 		if (!prog->autoload)
13334 			continue;
13335 
13336 		/* auto-attaching not supported for this program */
13337 		if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
13338 			continue;
13339 
13340 		/* if user already set the link manually, don't attempt auto-attach */
13341 		if (*link)
13342 			continue;
13343 
13344 		err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, link);
13345 		if (err) {
13346 			pr_warn("prog '%s': failed to auto-attach: %d\n",
13347 				bpf_program__name(prog), err);
13348 			return libbpf_err(err);
13349 		}
13350 
13351 		/* It's possible that for some SEC() definitions auto-attach
13352 		 * is supported in some cases (e.g., if definition completely
13353 		 * specifies target information), but is not in other cases.
13354 		 * SEC("uprobe") is one such case. If user specified target
13355 		 * binary and function name, such BPF program can be
13356 		 * auto-attached. But if not, it shouldn't trigger skeleton's
13357 		 * attach to fail. It should just be skipped.
13358 		 * attach_fn signals such case with returning 0 (no error) and
13359 		 * setting link to NULL.
13360 		 */
13361 	}
13362 
13363 	return 0;
13364 }
13365 
13366 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
13367 {
13368 	int i;
13369 
13370 	for (i = 0; i < s->prog_cnt; i++) {
13371 		struct bpf_link **link = s->progs[i].link;
13372 
13373 		bpf_link__destroy(*link);
13374 		*link = NULL;
13375 	}
13376 }
13377 
13378 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
13379 {
13380 	if (!s)
13381 		return;
13382 
13383 	if (s->progs)
13384 		bpf_object__detach_skeleton(s);
13385 	if (s->obj)
13386 		bpf_object__close(*s->obj);
13387 	free(s->maps);
13388 	free(s->progs);
13389 	free(s);
13390 }
13391