xref: /linux/tools/lib/bpf/libbpf.c (revision 04317b129e4eb5c6f4a58bb899b2019c1545320b)
1 // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
2 
3 /*
4  * Common eBPF ELF object loading operations.
5  *
6  * Copyright (C) 2013-2015 Alexei Starovoitov <ast@kernel.org>
7  * Copyright (C) 2015 Wang Nan <wangnan0@huawei.com>
8  * Copyright (C) 2015 Huawei Inc.
9  * Copyright (C) 2017 Nicira, Inc.
10  * Copyright (C) 2019 Isovalent, Inc.
11  */
12 
13 #ifndef _GNU_SOURCE
14 #define _GNU_SOURCE
15 #endif
16 #include <stdlib.h>
17 #include <stdio.h>
18 #include <stdarg.h>
19 #include <libgen.h>
20 #include <inttypes.h>
21 #include <limits.h>
22 #include <string.h>
23 #include <unistd.h>
24 #include <endian.h>
25 #include <fcntl.h>
26 #include <errno.h>
27 #include <ctype.h>
28 #include <asm/unistd.h>
29 #include <linux/err.h>
30 #include <linux/kernel.h>
31 #include <linux/bpf.h>
32 #include <linux/btf.h>
33 #include <linux/filter.h>
34 #include <linux/limits.h>
35 #include <linux/perf_event.h>
36 #include <linux/ring_buffer.h>
37 #include <sys/epoll.h>
38 #include <sys/ioctl.h>
39 #include <sys/mman.h>
40 #include <sys/stat.h>
41 #include <sys/types.h>
42 #include <sys/vfs.h>
43 #include <sys/utsname.h>
44 #include <sys/resource.h>
45 #include <libelf.h>
46 #include <gelf.h>
47 #include <zlib.h>
48 
49 #include "libbpf.h"
50 #include "bpf.h"
51 #include "btf.h"
52 #include "str_error.h"
53 #include "libbpf_internal.h"
54 #include "hashmap.h"
55 #include "bpf_gen_internal.h"
56 #include "zip.h"
57 
58 #ifndef BPF_FS_MAGIC
59 #define BPF_FS_MAGIC		0xcafe4a11
60 #endif
61 
62 #define BPF_INSN_SZ (sizeof(struct bpf_insn))
63 
64 /* vsprintf() in __base_pr() uses nonliteral format string. It may break
65  * compilation if user enables corresponding warning. Disable it explicitly.
66  */
67 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
68 
69 #define __printf(a, b)	__attribute__((format(printf, a, b)))
70 
71 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj);
72 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog);
73 
74 static const char * const attach_type_name[] = {
75 	[BPF_CGROUP_INET_INGRESS]	= "cgroup_inet_ingress",
76 	[BPF_CGROUP_INET_EGRESS]	= "cgroup_inet_egress",
77 	[BPF_CGROUP_INET_SOCK_CREATE]	= "cgroup_inet_sock_create",
78 	[BPF_CGROUP_INET_SOCK_RELEASE]	= "cgroup_inet_sock_release",
79 	[BPF_CGROUP_SOCK_OPS]		= "cgroup_sock_ops",
80 	[BPF_CGROUP_DEVICE]		= "cgroup_device",
81 	[BPF_CGROUP_INET4_BIND]		= "cgroup_inet4_bind",
82 	[BPF_CGROUP_INET6_BIND]		= "cgroup_inet6_bind",
83 	[BPF_CGROUP_INET4_CONNECT]	= "cgroup_inet4_connect",
84 	[BPF_CGROUP_INET6_CONNECT]	= "cgroup_inet6_connect",
85 	[BPF_CGROUP_INET4_POST_BIND]	= "cgroup_inet4_post_bind",
86 	[BPF_CGROUP_INET6_POST_BIND]	= "cgroup_inet6_post_bind",
87 	[BPF_CGROUP_INET4_GETPEERNAME]	= "cgroup_inet4_getpeername",
88 	[BPF_CGROUP_INET6_GETPEERNAME]	= "cgroup_inet6_getpeername",
89 	[BPF_CGROUP_INET4_GETSOCKNAME]	= "cgroup_inet4_getsockname",
90 	[BPF_CGROUP_INET6_GETSOCKNAME]	= "cgroup_inet6_getsockname",
91 	[BPF_CGROUP_UDP4_SENDMSG]	= "cgroup_udp4_sendmsg",
92 	[BPF_CGROUP_UDP6_SENDMSG]	= "cgroup_udp6_sendmsg",
93 	[BPF_CGROUP_SYSCTL]		= "cgroup_sysctl",
94 	[BPF_CGROUP_UDP4_RECVMSG]	= "cgroup_udp4_recvmsg",
95 	[BPF_CGROUP_UDP6_RECVMSG]	= "cgroup_udp6_recvmsg",
96 	[BPF_CGROUP_GETSOCKOPT]		= "cgroup_getsockopt",
97 	[BPF_CGROUP_SETSOCKOPT]		= "cgroup_setsockopt",
98 	[BPF_SK_SKB_STREAM_PARSER]	= "sk_skb_stream_parser",
99 	[BPF_SK_SKB_STREAM_VERDICT]	= "sk_skb_stream_verdict",
100 	[BPF_SK_SKB_VERDICT]		= "sk_skb_verdict",
101 	[BPF_SK_MSG_VERDICT]		= "sk_msg_verdict",
102 	[BPF_LIRC_MODE2]		= "lirc_mode2",
103 	[BPF_FLOW_DISSECTOR]		= "flow_dissector",
104 	[BPF_TRACE_RAW_TP]		= "trace_raw_tp",
105 	[BPF_TRACE_FENTRY]		= "trace_fentry",
106 	[BPF_TRACE_FEXIT]		= "trace_fexit",
107 	[BPF_MODIFY_RETURN]		= "modify_return",
108 	[BPF_LSM_MAC]			= "lsm_mac",
109 	[BPF_LSM_CGROUP]		= "lsm_cgroup",
110 	[BPF_SK_LOOKUP]			= "sk_lookup",
111 	[BPF_TRACE_ITER]		= "trace_iter",
112 	[BPF_XDP_DEVMAP]		= "xdp_devmap",
113 	[BPF_XDP_CPUMAP]		= "xdp_cpumap",
114 	[BPF_XDP]			= "xdp",
115 	[BPF_SK_REUSEPORT_SELECT]	= "sk_reuseport_select",
116 	[BPF_SK_REUSEPORT_SELECT_OR_MIGRATE]	= "sk_reuseport_select_or_migrate",
117 	[BPF_PERF_EVENT]		= "perf_event",
118 	[BPF_TRACE_KPROBE_MULTI]	= "trace_kprobe_multi",
119 	[BPF_STRUCT_OPS]		= "struct_ops",
120 	[BPF_NETFILTER]			= "netfilter",
121 	[BPF_TCX_INGRESS]		= "tcx_ingress",
122 	[BPF_TCX_EGRESS]		= "tcx_egress",
123 	[BPF_TRACE_UPROBE_MULTI]	= "trace_uprobe_multi",
124 };
125 
126 static const char * const link_type_name[] = {
127 	[BPF_LINK_TYPE_UNSPEC]			= "unspec",
128 	[BPF_LINK_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
129 	[BPF_LINK_TYPE_TRACING]			= "tracing",
130 	[BPF_LINK_TYPE_CGROUP]			= "cgroup",
131 	[BPF_LINK_TYPE_ITER]			= "iter",
132 	[BPF_LINK_TYPE_NETNS]			= "netns",
133 	[BPF_LINK_TYPE_XDP]			= "xdp",
134 	[BPF_LINK_TYPE_PERF_EVENT]		= "perf_event",
135 	[BPF_LINK_TYPE_KPROBE_MULTI]		= "kprobe_multi",
136 	[BPF_LINK_TYPE_STRUCT_OPS]		= "struct_ops",
137 	[BPF_LINK_TYPE_NETFILTER]		= "netfilter",
138 	[BPF_LINK_TYPE_TCX]			= "tcx",
139 	[BPF_LINK_TYPE_UPROBE_MULTI]		= "uprobe_multi",
140 };
141 
142 static const char * const map_type_name[] = {
143 	[BPF_MAP_TYPE_UNSPEC]			= "unspec",
144 	[BPF_MAP_TYPE_HASH]			= "hash",
145 	[BPF_MAP_TYPE_ARRAY]			= "array",
146 	[BPF_MAP_TYPE_PROG_ARRAY]		= "prog_array",
147 	[BPF_MAP_TYPE_PERF_EVENT_ARRAY]		= "perf_event_array",
148 	[BPF_MAP_TYPE_PERCPU_HASH]		= "percpu_hash",
149 	[BPF_MAP_TYPE_PERCPU_ARRAY]		= "percpu_array",
150 	[BPF_MAP_TYPE_STACK_TRACE]		= "stack_trace",
151 	[BPF_MAP_TYPE_CGROUP_ARRAY]		= "cgroup_array",
152 	[BPF_MAP_TYPE_LRU_HASH]			= "lru_hash",
153 	[BPF_MAP_TYPE_LRU_PERCPU_HASH]		= "lru_percpu_hash",
154 	[BPF_MAP_TYPE_LPM_TRIE]			= "lpm_trie",
155 	[BPF_MAP_TYPE_ARRAY_OF_MAPS]		= "array_of_maps",
156 	[BPF_MAP_TYPE_HASH_OF_MAPS]		= "hash_of_maps",
157 	[BPF_MAP_TYPE_DEVMAP]			= "devmap",
158 	[BPF_MAP_TYPE_DEVMAP_HASH]		= "devmap_hash",
159 	[BPF_MAP_TYPE_SOCKMAP]			= "sockmap",
160 	[BPF_MAP_TYPE_CPUMAP]			= "cpumap",
161 	[BPF_MAP_TYPE_XSKMAP]			= "xskmap",
162 	[BPF_MAP_TYPE_SOCKHASH]			= "sockhash",
163 	[BPF_MAP_TYPE_CGROUP_STORAGE]		= "cgroup_storage",
164 	[BPF_MAP_TYPE_REUSEPORT_SOCKARRAY]	= "reuseport_sockarray",
165 	[BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE]	= "percpu_cgroup_storage",
166 	[BPF_MAP_TYPE_QUEUE]			= "queue",
167 	[BPF_MAP_TYPE_STACK]			= "stack",
168 	[BPF_MAP_TYPE_SK_STORAGE]		= "sk_storage",
169 	[BPF_MAP_TYPE_STRUCT_OPS]		= "struct_ops",
170 	[BPF_MAP_TYPE_RINGBUF]			= "ringbuf",
171 	[BPF_MAP_TYPE_INODE_STORAGE]		= "inode_storage",
172 	[BPF_MAP_TYPE_TASK_STORAGE]		= "task_storage",
173 	[BPF_MAP_TYPE_BLOOM_FILTER]		= "bloom_filter",
174 	[BPF_MAP_TYPE_USER_RINGBUF]             = "user_ringbuf",
175 	[BPF_MAP_TYPE_CGRP_STORAGE]		= "cgrp_storage",
176 };
177 
178 static const char * const prog_type_name[] = {
179 	[BPF_PROG_TYPE_UNSPEC]			= "unspec",
180 	[BPF_PROG_TYPE_SOCKET_FILTER]		= "socket_filter",
181 	[BPF_PROG_TYPE_KPROBE]			= "kprobe",
182 	[BPF_PROG_TYPE_SCHED_CLS]		= "sched_cls",
183 	[BPF_PROG_TYPE_SCHED_ACT]		= "sched_act",
184 	[BPF_PROG_TYPE_TRACEPOINT]		= "tracepoint",
185 	[BPF_PROG_TYPE_XDP]			= "xdp",
186 	[BPF_PROG_TYPE_PERF_EVENT]		= "perf_event",
187 	[BPF_PROG_TYPE_CGROUP_SKB]		= "cgroup_skb",
188 	[BPF_PROG_TYPE_CGROUP_SOCK]		= "cgroup_sock",
189 	[BPF_PROG_TYPE_LWT_IN]			= "lwt_in",
190 	[BPF_PROG_TYPE_LWT_OUT]			= "lwt_out",
191 	[BPF_PROG_TYPE_LWT_XMIT]		= "lwt_xmit",
192 	[BPF_PROG_TYPE_SOCK_OPS]		= "sock_ops",
193 	[BPF_PROG_TYPE_SK_SKB]			= "sk_skb",
194 	[BPF_PROG_TYPE_CGROUP_DEVICE]		= "cgroup_device",
195 	[BPF_PROG_TYPE_SK_MSG]			= "sk_msg",
196 	[BPF_PROG_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
197 	[BPF_PROG_TYPE_CGROUP_SOCK_ADDR]	= "cgroup_sock_addr",
198 	[BPF_PROG_TYPE_LWT_SEG6LOCAL]		= "lwt_seg6local",
199 	[BPF_PROG_TYPE_LIRC_MODE2]		= "lirc_mode2",
200 	[BPF_PROG_TYPE_SK_REUSEPORT]		= "sk_reuseport",
201 	[BPF_PROG_TYPE_FLOW_DISSECTOR]		= "flow_dissector",
202 	[BPF_PROG_TYPE_CGROUP_SYSCTL]		= "cgroup_sysctl",
203 	[BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE]	= "raw_tracepoint_writable",
204 	[BPF_PROG_TYPE_CGROUP_SOCKOPT]		= "cgroup_sockopt",
205 	[BPF_PROG_TYPE_TRACING]			= "tracing",
206 	[BPF_PROG_TYPE_STRUCT_OPS]		= "struct_ops",
207 	[BPF_PROG_TYPE_EXT]			= "ext",
208 	[BPF_PROG_TYPE_LSM]			= "lsm",
209 	[BPF_PROG_TYPE_SK_LOOKUP]		= "sk_lookup",
210 	[BPF_PROG_TYPE_SYSCALL]			= "syscall",
211 	[BPF_PROG_TYPE_NETFILTER]		= "netfilter",
212 };
213 
214 static int __base_pr(enum libbpf_print_level level, const char *format,
215 		     va_list args)
216 {
217 	if (level == LIBBPF_DEBUG)
218 		return 0;
219 
220 	return vfprintf(stderr, format, args);
221 }
222 
223 static libbpf_print_fn_t __libbpf_pr = __base_pr;
224 
225 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
226 {
227 	libbpf_print_fn_t old_print_fn;
228 
229 	old_print_fn = __atomic_exchange_n(&__libbpf_pr, fn, __ATOMIC_RELAXED);
230 
231 	return old_print_fn;
232 }
233 
234 __printf(2, 3)
235 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
236 {
237 	va_list args;
238 	int old_errno;
239 	libbpf_print_fn_t print_fn;
240 
241 	print_fn = __atomic_load_n(&__libbpf_pr, __ATOMIC_RELAXED);
242 	if (!print_fn)
243 		return;
244 
245 	old_errno = errno;
246 
247 	va_start(args, format);
248 	__libbpf_pr(level, format, args);
249 	va_end(args);
250 
251 	errno = old_errno;
252 }
253 
254 static void pr_perm_msg(int err)
255 {
256 	struct rlimit limit;
257 	char buf[100];
258 
259 	if (err != -EPERM || geteuid() != 0)
260 		return;
261 
262 	err = getrlimit(RLIMIT_MEMLOCK, &limit);
263 	if (err)
264 		return;
265 
266 	if (limit.rlim_cur == RLIM_INFINITY)
267 		return;
268 
269 	if (limit.rlim_cur < 1024)
270 		snprintf(buf, sizeof(buf), "%zu bytes", (size_t)limit.rlim_cur);
271 	else if (limit.rlim_cur < 1024*1024)
272 		snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
273 	else
274 		snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
275 
276 	pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
277 		buf);
278 }
279 
280 #define STRERR_BUFSIZE  128
281 
282 /* Copied from tools/perf/util/util.h */
283 #ifndef zfree
284 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
285 #endif
286 
287 #ifndef zclose
288 # define zclose(fd) ({			\
289 	int ___err = 0;			\
290 	if ((fd) >= 0)			\
291 		___err = close((fd));	\
292 	fd = -1;			\
293 	___err; })
294 #endif
295 
296 static inline __u64 ptr_to_u64(const void *ptr)
297 {
298 	return (__u64) (unsigned long) ptr;
299 }
300 
301 int libbpf_set_strict_mode(enum libbpf_strict_mode mode)
302 {
303 	/* as of v1.0 libbpf_set_strict_mode() is a no-op */
304 	return 0;
305 }
306 
307 __u32 libbpf_major_version(void)
308 {
309 	return LIBBPF_MAJOR_VERSION;
310 }
311 
312 __u32 libbpf_minor_version(void)
313 {
314 	return LIBBPF_MINOR_VERSION;
315 }
316 
317 const char *libbpf_version_string(void)
318 {
319 #define __S(X) #X
320 #define _S(X) __S(X)
321 	return  "v" _S(LIBBPF_MAJOR_VERSION) "." _S(LIBBPF_MINOR_VERSION);
322 #undef _S
323 #undef __S
324 }
325 
326 enum reloc_type {
327 	RELO_LD64,
328 	RELO_CALL,
329 	RELO_DATA,
330 	RELO_EXTERN_LD64,
331 	RELO_EXTERN_CALL,
332 	RELO_SUBPROG_ADDR,
333 	RELO_CORE,
334 };
335 
336 struct reloc_desc {
337 	enum reloc_type type;
338 	int insn_idx;
339 	union {
340 		const struct bpf_core_relo *core_relo; /* used when type == RELO_CORE */
341 		struct {
342 			int map_idx;
343 			int sym_off;
344 			int ext_idx;
345 		};
346 	};
347 };
348 
349 /* stored as sec_def->cookie for all libbpf-supported SEC()s */
350 enum sec_def_flags {
351 	SEC_NONE = 0,
352 	/* expected_attach_type is optional, if kernel doesn't support that */
353 	SEC_EXP_ATTACH_OPT = 1,
354 	/* legacy, only used by libbpf_get_type_names() and
355 	 * libbpf_attach_type_by_name(), not used by libbpf itself at all.
356 	 * This used to be associated with cgroup (and few other) BPF programs
357 	 * that were attachable through BPF_PROG_ATTACH command. Pretty
358 	 * meaningless nowadays, though.
359 	 */
360 	SEC_ATTACHABLE = 2,
361 	SEC_ATTACHABLE_OPT = SEC_ATTACHABLE | SEC_EXP_ATTACH_OPT,
362 	/* attachment target is specified through BTF ID in either kernel or
363 	 * other BPF program's BTF object
364 	 */
365 	SEC_ATTACH_BTF = 4,
366 	/* BPF program type allows sleeping/blocking in kernel */
367 	SEC_SLEEPABLE = 8,
368 	/* BPF program support non-linear XDP buffer */
369 	SEC_XDP_FRAGS = 16,
370 	/* Setup proper attach type for usdt probes. */
371 	SEC_USDT = 32,
372 };
373 
374 struct bpf_sec_def {
375 	char *sec;
376 	enum bpf_prog_type prog_type;
377 	enum bpf_attach_type expected_attach_type;
378 	long cookie;
379 	int handler_id;
380 
381 	libbpf_prog_setup_fn_t prog_setup_fn;
382 	libbpf_prog_prepare_load_fn_t prog_prepare_load_fn;
383 	libbpf_prog_attach_fn_t prog_attach_fn;
384 };
385 
386 /*
387  * bpf_prog should be a better name but it has been used in
388  * linux/filter.h.
389  */
390 struct bpf_program {
391 	char *name;
392 	char *sec_name;
393 	size_t sec_idx;
394 	const struct bpf_sec_def *sec_def;
395 	/* this program's instruction offset (in number of instructions)
396 	 * within its containing ELF section
397 	 */
398 	size_t sec_insn_off;
399 	/* number of original instructions in ELF section belonging to this
400 	 * program, not taking into account subprogram instructions possible
401 	 * appended later during relocation
402 	 */
403 	size_t sec_insn_cnt;
404 	/* Offset (in number of instructions) of the start of instruction
405 	 * belonging to this BPF program  within its containing main BPF
406 	 * program. For the entry-point (main) BPF program, this is always
407 	 * zero. For a sub-program, this gets reset before each of main BPF
408 	 * programs are processed and relocated and is used to determined
409 	 * whether sub-program was already appended to the main program, and
410 	 * if yes, at which instruction offset.
411 	 */
412 	size_t sub_insn_off;
413 
414 	/* instructions that belong to BPF program; insns[0] is located at
415 	 * sec_insn_off instruction within its ELF section in ELF file, so
416 	 * when mapping ELF file instruction index to the local instruction,
417 	 * one needs to subtract sec_insn_off; and vice versa.
418 	 */
419 	struct bpf_insn *insns;
420 	/* actual number of instruction in this BPF program's image; for
421 	 * entry-point BPF programs this includes the size of main program
422 	 * itself plus all the used sub-programs, appended at the end
423 	 */
424 	size_t insns_cnt;
425 
426 	struct reloc_desc *reloc_desc;
427 	int nr_reloc;
428 
429 	/* BPF verifier log settings */
430 	char *log_buf;
431 	size_t log_size;
432 	__u32 log_level;
433 
434 	struct bpf_object *obj;
435 
436 	int fd;
437 	bool autoload;
438 	bool autoattach;
439 	bool sym_global;
440 	bool mark_btf_static;
441 	enum bpf_prog_type type;
442 	enum bpf_attach_type expected_attach_type;
443 	int exception_cb_idx;
444 
445 	int prog_ifindex;
446 	__u32 attach_btf_obj_fd;
447 	__u32 attach_btf_id;
448 	__u32 attach_prog_fd;
449 
450 	void *func_info;
451 	__u32 func_info_rec_size;
452 	__u32 func_info_cnt;
453 
454 	void *line_info;
455 	__u32 line_info_rec_size;
456 	__u32 line_info_cnt;
457 	__u32 prog_flags;
458 };
459 
460 struct bpf_struct_ops {
461 	const char *tname;
462 	const struct btf_type *type;
463 	struct bpf_program **progs;
464 	__u32 *kern_func_off;
465 	/* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
466 	void *data;
467 	/* e.g. struct bpf_struct_ops_tcp_congestion_ops in
468 	 *      btf_vmlinux's format.
469 	 * struct bpf_struct_ops_tcp_congestion_ops {
470 	 *	[... some other kernel fields ...]
471 	 *	struct tcp_congestion_ops data;
472 	 * }
473 	 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
474 	 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
475 	 * from "data".
476 	 */
477 	void *kern_vdata;
478 	__u32 type_id;
479 };
480 
481 #define DATA_SEC ".data"
482 #define BSS_SEC ".bss"
483 #define RODATA_SEC ".rodata"
484 #define KCONFIG_SEC ".kconfig"
485 #define KSYMS_SEC ".ksyms"
486 #define STRUCT_OPS_SEC ".struct_ops"
487 #define STRUCT_OPS_LINK_SEC ".struct_ops.link"
488 
489 enum libbpf_map_type {
490 	LIBBPF_MAP_UNSPEC,
491 	LIBBPF_MAP_DATA,
492 	LIBBPF_MAP_BSS,
493 	LIBBPF_MAP_RODATA,
494 	LIBBPF_MAP_KCONFIG,
495 };
496 
497 struct bpf_map_def {
498 	unsigned int type;
499 	unsigned int key_size;
500 	unsigned int value_size;
501 	unsigned int max_entries;
502 	unsigned int map_flags;
503 };
504 
505 struct bpf_map {
506 	struct bpf_object *obj;
507 	char *name;
508 	/* real_name is defined for special internal maps (.rodata*,
509 	 * .data*, .bss, .kconfig) and preserves their original ELF section
510 	 * name. This is important to be able to find corresponding BTF
511 	 * DATASEC information.
512 	 */
513 	char *real_name;
514 	int fd;
515 	int sec_idx;
516 	size_t sec_offset;
517 	int map_ifindex;
518 	int inner_map_fd;
519 	struct bpf_map_def def;
520 	__u32 numa_node;
521 	__u32 btf_var_idx;
522 	__u32 btf_key_type_id;
523 	__u32 btf_value_type_id;
524 	__u32 btf_vmlinux_value_type_id;
525 	enum libbpf_map_type libbpf_type;
526 	void *mmaped;
527 	struct bpf_struct_ops *st_ops;
528 	struct bpf_map *inner_map;
529 	void **init_slots;
530 	int init_slots_sz;
531 	char *pin_path;
532 	bool pinned;
533 	bool reused;
534 	bool autocreate;
535 	__u64 map_extra;
536 };
537 
538 enum extern_type {
539 	EXT_UNKNOWN,
540 	EXT_KCFG,
541 	EXT_KSYM,
542 };
543 
544 enum kcfg_type {
545 	KCFG_UNKNOWN,
546 	KCFG_CHAR,
547 	KCFG_BOOL,
548 	KCFG_INT,
549 	KCFG_TRISTATE,
550 	KCFG_CHAR_ARR,
551 };
552 
553 struct extern_desc {
554 	enum extern_type type;
555 	int sym_idx;
556 	int btf_id;
557 	int sec_btf_id;
558 	const char *name;
559 	char *essent_name;
560 	bool is_set;
561 	bool is_weak;
562 	union {
563 		struct {
564 			enum kcfg_type type;
565 			int sz;
566 			int align;
567 			int data_off;
568 			bool is_signed;
569 		} kcfg;
570 		struct {
571 			unsigned long long addr;
572 
573 			/* target btf_id of the corresponding kernel var. */
574 			int kernel_btf_obj_fd;
575 			int kernel_btf_id;
576 
577 			/* local btf_id of the ksym extern's type. */
578 			__u32 type_id;
579 			/* BTF fd index to be patched in for insn->off, this is
580 			 * 0 for vmlinux BTF, index in obj->fd_array for module
581 			 * BTF
582 			 */
583 			__s16 btf_fd_idx;
584 		} ksym;
585 	};
586 };
587 
588 struct module_btf {
589 	struct btf *btf;
590 	char *name;
591 	__u32 id;
592 	int fd;
593 	int fd_array_idx;
594 };
595 
596 enum sec_type {
597 	SEC_UNUSED = 0,
598 	SEC_RELO,
599 	SEC_BSS,
600 	SEC_DATA,
601 	SEC_RODATA,
602 };
603 
604 struct elf_sec_desc {
605 	enum sec_type sec_type;
606 	Elf64_Shdr *shdr;
607 	Elf_Data *data;
608 };
609 
610 struct elf_state {
611 	int fd;
612 	const void *obj_buf;
613 	size_t obj_buf_sz;
614 	Elf *elf;
615 	Elf64_Ehdr *ehdr;
616 	Elf_Data *symbols;
617 	Elf_Data *st_ops_data;
618 	Elf_Data *st_ops_link_data;
619 	size_t shstrndx; /* section index for section name strings */
620 	size_t strtabidx;
621 	struct elf_sec_desc *secs;
622 	size_t sec_cnt;
623 	int btf_maps_shndx;
624 	__u32 btf_maps_sec_btf_id;
625 	int text_shndx;
626 	int symbols_shndx;
627 	int st_ops_shndx;
628 	int st_ops_link_shndx;
629 };
630 
631 struct usdt_manager;
632 
633 struct bpf_object {
634 	char name[BPF_OBJ_NAME_LEN];
635 	char license[64];
636 	__u32 kern_version;
637 
638 	struct bpf_program *programs;
639 	size_t nr_programs;
640 	struct bpf_map *maps;
641 	size_t nr_maps;
642 	size_t maps_cap;
643 
644 	char *kconfig;
645 	struct extern_desc *externs;
646 	int nr_extern;
647 	int kconfig_map_idx;
648 
649 	bool loaded;
650 	bool has_subcalls;
651 	bool has_rodata;
652 
653 	struct bpf_gen *gen_loader;
654 
655 	/* Information when doing ELF related work. Only valid if efile.elf is not NULL */
656 	struct elf_state efile;
657 
658 	struct btf *btf;
659 	struct btf_ext *btf_ext;
660 
661 	/* Parse and load BTF vmlinux if any of the programs in the object need
662 	 * it at load time.
663 	 */
664 	struct btf *btf_vmlinux;
665 	/* Path to the custom BTF to be used for BPF CO-RE relocations as an
666 	 * override for vmlinux BTF.
667 	 */
668 	char *btf_custom_path;
669 	/* vmlinux BTF override for CO-RE relocations */
670 	struct btf *btf_vmlinux_override;
671 	/* Lazily initialized kernel module BTFs */
672 	struct module_btf *btf_modules;
673 	bool btf_modules_loaded;
674 	size_t btf_module_cnt;
675 	size_t btf_module_cap;
676 
677 	/* optional log settings passed to BPF_BTF_LOAD and BPF_PROG_LOAD commands */
678 	char *log_buf;
679 	size_t log_size;
680 	__u32 log_level;
681 
682 	int *fd_array;
683 	size_t fd_array_cap;
684 	size_t fd_array_cnt;
685 
686 	struct usdt_manager *usdt_man;
687 
688 	char path[];
689 };
690 
691 static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
692 static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
693 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
694 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
695 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn);
696 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
697 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
698 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx);
699 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx);
700 
701 void bpf_program__unload(struct bpf_program *prog)
702 {
703 	if (!prog)
704 		return;
705 
706 	zclose(prog->fd);
707 
708 	zfree(&prog->func_info);
709 	zfree(&prog->line_info);
710 }
711 
712 static void bpf_program__exit(struct bpf_program *prog)
713 {
714 	if (!prog)
715 		return;
716 
717 	bpf_program__unload(prog);
718 	zfree(&prog->name);
719 	zfree(&prog->sec_name);
720 	zfree(&prog->insns);
721 	zfree(&prog->reloc_desc);
722 
723 	prog->nr_reloc = 0;
724 	prog->insns_cnt = 0;
725 	prog->sec_idx = -1;
726 }
727 
728 static bool insn_is_subprog_call(const struct bpf_insn *insn)
729 {
730 	return BPF_CLASS(insn->code) == BPF_JMP &&
731 	       BPF_OP(insn->code) == BPF_CALL &&
732 	       BPF_SRC(insn->code) == BPF_K &&
733 	       insn->src_reg == BPF_PSEUDO_CALL &&
734 	       insn->dst_reg == 0 &&
735 	       insn->off == 0;
736 }
737 
738 static bool is_call_insn(const struct bpf_insn *insn)
739 {
740 	return insn->code == (BPF_JMP | BPF_CALL);
741 }
742 
743 static bool insn_is_pseudo_func(struct bpf_insn *insn)
744 {
745 	return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
746 }
747 
748 static int
749 bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
750 		      const char *name, size_t sec_idx, const char *sec_name,
751 		      size_t sec_off, void *insn_data, size_t insn_data_sz)
752 {
753 	if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
754 		pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
755 			sec_name, name, sec_off, insn_data_sz);
756 		return -EINVAL;
757 	}
758 
759 	memset(prog, 0, sizeof(*prog));
760 	prog->obj = obj;
761 
762 	prog->sec_idx = sec_idx;
763 	prog->sec_insn_off = sec_off / BPF_INSN_SZ;
764 	prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
765 	/* insns_cnt can later be increased by appending used subprograms */
766 	prog->insns_cnt = prog->sec_insn_cnt;
767 
768 	prog->type = BPF_PROG_TYPE_UNSPEC;
769 	prog->fd = -1;
770 	prog->exception_cb_idx = -1;
771 
772 	/* libbpf's convention for SEC("?abc...") is that it's just like
773 	 * SEC("abc...") but the corresponding bpf_program starts out with
774 	 * autoload set to false.
775 	 */
776 	if (sec_name[0] == '?') {
777 		prog->autoload = false;
778 		/* from now on forget there was ? in section name */
779 		sec_name++;
780 	} else {
781 		prog->autoload = true;
782 	}
783 
784 	prog->autoattach = true;
785 
786 	/* inherit object's log_level */
787 	prog->log_level = obj->log_level;
788 
789 	prog->sec_name = strdup(sec_name);
790 	if (!prog->sec_name)
791 		goto errout;
792 
793 	prog->name = strdup(name);
794 	if (!prog->name)
795 		goto errout;
796 
797 	prog->insns = malloc(insn_data_sz);
798 	if (!prog->insns)
799 		goto errout;
800 	memcpy(prog->insns, insn_data, insn_data_sz);
801 
802 	return 0;
803 errout:
804 	pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
805 	bpf_program__exit(prog);
806 	return -ENOMEM;
807 }
808 
809 static int
810 bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
811 			 const char *sec_name, int sec_idx)
812 {
813 	Elf_Data *symbols = obj->efile.symbols;
814 	struct bpf_program *prog, *progs;
815 	void *data = sec_data->d_buf;
816 	size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
817 	int nr_progs, err, i;
818 	const char *name;
819 	Elf64_Sym *sym;
820 
821 	progs = obj->programs;
822 	nr_progs = obj->nr_programs;
823 	nr_syms = symbols->d_size / sizeof(Elf64_Sym);
824 
825 	for (i = 0; i < nr_syms; i++) {
826 		sym = elf_sym_by_idx(obj, i);
827 
828 		if (sym->st_shndx != sec_idx)
829 			continue;
830 		if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC)
831 			continue;
832 
833 		prog_sz = sym->st_size;
834 		sec_off = sym->st_value;
835 
836 		name = elf_sym_str(obj, sym->st_name);
837 		if (!name) {
838 			pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
839 				sec_name, sec_off);
840 			return -LIBBPF_ERRNO__FORMAT;
841 		}
842 
843 		if (sec_off + prog_sz > sec_sz) {
844 			pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
845 				sec_name, sec_off);
846 			return -LIBBPF_ERRNO__FORMAT;
847 		}
848 
849 		if (sec_idx != obj->efile.text_shndx && ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
850 			pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
851 			return -ENOTSUP;
852 		}
853 
854 		pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
855 			 sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
856 
857 		progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
858 		if (!progs) {
859 			/*
860 			 * In this case the original obj->programs
861 			 * is still valid, so don't need special treat for
862 			 * bpf_close_object().
863 			 */
864 			pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
865 				sec_name, name);
866 			return -ENOMEM;
867 		}
868 		obj->programs = progs;
869 
870 		prog = &progs[nr_progs];
871 
872 		err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
873 					    sec_off, data + sec_off, prog_sz);
874 		if (err)
875 			return err;
876 
877 		if (ELF64_ST_BIND(sym->st_info) != STB_LOCAL)
878 			prog->sym_global = true;
879 
880 		/* if function is a global/weak symbol, but has restricted
881 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
882 		 * as static to enable more permissive BPF verification mode
883 		 * with more outside context available to BPF verifier
884 		 */
885 		if (prog->sym_global && (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
886 		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL))
887 			prog->mark_btf_static = true;
888 
889 		nr_progs++;
890 		obj->nr_programs = nr_progs;
891 	}
892 
893 	return 0;
894 }
895 
896 static const struct btf_member *
897 find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
898 {
899 	struct btf_member *m;
900 	int i;
901 
902 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
903 		if (btf_member_bit_offset(t, i) == bit_offset)
904 			return m;
905 	}
906 
907 	return NULL;
908 }
909 
910 static const struct btf_member *
911 find_member_by_name(const struct btf *btf, const struct btf_type *t,
912 		    const char *name)
913 {
914 	struct btf_member *m;
915 	int i;
916 
917 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
918 		if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
919 			return m;
920 	}
921 
922 	return NULL;
923 }
924 
925 #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
926 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
927 				   const char *name, __u32 kind);
928 
929 static int
930 find_struct_ops_kern_types(const struct btf *btf, const char *tname,
931 			   const struct btf_type **type, __u32 *type_id,
932 			   const struct btf_type **vtype, __u32 *vtype_id,
933 			   const struct btf_member **data_member)
934 {
935 	const struct btf_type *kern_type, *kern_vtype;
936 	const struct btf_member *kern_data_member;
937 	__s32 kern_vtype_id, kern_type_id;
938 	__u32 i;
939 
940 	kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
941 	if (kern_type_id < 0) {
942 		pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n",
943 			tname);
944 		return kern_type_id;
945 	}
946 	kern_type = btf__type_by_id(btf, kern_type_id);
947 
948 	/* Find the corresponding "map_value" type that will be used
949 	 * in map_update(BPF_MAP_TYPE_STRUCT_OPS).  For example,
950 	 * find "struct bpf_struct_ops_tcp_congestion_ops" from the
951 	 * btf_vmlinux.
952 	 */
953 	kern_vtype_id = find_btf_by_prefix_kind(btf, STRUCT_OPS_VALUE_PREFIX,
954 						tname, BTF_KIND_STRUCT);
955 	if (kern_vtype_id < 0) {
956 		pr_warn("struct_ops init_kern: struct %s%s is not found in kernel BTF\n",
957 			STRUCT_OPS_VALUE_PREFIX, tname);
958 		return kern_vtype_id;
959 	}
960 	kern_vtype = btf__type_by_id(btf, kern_vtype_id);
961 
962 	/* Find "struct tcp_congestion_ops" from
963 	 * struct bpf_struct_ops_tcp_congestion_ops {
964 	 *	[ ... ]
965 	 *	struct tcp_congestion_ops data;
966 	 * }
967 	 */
968 	kern_data_member = btf_members(kern_vtype);
969 	for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
970 		if (kern_data_member->type == kern_type_id)
971 			break;
972 	}
973 	if (i == btf_vlen(kern_vtype)) {
974 		pr_warn("struct_ops init_kern: struct %s data is not found in struct %s%s\n",
975 			tname, STRUCT_OPS_VALUE_PREFIX, tname);
976 		return -EINVAL;
977 	}
978 
979 	*type = kern_type;
980 	*type_id = kern_type_id;
981 	*vtype = kern_vtype;
982 	*vtype_id = kern_vtype_id;
983 	*data_member = kern_data_member;
984 
985 	return 0;
986 }
987 
988 static bool bpf_map__is_struct_ops(const struct bpf_map *map)
989 {
990 	return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
991 }
992 
993 /* Init the map's fields that depend on kern_btf */
994 static int bpf_map__init_kern_struct_ops(struct bpf_map *map,
995 					 const struct btf *btf,
996 					 const struct btf *kern_btf)
997 {
998 	const struct btf_member *member, *kern_member, *kern_data_member;
999 	const struct btf_type *type, *kern_type, *kern_vtype;
1000 	__u32 i, kern_type_id, kern_vtype_id, kern_data_off;
1001 	struct bpf_struct_ops *st_ops;
1002 	void *data, *kern_data;
1003 	const char *tname;
1004 	int err;
1005 
1006 	st_ops = map->st_ops;
1007 	type = st_ops->type;
1008 	tname = st_ops->tname;
1009 	err = find_struct_ops_kern_types(kern_btf, tname,
1010 					 &kern_type, &kern_type_id,
1011 					 &kern_vtype, &kern_vtype_id,
1012 					 &kern_data_member);
1013 	if (err)
1014 		return err;
1015 
1016 	pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
1017 		 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
1018 
1019 	map->def.value_size = kern_vtype->size;
1020 	map->btf_vmlinux_value_type_id = kern_vtype_id;
1021 
1022 	st_ops->kern_vdata = calloc(1, kern_vtype->size);
1023 	if (!st_ops->kern_vdata)
1024 		return -ENOMEM;
1025 
1026 	data = st_ops->data;
1027 	kern_data_off = kern_data_member->offset / 8;
1028 	kern_data = st_ops->kern_vdata + kern_data_off;
1029 
1030 	member = btf_members(type);
1031 	for (i = 0; i < btf_vlen(type); i++, member++) {
1032 		const struct btf_type *mtype, *kern_mtype;
1033 		__u32 mtype_id, kern_mtype_id;
1034 		void *mdata, *kern_mdata;
1035 		__s64 msize, kern_msize;
1036 		__u32 moff, kern_moff;
1037 		__u32 kern_member_idx;
1038 		const char *mname;
1039 
1040 		mname = btf__name_by_offset(btf, member->name_off);
1041 		kern_member = find_member_by_name(kern_btf, kern_type, mname);
1042 		if (!kern_member) {
1043 			pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
1044 				map->name, mname);
1045 			return -ENOTSUP;
1046 		}
1047 
1048 		kern_member_idx = kern_member - btf_members(kern_type);
1049 		if (btf_member_bitfield_size(type, i) ||
1050 		    btf_member_bitfield_size(kern_type, kern_member_idx)) {
1051 			pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
1052 				map->name, mname);
1053 			return -ENOTSUP;
1054 		}
1055 
1056 		moff = member->offset / 8;
1057 		kern_moff = kern_member->offset / 8;
1058 
1059 		mdata = data + moff;
1060 		kern_mdata = kern_data + kern_moff;
1061 
1062 		mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
1063 		kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
1064 						    &kern_mtype_id);
1065 		if (BTF_INFO_KIND(mtype->info) !=
1066 		    BTF_INFO_KIND(kern_mtype->info)) {
1067 			pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
1068 				map->name, mname, BTF_INFO_KIND(mtype->info),
1069 				BTF_INFO_KIND(kern_mtype->info));
1070 			return -ENOTSUP;
1071 		}
1072 
1073 		if (btf_is_ptr(mtype)) {
1074 			struct bpf_program *prog;
1075 
1076 			prog = st_ops->progs[i];
1077 			if (!prog)
1078 				continue;
1079 
1080 			kern_mtype = skip_mods_and_typedefs(kern_btf,
1081 							    kern_mtype->type,
1082 							    &kern_mtype_id);
1083 
1084 			/* mtype->type must be a func_proto which was
1085 			 * guaranteed in bpf_object__collect_st_ops_relos(),
1086 			 * so only check kern_mtype for func_proto here.
1087 			 */
1088 			if (!btf_is_func_proto(kern_mtype)) {
1089 				pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
1090 					map->name, mname);
1091 				return -ENOTSUP;
1092 			}
1093 
1094 			prog->attach_btf_id = kern_type_id;
1095 			prog->expected_attach_type = kern_member_idx;
1096 
1097 			st_ops->kern_func_off[i] = kern_data_off + kern_moff;
1098 
1099 			pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
1100 				 map->name, mname, prog->name, moff,
1101 				 kern_moff);
1102 
1103 			continue;
1104 		}
1105 
1106 		msize = btf__resolve_size(btf, mtype_id);
1107 		kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
1108 		if (msize < 0 || kern_msize < 0 || msize != kern_msize) {
1109 			pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
1110 				map->name, mname, (ssize_t)msize,
1111 				(ssize_t)kern_msize);
1112 			return -ENOTSUP;
1113 		}
1114 
1115 		pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
1116 			 map->name, mname, (unsigned int)msize,
1117 			 moff, kern_moff);
1118 		memcpy(kern_mdata, mdata, msize);
1119 	}
1120 
1121 	return 0;
1122 }
1123 
1124 static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
1125 {
1126 	struct bpf_map *map;
1127 	size_t i;
1128 	int err;
1129 
1130 	for (i = 0; i < obj->nr_maps; i++) {
1131 		map = &obj->maps[i];
1132 
1133 		if (!bpf_map__is_struct_ops(map))
1134 			continue;
1135 
1136 		err = bpf_map__init_kern_struct_ops(map, obj->btf,
1137 						    obj->btf_vmlinux);
1138 		if (err)
1139 			return err;
1140 	}
1141 
1142 	return 0;
1143 }
1144 
1145 static int init_struct_ops_maps(struct bpf_object *obj, const char *sec_name,
1146 				int shndx, Elf_Data *data, __u32 map_flags)
1147 {
1148 	const struct btf_type *type, *datasec;
1149 	const struct btf_var_secinfo *vsi;
1150 	struct bpf_struct_ops *st_ops;
1151 	const char *tname, *var_name;
1152 	__s32 type_id, datasec_id;
1153 	const struct btf *btf;
1154 	struct bpf_map *map;
1155 	__u32 i;
1156 
1157 	if (shndx == -1)
1158 		return 0;
1159 
1160 	btf = obj->btf;
1161 	datasec_id = btf__find_by_name_kind(btf, sec_name,
1162 					    BTF_KIND_DATASEC);
1163 	if (datasec_id < 0) {
1164 		pr_warn("struct_ops init: DATASEC %s not found\n",
1165 			sec_name);
1166 		return -EINVAL;
1167 	}
1168 
1169 	datasec = btf__type_by_id(btf, datasec_id);
1170 	vsi = btf_var_secinfos(datasec);
1171 	for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
1172 		type = btf__type_by_id(obj->btf, vsi->type);
1173 		var_name = btf__name_by_offset(obj->btf, type->name_off);
1174 
1175 		type_id = btf__resolve_type(obj->btf, vsi->type);
1176 		if (type_id < 0) {
1177 			pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
1178 				vsi->type, sec_name);
1179 			return -EINVAL;
1180 		}
1181 
1182 		type = btf__type_by_id(obj->btf, type_id);
1183 		tname = btf__name_by_offset(obj->btf, type->name_off);
1184 		if (!tname[0]) {
1185 			pr_warn("struct_ops init: anonymous type is not supported\n");
1186 			return -ENOTSUP;
1187 		}
1188 		if (!btf_is_struct(type)) {
1189 			pr_warn("struct_ops init: %s is not a struct\n", tname);
1190 			return -EINVAL;
1191 		}
1192 
1193 		map = bpf_object__add_map(obj);
1194 		if (IS_ERR(map))
1195 			return PTR_ERR(map);
1196 
1197 		map->sec_idx = shndx;
1198 		map->sec_offset = vsi->offset;
1199 		map->name = strdup(var_name);
1200 		if (!map->name)
1201 			return -ENOMEM;
1202 
1203 		map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
1204 		map->def.key_size = sizeof(int);
1205 		map->def.value_size = type->size;
1206 		map->def.max_entries = 1;
1207 		map->def.map_flags = map_flags;
1208 
1209 		map->st_ops = calloc(1, sizeof(*map->st_ops));
1210 		if (!map->st_ops)
1211 			return -ENOMEM;
1212 		st_ops = map->st_ops;
1213 		st_ops->data = malloc(type->size);
1214 		st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1215 		st_ops->kern_func_off = malloc(btf_vlen(type) *
1216 					       sizeof(*st_ops->kern_func_off));
1217 		if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1218 			return -ENOMEM;
1219 
1220 		if (vsi->offset + type->size > data->d_size) {
1221 			pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1222 				var_name, sec_name);
1223 			return -EINVAL;
1224 		}
1225 
1226 		memcpy(st_ops->data,
1227 		       data->d_buf + vsi->offset,
1228 		       type->size);
1229 		st_ops->tname = tname;
1230 		st_ops->type = type;
1231 		st_ops->type_id = type_id;
1232 
1233 		pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
1234 			 tname, type_id, var_name, vsi->offset);
1235 	}
1236 
1237 	return 0;
1238 }
1239 
1240 static int bpf_object_init_struct_ops(struct bpf_object *obj)
1241 {
1242 	int err;
1243 
1244 	err = init_struct_ops_maps(obj, STRUCT_OPS_SEC, obj->efile.st_ops_shndx,
1245 				   obj->efile.st_ops_data, 0);
1246 	err = err ?: init_struct_ops_maps(obj, STRUCT_OPS_LINK_SEC,
1247 					  obj->efile.st_ops_link_shndx,
1248 					  obj->efile.st_ops_link_data,
1249 					  BPF_F_LINK);
1250 	return err;
1251 }
1252 
1253 static struct bpf_object *bpf_object__new(const char *path,
1254 					  const void *obj_buf,
1255 					  size_t obj_buf_sz,
1256 					  const char *obj_name)
1257 {
1258 	struct bpf_object *obj;
1259 	char *end;
1260 
1261 	obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1262 	if (!obj) {
1263 		pr_warn("alloc memory failed for %s\n", path);
1264 		return ERR_PTR(-ENOMEM);
1265 	}
1266 
1267 	strcpy(obj->path, path);
1268 	if (obj_name) {
1269 		libbpf_strlcpy(obj->name, obj_name, sizeof(obj->name));
1270 	} else {
1271 		/* Using basename() GNU version which doesn't modify arg. */
1272 		libbpf_strlcpy(obj->name, basename((void *)path), sizeof(obj->name));
1273 		end = strchr(obj->name, '.');
1274 		if (end)
1275 			*end = 0;
1276 	}
1277 
1278 	obj->efile.fd = -1;
1279 	/*
1280 	 * Caller of this function should also call
1281 	 * bpf_object__elf_finish() after data collection to return
1282 	 * obj_buf to user. If not, we should duplicate the buffer to
1283 	 * avoid user freeing them before elf finish.
1284 	 */
1285 	obj->efile.obj_buf = obj_buf;
1286 	obj->efile.obj_buf_sz = obj_buf_sz;
1287 	obj->efile.btf_maps_shndx = -1;
1288 	obj->efile.st_ops_shndx = -1;
1289 	obj->efile.st_ops_link_shndx = -1;
1290 	obj->kconfig_map_idx = -1;
1291 
1292 	obj->kern_version = get_kernel_version();
1293 	obj->loaded = false;
1294 
1295 	return obj;
1296 }
1297 
1298 static void bpf_object__elf_finish(struct bpf_object *obj)
1299 {
1300 	if (!obj->efile.elf)
1301 		return;
1302 
1303 	elf_end(obj->efile.elf);
1304 	obj->efile.elf = NULL;
1305 	obj->efile.symbols = NULL;
1306 	obj->efile.st_ops_data = NULL;
1307 	obj->efile.st_ops_link_data = NULL;
1308 
1309 	zfree(&obj->efile.secs);
1310 	obj->efile.sec_cnt = 0;
1311 	zclose(obj->efile.fd);
1312 	obj->efile.obj_buf = NULL;
1313 	obj->efile.obj_buf_sz = 0;
1314 }
1315 
1316 static int bpf_object__elf_init(struct bpf_object *obj)
1317 {
1318 	Elf64_Ehdr *ehdr;
1319 	int err = 0;
1320 	Elf *elf;
1321 
1322 	if (obj->efile.elf) {
1323 		pr_warn("elf: init internal error\n");
1324 		return -LIBBPF_ERRNO__LIBELF;
1325 	}
1326 
1327 	if (obj->efile.obj_buf_sz > 0) {
1328 		/* obj_buf should have been validated by bpf_object__open_mem(). */
1329 		elf = elf_memory((char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
1330 	} else {
1331 		obj->efile.fd = open(obj->path, O_RDONLY | O_CLOEXEC);
1332 		if (obj->efile.fd < 0) {
1333 			char errmsg[STRERR_BUFSIZE], *cp;
1334 
1335 			err = -errno;
1336 			cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
1337 			pr_warn("elf: failed to open %s: %s\n", obj->path, cp);
1338 			return err;
1339 		}
1340 
1341 		elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1342 	}
1343 
1344 	if (!elf) {
1345 		pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
1346 		err = -LIBBPF_ERRNO__LIBELF;
1347 		goto errout;
1348 	}
1349 
1350 	obj->efile.elf = elf;
1351 
1352 	if (elf_kind(elf) != ELF_K_ELF) {
1353 		err = -LIBBPF_ERRNO__FORMAT;
1354 		pr_warn("elf: '%s' is not a proper ELF object\n", obj->path);
1355 		goto errout;
1356 	}
1357 
1358 	if (gelf_getclass(elf) != ELFCLASS64) {
1359 		err = -LIBBPF_ERRNO__FORMAT;
1360 		pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path);
1361 		goto errout;
1362 	}
1363 
1364 	obj->efile.ehdr = ehdr = elf64_getehdr(elf);
1365 	if (!obj->efile.ehdr) {
1366 		pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
1367 		err = -LIBBPF_ERRNO__FORMAT;
1368 		goto errout;
1369 	}
1370 
1371 	if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
1372 		pr_warn("elf: failed to get section names section index for %s: %s\n",
1373 			obj->path, elf_errmsg(-1));
1374 		err = -LIBBPF_ERRNO__FORMAT;
1375 		goto errout;
1376 	}
1377 
1378 	/* ELF is corrupted/truncated, avoid calling elf_strptr. */
1379 	if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
1380 		pr_warn("elf: failed to get section names strings from %s: %s\n",
1381 			obj->path, elf_errmsg(-1));
1382 		err = -LIBBPF_ERRNO__FORMAT;
1383 		goto errout;
1384 	}
1385 
1386 	/* Old LLVM set e_machine to EM_NONE */
1387 	if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
1388 		pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
1389 		err = -LIBBPF_ERRNO__FORMAT;
1390 		goto errout;
1391 	}
1392 
1393 	return 0;
1394 errout:
1395 	bpf_object__elf_finish(obj);
1396 	return err;
1397 }
1398 
1399 static int bpf_object__check_endianness(struct bpf_object *obj)
1400 {
1401 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1402 	if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2LSB)
1403 		return 0;
1404 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1405 	if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2MSB)
1406 		return 0;
1407 #else
1408 # error "Unrecognized __BYTE_ORDER__"
1409 #endif
1410 	pr_warn("elf: endianness mismatch in %s.\n", obj->path);
1411 	return -LIBBPF_ERRNO__ENDIAN;
1412 }
1413 
1414 static int
1415 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1416 {
1417 	if (!data) {
1418 		pr_warn("invalid license section in %s\n", obj->path);
1419 		return -LIBBPF_ERRNO__FORMAT;
1420 	}
1421 	/* libbpf_strlcpy() only copies first N - 1 bytes, so size + 1 won't
1422 	 * go over allowed ELF data section buffer
1423 	 */
1424 	libbpf_strlcpy(obj->license, data, min(size + 1, sizeof(obj->license)));
1425 	pr_debug("license of %s is %s\n", obj->path, obj->license);
1426 	return 0;
1427 }
1428 
1429 static int
1430 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1431 {
1432 	__u32 kver;
1433 
1434 	if (!data || size != sizeof(kver)) {
1435 		pr_warn("invalid kver section in %s\n", obj->path);
1436 		return -LIBBPF_ERRNO__FORMAT;
1437 	}
1438 	memcpy(&kver, data, sizeof(kver));
1439 	obj->kern_version = kver;
1440 	pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1441 	return 0;
1442 }
1443 
1444 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1445 {
1446 	if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1447 	    type == BPF_MAP_TYPE_HASH_OF_MAPS)
1448 		return true;
1449 	return false;
1450 }
1451 
1452 static int find_elf_sec_sz(const struct bpf_object *obj, const char *name, __u32 *size)
1453 {
1454 	Elf_Data *data;
1455 	Elf_Scn *scn;
1456 
1457 	if (!name)
1458 		return -EINVAL;
1459 
1460 	scn = elf_sec_by_name(obj, name);
1461 	data = elf_sec_data(obj, scn);
1462 	if (data) {
1463 		*size = data->d_size;
1464 		return 0; /* found it */
1465 	}
1466 
1467 	return -ENOENT;
1468 }
1469 
1470 static Elf64_Sym *find_elf_var_sym(const struct bpf_object *obj, const char *name)
1471 {
1472 	Elf_Data *symbols = obj->efile.symbols;
1473 	const char *sname;
1474 	size_t si;
1475 
1476 	for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
1477 		Elf64_Sym *sym = elf_sym_by_idx(obj, si);
1478 
1479 		if (ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)
1480 			continue;
1481 
1482 		if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL &&
1483 		    ELF64_ST_BIND(sym->st_info) != STB_WEAK)
1484 			continue;
1485 
1486 		sname = elf_sym_str(obj, sym->st_name);
1487 		if (!sname) {
1488 			pr_warn("failed to get sym name string for var %s\n", name);
1489 			return ERR_PTR(-EIO);
1490 		}
1491 		if (strcmp(name, sname) == 0)
1492 			return sym;
1493 	}
1494 
1495 	return ERR_PTR(-ENOENT);
1496 }
1497 
1498 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1499 {
1500 	struct bpf_map *map;
1501 	int err;
1502 
1503 	err = libbpf_ensure_mem((void **)&obj->maps, &obj->maps_cap,
1504 				sizeof(*obj->maps), obj->nr_maps + 1);
1505 	if (err)
1506 		return ERR_PTR(err);
1507 
1508 	map = &obj->maps[obj->nr_maps++];
1509 	map->obj = obj;
1510 	map->fd = -1;
1511 	map->inner_map_fd = -1;
1512 	map->autocreate = true;
1513 
1514 	return map;
1515 }
1516 
1517 static size_t bpf_map_mmap_sz(unsigned int value_sz, unsigned int max_entries)
1518 {
1519 	const long page_sz = sysconf(_SC_PAGE_SIZE);
1520 	size_t map_sz;
1521 
1522 	map_sz = (size_t)roundup(value_sz, 8) * max_entries;
1523 	map_sz = roundup(map_sz, page_sz);
1524 	return map_sz;
1525 }
1526 
1527 static int bpf_map_mmap_resize(struct bpf_map *map, size_t old_sz, size_t new_sz)
1528 {
1529 	void *mmaped;
1530 
1531 	if (!map->mmaped)
1532 		return -EINVAL;
1533 
1534 	if (old_sz == new_sz)
1535 		return 0;
1536 
1537 	mmaped = mmap(NULL, new_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1538 	if (mmaped == MAP_FAILED)
1539 		return -errno;
1540 
1541 	memcpy(mmaped, map->mmaped, min(old_sz, new_sz));
1542 	munmap(map->mmaped, old_sz);
1543 	map->mmaped = mmaped;
1544 	return 0;
1545 }
1546 
1547 static char *internal_map_name(struct bpf_object *obj, const char *real_name)
1548 {
1549 	char map_name[BPF_OBJ_NAME_LEN], *p;
1550 	int pfx_len, sfx_len = max((size_t)7, strlen(real_name));
1551 
1552 	/* This is one of the more confusing parts of libbpf for various
1553 	 * reasons, some of which are historical. The original idea for naming
1554 	 * internal names was to include as much of BPF object name prefix as
1555 	 * possible, so that it can be distinguished from similar internal
1556 	 * maps of a different BPF object.
1557 	 * As an example, let's say we have bpf_object named 'my_object_name'
1558 	 * and internal map corresponding to '.rodata' ELF section. The final
1559 	 * map name advertised to user and to the kernel will be
1560 	 * 'my_objec.rodata', taking first 8 characters of object name and
1561 	 * entire 7 characters of '.rodata'.
1562 	 * Somewhat confusingly, if internal map ELF section name is shorter
1563 	 * than 7 characters, e.g., '.bss', we still reserve 7 characters
1564 	 * for the suffix, even though we only have 4 actual characters, and
1565 	 * resulting map will be called 'my_objec.bss', not even using all 15
1566 	 * characters allowed by the kernel. Oh well, at least the truncated
1567 	 * object name is somewhat consistent in this case. But if the map
1568 	 * name is '.kconfig', we'll still have entirety of '.kconfig' added
1569 	 * (8 chars) and thus will be left with only first 7 characters of the
1570 	 * object name ('my_obje'). Happy guessing, user, that the final map
1571 	 * name will be "my_obje.kconfig".
1572 	 * Now, with libbpf starting to support arbitrarily named .rodata.*
1573 	 * and .data.* data sections, it's possible that ELF section name is
1574 	 * longer than allowed 15 chars, so we now need to be careful to take
1575 	 * only up to 15 first characters of ELF name, taking no BPF object
1576 	 * name characters at all. So '.rodata.abracadabra' will result in
1577 	 * '.rodata.abracad' kernel and user-visible name.
1578 	 * We need to keep this convoluted logic intact for .data, .bss and
1579 	 * .rodata maps, but for new custom .data.custom and .rodata.custom
1580 	 * maps we use their ELF names as is, not prepending bpf_object name
1581 	 * in front. We still need to truncate them to 15 characters for the
1582 	 * kernel. Full name can be recovered for such maps by using DATASEC
1583 	 * BTF type associated with such map's value type, though.
1584 	 */
1585 	if (sfx_len >= BPF_OBJ_NAME_LEN)
1586 		sfx_len = BPF_OBJ_NAME_LEN - 1;
1587 
1588 	/* if there are two or more dots in map name, it's a custom dot map */
1589 	if (strchr(real_name + 1, '.') != NULL)
1590 		pfx_len = 0;
1591 	else
1592 		pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
1593 
1594 	snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1595 		 sfx_len, real_name);
1596 
1597 	/* sanitise map name to characters allowed by kernel */
1598 	for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1599 		if (!isalnum(*p) && *p != '_' && *p != '.')
1600 			*p = '_';
1601 
1602 	return strdup(map_name);
1603 }
1604 
1605 static int
1606 map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map);
1607 
1608 /* Internal BPF map is mmap()'able only if at least one of corresponding
1609  * DATASEC's VARs are to be exposed through BPF skeleton. I.e., it's a GLOBAL
1610  * variable and it's not marked as __hidden (which turns it into, effectively,
1611  * a STATIC variable).
1612  */
1613 static bool map_is_mmapable(struct bpf_object *obj, struct bpf_map *map)
1614 {
1615 	const struct btf_type *t, *vt;
1616 	struct btf_var_secinfo *vsi;
1617 	int i, n;
1618 
1619 	if (!map->btf_value_type_id)
1620 		return false;
1621 
1622 	t = btf__type_by_id(obj->btf, map->btf_value_type_id);
1623 	if (!btf_is_datasec(t))
1624 		return false;
1625 
1626 	vsi = btf_var_secinfos(t);
1627 	for (i = 0, n = btf_vlen(t); i < n; i++, vsi++) {
1628 		vt = btf__type_by_id(obj->btf, vsi->type);
1629 		if (!btf_is_var(vt))
1630 			continue;
1631 
1632 		if (btf_var(vt)->linkage != BTF_VAR_STATIC)
1633 			return true;
1634 	}
1635 
1636 	return false;
1637 }
1638 
1639 static int
1640 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
1641 			      const char *real_name, int sec_idx, void *data, size_t data_sz)
1642 {
1643 	struct bpf_map_def *def;
1644 	struct bpf_map *map;
1645 	size_t mmap_sz;
1646 	int err;
1647 
1648 	map = bpf_object__add_map(obj);
1649 	if (IS_ERR(map))
1650 		return PTR_ERR(map);
1651 
1652 	map->libbpf_type = type;
1653 	map->sec_idx = sec_idx;
1654 	map->sec_offset = 0;
1655 	map->real_name = strdup(real_name);
1656 	map->name = internal_map_name(obj, real_name);
1657 	if (!map->real_name || !map->name) {
1658 		zfree(&map->real_name);
1659 		zfree(&map->name);
1660 		return -ENOMEM;
1661 	}
1662 
1663 	def = &map->def;
1664 	def->type = BPF_MAP_TYPE_ARRAY;
1665 	def->key_size = sizeof(int);
1666 	def->value_size = data_sz;
1667 	def->max_entries = 1;
1668 	def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
1669 			 ? BPF_F_RDONLY_PROG : 0;
1670 
1671 	/* failures are fine because of maps like .rodata.str1.1 */
1672 	(void) map_fill_btf_type_info(obj, map);
1673 
1674 	if (map_is_mmapable(obj, map))
1675 		def->map_flags |= BPF_F_MMAPABLE;
1676 
1677 	pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
1678 		 map->name, map->sec_idx, map->sec_offset, def->map_flags);
1679 
1680 	mmap_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
1681 	map->mmaped = mmap(NULL, mmap_sz, PROT_READ | PROT_WRITE,
1682 			   MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1683 	if (map->mmaped == MAP_FAILED) {
1684 		err = -errno;
1685 		map->mmaped = NULL;
1686 		pr_warn("failed to alloc map '%s' content buffer: %d\n",
1687 			map->name, err);
1688 		zfree(&map->real_name);
1689 		zfree(&map->name);
1690 		return err;
1691 	}
1692 
1693 	if (data)
1694 		memcpy(map->mmaped, data, data_sz);
1695 
1696 	pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
1697 	return 0;
1698 }
1699 
1700 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
1701 {
1702 	struct elf_sec_desc *sec_desc;
1703 	const char *sec_name;
1704 	int err = 0, sec_idx;
1705 
1706 	/*
1707 	 * Populate obj->maps with libbpf internal maps.
1708 	 */
1709 	for (sec_idx = 1; sec_idx < obj->efile.sec_cnt; sec_idx++) {
1710 		sec_desc = &obj->efile.secs[sec_idx];
1711 
1712 		/* Skip recognized sections with size 0. */
1713 		if (!sec_desc->data || sec_desc->data->d_size == 0)
1714 			continue;
1715 
1716 		switch (sec_desc->sec_type) {
1717 		case SEC_DATA:
1718 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1719 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
1720 							    sec_name, sec_idx,
1721 							    sec_desc->data->d_buf,
1722 							    sec_desc->data->d_size);
1723 			break;
1724 		case SEC_RODATA:
1725 			obj->has_rodata = true;
1726 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1727 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
1728 							    sec_name, sec_idx,
1729 							    sec_desc->data->d_buf,
1730 							    sec_desc->data->d_size);
1731 			break;
1732 		case SEC_BSS:
1733 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1734 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
1735 							    sec_name, sec_idx,
1736 							    NULL,
1737 							    sec_desc->data->d_size);
1738 			break;
1739 		default:
1740 			/* skip */
1741 			break;
1742 		}
1743 		if (err)
1744 			return err;
1745 	}
1746 	return 0;
1747 }
1748 
1749 
1750 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
1751 					       const void *name)
1752 {
1753 	int i;
1754 
1755 	for (i = 0; i < obj->nr_extern; i++) {
1756 		if (strcmp(obj->externs[i].name, name) == 0)
1757 			return &obj->externs[i];
1758 	}
1759 	return NULL;
1760 }
1761 
1762 static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
1763 			      char value)
1764 {
1765 	switch (ext->kcfg.type) {
1766 	case KCFG_BOOL:
1767 		if (value == 'm') {
1768 			pr_warn("extern (kcfg) '%s': value '%c' implies tristate or char type\n",
1769 				ext->name, value);
1770 			return -EINVAL;
1771 		}
1772 		*(bool *)ext_val = value == 'y' ? true : false;
1773 		break;
1774 	case KCFG_TRISTATE:
1775 		if (value == 'y')
1776 			*(enum libbpf_tristate *)ext_val = TRI_YES;
1777 		else if (value == 'm')
1778 			*(enum libbpf_tristate *)ext_val = TRI_MODULE;
1779 		else /* value == 'n' */
1780 			*(enum libbpf_tristate *)ext_val = TRI_NO;
1781 		break;
1782 	case KCFG_CHAR:
1783 		*(char *)ext_val = value;
1784 		break;
1785 	case KCFG_UNKNOWN:
1786 	case KCFG_INT:
1787 	case KCFG_CHAR_ARR:
1788 	default:
1789 		pr_warn("extern (kcfg) '%s': value '%c' implies bool, tristate, or char type\n",
1790 			ext->name, value);
1791 		return -EINVAL;
1792 	}
1793 	ext->is_set = true;
1794 	return 0;
1795 }
1796 
1797 static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
1798 			      const char *value)
1799 {
1800 	size_t len;
1801 
1802 	if (ext->kcfg.type != KCFG_CHAR_ARR) {
1803 		pr_warn("extern (kcfg) '%s': value '%s' implies char array type\n",
1804 			ext->name, value);
1805 		return -EINVAL;
1806 	}
1807 
1808 	len = strlen(value);
1809 	if (value[len - 1] != '"') {
1810 		pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
1811 			ext->name, value);
1812 		return -EINVAL;
1813 	}
1814 
1815 	/* strip quotes */
1816 	len -= 2;
1817 	if (len >= ext->kcfg.sz) {
1818 		pr_warn("extern (kcfg) '%s': long string '%s' of (%zu bytes) truncated to %d bytes\n",
1819 			ext->name, value, len, ext->kcfg.sz - 1);
1820 		len = ext->kcfg.sz - 1;
1821 	}
1822 	memcpy(ext_val, value + 1, len);
1823 	ext_val[len] = '\0';
1824 	ext->is_set = true;
1825 	return 0;
1826 }
1827 
1828 static int parse_u64(const char *value, __u64 *res)
1829 {
1830 	char *value_end;
1831 	int err;
1832 
1833 	errno = 0;
1834 	*res = strtoull(value, &value_end, 0);
1835 	if (errno) {
1836 		err = -errno;
1837 		pr_warn("failed to parse '%s' as integer: %d\n", value, err);
1838 		return err;
1839 	}
1840 	if (*value_end) {
1841 		pr_warn("failed to parse '%s' as integer completely\n", value);
1842 		return -EINVAL;
1843 	}
1844 	return 0;
1845 }
1846 
1847 static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
1848 {
1849 	int bit_sz = ext->kcfg.sz * 8;
1850 
1851 	if (ext->kcfg.sz == 8)
1852 		return true;
1853 
1854 	/* Validate that value stored in u64 fits in integer of `ext->sz`
1855 	 * bytes size without any loss of information. If the target integer
1856 	 * is signed, we rely on the following limits of integer type of
1857 	 * Y bits and subsequent transformation:
1858 	 *
1859 	 *     -2^(Y-1) <= X           <= 2^(Y-1) - 1
1860 	 *            0 <= X + 2^(Y-1) <= 2^Y - 1
1861 	 *            0 <= X + 2^(Y-1) <  2^Y
1862 	 *
1863 	 *  For unsigned target integer, check that all the (64 - Y) bits are
1864 	 *  zero.
1865 	 */
1866 	if (ext->kcfg.is_signed)
1867 		return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
1868 	else
1869 		return (v >> bit_sz) == 0;
1870 }
1871 
1872 static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
1873 			      __u64 value)
1874 {
1875 	if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR &&
1876 	    ext->kcfg.type != KCFG_BOOL) {
1877 		pr_warn("extern (kcfg) '%s': value '%llu' implies integer, char, or boolean type\n",
1878 			ext->name, (unsigned long long)value);
1879 		return -EINVAL;
1880 	}
1881 	if (ext->kcfg.type == KCFG_BOOL && value > 1) {
1882 		pr_warn("extern (kcfg) '%s': value '%llu' isn't boolean compatible\n",
1883 			ext->name, (unsigned long long)value);
1884 		return -EINVAL;
1885 
1886 	}
1887 	if (!is_kcfg_value_in_range(ext, value)) {
1888 		pr_warn("extern (kcfg) '%s': value '%llu' doesn't fit in %d bytes\n",
1889 			ext->name, (unsigned long long)value, ext->kcfg.sz);
1890 		return -ERANGE;
1891 	}
1892 	switch (ext->kcfg.sz) {
1893 	case 1:
1894 		*(__u8 *)ext_val = value;
1895 		break;
1896 	case 2:
1897 		*(__u16 *)ext_val = value;
1898 		break;
1899 	case 4:
1900 		*(__u32 *)ext_val = value;
1901 		break;
1902 	case 8:
1903 		*(__u64 *)ext_val = value;
1904 		break;
1905 	default:
1906 		return -EINVAL;
1907 	}
1908 	ext->is_set = true;
1909 	return 0;
1910 }
1911 
1912 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
1913 					    char *buf, void *data)
1914 {
1915 	struct extern_desc *ext;
1916 	char *sep, *value;
1917 	int len, err = 0;
1918 	void *ext_val;
1919 	__u64 num;
1920 
1921 	if (!str_has_pfx(buf, "CONFIG_"))
1922 		return 0;
1923 
1924 	sep = strchr(buf, '=');
1925 	if (!sep) {
1926 		pr_warn("failed to parse '%s': no separator\n", buf);
1927 		return -EINVAL;
1928 	}
1929 
1930 	/* Trim ending '\n' */
1931 	len = strlen(buf);
1932 	if (buf[len - 1] == '\n')
1933 		buf[len - 1] = '\0';
1934 	/* Split on '=' and ensure that a value is present. */
1935 	*sep = '\0';
1936 	if (!sep[1]) {
1937 		*sep = '=';
1938 		pr_warn("failed to parse '%s': no value\n", buf);
1939 		return -EINVAL;
1940 	}
1941 
1942 	ext = find_extern_by_name(obj, buf);
1943 	if (!ext || ext->is_set)
1944 		return 0;
1945 
1946 	ext_val = data + ext->kcfg.data_off;
1947 	value = sep + 1;
1948 
1949 	switch (*value) {
1950 	case 'y': case 'n': case 'm':
1951 		err = set_kcfg_value_tri(ext, ext_val, *value);
1952 		break;
1953 	case '"':
1954 		err = set_kcfg_value_str(ext, ext_val, value);
1955 		break;
1956 	default:
1957 		/* assume integer */
1958 		err = parse_u64(value, &num);
1959 		if (err) {
1960 			pr_warn("extern (kcfg) '%s': value '%s' isn't a valid integer\n", ext->name, value);
1961 			return err;
1962 		}
1963 		if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
1964 			pr_warn("extern (kcfg) '%s': value '%s' implies integer type\n", ext->name, value);
1965 			return -EINVAL;
1966 		}
1967 		err = set_kcfg_value_num(ext, ext_val, num);
1968 		break;
1969 	}
1970 	if (err)
1971 		return err;
1972 	pr_debug("extern (kcfg) '%s': set to %s\n", ext->name, value);
1973 	return 0;
1974 }
1975 
1976 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
1977 {
1978 	char buf[PATH_MAX];
1979 	struct utsname uts;
1980 	int len, err = 0;
1981 	gzFile file;
1982 
1983 	uname(&uts);
1984 	len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
1985 	if (len < 0)
1986 		return -EINVAL;
1987 	else if (len >= PATH_MAX)
1988 		return -ENAMETOOLONG;
1989 
1990 	/* gzopen also accepts uncompressed files. */
1991 	file = gzopen(buf, "re");
1992 	if (!file)
1993 		file = gzopen("/proc/config.gz", "re");
1994 
1995 	if (!file) {
1996 		pr_warn("failed to open system Kconfig\n");
1997 		return -ENOENT;
1998 	}
1999 
2000 	while (gzgets(file, buf, sizeof(buf))) {
2001 		err = bpf_object__process_kconfig_line(obj, buf, data);
2002 		if (err) {
2003 			pr_warn("error parsing system Kconfig line '%s': %d\n",
2004 				buf, err);
2005 			goto out;
2006 		}
2007 	}
2008 
2009 out:
2010 	gzclose(file);
2011 	return err;
2012 }
2013 
2014 static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
2015 					const char *config, void *data)
2016 {
2017 	char buf[PATH_MAX];
2018 	int err = 0;
2019 	FILE *file;
2020 
2021 	file = fmemopen((void *)config, strlen(config), "r");
2022 	if (!file) {
2023 		err = -errno;
2024 		pr_warn("failed to open in-memory Kconfig: %d\n", err);
2025 		return err;
2026 	}
2027 
2028 	while (fgets(buf, sizeof(buf), file)) {
2029 		err = bpf_object__process_kconfig_line(obj, buf, data);
2030 		if (err) {
2031 			pr_warn("error parsing in-memory Kconfig line '%s': %d\n",
2032 				buf, err);
2033 			break;
2034 		}
2035 	}
2036 
2037 	fclose(file);
2038 	return err;
2039 }
2040 
2041 static int bpf_object__init_kconfig_map(struct bpf_object *obj)
2042 {
2043 	struct extern_desc *last_ext = NULL, *ext;
2044 	size_t map_sz;
2045 	int i, err;
2046 
2047 	for (i = 0; i < obj->nr_extern; i++) {
2048 		ext = &obj->externs[i];
2049 		if (ext->type == EXT_KCFG)
2050 			last_ext = ext;
2051 	}
2052 
2053 	if (!last_ext)
2054 		return 0;
2055 
2056 	map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
2057 	err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
2058 					    ".kconfig", obj->efile.symbols_shndx,
2059 					    NULL, map_sz);
2060 	if (err)
2061 		return err;
2062 
2063 	obj->kconfig_map_idx = obj->nr_maps - 1;
2064 
2065 	return 0;
2066 }
2067 
2068 const struct btf_type *
2069 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
2070 {
2071 	const struct btf_type *t = btf__type_by_id(btf, id);
2072 
2073 	if (res_id)
2074 		*res_id = id;
2075 
2076 	while (btf_is_mod(t) || btf_is_typedef(t)) {
2077 		if (res_id)
2078 			*res_id = t->type;
2079 		t = btf__type_by_id(btf, t->type);
2080 	}
2081 
2082 	return t;
2083 }
2084 
2085 static const struct btf_type *
2086 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
2087 {
2088 	const struct btf_type *t;
2089 
2090 	t = skip_mods_and_typedefs(btf, id, NULL);
2091 	if (!btf_is_ptr(t))
2092 		return NULL;
2093 
2094 	t = skip_mods_and_typedefs(btf, t->type, res_id);
2095 
2096 	return btf_is_func_proto(t) ? t : NULL;
2097 }
2098 
2099 static const char *__btf_kind_str(__u16 kind)
2100 {
2101 	switch (kind) {
2102 	case BTF_KIND_UNKN: return "void";
2103 	case BTF_KIND_INT: return "int";
2104 	case BTF_KIND_PTR: return "ptr";
2105 	case BTF_KIND_ARRAY: return "array";
2106 	case BTF_KIND_STRUCT: return "struct";
2107 	case BTF_KIND_UNION: return "union";
2108 	case BTF_KIND_ENUM: return "enum";
2109 	case BTF_KIND_FWD: return "fwd";
2110 	case BTF_KIND_TYPEDEF: return "typedef";
2111 	case BTF_KIND_VOLATILE: return "volatile";
2112 	case BTF_KIND_CONST: return "const";
2113 	case BTF_KIND_RESTRICT: return "restrict";
2114 	case BTF_KIND_FUNC: return "func";
2115 	case BTF_KIND_FUNC_PROTO: return "func_proto";
2116 	case BTF_KIND_VAR: return "var";
2117 	case BTF_KIND_DATASEC: return "datasec";
2118 	case BTF_KIND_FLOAT: return "float";
2119 	case BTF_KIND_DECL_TAG: return "decl_tag";
2120 	case BTF_KIND_TYPE_TAG: return "type_tag";
2121 	case BTF_KIND_ENUM64: return "enum64";
2122 	default: return "unknown";
2123 	}
2124 }
2125 
2126 const char *btf_kind_str(const struct btf_type *t)
2127 {
2128 	return __btf_kind_str(btf_kind(t));
2129 }
2130 
2131 /*
2132  * Fetch integer attribute of BTF map definition. Such attributes are
2133  * represented using a pointer to an array, in which dimensionality of array
2134  * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2135  * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2136  * type definition, while using only sizeof(void *) space in ELF data section.
2137  */
2138 static bool get_map_field_int(const char *map_name, const struct btf *btf,
2139 			      const struct btf_member *m, __u32 *res)
2140 {
2141 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2142 	const char *name = btf__name_by_offset(btf, m->name_off);
2143 	const struct btf_array *arr_info;
2144 	const struct btf_type *arr_t;
2145 
2146 	if (!btf_is_ptr(t)) {
2147 		pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2148 			map_name, name, btf_kind_str(t));
2149 		return false;
2150 	}
2151 
2152 	arr_t = btf__type_by_id(btf, t->type);
2153 	if (!arr_t) {
2154 		pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2155 			map_name, name, t->type);
2156 		return false;
2157 	}
2158 	if (!btf_is_array(arr_t)) {
2159 		pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2160 			map_name, name, btf_kind_str(arr_t));
2161 		return false;
2162 	}
2163 	arr_info = btf_array(arr_t);
2164 	*res = arr_info->nelems;
2165 	return true;
2166 }
2167 
2168 static int pathname_concat(char *buf, size_t buf_sz, const char *path, const char *name)
2169 {
2170 	int len;
2171 
2172 	len = snprintf(buf, buf_sz, "%s/%s", path, name);
2173 	if (len < 0)
2174 		return -EINVAL;
2175 	if (len >= buf_sz)
2176 		return -ENAMETOOLONG;
2177 
2178 	return 0;
2179 }
2180 
2181 static int build_map_pin_path(struct bpf_map *map, const char *path)
2182 {
2183 	char buf[PATH_MAX];
2184 	int err;
2185 
2186 	if (!path)
2187 		path = "/sys/fs/bpf";
2188 
2189 	err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
2190 	if (err)
2191 		return err;
2192 
2193 	return bpf_map__set_pin_path(map, buf);
2194 }
2195 
2196 /* should match definition in bpf_helpers.h */
2197 enum libbpf_pin_type {
2198 	LIBBPF_PIN_NONE,
2199 	/* PIN_BY_NAME: pin maps by name (in /sys/fs/bpf by default) */
2200 	LIBBPF_PIN_BY_NAME,
2201 };
2202 
2203 int parse_btf_map_def(const char *map_name, struct btf *btf,
2204 		      const struct btf_type *def_t, bool strict,
2205 		      struct btf_map_def *map_def, struct btf_map_def *inner_def)
2206 {
2207 	const struct btf_type *t;
2208 	const struct btf_member *m;
2209 	bool is_inner = inner_def == NULL;
2210 	int vlen, i;
2211 
2212 	vlen = btf_vlen(def_t);
2213 	m = btf_members(def_t);
2214 	for (i = 0; i < vlen; i++, m++) {
2215 		const char *name = btf__name_by_offset(btf, m->name_off);
2216 
2217 		if (!name) {
2218 			pr_warn("map '%s': invalid field #%d.\n", map_name, i);
2219 			return -EINVAL;
2220 		}
2221 		if (strcmp(name, "type") == 0) {
2222 			if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
2223 				return -EINVAL;
2224 			map_def->parts |= MAP_DEF_MAP_TYPE;
2225 		} else if (strcmp(name, "max_entries") == 0) {
2226 			if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
2227 				return -EINVAL;
2228 			map_def->parts |= MAP_DEF_MAX_ENTRIES;
2229 		} else if (strcmp(name, "map_flags") == 0) {
2230 			if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
2231 				return -EINVAL;
2232 			map_def->parts |= MAP_DEF_MAP_FLAGS;
2233 		} else if (strcmp(name, "numa_node") == 0) {
2234 			if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
2235 				return -EINVAL;
2236 			map_def->parts |= MAP_DEF_NUMA_NODE;
2237 		} else if (strcmp(name, "key_size") == 0) {
2238 			__u32 sz;
2239 
2240 			if (!get_map_field_int(map_name, btf, m, &sz))
2241 				return -EINVAL;
2242 			if (map_def->key_size && map_def->key_size != sz) {
2243 				pr_warn("map '%s': conflicting key size %u != %u.\n",
2244 					map_name, map_def->key_size, sz);
2245 				return -EINVAL;
2246 			}
2247 			map_def->key_size = sz;
2248 			map_def->parts |= MAP_DEF_KEY_SIZE;
2249 		} else if (strcmp(name, "key") == 0) {
2250 			__s64 sz;
2251 
2252 			t = btf__type_by_id(btf, m->type);
2253 			if (!t) {
2254 				pr_warn("map '%s': key type [%d] not found.\n",
2255 					map_name, m->type);
2256 				return -EINVAL;
2257 			}
2258 			if (!btf_is_ptr(t)) {
2259 				pr_warn("map '%s': key spec is not PTR: %s.\n",
2260 					map_name, btf_kind_str(t));
2261 				return -EINVAL;
2262 			}
2263 			sz = btf__resolve_size(btf, t->type);
2264 			if (sz < 0) {
2265 				pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2266 					map_name, t->type, (ssize_t)sz);
2267 				return sz;
2268 			}
2269 			if (map_def->key_size && map_def->key_size != sz) {
2270 				pr_warn("map '%s': conflicting key size %u != %zd.\n",
2271 					map_name, map_def->key_size, (ssize_t)sz);
2272 				return -EINVAL;
2273 			}
2274 			map_def->key_size = sz;
2275 			map_def->key_type_id = t->type;
2276 			map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
2277 		} else if (strcmp(name, "value_size") == 0) {
2278 			__u32 sz;
2279 
2280 			if (!get_map_field_int(map_name, btf, m, &sz))
2281 				return -EINVAL;
2282 			if (map_def->value_size && map_def->value_size != sz) {
2283 				pr_warn("map '%s': conflicting value size %u != %u.\n",
2284 					map_name, map_def->value_size, sz);
2285 				return -EINVAL;
2286 			}
2287 			map_def->value_size = sz;
2288 			map_def->parts |= MAP_DEF_VALUE_SIZE;
2289 		} else if (strcmp(name, "value") == 0) {
2290 			__s64 sz;
2291 
2292 			t = btf__type_by_id(btf, m->type);
2293 			if (!t) {
2294 				pr_warn("map '%s': value type [%d] not found.\n",
2295 					map_name, m->type);
2296 				return -EINVAL;
2297 			}
2298 			if (!btf_is_ptr(t)) {
2299 				pr_warn("map '%s': value spec is not PTR: %s.\n",
2300 					map_name, btf_kind_str(t));
2301 				return -EINVAL;
2302 			}
2303 			sz = btf__resolve_size(btf, t->type);
2304 			if (sz < 0) {
2305 				pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2306 					map_name, t->type, (ssize_t)sz);
2307 				return sz;
2308 			}
2309 			if (map_def->value_size && map_def->value_size != sz) {
2310 				pr_warn("map '%s': conflicting value size %u != %zd.\n",
2311 					map_name, map_def->value_size, (ssize_t)sz);
2312 				return -EINVAL;
2313 			}
2314 			map_def->value_size = sz;
2315 			map_def->value_type_id = t->type;
2316 			map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
2317 		}
2318 		else if (strcmp(name, "values") == 0) {
2319 			bool is_map_in_map = bpf_map_type__is_map_in_map(map_def->map_type);
2320 			bool is_prog_array = map_def->map_type == BPF_MAP_TYPE_PROG_ARRAY;
2321 			const char *desc = is_map_in_map ? "map-in-map inner" : "prog-array value";
2322 			char inner_map_name[128];
2323 			int err;
2324 
2325 			if (is_inner) {
2326 				pr_warn("map '%s': multi-level inner maps not supported.\n",
2327 					map_name);
2328 				return -ENOTSUP;
2329 			}
2330 			if (i != vlen - 1) {
2331 				pr_warn("map '%s': '%s' member should be last.\n",
2332 					map_name, name);
2333 				return -EINVAL;
2334 			}
2335 			if (!is_map_in_map && !is_prog_array) {
2336 				pr_warn("map '%s': should be map-in-map or prog-array.\n",
2337 					map_name);
2338 				return -ENOTSUP;
2339 			}
2340 			if (map_def->value_size && map_def->value_size != 4) {
2341 				pr_warn("map '%s': conflicting value size %u != 4.\n",
2342 					map_name, map_def->value_size);
2343 				return -EINVAL;
2344 			}
2345 			map_def->value_size = 4;
2346 			t = btf__type_by_id(btf, m->type);
2347 			if (!t) {
2348 				pr_warn("map '%s': %s type [%d] not found.\n",
2349 					map_name, desc, m->type);
2350 				return -EINVAL;
2351 			}
2352 			if (!btf_is_array(t) || btf_array(t)->nelems) {
2353 				pr_warn("map '%s': %s spec is not a zero-sized array.\n",
2354 					map_name, desc);
2355 				return -EINVAL;
2356 			}
2357 			t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
2358 			if (!btf_is_ptr(t)) {
2359 				pr_warn("map '%s': %s def is of unexpected kind %s.\n",
2360 					map_name, desc, btf_kind_str(t));
2361 				return -EINVAL;
2362 			}
2363 			t = skip_mods_and_typedefs(btf, t->type, NULL);
2364 			if (is_prog_array) {
2365 				if (!btf_is_func_proto(t)) {
2366 					pr_warn("map '%s': prog-array value def is of unexpected kind %s.\n",
2367 						map_name, btf_kind_str(t));
2368 					return -EINVAL;
2369 				}
2370 				continue;
2371 			}
2372 			if (!btf_is_struct(t)) {
2373 				pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2374 					map_name, btf_kind_str(t));
2375 				return -EINVAL;
2376 			}
2377 
2378 			snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2379 			err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
2380 			if (err)
2381 				return err;
2382 
2383 			map_def->parts |= MAP_DEF_INNER_MAP;
2384 		} else if (strcmp(name, "pinning") == 0) {
2385 			__u32 val;
2386 
2387 			if (is_inner) {
2388 				pr_warn("map '%s': inner def can't be pinned.\n", map_name);
2389 				return -EINVAL;
2390 			}
2391 			if (!get_map_field_int(map_name, btf, m, &val))
2392 				return -EINVAL;
2393 			if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
2394 				pr_warn("map '%s': invalid pinning value %u.\n",
2395 					map_name, val);
2396 				return -EINVAL;
2397 			}
2398 			map_def->pinning = val;
2399 			map_def->parts |= MAP_DEF_PINNING;
2400 		} else if (strcmp(name, "map_extra") == 0) {
2401 			__u32 map_extra;
2402 
2403 			if (!get_map_field_int(map_name, btf, m, &map_extra))
2404 				return -EINVAL;
2405 			map_def->map_extra = map_extra;
2406 			map_def->parts |= MAP_DEF_MAP_EXTRA;
2407 		} else {
2408 			if (strict) {
2409 				pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
2410 				return -ENOTSUP;
2411 			}
2412 			pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
2413 		}
2414 	}
2415 
2416 	if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2417 		pr_warn("map '%s': map type isn't specified.\n", map_name);
2418 		return -EINVAL;
2419 	}
2420 
2421 	return 0;
2422 }
2423 
2424 static size_t adjust_ringbuf_sz(size_t sz)
2425 {
2426 	__u32 page_sz = sysconf(_SC_PAGE_SIZE);
2427 	__u32 mul;
2428 
2429 	/* if user forgot to set any size, make sure they see error */
2430 	if (sz == 0)
2431 		return 0;
2432 	/* Kernel expects BPF_MAP_TYPE_RINGBUF's max_entries to be
2433 	 * a power-of-2 multiple of kernel's page size. If user diligently
2434 	 * satisified these conditions, pass the size through.
2435 	 */
2436 	if ((sz % page_sz) == 0 && is_pow_of_2(sz / page_sz))
2437 		return sz;
2438 
2439 	/* Otherwise find closest (page_sz * power_of_2) product bigger than
2440 	 * user-set size to satisfy both user size request and kernel
2441 	 * requirements and substitute correct max_entries for map creation.
2442 	 */
2443 	for (mul = 1; mul <= UINT_MAX / page_sz; mul <<= 1) {
2444 		if (mul * page_sz > sz)
2445 			return mul * page_sz;
2446 	}
2447 
2448 	/* if it's impossible to satisfy the conditions (i.e., user size is
2449 	 * very close to UINT_MAX but is not a power-of-2 multiple of
2450 	 * page_size) then just return original size and let kernel reject it
2451 	 */
2452 	return sz;
2453 }
2454 
2455 static bool map_is_ringbuf(const struct bpf_map *map)
2456 {
2457 	return map->def.type == BPF_MAP_TYPE_RINGBUF ||
2458 	       map->def.type == BPF_MAP_TYPE_USER_RINGBUF;
2459 }
2460 
2461 static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2462 {
2463 	map->def.type = def->map_type;
2464 	map->def.key_size = def->key_size;
2465 	map->def.value_size = def->value_size;
2466 	map->def.max_entries = def->max_entries;
2467 	map->def.map_flags = def->map_flags;
2468 	map->map_extra = def->map_extra;
2469 
2470 	map->numa_node = def->numa_node;
2471 	map->btf_key_type_id = def->key_type_id;
2472 	map->btf_value_type_id = def->value_type_id;
2473 
2474 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
2475 	if (map_is_ringbuf(map))
2476 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
2477 
2478 	if (def->parts & MAP_DEF_MAP_TYPE)
2479 		pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2480 
2481 	if (def->parts & MAP_DEF_KEY_TYPE)
2482 		pr_debug("map '%s': found key [%u], sz = %u.\n",
2483 			 map->name, def->key_type_id, def->key_size);
2484 	else if (def->parts & MAP_DEF_KEY_SIZE)
2485 		pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2486 
2487 	if (def->parts & MAP_DEF_VALUE_TYPE)
2488 		pr_debug("map '%s': found value [%u], sz = %u.\n",
2489 			 map->name, def->value_type_id, def->value_size);
2490 	else if (def->parts & MAP_DEF_VALUE_SIZE)
2491 		pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2492 
2493 	if (def->parts & MAP_DEF_MAX_ENTRIES)
2494 		pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2495 	if (def->parts & MAP_DEF_MAP_FLAGS)
2496 		pr_debug("map '%s': found map_flags = 0x%x.\n", map->name, def->map_flags);
2497 	if (def->parts & MAP_DEF_MAP_EXTRA)
2498 		pr_debug("map '%s': found map_extra = 0x%llx.\n", map->name,
2499 			 (unsigned long long)def->map_extra);
2500 	if (def->parts & MAP_DEF_PINNING)
2501 		pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2502 	if (def->parts & MAP_DEF_NUMA_NODE)
2503 		pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2504 
2505 	if (def->parts & MAP_DEF_INNER_MAP)
2506 		pr_debug("map '%s': found inner map definition.\n", map->name);
2507 }
2508 
2509 static const char *btf_var_linkage_str(__u32 linkage)
2510 {
2511 	switch (linkage) {
2512 	case BTF_VAR_STATIC: return "static";
2513 	case BTF_VAR_GLOBAL_ALLOCATED: return "global";
2514 	case BTF_VAR_GLOBAL_EXTERN: return "extern";
2515 	default: return "unknown";
2516 	}
2517 }
2518 
2519 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2520 					 const struct btf_type *sec,
2521 					 int var_idx, int sec_idx,
2522 					 const Elf_Data *data, bool strict,
2523 					 const char *pin_root_path)
2524 {
2525 	struct btf_map_def map_def = {}, inner_def = {};
2526 	const struct btf_type *var, *def;
2527 	const struct btf_var_secinfo *vi;
2528 	const struct btf_var *var_extra;
2529 	const char *map_name;
2530 	struct bpf_map *map;
2531 	int err;
2532 
2533 	vi = btf_var_secinfos(sec) + var_idx;
2534 	var = btf__type_by_id(obj->btf, vi->type);
2535 	var_extra = btf_var(var);
2536 	map_name = btf__name_by_offset(obj->btf, var->name_off);
2537 
2538 	if (map_name == NULL || map_name[0] == '\0') {
2539 		pr_warn("map #%d: empty name.\n", var_idx);
2540 		return -EINVAL;
2541 	}
2542 	if ((__u64)vi->offset + vi->size > data->d_size) {
2543 		pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2544 		return -EINVAL;
2545 	}
2546 	if (!btf_is_var(var)) {
2547 		pr_warn("map '%s': unexpected var kind %s.\n",
2548 			map_name, btf_kind_str(var));
2549 		return -EINVAL;
2550 	}
2551 	if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
2552 		pr_warn("map '%s': unsupported map linkage %s.\n",
2553 			map_name, btf_var_linkage_str(var_extra->linkage));
2554 		return -EOPNOTSUPP;
2555 	}
2556 
2557 	def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2558 	if (!btf_is_struct(def)) {
2559 		pr_warn("map '%s': unexpected def kind %s.\n",
2560 			map_name, btf_kind_str(var));
2561 		return -EINVAL;
2562 	}
2563 	if (def->size > vi->size) {
2564 		pr_warn("map '%s': invalid def size.\n", map_name);
2565 		return -EINVAL;
2566 	}
2567 
2568 	map = bpf_object__add_map(obj);
2569 	if (IS_ERR(map))
2570 		return PTR_ERR(map);
2571 	map->name = strdup(map_name);
2572 	if (!map->name) {
2573 		pr_warn("map '%s': failed to alloc map name.\n", map_name);
2574 		return -ENOMEM;
2575 	}
2576 	map->libbpf_type = LIBBPF_MAP_UNSPEC;
2577 	map->def.type = BPF_MAP_TYPE_UNSPEC;
2578 	map->sec_idx = sec_idx;
2579 	map->sec_offset = vi->offset;
2580 	map->btf_var_idx = var_idx;
2581 	pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2582 		 map_name, map->sec_idx, map->sec_offset);
2583 
2584 	err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
2585 	if (err)
2586 		return err;
2587 
2588 	fill_map_from_def(map, &map_def);
2589 
2590 	if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
2591 		err = build_map_pin_path(map, pin_root_path);
2592 		if (err) {
2593 			pr_warn("map '%s': couldn't build pin path.\n", map->name);
2594 			return err;
2595 		}
2596 	}
2597 
2598 	if (map_def.parts & MAP_DEF_INNER_MAP) {
2599 		map->inner_map = calloc(1, sizeof(*map->inner_map));
2600 		if (!map->inner_map)
2601 			return -ENOMEM;
2602 		map->inner_map->fd = -1;
2603 		map->inner_map->sec_idx = sec_idx;
2604 		map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
2605 		if (!map->inner_map->name)
2606 			return -ENOMEM;
2607 		sprintf(map->inner_map->name, "%s.inner", map_name);
2608 
2609 		fill_map_from_def(map->inner_map, &inner_def);
2610 	}
2611 
2612 	err = map_fill_btf_type_info(obj, map);
2613 	if (err)
2614 		return err;
2615 
2616 	return 0;
2617 }
2618 
2619 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
2620 					  const char *pin_root_path)
2621 {
2622 	const struct btf_type *sec = NULL;
2623 	int nr_types, i, vlen, err;
2624 	const struct btf_type *t;
2625 	const char *name;
2626 	Elf_Data *data;
2627 	Elf_Scn *scn;
2628 
2629 	if (obj->efile.btf_maps_shndx < 0)
2630 		return 0;
2631 
2632 	scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
2633 	data = elf_sec_data(obj, scn);
2634 	if (!scn || !data) {
2635 		pr_warn("elf: failed to get %s map definitions for %s\n",
2636 			MAPS_ELF_SEC, obj->path);
2637 		return -EINVAL;
2638 	}
2639 
2640 	nr_types = btf__type_cnt(obj->btf);
2641 	for (i = 1; i < nr_types; i++) {
2642 		t = btf__type_by_id(obj->btf, i);
2643 		if (!btf_is_datasec(t))
2644 			continue;
2645 		name = btf__name_by_offset(obj->btf, t->name_off);
2646 		if (strcmp(name, MAPS_ELF_SEC) == 0) {
2647 			sec = t;
2648 			obj->efile.btf_maps_sec_btf_id = i;
2649 			break;
2650 		}
2651 	}
2652 
2653 	if (!sec) {
2654 		pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
2655 		return -ENOENT;
2656 	}
2657 
2658 	vlen = btf_vlen(sec);
2659 	for (i = 0; i < vlen; i++) {
2660 		err = bpf_object__init_user_btf_map(obj, sec, i,
2661 						    obj->efile.btf_maps_shndx,
2662 						    data, strict,
2663 						    pin_root_path);
2664 		if (err)
2665 			return err;
2666 	}
2667 
2668 	return 0;
2669 }
2670 
2671 static int bpf_object__init_maps(struct bpf_object *obj,
2672 				 const struct bpf_object_open_opts *opts)
2673 {
2674 	const char *pin_root_path;
2675 	bool strict;
2676 	int err = 0;
2677 
2678 	strict = !OPTS_GET(opts, relaxed_maps, false);
2679 	pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
2680 
2681 	err = bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
2682 	err = err ?: bpf_object__init_global_data_maps(obj);
2683 	err = err ?: bpf_object__init_kconfig_map(obj);
2684 	err = err ?: bpf_object_init_struct_ops(obj);
2685 
2686 	return err;
2687 }
2688 
2689 static bool section_have_execinstr(struct bpf_object *obj, int idx)
2690 {
2691 	Elf64_Shdr *sh;
2692 
2693 	sh = elf_sec_hdr(obj, elf_sec_by_idx(obj, idx));
2694 	if (!sh)
2695 		return false;
2696 
2697 	return sh->sh_flags & SHF_EXECINSTR;
2698 }
2699 
2700 static bool btf_needs_sanitization(struct bpf_object *obj)
2701 {
2702 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2703 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2704 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2705 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2706 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2707 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2708 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
2709 
2710 	return !has_func || !has_datasec || !has_func_global || !has_float ||
2711 	       !has_decl_tag || !has_type_tag || !has_enum64;
2712 }
2713 
2714 static int bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *btf)
2715 {
2716 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2717 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2718 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2719 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2720 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2721 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2722 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
2723 	int enum64_placeholder_id = 0;
2724 	struct btf_type *t;
2725 	int i, j, vlen;
2726 
2727 	for (i = 1; i < btf__type_cnt(btf); i++) {
2728 		t = (struct btf_type *)btf__type_by_id(btf, i);
2729 
2730 		if ((!has_datasec && btf_is_var(t)) || (!has_decl_tag && btf_is_decl_tag(t))) {
2731 			/* replace VAR/DECL_TAG with INT */
2732 			t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
2733 			/*
2734 			 * using size = 1 is the safest choice, 4 will be too
2735 			 * big and cause kernel BTF validation failure if
2736 			 * original variable took less than 4 bytes
2737 			 */
2738 			t->size = 1;
2739 			*(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
2740 		} else if (!has_datasec && btf_is_datasec(t)) {
2741 			/* replace DATASEC with STRUCT */
2742 			const struct btf_var_secinfo *v = btf_var_secinfos(t);
2743 			struct btf_member *m = btf_members(t);
2744 			struct btf_type *vt;
2745 			char *name;
2746 
2747 			name = (char *)btf__name_by_offset(btf, t->name_off);
2748 			while (*name) {
2749 				if (*name == '.')
2750 					*name = '_';
2751 				name++;
2752 			}
2753 
2754 			vlen = btf_vlen(t);
2755 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
2756 			for (j = 0; j < vlen; j++, v++, m++) {
2757 				/* order of field assignments is important */
2758 				m->offset = v->offset * 8;
2759 				m->type = v->type;
2760 				/* preserve variable name as member name */
2761 				vt = (void *)btf__type_by_id(btf, v->type);
2762 				m->name_off = vt->name_off;
2763 			}
2764 		} else if (!has_func && btf_is_func_proto(t)) {
2765 			/* replace FUNC_PROTO with ENUM */
2766 			vlen = btf_vlen(t);
2767 			t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
2768 			t->size = sizeof(__u32); /* kernel enforced */
2769 		} else if (!has_func && btf_is_func(t)) {
2770 			/* replace FUNC with TYPEDEF */
2771 			t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
2772 		} else if (!has_func_global && btf_is_func(t)) {
2773 			/* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
2774 			t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
2775 		} else if (!has_float && btf_is_float(t)) {
2776 			/* replace FLOAT with an equally-sized empty STRUCT;
2777 			 * since C compilers do not accept e.g. "float" as a
2778 			 * valid struct name, make it anonymous
2779 			 */
2780 			t->name_off = 0;
2781 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
2782 		} else if (!has_type_tag && btf_is_type_tag(t)) {
2783 			/* replace TYPE_TAG with a CONST */
2784 			t->name_off = 0;
2785 			t->info = BTF_INFO_ENC(BTF_KIND_CONST, 0, 0);
2786 		} else if (!has_enum64 && btf_is_enum(t)) {
2787 			/* clear the kflag */
2788 			t->info = btf_type_info(btf_kind(t), btf_vlen(t), false);
2789 		} else if (!has_enum64 && btf_is_enum64(t)) {
2790 			/* replace ENUM64 with a union */
2791 			struct btf_member *m;
2792 
2793 			if (enum64_placeholder_id == 0) {
2794 				enum64_placeholder_id = btf__add_int(btf, "enum64_placeholder", 1, 0);
2795 				if (enum64_placeholder_id < 0)
2796 					return enum64_placeholder_id;
2797 
2798 				t = (struct btf_type *)btf__type_by_id(btf, i);
2799 			}
2800 
2801 			m = btf_members(t);
2802 			vlen = btf_vlen(t);
2803 			t->info = BTF_INFO_ENC(BTF_KIND_UNION, 0, vlen);
2804 			for (j = 0; j < vlen; j++, m++) {
2805 				m->type = enum64_placeholder_id;
2806 				m->offset = 0;
2807 			}
2808 		}
2809 	}
2810 
2811 	return 0;
2812 }
2813 
2814 static bool libbpf_needs_btf(const struct bpf_object *obj)
2815 {
2816 	return obj->efile.btf_maps_shndx >= 0 ||
2817 	       obj->efile.st_ops_shndx >= 0 ||
2818 	       obj->efile.st_ops_link_shndx >= 0 ||
2819 	       obj->nr_extern > 0;
2820 }
2821 
2822 static bool kernel_needs_btf(const struct bpf_object *obj)
2823 {
2824 	return obj->efile.st_ops_shndx >= 0 || obj->efile.st_ops_link_shndx >= 0;
2825 }
2826 
2827 static int bpf_object__init_btf(struct bpf_object *obj,
2828 				Elf_Data *btf_data,
2829 				Elf_Data *btf_ext_data)
2830 {
2831 	int err = -ENOENT;
2832 
2833 	if (btf_data) {
2834 		obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
2835 		err = libbpf_get_error(obj->btf);
2836 		if (err) {
2837 			obj->btf = NULL;
2838 			pr_warn("Error loading ELF section %s: %d.\n", BTF_ELF_SEC, err);
2839 			goto out;
2840 		}
2841 		/* enforce 8-byte pointers for BPF-targeted BTFs */
2842 		btf__set_pointer_size(obj->btf, 8);
2843 	}
2844 	if (btf_ext_data) {
2845 		struct btf_ext_info *ext_segs[3];
2846 		int seg_num, sec_num;
2847 
2848 		if (!obj->btf) {
2849 			pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
2850 				 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
2851 			goto out;
2852 		}
2853 		obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
2854 		err = libbpf_get_error(obj->btf_ext);
2855 		if (err) {
2856 			pr_warn("Error loading ELF section %s: %d. Ignored and continue.\n",
2857 				BTF_EXT_ELF_SEC, err);
2858 			obj->btf_ext = NULL;
2859 			goto out;
2860 		}
2861 
2862 		/* setup .BTF.ext to ELF section mapping */
2863 		ext_segs[0] = &obj->btf_ext->func_info;
2864 		ext_segs[1] = &obj->btf_ext->line_info;
2865 		ext_segs[2] = &obj->btf_ext->core_relo_info;
2866 		for (seg_num = 0; seg_num < ARRAY_SIZE(ext_segs); seg_num++) {
2867 			struct btf_ext_info *seg = ext_segs[seg_num];
2868 			const struct btf_ext_info_sec *sec;
2869 			const char *sec_name;
2870 			Elf_Scn *scn;
2871 
2872 			if (seg->sec_cnt == 0)
2873 				continue;
2874 
2875 			seg->sec_idxs = calloc(seg->sec_cnt, sizeof(*seg->sec_idxs));
2876 			if (!seg->sec_idxs) {
2877 				err = -ENOMEM;
2878 				goto out;
2879 			}
2880 
2881 			sec_num = 0;
2882 			for_each_btf_ext_sec(seg, sec) {
2883 				/* preventively increment index to avoid doing
2884 				 * this before every continue below
2885 				 */
2886 				sec_num++;
2887 
2888 				sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
2889 				if (str_is_empty(sec_name))
2890 					continue;
2891 				scn = elf_sec_by_name(obj, sec_name);
2892 				if (!scn)
2893 					continue;
2894 
2895 				seg->sec_idxs[sec_num - 1] = elf_ndxscn(scn);
2896 			}
2897 		}
2898 	}
2899 out:
2900 	if (err && libbpf_needs_btf(obj)) {
2901 		pr_warn("BTF is required, but is missing or corrupted.\n");
2902 		return err;
2903 	}
2904 	return 0;
2905 }
2906 
2907 static int compare_vsi_off(const void *_a, const void *_b)
2908 {
2909 	const struct btf_var_secinfo *a = _a;
2910 	const struct btf_var_secinfo *b = _b;
2911 
2912 	return a->offset - b->offset;
2913 }
2914 
2915 static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
2916 			     struct btf_type *t)
2917 {
2918 	__u32 size = 0, i, vars = btf_vlen(t);
2919 	const char *sec_name = btf__name_by_offset(btf, t->name_off);
2920 	struct btf_var_secinfo *vsi;
2921 	bool fixup_offsets = false;
2922 	int err;
2923 
2924 	if (!sec_name) {
2925 		pr_debug("No name found in string section for DATASEC kind.\n");
2926 		return -ENOENT;
2927 	}
2928 
2929 	/* Extern-backing datasecs (.ksyms, .kconfig) have their size and
2930 	 * variable offsets set at the previous step. Further, not every
2931 	 * extern BTF VAR has corresponding ELF symbol preserved, so we skip
2932 	 * all fixups altogether for such sections and go straight to sorting
2933 	 * VARs within their DATASEC.
2934 	 */
2935 	if (strcmp(sec_name, KCONFIG_SEC) == 0 || strcmp(sec_name, KSYMS_SEC) == 0)
2936 		goto sort_vars;
2937 
2938 	/* Clang leaves DATASEC size and VAR offsets as zeroes, so we need to
2939 	 * fix this up. But BPF static linker already fixes this up and fills
2940 	 * all the sizes and offsets during static linking. So this step has
2941 	 * to be optional. But the STV_HIDDEN handling is non-optional for any
2942 	 * non-extern DATASEC, so the variable fixup loop below handles both
2943 	 * functions at the same time, paying the cost of BTF VAR <-> ELF
2944 	 * symbol matching just once.
2945 	 */
2946 	if (t->size == 0) {
2947 		err = find_elf_sec_sz(obj, sec_name, &size);
2948 		if (err || !size) {
2949 			pr_debug("sec '%s': failed to determine size from ELF: size %u, err %d\n",
2950 				 sec_name, size, err);
2951 			return -ENOENT;
2952 		}
2953 
2954 		t->size = size;
2955 		fixup_offsets = true;
2956 	}
2957 
2958 	for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
2959 		const struct btf_type *t_var;
2960 		struct btf_var *var;
2961 		const char *var_name;
2962 		Elf64_Sym *sym;
2963 
2964 		t_var = btf__type_by_id(btf, vsi->type);
2965 		if (!t_var || !btf_is_var(t_var)) {
2966 			pr_debug("sec '%s': unexpected non-VAR type found\n", sec_name);
2967 			return -EINVAL;
2968 		}
2969 
2970 		var = btf_var(t_var);
2971 		if (var->linkage == BTF_VAR_STATIC || var->linkage == BTF_VAR_GLOBAL_EXTERN)
2972 			continue;
2973 
2974 		var_name = btf__name_by_offset(btf, t_var->name_off);
2975 		if (!var_name) {
2976 			pr_debug("sec '%s': failed to find name of DATASEC's member #%d\n",
2977 				 sec_name, i);
2978 			return -ENOENT;
2979 		}
2980 
2981 		sym = find_elf_var_sym(obj, var_name);
2982 		if (IS_ERR(sym)) {
2983 			pr_debug("sec '%s': failed to find ELF symbol for VAR '%s'\n",
2984 				 sec_name, var_name);
2985 			return -ENOENT;
2986 		}
2987 
2988 		if (fixup_offsets)
2989 			vsi->offset = sym->st_value;
2990 
2991 		/* if variable is a global/weak symbol, but has restricted
2992 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF VAR
2993 		 * as static. This follows similar logic for functions (BPF
2994 		 * subprogs) and influences libbpf's further decisions about
2995 		 * whether to make global data BPF array maps as
2996 		 * BPF_F_MMAPABLE.
2997 		 */
2998 		if (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
2999 		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL)
3000 			var->linkage = BTF_VAR_STATIC;
3001 	}
3002 
3003 sort_vars:
3004 	qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
3005 	return 0;
3006 }
3007 
3008 static int bpf_object_fixup_btf(struct bpf_object *obj)
3009 {
3010 	int i, n, err = 0;
3011 
3012 	if (!obj->btf)
3013 		return 0;
3014 
3015 	n = btf__type_cnt(obj->btf);
3016 	for (i = 1; i < n; i++) {
3017 		struct btf_type *t = btf_type_by_id(obj->btf, i);
3018 
3019 		/* Loader needs to fix up some of the things compiler
3020 		 * couldn't get its hands on while emitting BTF. This
3021 		 * is section size and global variable offset. We use
3022 		 * the info from the ELF itself for this purpose.
3023 		 */
3024 		if (btf_is_datasec(t)) {
3025 			err = btf_fixup_datasec(obj, obj->btf, t);
3026 			if (err)
3027 				return err;
3028 		}
3029 	}
3030 
3031 	return 0;
3032 }
3033 
3034 static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
3035 {
3036 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
3037 	    prog->type == BPF_PROG_TYPE_LSM)
3038 		return true;
3039 
3040 	/* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
3041 	 * also need vmlinux BTF
3042 	 */
3043 	if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
3044 		return true;
3045 
3046 	return false;
3047 }
3048 
3049 static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
3050 {
3051 	struct bpf_program *prog;
3052 	int i;
3053 
3054 	/* CO-RE relocations need kernel BTF, only when btf_custom_path
3055 	 * is not specified
3056 	 */
3057 	if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
3058 		return true;
3059 
3060 	/* Support for typed ksyms needs kernel BTF */
3061 	for (i = 0; i < obj->nr_extern; i++) {
3062 		const struct extern_desc *ext;
3063 
3064 		ext = &obj->externs[i];
3065 		if (ext->type == EXT_KSYM && ext->ksym.type_id)
3066 			return true;
3067 	}
3068 
3069 	bpf_object__for_each_program(prog, obj) {
3070 		if (!prog->autoload)
3071 			continue;
3072 		if (prog_needs_vmlinux_btf(prog))
3073 			return true;
3074 	}
3075 
3076 	return false;
3077 }
3078 
3079 static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
3080 {
3081 	int err;
3082 
3083 	/* btf_vmlinux could be loaded earlier */
3084 	if (obj->btf_vmlinux || obj->gen_loader)
3085 		return 0;
3086 
3087 	if (!force && !obj_needs_vmlinux_btf(obj))
3088 		return 0;
3089 
3090 	obj->btf_vmlinux = btf__load_vmlinux_btf();
3091 	err = libbpf_get_error(obj->btf_vmlinux);
3092 	if (err) {
3093 		pr_warn("Error loading vmlinux BTF: %d\n", err);
3094 		obj->btf_vmlinux = NULL;
3095 		return err;
3096 	}
3097 	return 0;
3098 }
3099 
3100 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
3101 {
3102 	struct btf *kern_btf = obj->btf;
3103 	bool btf_mandatory, sanitize;
3104 	int i, err = 0;
3105 
3106 	if (!obj->btf)
3107 		return 0;
3108 
3109 	if (!kernel_supports(obj, FEAT_BTF)) {
3110 		if (kernel_needs_btf(obj)) {
3111 			err = -EOPNOTSUPP;
3112 			goto report;
3113 		}
3114 		pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
3115 		return 0;
3116 	}
3117 
3118 	/* Even though some subprogs are global/weak, user might prefer more
3119 	 * permissive BPF verification process that BPF verifier performs for
3120 	 * static functions, taking into account more context from the caller
3121 	 * functions. In such case, they need to mark such subprogs with
3122 	 * __attribute__((visibility("hidden"))) and libbpf will adjust
3123 	 * corresponding FUNC BTF type to be marked as static and trigger more
3124 	 * involved BPF verification process.
3125 	 */
3126 	for (i = 0; i < obj->nr_programs; i++) {
3127 		struct bpf_program *prog = &obj->programs[i];
3128 		struct btf_type *t;
3129 		const char *name;
3130 		int j, n;
3131 
3132 		if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
3133 			continue;
3134 
3135 		n = btf__type_cnt(obj->btf);
3136 		for (j = 1; j < n; j++) {
3137 			t = btf_type_by_id(obj->btf, j);
3138 			if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
3139 				continue;
3140 
3141 			name = btf__str_by_offset(obj->btf, t->name_off);
3142 			if (strcmp(name, prog->name) != 0)
3143 				continue;
3144 
3145 			t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
3146 			break;
3147 		}
3148 	}
3149 
3150 	if (!kernel_supports(obj, FEAT_BTF_DECL_TAG))
3151 		goto skip_exception_cb;
3152 	for (i = 0; i < obj->nr_programs; i++) {
3153 		struct bpf_program *prog = &obj->programs[i];
3154 		int j, k, n;
3155 
3156 		if (prog_is_subprog(obj, prog))
3157 			continue;
3158 		n = btf__type_cnt(obj->btf);
3159 		for (j = 1; j < n; j++) {
3160 			const char *str = "exception_callback:", *name;
3161 			size_t len = strlen(str);
3162 			struct btf_type *t;
3163 
3164 			t = btf_type_by_id(obj->btf, j);
3165 			if (!btf_is_decl_tag(t) || btf_decl_tag(t)->component_idx != -1)
3166 				continue;
3167 
3168 			name = btf__str_by_offset(obj->btf, t->name_off);
3169 			if (strncmp(name, str, len))
3170 				continue;
3171 
3172 			t = btf_type_by_id(obj->btf, t->type);
3173 			if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
3174 				pr_warn("prog '%s': exception_callback:<value> decl tag not applied to the main program\n",
3175 					prog->name);
3176 				return -EINVAL;
3177 			}
3178 			if (strcmp(prog->name, btf__str_by_offset(obj->btf, t->name_off)))
3179 				continue;
3180 			/* Multiple callbacks are specified for the same prog,
3181 			 * the verifier will eventually return an error for this
3182 			 * case, hence simply skip appending a subprog.
3183 			 */
3184 			if (prog->exception_cb_idx >= 0) {
3185 				prog->exception_cb_idx = -1;
3186 				break;
3187 			}
3188 
3189 			name += len;
3190 			if (str_is_empty(name)) {
3191 				pr_warn("prog '%s': exception_callback:<value> decl tag contains empty value\n",
3192 					prog->name);
3193 				return -EINVAL;
3194 			}
3195 
3196 			for (k = 0; k < obj->nr_programs; k++) {
3197 				struct bpf_program *subprog = &obj->programs[k];
3198 
3199 				if (!prog_is_subprog(obj, subprog))
3200 					continue;
3201 				if (strcmp(name, subprog->name))
3202 					continue;
3203 				/* Enforce non-hidden, as from verifier point of
3204 				 * view it expects global functions, whereas the
3205 				 * mark_btf_static fixes up linkage as static.
3206 				 */
3207 				if (!subprog->sym_global || subprog->mark_btf_static) {
3208 					pr_warn("prog '%s': exception callback %s must be a global non-hidden function\n",
3209 						prog->name, subprog->name);
3210 					return -EINVAL;
3211 				}
3212 				/* Let's see if we already saw a static exception callback with the same name */
3213 				if (prog->exception_cb_idx >= 0) {
3214 					pr_warn("prog '%s': multiple subprogs with same name as exception callback '%s'\n",
3215 					        prog->name, subprog->name);
3216 					return -EINVAL;
3217 				}
3218 				prog->exception_cb_idx = k;
3219 				break;
3220 			}
3221 
3222 			if (prog->exception_cb_idx >= 0)
3223 				continue;
3224 			pr_warn("prog '%s': cannot find exception callback '%s'\n", prog->name, name);
3225 			return -ENOENT;
3226 		}
3227 	}
3228 skip_exception_cb:
3229 
3230 	sanitize = btf_needs_sanitization(obj);
3231 	if (sanitize) {
3232 		const void *raw_data;
3233 		__u32 sz;
3234 
3235 		/* clone BTF to sanitize a copy and leave the original intact */
3236 		raw_data = btf__raw_data(obj->btf, &sz);
3237 		kern_btf = btf__new(raw_data, sz);
3238 		err = libbpf_get_error(kern_btf);
3239 		if (err)
3240 			return err;
3241 
3242 		/* enforce 8-byte pointers for BPF-targeted BTFs */
3243 		btf__set_pointer_size(obj->btf, 8);
3244 		err = bpf_object__sanitize_btf(obj, kern_btf);
3245 		if (err)
3246 			return err;
3247 	}
3248 
3249 	if (obj->gen_loader) {
3250 		__u32 raw_size = 0;
3251 		const void *raw_data = btf__raw_data(kern_btf, &raw_size);
3252 
3253 		if (!raw_data)
3254 			return -ENOMEM;
3255 		bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
3256 		/* Pretend to have valid FD to pass various fd >= 0 checks.
3257 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
3258 		 */
3259 		btf__set_fd(kern_btf, 0);
3260 	} else {
3261 		/* currently BPF_BTF_LOAD only supports log_level 1 */
3262 		err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
3263 					   obj->log_level ? 1 : 0);
3264 	}
3265 	if (sanitize) {
3266 		if (!err) {
3267 			/* move fd to libbpf's BTF */
3268 			btf__set_fd(obj->btf, btf__fd(kern_btf));
3269 			btf__set_fd(kern_btf, -1);
3270 		}
3271 		btf__free(kern_btf);
3272 	}
3273 report:
3274 	if (err) {
3275 		btf_mandatory = kernel_needs_btf(obj);
3276 		pr_warn("Error loading .BTF into kernel: %d. %s\n", err,
3277 			btf_mandatory ? "BTF is mandatory, can't proceed."
3278 				      : "BTF is optional, ignoring.");
3279 		if (!btf_mandatory)
3280 			err = 0;
3281 	}
3282 	return err;
3283 }
3284 
3285 static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
3286 {
3287 	const char *name;
3288 
3289 	name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
3290 	if (!name) {
3291 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3292 			off, obj->path, elf_errmsg(-1));
3293 		return NULL;
3294 	}
3295 
3296 	return name;
3297 }
3298 
3299 static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
3300 {
3301 	const char *name;
3302 
3303 	name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
3304 	if (!name) {
3305 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3306 			off, obj->path, elf_errmsg(-1));
3307 		return NULL;
3308 	}
3309 
3310 	return name;
3311 }
3312 
3313 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
3314 {
3315 	Elf_Scn *scn;
3316 
3317 	scn = elf_getscn(obj->efile.elf, idx);
3318 	if (!scn) {
3319 		pr_warn("elf: failed to get section(%zu) from %s: %s\n",
3320 			idx, obj->path, elf_errmsg(-1));
3321 		return NULL;
3322 	}
3323 	return scn;
3324 }
3325 
3326 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
3327 {
3328 	Elf_Scn *scn = NULL;
3329 	Elf *elf = obj->efile.elf;
3330 	const char *sec_name;
3331 
3332 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3333 		sec_name = elf_sec_name(obj, scn);
3334 		if (!sec_name)
3335 			return NULL;
3336 
3337 		if (strcmp(sec_name, name) != 0)
3338 			continue;
3339 
3340 		return scn;
3341 	}
3342 	return NULL;
3343 }
3344 
3345 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn)
3346 {
3347 	Elf64_Shdr *shdr;
3348 
3349 	if (!scn)
3350 		return NULL;
3351 
3352 	shdr = elf64_getshdr(scn);
3353 	if (!shdr) {
3354 		pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
3355 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3356 		return NULL;
3357 	}
3358 
3359 	return shdr;
3360 }
3361 
3362 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
3363 {
3364 	const char *name;
3365 	Elf64_Shdr *sh;
3366 
3367 	if (!scn)
3368 		return NULL;
3369 
3370 	sh = elf_sec_hdr(obj, scn);
3371 	if (!sh)
3372 		return NULL;
3373 
3374 	name = elf_sec_str(obj, sh->sh_name);
3375 	if (!name) {
3376 		pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
3377 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3378 		return NULL;
3379 	}
3380 
3381 	return name;
3382 }
3383 
3384 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
3385 {
3386 	Elf_Data *data;
3387 
3388 	if (!scn)
3389 		return NULL;
3390 
3391 	data = elf_getdata(scn, 0);
3392 	if (!data) {
3393 		pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
3394 			elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
3395 			obj->path, elf_errmsg(-1));
3396 		return NULL;
3397 	}
3398 
3399 	return data;
3400 }
3401 
3402 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx)
3403 {
3404 	if (idx >= obj->efile.symbols->d_size / sizeof(Elf64_Sym))
3405 		return NULL;
3406 
3407 	return (Elf64_Sym *)obj->efile.symbols->d_buf + idx;
3408 }
3409 
3410 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx)
3411 {
3412 	if (idx >= data->d_size / sizeof(Elf64_Rel))
3413 		return NULL;
3414 
3415 	return (Elf64_Rel *)data->d_buf + idx;
3416 }
3417 
3418 static bool is_sec_name_dwarf(const char *name)
3419 {
3420 	/* approximation, but the actual list is too long */
3421 	return str_has_pfx(name, ".debug_");
3422 }
3423 
3424 static bool ignore_elf_section(Elf64_Shdr *hdr, const char *name)
3425 {
3426 	/* no special handling of .strtab */
3427 	if (hdr->sh_type == SHT_STRTAB)
3428 		return true;
3429 
3430 	/* ignore .llvm_addrsig section as well */
3431 	if (hdr->sh_type == SHT_LLVM_ADDRSIG)
3432 		return true;
3433 
3434 	/* no subprograms will lead to an empty .text section, ignore it */
3435 	if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
3436 	    strcmp(name, ".text") == 0)
3437 		return true;
3438 
3439 	/* DWARF sections */
3440 	if (is_sec_name_dwarf(name))
3441 		return true;
3442 
3443 	if (str_has_pfx(name, ".rel")) {
3444 		name += sizeof(".rel") - 1;
3445 		/* DWARF section relocations */
3446 		if (is_sec_name_dwarf(name))
3447 			return true;
3448 
3449 		/* .BTF and .BTF.ext don't need relocations */
3450 		if (strcmp(name, BTF_ELF_SEC) == 0 ||
3451 		    strcmp(name, BTF_EXT_ELF_SEC) == 0)
3452 			return true;
3453 	}
3454 
3455 	return false;
3456 }
3457 
3458 static int cmp_progs(const void *_a, const void *_b)
3459 {
3460 	const struct bpf_program *a = _a;
3461 	const struct bpf_program *b = _b;
3462 
3463 	if (a->sec_idx != b->sec_idx)
3464 		return a->sec_idx < b->sec_idx ? -1 : 1;
3465 
3466 	/* sec_insn_off can't be the same within the section */
3467 	return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
3468 }
3469 
3470 static int bpf_object__elf_collect(struct bpf_object *obj)
3471 {
3472 	struct elf_sec_desc *sec_desc;
3473 	Elf *elf = obj->efile.elf;
3474 	Elf_Data *btf_ext_data = NULL;
3475 	Elf_Data *btf_data = NULL;
3476 	int idx = 0, err = 0;
3477 	const char *name;
3478 	Elf_Data *data;
3479 	Elf_Scn *scn;
3480 	Elf64_Shdr *sh;
3481 
3482 	/* ELF section indices are 0-based, but sec #0 is special "invalid"
3483 	 * section. Since section count retrieved by elf_getshdrnum() does
3484 	 * include sec #0, it is already the necessary size of an array to keep
3485 	 * all the sections.
3486 	 */
3487 	if (elf_getshdrnum(obj->efile.elf, &obj->efile.sec_cnt)) {
3488 		pr_warn("elf: failed to get the number of sections for %s: %s\n",
3489 			obj->path, elf_errmsg(-1));
3490 		return -LIBBPF_ERRNO__FORMAT;
3491 	}
3492 	obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs));
3493 	if (!obj->efile.secs)
3494 		return -ENOMEM;
3495 
3496 	/* a bunch of ELF parsing functionality depends on processing symbols,
3497 	 * so do the first pass and find the symbol table
3498 	 */
3499 	scn = NULL;
3500 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3501 		sh = elf_sec_hdr(obj, scn);
3502 		if (!sh)
3503 			return -LIBBPF_ERRNO__FORMAT;
3504 
3505 		if (sh->sh_type == SHT_SYMTAB) {
3506 			if (obj->efile.symbols) {
3507 				pr_warn("elf: multiple symbol tables in %s\n", obj->path);
3508 				return -LIBBPF_ERRNO__FORMAT;
3509 			}
3510 
3511 			data = elf_sec_data(obj, scn);
3512 			if (!data)
3513 				return -LIBBPF_ERRNO__FORMAT;
3514 
3515 			idx = elf_ndxscn(scn);
3516 
3517 			obj->efile.symbols = data;
3518 			obj->efile.symbols_shndx = idx;
3519 			obj->efile.strtabidx = sh->sh_link;
3520 		}
3521 	}
3522 
3523 	if (!obj->efile.symbols) {
3524 		pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
3525 			obj->path);
3526 		return -ENOENT;
3527 	}
3528 
3529 	scn = NULL;
3530 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3531 		idx = elf_ndxscn(scn);
3532 		sec_desc = &obj->efile.secs[idx];
3533 
3534 		sh = elf_sec_hdr(obj, scn);
3535 		if (!sh)
3536 			return -LIBBPF_ERRNO__FORMAT;
3537 
3538 		name = elf_sec_str(obj, sh->sh_name);
3539 		if (!name)
3540 			return -LIBBPF_ERRNO__FORMAT;
3541 
3542 		if (ignore_elf_section(sh, name))
3543 			continue;
3544 
3545 		data = elf_sec_data(obj, scn);
3546 		if (!data)
3547 			return -LIBBPF_ERRNO__FORMAT;
3548 
3549 		pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
3550 			 idx, name, (unsigned long)data->d_size,
3551 			 (int)sh->sh_link, (unsigned long)sh->sh_flags,
3552 			 (int)sh->sh_type);
3553 
3554 		if (strcmp(name, "license") == 0) {
3555 			err = bpf_object__init_license(obj, data->d_buf, data->d_size);
3556 			if (err)
3557 				return err;
3558 		} else if (strcmp(name, "version") == 0) {
3559 			err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
3560 			if (err)
3561 				return err;
3562 		} else if (strcmp(name, "maps") == 0) {
3563 			pr_warn("elf: legacy map definitions in 'maps' section are not supported by libbpf v1.0+\n");
3564 			return -ENOTSUP;
3565 		} else if (strcmp(name, MAPS_ELF_SEC) == 0) {
3566 			obj->efile.btf_maps_shndx = idx;
3567 		} else if (strcmp(name, BTF_ELF_SEC) == 0) {
3568 			if (sh->sh_type != SHT_PROGBITS)
3569 				return -LIBBPF_ERRNO__FORMAT;
3570 			btf_data = data;
3571 		} else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
3572 			if (sh->sh_type != SHT_PROGBITS)
3573 				return -LIBBPF_ERRNO__FORMAT;
3574 			btf_ext_data = data;
3575 		} else if (sh->sh_type == SHT_SYMTAB) {
3576 			/* already processed during the first pass above */
3577 		} else if (sh->sh_type == SHT_PROGBITS && data->d_size > 0) {
3578 			if (sh->sh_flags & SHF_EXECINSTR) {
3579 				if (strcmp(name, ".text") == 0)
3580 					obj->efile.text_shndx = idx;
3581 				err = bpf_object__add_programs(obj, data, name, idx);
3582 				if (err)
3583 					return err;
3584 			} else if (strcmp(name, DATA_SEC) == 0 ||
3585 				   str_has_pfx(name, DATA_SEC ".")) {
3586 				sec_desc->sec_type = SEC_DATA;
3587 				sec_desc->shdr = sh;
3588 				sec_desc->data = data;
3589 			} else if (strcmp(name, RODATA_SEC) == 0 ||
3590 				   str_has_pfx(name, RODATA_SEC ".")) {
3591 				sec_desc->sec_type = SEC_RODATA;
3592 				sec_desc->shdr = sh;
3593 				sec_desc->data = data;
3594 			} else if (strcmp(name, STRUCT_OPS_SEC) == 0) {
3595 				obj->efile.st_ops_data = data;
3596 				obj->efile.st_ops_shndx = idx;
3597 			} else if (strcmp(name, STRUCT_OPS_LINK_SEC) == 0) {
3598 				obj->efile.st_ops_link_data = data;
3599 				obj->efile.st_ops_link_shndx = idx;
3600 			} else {
3601 				pr_info("elf: skipping unrecognized data section(%d) %s\n",
3602 					idx, name);
3603 			}
3604 		} else if (sh->sh_type == SHT_REL) {
3605 			int targ_sec_idx = sh->sh_info; /* points to other section */
3606 
3607 			if (sh->sh_entsize != sizeof(Elf64_Rel) ||
3608 			    targ_sec_idx >= obj->efile.sec_cnt)
3609 				return -LIBBPF_ERRNO__FORMAT;
3610 
3611 			/* Only do relo for section with exec instructions */
3612 			if (!section_have_execinstr(obj, targ_sec_idx) &&
3613 			    strcmp(name, ".rel" STRUCT_OPS_SEC) &&
3614 			    strcmp(name, ".rel" STRUCT_OPS_LINK_SEC) &&
3615 			    strcmp(name, ".rel" MAPS_ELF_SEC)) {
3616 				pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
3617 					idx, name, targ_sec_idx,
3618 					elf_sec_name(obj, elf_sec_by_idx(obj, targ_sec_idx)) ?: "<?>");
3619 				continue;
3620 			}
3621 
3622 			sec_desc->sec_type = SEC_RELO;
3623 			sec_desc->shdr = sh;
3624 			sec_desc->data = data;
3625 		} else if (sh->sh_type == SHT_NOBITS && (strcmp(name, BSS_SEC) == 0 ||
3626 							 str_has_pfx(name, BSS_SEC "."))) {
3627 			sec_desc->sec_type = SEC_BSS;
3628 			sec_desc->shdr = sh;
3629 			sec_desc->data = data;
3630 		} else {
3631 			pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
3632 				(size_t)sh->sh_size);
3633 		}
3634 	}
3635 
3636 	if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
3637 		pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
3638 		return -LIBBPF_ERRNO__FORMAT;
3639 	}
3640 
3641 	/* sort BPF programs by section name and in-section instruction offset
3642 	 * for faster search
3643 	 */
3644 	if (obj->nr_programs)
3645 		qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
3646 
3647 	return bpf_object__init_btf(obj, btf_data, btf_ext_data);
3648 }
3649 
3650 static bool sym_is_extern(const Elf64_Sym *sym)
3651 {
3652 	int bind = ELF64_ST_BIND(sym->st_info);
3653 	/* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
3654 	return sym->st_shndx == SHN_UNDEF &&
3655 	       (bind == STB_GLOBAL || bind == STB_WEAK) &&
3656 	       ELF64_ST_TYPE(sym->st_info) == STT_NOTYPE;
3657 }
3658 
3659 static bool sym_is_subprog(const Elf64_Sym *sym, int text_shndx)
3660 {
3661 	int bind = ELF64_ST_BIND(sym->st_info);
3662 	int type = ELF64_ST_TYPE(sym->st_info);
3663 
3664 	/* in .text section */
3665 	if (sym->st_shndx != text_shndx)
3666 		return false;
3667 
3668 	/* local function */
3669 	if (bind == STB_LOCAL && type == STT_SECTION)
3670 		return true;
3671 
3672 	/* global function */
3673 	return bind == STB_GLOBAL && type == STT_FUNC;
3674 }
3675 
3676 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
3677 {
3678 	const struct btf_type *t;
3679 	const char *tname;
3680 	int i, n;
3681 
3682 	if (!btf)
3683 		return -ESRCH;
3684 
3685 	n = btf__type_cnt(btf);
3686 	for (i = 1; i < n; i++) {
3687 		t = btf__type_by_id(btf, i);
3688 
3689 		if (!btf_is_var(t) && !btf_is_func(t))
3690 			continue;
3691 
3692 		tname = btf__name_by_offset(btf, t->name_off);
3693 		if (strcmp(tname, ext_name))
3694 			continue;
3695 
3696 		if (btf_is_var(t) &&
3697 		    btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
3698 			return -EINVAL;
3699 
3700 		if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
3701 			return -EINVAL;
3702 
3703 		return i;
3704 	}
3705 
3706 	return -ENOENT;
3707 }
3708 
3709 static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
3710 	const struct btf_var_secinfo *vs;
3711 	const struct btf_type *t;
3712 	int i, j, n;
3713 
3714 	if (!btf)
3715 		return -ESRCH;
3716 
3717 	n = btf__type_cnt(btf);
3718 	for (i = 1; i < n; i++) {
3719 		t = btf__type_by_id(btf, i);
3720 
3721 		if (!btf_is_datasec(t))
3722 			continue;
3723 
3724 		vs = btf_var_secinfos(t);
3725 		for (j = 0; j < btf_vlen(t); j++, vs++) {
3726 			if (vs->type == ext_btf_id)
3727 				return i;
3728 		}
3729 	}
3730 
3731 	return -ENOENT;
3732 }
3733 
3734 static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
3735 				     bool *is_signed)
3736 {
3737 	const struct btf_type *t;
3738 	const char *name;
3739 
3740 	t = skip_mods_and_typedefs(btf, id, NULL);
3741 	name = btf__name_by_offset(btf, t->name_off);
3742 
3743 	if (is_signed)
3744 		*is_signed = false;
3745 	switch (btf_kind(t)) {
3746 	case BTF_KIND_INT: {
3747 		int enc = btf_int_encoding(t);
3748 
3749 		if (enc & BTF_INT_BOOL)
3750 			return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
3751 		if (is_signed)
3752 			*is_signed = enc & BTF_INT_SIGNED;
3753 		if (t->size == 1)
3754 			return KCFG_CHAR;
3755 		if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
3756 			return KCFG_UNKNOWN;
3757 		return KCFG_INT;
3758 	}
3759 	case BTF_KIND_ENUM:
3760 		if (t->size != 4)
3761 			return KCFG_UNKNOWN;
3762 		if (strcmp(name, "libbpf_tristate"))
3763 			return KCFG_UNKNOWN;
3764 		return KCFG_TRISTATE;
3765 	case BTF_KIND_ENUM64:
3766 		if (strcmp(name, "libbpf_tristate"))
3767 			return KCFG_UNKNOWN;
3768 		return KCFG_TRISTATE;
3769 	case BTF_KIND_ARRAY:
3770 		if (btf_array(t)->nelems == 0)
3771 			return KCFG_UNKNOWN;
3772 		if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
3773 			return KCFG_UNKNOWN;
3774 		return KCFG_CHAR_ARR;
3775 	default:
3776 		return KCFG_UNKNOWN;
3777 	}
3778 }
3779 
3780 static int cmp_externs(const void *_a, const void *_b)
3781 {
3782 	const struct extern_desc *a = _a;
3783 	const struct extern_desc *b = _b;
3784 
3785 	if (a->type != b->type)
3786 		return a->type < b->type ? -1 : 1;
3787 
3788 	if (a->type == EXT_KCFG) {
3789 		/* descending order by alignment requirements */
3790 		if (a->kcfg.align != b->kcfg.align)
3791 			return a->kcfg.align > b->kcfg.align ? -1 : 1;
3792 		/* ascending order by size, within same alignment class */
3793 		if (a->kcfg.sz != b->kcfg.sz)
3794 			return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
3795 	}
3796 
3797 	/* resolve ties by name */
3798 	return strcmp(a->name, b->name);
3799 }
3800 
3801 static int find_int_btf_id(const struct btf *btf)
3802 {
3803 	const struct btf_type *t;
3804 	int i, n;
3805 
3806 	n = btf__type_cnt(btf);
3807 	for (i = 1; i < n; i++) {
3808 		t = btf__type_by_id(btf, i);
3809 
3810 		if (btf_is_int(t) && btf_int_bits(t) == 32)
3811 			return i;
3812 	}
3813 
3814 	return 0;
3815 }
3816 
3817 static int add_dummy_ksym_var(struct btf *btf)
3818 {
3819 	int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
3820 	const struct btf_var_secinfo *vs;
3821 	const struct btf_type *sec;
3822 
3823 	if (!btf)
3824 		return 0;
3825 
3826 	sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
3827 					    BTF_KIND_DATASEC);
3828 	if (sec_btf_id < 0)
3829 		return 0;
3830 
3831 	sec = btf__type_by_id(btf, sec_btf_id);
3832 	vs = btf_var_secinfos(sec);
3833 	for (i = 0; i < btf_vlen(sec); i++, vs++) {
3834 		const struct btf_type *vt;
3835 
3836 		vt = btf__type_by_id(btf, vs->type);
3837 		if (btf_is_func(vt))
3838 			break;
3839 	}
3840 
3841 	/* No func in ksyms sec.  No need to add dummy var. */
3842 	if (i == btf_vlen(sec))
3843 		return 0;
3844 
3845 	int_btf_id = find_int_btf_id(btf);
3846 	dummy_var_btf_id = btf__add_var(btf,
3847 					"dummy_ksym",
3848 					BTF_VAR_GLOBAL_ALLOCATED,
3849 					int_btf_id);
3850 	if (dummy_var_btf_id < 0)
3851 		pr_warn("cannot create a dummy_ksym var\n");
3852 
3853 	return dummy_var_btf_id;
3854 }
3855 
3856 static int bpf_object__collect_externs(struct bpf_object *obj)
3857 {
3858 	struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
3859 	const struct btf_type *t;
3860 	struct extern_desc *ext;
3861 	int i, n, off, dummy_var_btf_id;
3862 	const char *ext_name, *sec_name;
3863 	size_t ext_essent_len;
3864 	Elf_Scn *scn;
3865 	Elf64_Shdr *sh;
3866 
3867 	if (!obj->efile.symbols)
3868 		return 0;
3869 
3870 	scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
3871 	sh = elf_sec_hdr(obj, scn);
3872 	if (!sh || sh->sh_entsize != sizeof(Elf64_Sym))
3873 		return -LIBBPF_ERRNO__FORMAT;
3874 
3875 	dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
3876 	if (dummy_var_btf_id < 0)
3877 		return dummy_var_btf_id;
3878 
3879 	n = sh->sh_size / sh->sh_entsize;
3880 	pr_debug("looking for externs among %d symbols...\n", n);
3881 
3882 	for (i = 0; i < n; i++) {
3883 		Elf64_Sym *sym = elf_sym_by_idx(obj, i);
3884 
3885 		if (!sym)
3886 			return -LIBBPF_ERRNO__FORMAT;
3887 		if (!sym_is_extern(sym))
3888 			continue;
3889 		ext_name = elf_sym_str(obj, sym->st_name);
3890 		if (!ext_name || !ext_name[0])
3891 			continue;
3892 
3893 		ext = obj->externs;
3894 		ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
3895 		if (!ext)
3896 			return -ENOMEM;
3897 		obj->externs = ext;
3898 		ext = &ext[obj->nr_extern];
3899 		memset(ext, 0, sizeof(*ext));
3900 		obj->nr_extern++;
3901 
3902 		ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
3903 		if (ext->btf_id <= 0) {
3904 			pr_warn("failed to find BTF for extern '%s': %d\n",
3905 				ext_name, ext->btf_id);
3906 			return ext->btf_id;
3907 		}
3908 		t = btf__type_by_id(obj->btf, ext->btf_id);
3909 		ext->name = btf__name_by_offset(obj->btf, t->name_off);
3910 		ext->sym_idx = i;
3911 		ext->is_weak = ELF64_ST_BIND(sym->st_info) == STB_WEAK;
3912 
3913 		ext_essent_len = bpf_core_essential_name_len(ext->name);
3914 		ext->essent_name = NULL;
3915 		if (ext_essent_len != strlen(ext->name)) {
3916 			ext->essent_name = strndup(ext->name, ext_essent_len);
3917 			if (!ext->essent_name)
3918 				return -ENOMEM;
3919 		}
3920 
3921 		ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
3922 		if (ext->sec_btf_id <= 0) {
3923 			pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
3924 				ext_name, ext->btf_id, ext->sec_btf_id);
3925 			return ext->sec_btf_id;
3926 		}
3927 		sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
3928 		sec_name = btf__name_by_offset(obj->btf, sec->name_off);
3929 
3930 		if (strcmp(sec_name, KCONFIG_SEC) == 0) {
3931 			if (btf_is_func(t)) {
3932 				pr_warn("extern function %s is unsupported under %s section\n",
3933 					ext->name, KCONFIG_SEC);
3934 				return -ENOTSUP;
3935 			}
3936 			kcfg_sec = sec;
3937 			ext->type = EXT_KCFG;
3938 			ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
3939 			if (ext->kcfg.sz <= 0) {
3940 				pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
3941 					ext_name, ext->kcfg.sz);
3942 				return ext->kcfg.sz;
3943 			}
3944 			ext->kcfg.align = btf__align_of(obj->btf, t->type);
3945 			if (ext->kcfg.align <= 0) {
3946 				pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
3947 					ext_name, ext->kcfg.align);
3948 				return -EINVAL;
3949 			}
3950 			ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
3951 							&ext->kcfg.is_signed);
3952 			if (ext->kcfg.type == KCFG_UNKNOWN) {
3953 				pr_warn("extern (kcfg) '%s': type is unsupported\n", ext_name);
3954 				return -ENOTSUP;
3955 			}
3956 		} else if (strcmp(sec_name, KSYMS_SEC) == 0) {
3957 			ksym_sec = sec;
3958 			ext->type = EXT_KSYM;
3959 			skip_mods_and_typedefs(obj->btf, t->type,
3960 					       &ext->ksym.type_id);
3961 		} else {
3962 			pr_warn("unrecognized extern section '%s'\n", sec_name);
3963 			return -ENOTSUP;
3964 		}
3965 	}
3966 	pr_debug("collected %d externs total\n", obj->nr_extern);
3967 
3968 	if (!obj->nr_extern)
3969 		return 0;
3970 
3971 	/* sort externs by type, for kcfg ones also by (align, size, name) */
3972 	qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
3973 
3974 	/* for .ksyms section, we need to turn all externs into allocated
3975 	 * variables in BTF to pass kernel verification; we do this by
3976 	 * pretending that each extern is a 8-byte variable
3977 	 */
3978 	if (ksym_sec) {
3979 		/* find existing 4-byte integer type in BTF to use for fake
3980 		 * extern variables in DATASEC
3981 		 */
3982 		int int_btf_id = find_int_btf_id(obj->btf);
3983 		/* For extern function, a dummy_var added earlier
3984 		 * will be used to replace the vs->type and
3985 		 * its name string will be used to refill
3986 		 * the missing param's name.
3987 		 */
3988 		const struct btf_type *dummy_var;
3989 
3990 		dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
3991 		for (i = 0; i < obj->nr_extern; i++) {
3992 			ext = &obj->externs[i];
3993 			if (ext->type != EXT_KSYM)
3994 				continue;
3995 			pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
3996 				 i, ext->sym_idx, ext->name);
3997 		}
3998 
3999 		sec = ksym_sec;
4000 		n = btf_vlen(sec);
4001 		for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
4002 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4003 			struct btf_type *vt;
4004 
4005 			vt = (void *)btf__type_by_id(obj->btf, vs->type);
4006 			ext_name = btf__name_by_offset(obj->btf, vt->name_off);
4007 			ext = find_extern_by_name(obj, ext_name);
4008 			if (!ext) {
4009 				pr_warn("failed to find extern definition for BTF %s '%s'\n",
4010 					btf_kind_str(vt), ext_name);
4011 				return -ESRCH;
4012 			}
4013 			if (btf_is_func(vt)) {
4014 				const struct btf_type *func_proto;
4015 				struct btf_param *param;
4016 				int j;
4017 
4018 				func_proto = btf__type_by_id(obj->btf,
4019 							     vt->type);
4020 				param = btf_params(func_proto);
4021 				/* Reuse the dummy_var string if the
4022 				 * func proto does not have param name.
4023 				 */
4024 				for (j = 0; j < btf_vlen(func_proto); j++)
4025 					if (param[j].type && !param[j].name_off)
4026 						param[j].name_off =
4027 							dummy_var->name_off;
4028 				vs->type = dummy_var_btf_id;
4029 				vt->info &= ~0xffff;
4030 				vt->info |= BTF_FUNC_GLOBAL;
4031 			} else {
4032 				btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4033 				vt->type = int_btf_id;
4034 			}
4035 			vs->offset = off;
4036 			vs->size = sizeof(int);
4037 		}
4038 		sec->size = off;
4039 	}
4040 
4041 	if (kcfg_sec) {
4042 		sec = kcfg_sec;
4043 		/* for kcfg externs calculate their offsets within a .kconfig map */
4044 		off = 0;
4045 		for (i = 0; i < obj->nr_extern; i++) {
4046 			ext = &obj->externs[i];
4047 			if (ext->type != EXT_KCFG)
4048 				continue;
4049 
4050 			ext->kcfg.data_off = roundup(off, ext->kcfg.align);
4051 			off = ext->kcfg.data_off + ext->kcfg.sz;
4052 			pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
4053 				 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
4054 		}
4055 		sec->size = off;
4056 		n = btf_vlen(sec);
4057 		for (i = 0; i < n; i++) {
4058 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4059 
4060 			t = btf__type_by_id(obj->btf, vs->type);
4061 			ext_name = btf__name_by_offset(obj->btf, t->name_off);
4062 			ext = find_extern_by_name(obj, ext_name);
4063 			if (!ext) {
4064 				pr_warn("failed to find extern definition for BTF var '%s'\n",
4065 					ext_name);
4066 				return -ESRCH;
4067 			}
4068 			btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4069 			vs->offset = ext->kcfg.data_off;
4070 		}
4071 	}
4072 	return 0;
4073 }
4074 
4075 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog)
4076 {
4077 	return prog->sec_idx == obj->efile.text_shndx && obj->nr_programs > 1;
4078 }
4079 
4080 struct bpf_program *
4081 bpf_object__find_program_by_name(const struct bpf_object *obj,
4082 				 const char *name)
4083 {
4084 	struct bpf_program *prog;
4085 
4086 	bpf_object__for_each_program(prog, obj) {
4087 		if (prog_is_subprog(obj, prog))
4088 			continue;
4089 		if (!strcmp(prog->name, name))
4090 			return prog;
4091 	}
4092 	return errno = ENOENT, NULL;
4093 }
4094 
4095 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
4096 				      int shndx)
4097 {
4098 	switch (obj->efile.secs[shndx].sec_type) {
4099 	case SEC_BSS:
4100 	case SEC_DATA:
4101 	case SEC_RODATA:
4102 		return true;
4103 	default:
4104 		return false;
4105 	}
4106 }
4107 
4108 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
4109 				      int shndx)
4110 {
4111 	return shndx == obj->efile.btf_maps_shndx;
4112 }
4113 
4114 static enum libbpf_map_type
4115 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
4116 {
4117 	if (shndx == obj->efile.symbols_shndx)
4118 		return LIBBPF_MAP_KCONFIG;
4119 
4120 	switch (obj->efile.secs[shndx].sec_type) {
4121 	case SEC_BSS:
4122 		return LIBBPF_MAP_BSS;
4123 	case SEC_DATA:
4124 		return LIBBPF_MAP_DATA;
4125 	case SEC_RODATA:
4126 		return LIBBPF_MAP_RODATA;
4127 	default:
4128 		return LIBBPF_MAP_UNSPEC;
4129 	}
4130 }
4131 
4132 static int bpf_program__record_reloc(struct bpf_program *prog,
4133 				     struct reloc_desc *reloc_desc,
4134 				     __u32 insn_idx, const char *sym_name,
4135 				     const Elf64_Sym *sym, const Elf64_Rel *rel)
4136 {
4137 	struct bpf_insn *insn = &prog->insns[insn_idx];
4138 	size_t map_idx, nr_maps = prog->obj->nr_maps;
4139 	struct bpf_object *obj = prog->obj;
4140 	__u32 shdr_idx = sym->st_shndx;
4141 	enum libbpf_map_type type;
4142 	const char *sym_sec_name;
4143 	struct bpf_map *map;
4144 
4145 	if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
4146 		pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n",
4147 			prog->name, sym_name, insn_idx, insn->code);
4148 		return -LIBBPF_ERRNO__RELOC;
4149 	}
4150 
4151 	if (sym_is_extern(sym)) {
4152 		int sym_idx = ELF64_R_SYM(rel->r_info);
4153 		int i, n = obj->nr_extern;
4154 		struct extern_desc *ext;
4155 
4156 		for (i = 0; i < n; i++) {
4157 			ext = &obj->externs[i];
4158 			if (ext->sym_idx == sym_idx)
4159 				break;
4160 		}
4161 		if (i >= n) {
4162 			pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
4163 				prog->name, sym_name, sym_idx);
4164 			return -LIBBPF_ERRNO__RELOC;
4165 		}
4166 		pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
4167 			 prog->name, i, ext->name, ext->sym_idx, insn_idx);
4168 		if (insn->code == (BPF_JMP | BPF_CALL))
4169 			reloc_desc->type = RELO_EXTERN_CALL;
4170 		else
4171 			reloc_desc->type = RELO_EXTERN_LD64;
4172 		reloc_desc->insn_idx = insn_idx;
4173 		reloc_desc->ext_idx = i;
4174 		return 0;
4175 	}
4176 
4177 	/* sub-program call relocation */
4178 	if (is_call_insn(insn)) {
4179 		if (insn->src_reg != BPF_PSEUDO_CALL) {
4180 			pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
4181 			return -LIBBPF_ERRNO__RELOC;
4182 		}
4183 		/* text_shndx can be 0, if no default "main" program exists */
4184 		if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
4185 			sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4186 			pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
4187 				prog->name, sym_name, sym_sec_name);
4188 			return -LIBBPF_ERRNO__RELOC;
4189 		}
4190 		if (sym->st_value % BPF_INSN_SZ) {
4191 			pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
4192 				prog->name, sym_name, (size_t)sym->st_value);
4193 			return -LIBBPF_ERRNO__RELOC;
4194 		}
4195 		reloc_desc->type = RELO_CALL;
4196 		reloc_desc->insn_idx = insn_idx;
4197 		reloc_desc->sym_off = sym->st_value;
4198 		return 0;
4199 	}
4200 
4201 	if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
4202 		pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
4203 			prog->name, sym_name, shdr_idx);
4204 		return -LIBBPF_ERRNO__RELOC;
4205 	}
4206 
4207 	/* loading subprog addresses */
4208 	if (sym_is_subprog(sym, obj->efile.text_shndx)) {
4209 		/* global_func: sym->st_value = offset in the section, insn->imm = 0.
4210 		 * local_func: sym->st_value = 0, insn->imm = offset in the section.
4211 		 */
4212 		if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
4213 			pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
4214 				prog->name, sym_name, (size_t)sym->st_value, insn->imm);
4215 			return -LIBBPF_ERRNO__RELOC;
4216 		}
4217 
4218 		reloc_desc->type = RELO_SUBPROG_ADDR;
4219 		reloc_desc->insn_idx = insn_idx;
4220 		reloc_desc->sym_off = sym->st_value;
4221 		return 0;
4222 	}
4223 
4224 	type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
4225 	sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4226 
4227 	/* generic map reference relocation */
4228 	if (type == LIBBPF_MAP_UNSPEC) {
4229 		if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
4230 			pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
4231 				prog->name, sym_name, sym_sec_name);
4232 			return -LIBBPF_ERRNO__RELOC;
4233 		}
4234 		for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4235 			map = &obj->maps[map_idx];
4236 			if (map->libbpf_type != type ||
4237 			    map->sec_idx != sym->st_shndx ||
4238 			    map->sec_offset != sym->st_value)
4239 				continue;
4240 			pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n",
4241 				 prog->name, map_idx, map->name, map->sec_idx,
4242 				 map->sec_offset, insn_idx);
4243 			break;
4244 		}
4245 		if (map_idx >= nr_maps) {
4246 			pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
4247 				prog->name, sym_sec_name, (size_t)sym->st_value);
4248 			return -LIBBPF_ERRNO__RELOC;
4249 		}
4250 		reloc_desc->type = RELO_LD64;
4251 		reloc_desc->insn_idx = insn_idx;
4252 		reloc_desc->map_idx = map_idx;
4253 		reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
4254 		return 0;
4255 	}
4256 
4257 	/* global data map relocation */
4258 	if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
4259 		pr_warn("prog '%s': bad data relo against section '%s'\n",
4260 			prog->name, sym_sec_name);
4261 		return -LIBBPF_ERRNO__RELOC;
4262 	}
4263 	for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4264 		map = &obj->maps[map_idx];
4265 		if (map->libbpf_type != type || map->sec_idx != sym->st_shndx)
4266 			continue;
4267 		pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n",
4268 			 prog->name, map_idx, map->name, map->sec_idx,
4269 			 map->sec_offset, insn_idx);
4270 		break;
4271 	}
4272 	if (map_idx >= nr_maps) {
4273 		pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
4274 			prog->name, sym_sec_name);
4275 		return -LIBBPF_ERRNO__RELOC;
4276 	}
4277 
4278 	reloc_desc->type = RELO_DATA;
4279 	reloc_desc->insn_idx = insn_idx;
4280 	reloc_desc->map_idx = map_idx;
4281 	reloc_desc->sym_off = sym->st_value;
4282 	return 0;
4283 }
4284 
4285 static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
4286 {
4287 	return insn_idx >= prog->sec_insn_off &&
4288 	       insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
4289 }
4290 
4291 static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
4292 						 size_t sec_idx, size_t insn_idx)
4293 {
4294 	int l = 0, r = obj->nr_programs - 1, m;
4295 	struct bpf_program *prog;
4296 
4297 	if (!obj->nr_programs)
4298 		return NULL;
4299 
4300 	while (l < r) {
4301 		m = l + (r - l + 1) / 2;
4302 		prog = &obj->programs[m];
4303 
4304 		if (prog->sec_idx < sec_idx ||
4305 		    (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
4306 			l = m;
4307 		else
4308 			r = m - 1;
4309 	}
4310 	/* matching program could be at index l, but it still might be the
4311 	 * wrong one, so we need to double check conditions for the last time
4312 	 */
4313 	prog = &obj->programs[l];
4314 	if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
4315 		return prog;
4316 	return NULL;
4317 }
4318 
4319 static int
4320 bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
4321 {
4322 	const char *relo_sec_name, *sec_name;
4323 	size_t sec_idx = shdr->sh_info, sym_idx;
4324 	struct bpf_program *prog;
4325 	struct reloc_desc *relos;
4326 	int err, i, nrels;
4327 	const char *sym_name;
4328 	__u32 insn_idx;
4329 	Elf_Scn *scn;
4330 	Elf_Data *scn_data;
4331 	Elf64_Sym *sym;
4332 	Elf64_Rel *rel;
4333 
4334 	if (sec_idx >= obj->efile.sec_cnt)
4335 		return -EINVAL;
4336 
4337 	scn = elf_sec_by_idx(obj, sec_idx);
4338 	scn_data = elf_sec_data(obj, scn);
4339 
4340 	relo_sec_name = elf_sec_str(obj, shdr->sh_name);
4341 	sec_name = elf_sec_name(obj, scn);
4342 	if (!relo_sec_name || !sec_name)
4343 		return -EINVAL;
4344 
4345 	pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
4346 		 relo_sec_name, sec_idx, sec_name);
4347 	nrels = shdr->sh_size / shdr->sh_entsize;
4348 
4349 	for (i = 0; i < nrels; i++) {
4350 		rel = elf_rel_by_idx(data, i);
4351 		if (!rel) {
4352 			pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
4353 			return -LIBBPF_ERRNO__FORMAT;
4354 		}
4355 
4356 		sym_idx = ELF64_R_SYM(rel->r_info);
4357 		sym = elf_sym_by_idx(obj, sym_idx);
4358 		if (!sym) {
4359 			pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
4360 				relo_sec_name, sym_idx, i);
4361 			return -LIBBPF_ERRNO__FORMAT;
4362 		}
4363 
4364 		if (sym->st_shndx >= obj->efile.sec_cnt) {
4365 			pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
4366 				relo_sec_name, sym_idx, (size_t)sym->st_shndx, i);
4367 			return -LIBBPF_ERRNO__FORMAT;
4368 		}
4369 
4370 		if (rel->r_offset % BPF_INSN_SZ || rel->r_offset >= scn_data->d_size) {
4371 			pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
4372 				relo_sec_name, (size_t)rel->r_offset, i);
4373 			return -LIBBPF_ERRNO__FORMAT;
4374 		}
4375 
4376 		insn_idx = rel->r_offset / BPF_INSN_SZ;
4377 		/* relocations against static functions are recorded as
4378 		 * relocations against the section that contains a function;
4379 		 * in such case, symbol will be STT_SECTION and sym.st_name
4380 		 * will point to empty string (0), so fetch section name
4381 		 * instead
4382 		 */
4383 		if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
4384 			sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx));
4385 		else
4386 			sym_name = elf_sym_str(obj, sym->st_name);
4387 		sym_name = sym_name ?: "<?";
4388 
4389 		pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
4390 			 relo_sec_name, i, insn_idx, sym_name);
4391 
4392 		prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
4393 		if (!prog) {
4394 			pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
4395 				relo_sec_name, i, sec_name, insn_idx);
4396 			continue;
4397 		}
4398 
4399 		relos = libbpf_reallocarray(prog->reloc_desc,
4400 					    prog->nr_reloc + 1, sizeof(*relos));
4401 		if (!relos)
4402 			return -ENOMEM;
4403 		prog->reloc_desc = relos;
4404 
4405 		/* adjust insn_idx to local BPF program frame of reference */
4406 		insn_idx -= prog->sec_insn_off;
4407 		err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
4408 						insn_idx, sym_name, sym, rel);
4409 		if (err)
4410 			return err;
4411 
4412 		prog->nr_reloc++;
4413 	}
4414 	return 0;
4415 }
4416 
4417 static int map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map)
4418 {
4419 	int id;
4420 
4421 	if (!obj->btf)
4422 		return -ENOENT;
4423 
4424 	/* if it's BTF-defined map, we don't need to search for type IDs.
4425 	 * For struct_ops map, it does not need btf_key_type_id and
4426 	 * btf_value_type_id.
4427 	 */
4428 	if (map->sec_idx == obj->efile.btf_maps_shndx || bpf_map__is_struct_ops(map))
4429 		return 0;
4430 
4431 	/*
4432 	 * LLVM annotates global data differently in BTF, that is,
4433 	 * only as '.data', '.bss' or '.rodata'.
4434 	 */
4435 	if (!bpf_map__is_internal(map))
4436 		return -ENOENT;
4437 
4438 	id = btf__find_by_name(obj->btf, map->real_name);
4439 	if (id < 0)
4440 		return id;
4441 
4442 	map->btf_key_type_id = 0;
4443 	map->btf_value_type_id = id;
4444 	return 0;
4445 }
4446 
4447 static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
4448 {
4449 	char file[PATH_MAX], buff[4096];
4450 	FILE *fp;
4451 	__u32 val;
4452 	int err;
4453 
4454 	snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
4455 	memset(info, 0, sizeof(*info));
4456 
4457 	fp = fopen(file, "re");
4458 	if (!fp) {
4459 		err = -errno;
4460 		pr_warn("failed to open %s: %d. No procfs support?\n", file,
4461 			err);
4462 		return err;
4463 	}
4464 
4465 	while (fgets(buff, sizeof(buff), fp)) {
4466 		if (sscanf(buff, "map_type:\t%u", &val) == 1)
4467 			info->type = val;
4468 		else if (sscanf(buff, "key_size:\t%u", &val) == 1)
4469 			info->key_size = val;
4470 		else if (sscanf(buff, "value_size:\t%u", &val) == 1)
4471 			info->value_size = val;
4472 		else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
4473 			info->max_entries = val;
4474 		else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
4475 			info->map_flags = val;
4476 	}
4477 
4478 	fclose(fp);
4479 
4480 	return 0;
4481 }
4482 
4483 bool bpf_map__autocreate(const struct bpf_map *map)
4484 {
4485 	return map->autocreate;
4486 }
4487 
4488 int bpf_map__set_autocreate(struct bpf_map *map, bool autocreate)
4489 {
4490 	if (map->obj->loaded)
4491 		return libbpf_err(-EBUSY);
4492 
4493 	map->autocreate = autocreate;
4494 	return 0;
4495 }
4496 
4497 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
4498 {
4499 	struct bpf_map_info info;
4500 	__u32 len = sizeof(info), name_len;
4501 	int new_fd, err;
4502 	char *new_name;
4503 
4504 	memset(&info, 0, len);
4505 	err = bpf_map_get_info_by_fd(fd, &info, &len);
4506 	if (err && errno == EINVAL)
4507 		err = bpf_get_map_info_from_fdinfo(fd, &info);
4508 	if (err)
4509 		return libbpf_err(err);
4510 
4511 	name_len = strlen(info.name);
4512 	if (name_len == BPF_OBJ_NAME_LEN - 1 && strncmp(map->name, info.name, name_len) == 0)
4513 		new_name = strdup(map->name);
4514 	else
4515 		new_name = strdup(info.name);
4516 
4517 	if (!new_name)
4518 		return libbpf_err(-errno);
4519 
4520 	/*
4521 	 * Like dup(), but make sure new FD is >= 3 and has O_CLOEXEC set.
4522 	 * This is similar to what we do in ensure_good_fd(), but without
4523 	 * closing original FD.
4524 	 */
4525 	new_fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
4526 	if (new_fd < 0) {
4527 		err = -errno;
4528 		goto err_free_new_name;
4529 	}
4530 
4531 	err = zclose(map->fd);
4532 	if (err) {
4533 		err = -errno;
4534 		goto err_close_new_fd;
4535 	}
4536 	free(map->name);
4537 
4538 	map->fd = new_fd;
4539 	map->name = new_name;
4540 	map->def.type = info.type;
4541 	map->def.key_size = info.key_size;
4542 	map->def.value_size = info.value_size;
4543 	map->def.max_entries = info.max_entries;
4544 	map->def.map_flags = info.map_flags;
4545 	map->btf_key_type_id = info.btf_key_type_id;
4546 	map->btf_value_type_id = info.btf_value_type_id;
4547 	map->reused = true;
4548 	map->map_extra = info.map_extra;
4549 
4550 	return 0;
4551 
4552 err_close_new_fd:
4553 	close(new_fd);
4554 err_free_new_name:
4555 	free(new_name);
4556 	return libbpf_err(err);
4557 }
4558 
4559 __u32 bpf_map__max_entries(const struct bpf_map *map)
4560 {
4561 	return map->def.max_entries;
4562 }
4563 
4564 struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
4565 {
4566 	if (!bpf_map_type__is_map_in_map(map->def.type))
4567 		return errno = EINVAL, NULL;
4568 
4569 	return map->inner_map;
4570 }
4571 
4572 int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
4573 {
4574 	if (map->obj->loaded)
4575 		return libbpf_err(-EBUSY);
4576 
4577 	map->def.max_entries = max_entries;
4578 
4579 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
4580 	if (map_is_ringbuf(map))
4581 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
4582 
4583 	return 0;
4584 }
4585 
4586 static int
4587 bpf_object__probe_loading(struct bpf_object *obj)
4588 {
4589 	char *cp, errmsg[STRERR_BUFSIZE];
4590 	struct bpf_insn insns[] = {
4591 		BPF_MOV64_IMM(BPF_REG_0, 0),
4592 		BPF_EXIT_INSN(),
4593 	};
4594 	int ret, insn_cnt = ARRAY_SIZE(insns);
4595 
4596 	if (obj->gen_loader)
4597 		return 0;
4598 
4599 	ret = bump_rlimit_memlock();
4600 	if (ret)
4601 		pr_warn("Failed to bump RLIMIT_MEMLOCK (err = %d), you might need to do it explicitly!\n", ret);
4602 
4603 	/* make sure basic loading works */
4604 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4605 	if (ret < 0)
4606 		ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
4607 	if (ret < 0) {
4608 		ret = errno;
4609 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4610 		pr_warn("Error in %s():%s(%d). Couldn't load trivial BPF "
4611 			"program. Make sure your kernel supports BPF "
4612 			"(CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is "
4613 			"set to big enough value.\n", __func__, cp, ret);
4614 		return -ret;
4615 	}
4616 	close(ret);
4617 
4618 	return 0;
4619 }
4620 
4621 static int probe_fd(int fd)
4622 {
4623 	if (fd >= 0)
4624 		close(fd);
4625 	return fd >= 0;
4626 }
4627 
4628 static int probe_kern_prog_name(void)
4629 {
4630 	const size_t attr_sz = offsetofend(union bpf_attr, prog_name);
4631 	struct bpf_insn insns[] = {
4632 		BPF_MOV64_IMM(BPF_REG_0, 0),
4633 		BPF_EXIT_INSN(),
4634 	};
4635 	union bpf_attr attr;
4636 	int ret;
4637 
4638 	memset(&attr, 0, attr_sz);
4639 	attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
4640 	attr.license = ptr_to_u64("GPL");
4641 	attr.insns = ptr_to_u64(insns);
4642 	attr.insn_cnt = (__u32)ARRAY_SIZE(insns);
4643 	libbpf_strlcpy(attr.prog_name, "libbpf_nametest", sizeof(attr.prog_name));
4644 
4645 	/* make sure loading with name works */
4646 	ret = sys_bpf_prog_load(&attr, attr_sz, PROG_LOAD_ATTEMPTS);
4647 	return probe_fd(ret);
4648 }
4649 
4650 static int probe_kern_global_data(void)
4651 {
4652 	char *cp, errmsg[STRERR_BUFSIZE];
4653 	struct bpf_insn insns[] = {
4654 		BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
4655 		BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
4656 		BPF_MOV64_IMM(BPF_REG_0, 0),
4657 		BPF_EXIT_INSN(),
4658 	};
4659 	int ret, map, insn_cnt = ARRAY_SIZE(insns);
4660 
4661 	map = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_global", sizeof(int), 32, 1, NULL);
4662 	if (map < 0) {
4663 		ret = -errno;
4664 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4665 		pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4666 			__func__, cp, -ret);
4667 		return ret;
4668 	}
4669 
4670 	insns[0].imm = map;
4671 
4672 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4673 	close(map);
4674 	return probe_fd(ret);
4675 }
4676 
4677 static int probe_kern_btf(void)
4678 {
4679 	static const char strs[] = "\0int";
4680 	__u32 types[] = {
4681 		/* int */
4682 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4683 	};
4684 
4685 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4686 					     strs, sizeof(strs)));
4687 }
4688 
4689 static int probe_kern_btf_func(void)
4690 {
4691 	static const char strs[] = "\0int\0x\0a";
4692 	/* void x(int a) {} */
4693 	__u32 types[] = {
4694 		/* int */
4695 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4696 		/* FUNC_PROTO */                                /* [2] */
4697 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4698 		BTF_PARAM_ENC(7, 1),
4699 		/* FUNC x */                                    /* [3] */
4700 		BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
4701 	};
4702 
4703 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4704 					     strs, sizeof(strs)));
4705 }
4706 
4707 static int probe_kern_btf_func_global(void)
4708 {
4709 	static const char strs[] = "\0int\0x\0a";
4710 	/* static void x(int a) {} */
4711 	__u32 types[] = {
4712 		/* int */
4713 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4714 		/* FUNC_PROTO */                                /* [2] */
4715 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4716 		BTF_PARAM_ENC(7, 1),
4717 		/* FUNC x BTF_FUNC_GLOBAL */                    /* [3] */
4718 		BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, BTF_FUNC_GLOBAL), 2),
4719 	};
4720 
4721 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4722 					     strs, sizeof(strs)));
4723 }
4724 
4725 static int probe_kern_btf_datasec(void)
4726 {
4727 	static const char strs[] = "\0x\0.data";
4728 	/* static int a; */
4729 	__u32 types[] = {
4730 		/* int */
4731 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4732 		/* VAR x */                                     /* [2] */
4733 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4734 		BTF_VAR_STATIC,
4735 		/* DATASEC val */                               /* [3] */
4736 		BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
4737 		BTF_VAR_SECINFO_ENC(2, 0, 4),
4738 	};
4739 
4740 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4741 					     strs, sizeof(strs)));
4742 }
4743 
4744 static int probe_kern_btf_float(void)
4745 {
4746 	static const char strs[] = "\0float";
4747 	__u32 types[] = {
4748 		/* float */
4749 		BTF_TYPE_FLOAT_ENC(1, 4),
4750 	};
4751 
4752 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4753 					     strs, sizeof(strs)));
4754 }
4755 
4756 static int probe_kern_btf_decl_tag(void)
4757 {
4758 	static const char strs[] = "\0tag";
4759 	__u32 types[] = {
4760 		/* int */
4761 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4762 		/* VAR x */                                     /* [2] */
4763 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4764 		BTF_VAR_STATIC,
4765 		/* attr */
4766 		BTF_TYPE_DECL_TAG_ENC(1, 2, -1),
4767 	};
4768 
4769 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4770 					     strs, sizeof(strs)));
4771 }
4772 
4773 static int probe_kern_btf_type_tag(void)
4774 {
4775 	static const char strs[] = "\0tag";
4776 	__u32 types[] = {
4777 		/* int */
4778 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),		/* [1] */
4779 		/* attr */
4780 		BTF_TYPE_TYPE_TAG_ENC(1, 1),				/* [2] */
4781 		/* ptr */
4782 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_PTR, 0, 0), 2),	/* [3] */
4783 	};
4784 
4785 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4786 					     strs, sizeof(strs)));
4787 }
4788 
4789 static int probe_kern_array_mmap(void)
4790 {
4791 	LIBBPF_OPTS(bpf_map_create_opts, opts, .map_flags = BPF_F_MMAPABLE);
4792 	int fd;
4793 
4794 	fd = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_mmap", sizeof(int), sizeof(int), 1, &opts);
4795 	return probe_fd(fd);
4796 }
4797 
4798 static int probe_kern_exp_attach_type(void)
4799 {
4800 	LIBBPF_OPTS(bpf_prog_load_opts, opts, .expected_attach_type = BPF_CGROUP_INET_SOCK_CREATE);
4801 	struct bpf_insn insns[] = {
4802 		BPF_MOV64_IMM(BPF_REG_0, 0),
4803 		BPF_EXIT_INSN(),
4804 	};
4805 	int fd, insn_cnt = ARRAY_SIZE(insns);
4806 
4807 	/* use any valid combination of program type and (optional)
4808 	 * non-zero expected attach type (i.e., not a BPF_CGROUP_INET_INGRESS)
4809 	 * to see if kernel supports expected_attach_type field for
4810 	 * BPF_PROG_LOAD command
4811 	 */
4812 	fd = bpf_prog_load(BPF_PROG_TYPE_CGROUP_SOCK, NULL, "GPL", insns, insn_cnt, &opts);
4813 	return probe_fd(fd);
4814 }
4815 
4816 static int probe_kern_probe_read_kernel(void)
4817 {
4818 	struct bpf_insn insns[] = {
4819 		BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),	/* r1 = r10 (fp) */
4820 		BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -8),	/* r1 += -8 */
4821 		BPF_MOV64_IMM(BPF_REG_2, 8),		/* r2 = 8 */
4822 		BPF_MOV64_IMM(BPF_REG_3, 0),		/* r3 = 0 */
4823 		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_probe_read_kernel),
4824 		BPF_EXIT_INSN(),
4825 	};
4826 	int fd, insn_cnt = ARRAY_SIZE(insns);
4827 
4828 	fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
4829 	return probe_fd(fd);
4830 }
4831 
4832 static int probe_prog_bind_map(void)
4833 {
4834 	char *cp, errmsg[STRERR_BUFSIZE];
4835 	struct bpf_insn insns[] = {
4836 		BPF_MOV64_IMM(BPF_REG_0, 0),
4837 		BPF_EXIT_INSN(),
4838 	};
4839 	int ret, map, prog, insn_cnt = ARRAY_SIZE(insns);
4840 
4841 	map = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_det_bind", sizeof(int), 32, 1, NULL);
4842 	if (map < 0) {
4843 		ret = -errno;
4844 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4845 		pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4846 			__func__, cp, -ret);
4847 		return ret;
4848 	}
4849 
4850 	prog = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4851 	if (prog < 0) {
4852 		close(map);
4853 		return 0;
4854 	}
4855 
4856 	ret = bpf_prog_bind_map(prog, map, NULL);
4857 
4858 	close(map);
4859 	close(prog);
4860 
4861 	return ret >= 0;
4862 }
4863 
4864 static int probe_module_btf(void)
4865 {
4866 	static const char strs[] = "\0int";
4867 	__u32 types[] = {
4868 		/* int */
4869 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4870 	};
4871 	struct bpf_btf_info info;
4872 	__u32 len = sizeof(info);
4873 	char name[16];
4874 	int fd, err;
4875 
4876 	fd = libbpf__load_raw_btf((char *)types, sizeof(types), strs, sizeof(strs));
4877 	if (fd < 0)
4878 		return 0; /* BTF not supported at all */
4879 
4880 	memset(&info, 0, sizeof(info));
4881 	info.name = ptr_to_u64(name);
4882 	info.name_len = sizeof(name);
4883 
4884 	/* check that BPF_OBJ_GET_INFO_BY_FD supports specifying name pointer;
4885 	 * kernel's module BTF support coincides with support for
4886 	 * name/name_len fields in struct bpf_btf_info.
4887 	 */
4888 	err = bpf_btf_get_info_by_fd(fd, &info, &len);
4889 	close(fd);
4890 	return !err;
4891 }
4892 
4893 static int probe_perf_link(void)
4894 {
4895 	struct bpf_insn insns[] = {
4896 		BPF_MOV64_IMM(BPF_REG_0, 0),
4897 		BPF_EXIT_INSN(),
4898 	};
4899 	int prog_fd, link_fd, err;
4900 
4901 	prog_fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL",
4902 				insns, ARRAY_SIZE(insns), NULL);
4903 	if (prog_fd < 0)
4904 		return -errno;
4905 
4906 	/* use invalid perf_event FD to get EBADF, if link is supported;
4907 	 * otherwise EINVAL should be returned
4908 	 */
4909 	link_fd = bpf_link_create(prog_fd, -1, BPF_PERF_EVENT, NULL);
4910 	err = -errno; /* close() can clobber errno */
4911 
4912 	if (link_fd >= 0)
4913 		close(link_fd);
4914 	close(prog_fd);
4915 
4916 	return link_fd < 0 && err == -EBADF;
4917 }
4918 
4919 static int probe_uprobe_multi_link(void)
4920 {
4921 	LIBBPF_OPTS(bpf_prog_load_opts, load_opts,
4922 		.expected_attach_type = BPF_TRACE_UPROBE_MULTI,
4923 	);
4924 	LIBBPF_OPTS(bpf_link_create_opts, link_opts);
4925 	struct bpf_insn insns[] = {
4926 		BPF_MOV64_IMM(BPF_REG_0, 0),
4927 		BPF_EXIT_INSN(),
4928 	};
4929 	int prog_fd, link_fd, err;
4930 	unsigned long offset = 0;
4931 
4932 	prog_fd = bpf_prog_load(BPF_PROG_TYPE_KPROBE, NULL, "GPL",
4933 				insns, ARRAY_SIZE(insns), &load_opts);
4934 	if (prog_fd < 0)
4935 		return -errno;
4936 
4937 	/* Creating uprobe in '/' binary should fail with -EBADF. */
4938 	link_opts.uprobe_multi.path = "/";
4939 	link_opts.uprobe_multi.offsets = &offset;
4940 	link_opts.uprobe_multi.cnt = 1;
4941 
4942 	link_fd = bpf_link_create(prog_fd, -1, BPF_TRACE_UPROBE_MULTI, &link_opts);
4943 	err = -errno; /* close() can clobber errno */
4944 
4945 	if (link_fd >= 0)
4946 		close(link_fd);
4947 	close(prog_fd);
4948 
4949 	return link_fd < 0 && err == -EBADF;
4950 }
4951 
4952 static int probe_kern_bpf_cookie(void)
4953 {
4954 	struct bpf_insn insns[] = {
4955 		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_get_attach_cookie),
4956 		BPF_EXIT_INSN(),
4957 	};
4958 	int ret, insn_cnt = ARRAY_SIZE(insns);
4959 
4960 	ret = bpf_prog_load(BPF_PROG_TYPE_KPROBE, NULL, "GPL", insns, insn_cnt, NULL);
4961 	return probe_fd(ret);
4962 }
4963 
4964 static int probe_kern_btf_enum64(void)
4965 {
4966 	static const char strs[] = "\0enum64";
4967 	__u32 types[] = {
4968 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_ENUM64, 0, 0), 8),
4969 	};
4970 
4971 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4972 					     strs, sizeof(strs)));
4973 }
4974 
4975 static int probe_kern_syscall_wrapper(void);
4976 
4977 enum kern_feature_result {
4978 	FEAT_UNKNOWN = 0,
4979 	FEAT_SUPPORTED = 1,
4980 	FEAT_MISSING = 2,
4981 };
4982 
4983 typedef int (*feature_probe_fn)(void);
4984 
4985 static struct kern_feature_desc {
4986 	const char *desc;
4987 	feature_probe_fn probe;
4988 	enum kern_feature_result res;
4989 } feature_probes[__FEAT_CNT] = {
4990 	[FEAT_PROG_NAME] = {
4991 		"BPF program name", probe_kern_prog_name,
4992 	},
4993 	[FEAT_GLOBAL_DATA] = {
4994 		"global variables", probe_kern_global_data,
4995 	},
4996 	[FEAT_BTF] = {
4997 		"minimal BTF", probe_kern_btf,
4998 	},
4999 	[FEAT_BTF_FUNC] = {
5000 		"BTF functions", probe_kern_btf_func,
5001 	},
5002 	[FEAT_BTF_GLOBAL_FUNC] = {
5003 		"BTF global function", probe_kern_btf_func_global,
5004 	},
5005 	[FEAT_BTF_DATASEC] = {
5006 		"BTF data section and variable", probe_kern_btf_datasec,
5007 	},
5008 	[FEAT_ARRAY_MMAP] = {
5009 		"ARRAY map mmap()", probe_kern_array_mmap,
5010 	},
5011 	[FEAT_EXP_ATTACH_TYPE] = {
5012 		"BPF_PROG_LOAD expected_attach_type attribute",
5013 		probe_kern_exp_attach_type,
5014 	},
5015 	[FEAT_PROBE_READ_KERN] = {
5016 		"bpf_probe_read_kernel() helper", probe_kern_probe_read_kernel,
5017 	},
5018 	[FEAT_PROG_BIND_MAP] = {
5019 		"BPF_PROG_BIND_MAP support", probe_prog_bind_map,
5020 	},
5021 	[FEAT_MODULE_BTF] = {
5022 		"module BTF support", probe_module_btf,
5023 	},
5024 	[FEAT_BTF_FLOAT] = {
5025 		"BTF_KIND_FLOAT support", probe_kern_btf_float,
5026 	},
5027 	[FEAT_PERF_LINK] = {
5028 		"BPF perf link support", probe_perf_link,
5029 	},
5030 	[FEAT_BTF_DECL_TAG] = {
5031 		"BTF_KIND_DECL_TAG support", probe_kern_btf_decl_tag,
5032 	},
5033 	[FEAT_BTF_TYPE_TAG] = {
5034 		"BTF_KIND_TYPE_TAG support", probe_kern_btf_type_tag,
5035 	},
5036 	[FEAT_MEMCG_ACCOUNT] = {
5037 		"memcg-based memory accounting", probe_memcg_account,
5038 	},
5039 	[FEAT_BPF_COOKIE] = {
5040 		"BPF cookie support", probe_kern_bpf_cookie,
5041 	},
5042 	[FEAT_BTF_ENUM64] = {
5043 		"BTF_KIND_ENUM64 support", probe_kern_btf_enum64,
5044 	},
5045 	[FEAT_SYSCALL_WRAPPER] = {
5046 		"Kernel using syscall wrapper", probe_kern_syscall_wrapper,
5047 	},
5048 	[FEAT_UPROBE_MULTI_LINK] = {
5049 		"BPF multi-uprobe link support", probe_uprobe_multi_link,
5050 	},
5051 };
5052 
5053 bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
5054 {
5055 	struct kern_feature_desc *feat = &feature_probes[feat_id];
5056 	int ret;
5057 
5058 	if (obj && obj->gen_loader)
5059 		/* To generate loader program assume the latest kernel
5060 		 * to avoid doing extra prog_load, map_create syscalls.
5061 		 */
5062 		return true;
5063 
5064 	if (READ_ONCE(feat->res) == FEAT_UNKNOWN) {
5065 		ret = feat->probe();
5066 		if (ret > 0) {
5067 			WRITE_ONCE(feat->res, FEAT_SUPPORTED);
5068 		} else if (ret == 0) {
5069 			WRITE_ONCE(feat->res, FEAT_MISSING);
5070 		} else {
5071 			pr_warn("Detection of kernel %s support failed: %d\n", feat->desc, ret);
5072 			WRITE_ONCE(feat->res, FEAT_MISSING);
5073 		}
5074 	}
5075 
5076 	return READ_ONCE(feat->res) == FEAT_SUPPORTED;
5077 }
5078 
5079 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
5080 {
5081 	struct bpf_map_info map_info;
5082 	char msg[STRERR_BUFSIZE];
5083 	__u32 map_info_len = sizeof(map_info);
5084 	int err;
5085 
5086 	memset(&map_info, 0, map_info_len);
5087 	err = bpf_map_get_info_by_fd(map_fd, &map_info, &map_info_len);
5088 	if (err && errno == EINVAL)
5089 		err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
5090 	if (err) {
5091 		pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
5092 			libbpf_strerror_r(errno, msg, sizeof(msg)));
5093 		return false;
5094 	}
5095 
5096 	return (map_info.type == map->def.type &&
5097 		map_info.key_size == map->def.key_size &&
5098 		map_info.value_size == map->def.value_size &&
5099 		map_info.max_entries == map->def.max_entries &&
5100 		map_info.map_flags == map->def.map_flags &&
5101 		map_info.map_extra == map->map_extra);
5102 }
5103 
5104 static int
5105 bpf_object__reuse_map(struct bpf_map *map)
5106 {
5107 	char *cp, errmsg[STRERR_BUFSIZE];
5108 	int err, pin_fd;
5109 
5110 	pin_fd = bpf_obj_get(map->pin_path);
5111 	if (pin_fd < 0) {
5112 		err = -errno;
5113 		if (err == -ENOENT) {
5114 			pr_debug("found no pinned map to reuse at '%s'\n",
5115 				 map->pin_path);
5116 			return 0;
5117 		}
5118 
5119 		cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
5120 		pr_warn("couldn't retrieve pinned map '%s': %s\n",
5121 			map->pin_path, cp);
5122 		return err;
5123 	}
5124 
5125 	if (!map_is_reuse_compat(map, pin_fd)) {
5126 		pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
5127 			map->pin_path);
5128 		close(pin_fd);
5129 		return -EINVAL;
5130 	}
5131 
5132 	err = bpf_map__reuse_fd(map, pin_fd);
5133 	close(pin_fd);
5134 	if (err)
5135 		return err;
5136 
5137 	map->pinned = true;
5138 	pr_debug("reused pinned map at '%s'\n", map->pin_path);
5139 
5140 	return 0;
5141 }
5142 
5143 static int
5144 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
5145 {
5146 	enum libbpf_map_type map_type = map->libbpf_type;
5147 	char *cp, errmsg[STRERR_BUFSIZE];
5148 	int err, zero = 0;
5149 
5150 	if (obj->gen_loader) {
5151 		bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
5152 					 map->mmaped, map->def.value_size);
5153 		if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
5154 			bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
5155 		return 0;
5156 	}
5157 	err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
5158 	if (err) {
5159 		err = -errno;
5160 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5161 		pr_warn("Error setting initial map(%s) contents: %s\n",
5162 			map->name, cp);
5163 		return err;
5164 	}
5165 
5166 	/* Freeze .rodata and .kconfig map as read-only from syscall side. */
5167 	if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
5168 		err = bpf_map_freeze(map->fd);
5169 		if (err) {
5170 			err = -errno;
5171 			cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5172 			pr_warn("Error freezing map(%s) as read-only: %s\n",
5173 				map->name, cp);
5174 			return err;
5175 		}
5176 	}
5177 	return 0;
5178 }
5179 
5180 static void bpf_map__destroy(struct bpf_map *map);
5181 
5182 static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
5183 {
5184 	LIBBPF_OPTS(bpf_map_create_opts, create_attr);
5185 	struct bpf_map_def *def = &map->def;
5186 	const char *map_name = NULL;
5187 	int err = 0;
5188 
5189 	if (kernel_supports(obj, FEAT_PROG_NAME))
5190 		map_name = map->name;
5191 	create_attr.map_ifindex = map->map_ifindex;
5192 	create_attr.map_flags = def->map_flags;
5193 	create_attr.numa_node = map->numa_node;
5194 	create_attr.map_extra = map->map_extra;
5195 
5196 	if (bpf_map__is_struct_ops(map))
5197 		create_attr.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
5198 
5199 	if (obj->btf && btf__fd(obj->btf) >= 0) {
5200 		create_attr.btf_fd = btf__fd(obj->btf);
5201 		create_attr.btf_key_type_id = map->btf_key_type_id;
5202 		create_attr.btf_value_type_id = map->btf_value_type_id;
5203 	}
5204 
5205 	if (bpf_map_type__is_map_in_map(def->type)) {
5206 		if (map->inner_map) {
5207 			err = bpf_object__create_map(obj, map->inner_map, true);
5208 			if (err) {
5209 				pr_warn("map '%s': failed to create inner map: %d\n",
5210 					map->name, err);
5211 				return err;
5212 			}
5213 			map->inner_map_fd = bpf_map__fd(map->inner_map);
5214 		}
5215 		if (map->inner_map_fd >= 0)
5216 			create_attr.inner_map_fd = map->inner_map_fd;
5217 	}
5218 
5219 	switch (def->type) {
5220 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5221 	case BPF_MAP_TYPE_CGROUP_ARRAY:
5222 	case BPF_MAP_TYPE_STACK_TRACE:
5223 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5224 	case BPF_MAP_TYPE_HASH_OF_MAPS:
5225 	case BPF_MAP_TYPE_DEVMAP:
5226 	case BPF_MAP_TYPE_DEVMAP_HASH:
5227 	case BPF_MAP_TYPE_CPUMAP:
5228 	case BPF_MAP_TYPE_XSKMAP:
5229 	case BPF_MAP_TYPE_SOCKMAP:
5230 	case BPF_MAP_TYPE_SOCKHASH:
5231 	case BPF_MAP_TYPE_QUEUE:
5232 	case BPF_MAP_TYPE_STACK:
5233 		create_attr.btf_fd = 0;
5234 		create_attr.btf_key_type_id = 0;
5235 		create_attr.btf_value_type_id = 0;
5236 		map->btf_key_type_id = 0;
5237 		map->btf_value_type_id = 0;
5238 	default:
5239 		break;
5240 	}
5241 
5242 	if (obj->gen_loader) {
5243 		bpf_gen__map_create(obj->gen_loader, def->type, map_name,
5244 				    def->key_size, def->value_size, def->max_entries,
5245 				    &create_attr, is_inner ? -1 : map - obj->maps);
5246 		/* Pretend to have valid FD to pass various fd >= 0 checks.
5247 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
5248 		 */
5249 		map->fd = 0;
5250 	} else {
5251 		map->fd = bpf_map_create(def->type, map_name,
5252 					 def->key_size, def->value_size,
5253 					 def->max_entries, &create_attr);
5254 	}
5255 	if (map->fd < 0 && (create_attr.btf_key_type_id ||
5256 			    create_attr.btf_value_type_id)) {
5257 		char *cp, errmsg[STRERR_BUFSIZE];
5258 
5259 		err = -errno;
5260 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5261 		pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
5262 			map->name, cp, err);
5263 		create_attr.btf_fd = 0;
5264 		create_attr.btf_key_type_id = 0;
5265 		create_attr.btf_value_type_id = 0;
5266 		map->btf_key_type_id = 0;
5267 		map->btf_value_type_id = 0;
5268 		map->fd = bpf_map_create(def->type, map_name,
5269 					 def->key_size, def->value_size,
5270 					 def->max_entries, &create_attr);
5271 	}
5272 
5273 	err = map->fd < 0 ? -errno : 0;
5274 
5275 	if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
5276 		if (obj->gen_loader)
5277 			map->inner_map->fd = -1;
5278 		bpf_map__destroy(map->inner_map);
5279 		zfree(&map->inner_map);
5280 	}
5281 
5282 	return err;
5283 }
5284 
5285 static int init_map_in_map_slots(struct bpf_object *obj, struct bpf_map *map)
5286 {
5287 	const struct bpf_map *targ_map;
5288 	unsigned int i;
5289 	int fd, err = 0;
5290 
5291 	for (i = 0; i < map->init_slots_sz; i++) {
5292 		if (!map->init_slots[i])
5293 			continue;
5294 
5295 		targ_map = map->init_slots[i];
5296 		fd = bpf_map__fd(targ_map);
5297 
5298 		if (obj->gen_loader) {
5299 			bpf_gen__populate_outer_map(obj->gen_loader,
5300 						    map - obj->maps, i,
5301 						    targ_map - obj->maps);
5302 		} else {
5303 			err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5304 		}
5305 		if (err) {
5306 			err = -errno;
5307 			pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %d\n",
5308 				map->name, i, targ_map->name, fd, err);
5309 			return err;
5310 		}
5311 		pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
5312 			 map->name, i, targ_map->name, fd);
5313 	}
5314 
5315 	zfree(&map->init_slots);
5316 	map->init_slots_sz = 0;
5317 
5318 	return 0;
5319 }
5320 
5321 static int init_prog_array_slots(struct bpf_object *obj, struct bpf_map *map)
5322 {
5323 	const struct bpf_program *targ_prog;
5324 	unsigned int i;
5325 	int fd, err;
5326 
5327 	if (obj->gen_loader)
5328 		return -ENOTSUP;
5329 
5330 	for (i = 0; i < map->init_slots_sz; i++) {
5331 		if (!map->init_slots[i])
5332 			continue;
5333 
5334 		targ_prog = map->init_slots[i];
5335 		fd = bpf_program__fd(targ_prog);
5336 
5337 		err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5338 		if (err) {
5339 			err = -errno;
5340 			pr_warn("map '%s': failed to initialize slot [%d] to prog '%s' fd=%d: %d\n",
5341 				map->name, i, targ_prog->name, fd, err);
5342 			return err;
5343 		}
5344 		pr_debug("map '%s': slot [%d] set to prog '%s' fd=%d\n",
5345 			 map->name, i, targ_prog->name, fd);
5346 	}
5347 
5348 	zfree(&map->init_slots);
5349 	map->init_slots_sz = 0;
5350 
5351 	return 0;
5352 }
5353 
5354 static int bpf_object_init_prog_arrays(struct bpf_object *obj)
5355 {
5356 	struct bpf_map *map;
5357 	int i, err;
5358 
5359 	for (i = 0; i < obj->nr_maps; i++) {
5360 		map = &obj->maps[i];
5361 
5362 		if (!map->init_slots_sz || map->def.type != BPF_MAP_TYPE_PROG_ARRAY)
5363 			continue;
5364 
5365 		err = init_prog_array_slots(obj, map);
5366 		if (err < 0) {
5367 			zclose(map->fd);
5368 			return err;
5369 		}
5370 	}
5371 	return 0;
5372 }
5373 
5374 static int map_set_def_max_entries(struct bpf_map *map)
5375 {
5376 	if (map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !map->def.max_entries) {
5377 		int nr_cpus;
5378 
5379 		nr_cpus = libbpf_num_possible_cpus();
5380 		if (nr_cpus < 0) {
5381 			pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
5382 				map->name, nr_cpus);
5383 			return nr_cpus;
5384 		}
5385 		pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
5386 		map->def.max_entries = nr_cpus;
5387 	}
5388 
5389 	return 0;
5390 }
5391 
5392 static int
5393 bpf_object__create_maps(struct bpf_object *obj)
5394 {
5395 	struct bpf_map *map;
5396 	char *cp, errmsg[STRERR_BUFSIZE];
5397 	unsigned int i, j;
5398 	int err;
5399 	bool retried;
5400 
5401 	for (i = 0; i < obj->nr_maps; i++) {
5402 		map = &obj->maps[i];
5403 
5404 		/* To support old kernels, we skip creating global data maps
5405 		 * (.rodata, .data, .kconfig, etc); later on, during program
5406 		 * loading, if we detect that at least one of the to-be-loaded
5407 		 * programs is referencing any global data map, we'll error
5408 		 * out with program name and relocation index logged.
5409 		 * This approach allows to accommodate Clang emitting
5410 		 * unnecessary .rodata.str1.1 sections for string literals,
5411 		 * but also it allows to have CO-RE applications that use
5412 		 * global variables in some of BPF programs, but not others.
5413 		 * If those global variable-using programs are not loaded at
5414 		 * runtime due to bpf_program__set_autoload(prog, false),
5415 		 * bpf_object loading will succeed just fine even on old
5416 		 * kernels.
5417 		 */
5418 		if (bpf_map__is_internal(map) && !kernel_supports(obj, FEAT_GLOBAL_DATA))
5419 			map->autocreate = false;
5420 
5421 		if (!map->autocreate) {
5422 			pr_debug("map '%s': skipped auto-creating...\n", map->name);
5423 			continue;
5424 		}
5425 
5426 		err = map_set_def_max_entries(map);
5427 		if (err)
5428 			goto err_out;
5429 
5430 		retried = false;
5431 retry:
5432 		if (map->pin_path) {
5433 			err = bpf_object__reuse_map(map);
5434 			if (err) {
5435 				pr_warn("map '%s': error reusing pinned map\n",
5436 					map->name);
5437 				goto err_out;
5438 			}
5439 			if (retried && map->fd < 0) {
5440 				pr_warn("map '%s': cannot find pinned map\n",
5441 					map->name);
5442 				err = -ENOENT;
5443 				goto err_out;
5444 			}
5445 		}
5446 
5447 		if (map->fd >= 0) {
5448 			pr_debug("map '%s': skipping creation (preset fd=%d)\n",
5449 				 map->name, map->fd);
5450 		} else {
5451 			err = bpf_object__create_map(obj, map, false);
5452 			if (err)
5453 				goto err_out;
5454 
5455 			pr_debug("map '%s': created successfully, fd=%d\n",
5456 				 map->name, map->fd);
5457 
5458 			if (bpf_map__is_internal(map)) {
5459 				err = bpf_object__populate_internal_map(obj, map);
5460 				if (err < 0) {
5461 					zclose(map->fd);
5462 					goto err_out;
5463 				}
5464 			}
5465 
5466 			if (map->init_slots_sz && map->def.type != BPF_MAP_TYPE_PROG_ARRAY) {
5467 				err = init_map_in_map_slots(obj, map);
5468 				if (err < 0) {
5469 					zclose(map->fd);
5470 					goto err_out;
5471 				}
5472 			}
5473 		}
5474 
5475 		if (map->pin_path && !map->pinned) {
5476 			err = bpf_map__pin(map, NULL);
5477 			if (err) {
5478 				zclose(map->fd);
5479 				if (!retried && err == -EEXIST) {
5480 					retried = true;
5481 					goto retry;
5482 				}
5483 				pr_warn("map '%s': failed to auto-pin at '%s': %d\n",
5484 					map->name, map->pin_path, err);
5485 				goto err_out;
5486 			}
5487 		}
5488 	}
5489 
5490 	return 0;
5491 
5492 err_out:
5493 	cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5494 	pr_warn("map '%s': failed to create: %s(%d)\n", map->name, cp, err);
5495 	pr_perm_msg(err);
5496 	for (j = 0; j < i; j++)
5497 		zclose(obj->maps[j].fd);
5498 	return err;
5499 }
5500 
5501 static bool bpf_core_is_flavor_sep(const char *s)
5502 {
5503 	/* check X___Y name pattern, where X and Y are not underscores */
5504 	return s[0] != '_' &&				      /* X */
5505 	       s[1] == '_' && s[2] == '_' && s[3] == '_' &&   /* ___ */
5506 	       s[4] != '_';				      /* Y */
5507 }
5508 
5509 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
5510  * before last triple underscore. Struct name part after last triple
5511  * underscore is ignored by BPF CO-RE relocation during relocation matching.
5512  */
5513 size_t bpf_core_essential_name_len(const char *name)
5514 {
5515 	size_t n = strlen(name);
5516 	int i;
5517 
5518 	for (i = n - 5; i >= 0; i--) {
5519 		if (bpf_core_is_flavor_sep(name + i))
5520 			return i + 1;
5521 	}
5522 	return n;
5523 }
5524 
5525 void bpf_core_free_cands(struct bpf_core_cand_list *cands)
5526 {
5527 	if (!cands)
5528 		return;
5529 
5530 	free(cands->cands);
5531 	free(cands);
5532 }
5533 
5534 int bpf_core_add_cands(struct bpf_core_cand *local_cand,
5535 		       size_t local_essent_len,
5536 		       const struct btf *targ_btf,
5537 		       const char *targ_btf_name,
5538 		       int targ_start_id,
5539 		       struct bpf_core_cand_list *cands)
5540 {
5541 	struct bpf_core_cand *new_cands, *cand;
5542 	const struct btf_type *t, *local_t;
5543 	const char *targ_name, *local_name;
5544 	size_t targ_essent_len;
5545 	int n, i;
5546 
5547 	local_t = btf__type_by_id(local_cand->btf, local_cand->id);
5548 	local_name = btf__str_by_offset(local_cand->btf, local_t->name_off);
5549 
5550 	n = btf__type_cnt(targ_btf);
5551 	for (i = targ_start_id; i < n; i++) {
5552 		t = btf__type_by_id(targ_btf, i);
5553 		if (!btf_kind_core_compat(t, local_t))
5554 			continue;
5555 
5556 		targ_name = btf__name_by_offset(targ_btf, t->name_off);
5557 		if (str_is_empty(targ_name))
5558 			continue;
5559 
5560 		targ_essent_len = bpf_core_essential_name_len(targ_name);
5561 		if (targ_essent_len != local_essent_len)
5562 			continue;
5563 
5564 		if (strncmp(local_name, targ_name, local_essent_len) != 0)
5565 			continue;
5566 
5567 		pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s in [%s]\n",
5568 			 local_cand->id, btf_kind_str(local_t),
5569 			 local_name, i, btf_kind_str(t), targ_name,
5570 			 targ_btf_name);
5571 		new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
5572 					      sizeof(*cands->cands));
5573 		if (!new_cands)
5574 			return -ENOMEM;
5575 
5576 		cand = &new_cands[cands->len];
5577 		cand->btf = targ_btf;
5578 		cand->id = i;
5579 
5580 		cands->cands = new_cands;
5581 		cands->len++;
5582 	}
5583 	return 0;
5584 }
5585 
5586 static int load_module_btfs(struct bpf_object *obj)
5587 {
5588 	struct bpf_btf_info info;
5589 	struct module_btf *mod_btf;
5590 	struct btf *btf;
5591 	char name[64];
5592 	__u32 id = 0, len;
5593 	int err, fd;
5594 
5595 	if (obj->btf_modules_loaded)
5596 		return 0;
5597 
5598 	if (obj->gen_loader)
5599 		return 0;
5600 
5601 	/* don't do this again, even if we find no module BTFs */
5602 	obj->btf_modules_loaded = true;
5603 
5604 	/* kernel too old to support module BTFs */
5605 	if (!kernel_supports(obj, FEAT_MODULE_BTF))
5606 		return 0;
5607 
5608 	while (true) {
5609 		err = bpf_btf_get_next_id(id, &id);
5610 		if (err && errno == ENOENT)
5611 			return 0;
5612 		if (err && errno == EPERM) {
5613 			pr_debug("skipping module BTFs loading, missing privileges\n");
5614 			return 0;
5615 		}
5616 		if (err) {
5617 			err = -errno;
5618 			pr_warn("failed to iterate BTF objects: %d\n", err);
5619 			return err;
5620 		}
5621 
5622 		fd = bpf_btf_get_fd_by_id(id);
5623 		if (fd < 0) {
5624 			if (errno == ENOENT)
5625 				continue; /* expected race: BTF was unloaded */
5626 			err = -errno;
5627 			pr_warn("failed to get BTF object #%d FD: %d\n", id, err);
5628 			return err;
5629 		}
5630 
5631 		len = sizeof(info);
5632 		memset(&info, 0, sizeof(info));
5633 		info.name = ptr_to_u64(name);
5634 		info.name_len = sizeof(name);
5635 
5636 		err = bpf_btf_get_info_by_fd(fd, &info, &len);
5637 		if (err) {
5638 			err = -errno;
5639 			pr_warn("failed to get BTF object #%d info: %d\n", id, err);
5640 			goto err_out;
5641 		}
5642 
5643 		/* ignore non-module BTFs */
5644 		if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
5645 			close(fd);
5646 			continue;
5647 		}
5648 
5649 		btf = btf_get_from_fd(fd, obj->btf_vmlinux);
5650 		err = libbpf_get_error(btf);
5651 		if (err) {
5652 			pr_warn("failed to load module [%s]'s BTF object #%d: %d\n",
5653 				name, id, err);
5654 			goto err_out;
5655 		}
5656 
5657 		err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
5658 					sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
5659 		if (err)
5660 			goto err_out;
5661 
5662 		mod_btf = &obj->btf_modules[obj->btf_module_cnt++];
5663 
5664 		mod_btf->btf = btf;
5665 		mod_btf->id = id;
5666 		mod_btf->fd = fd;
5667 		mod_btf->name = strdup(name);
5668 		if (!mod_btf->name) {
5669 			err = -ENOMEM;
5670 			goto err_out;
5671 		}
5672 		continue;
5673 
5674 err_out:
5675 		close(fd);
5676 		return err;
5677 	}
5678 
5679 	return 0;
5680 }
5681 
5682 static struct bpf_core_cand_list *
5683 bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
5684 {
5685 	struct bpf_core_cand local_cand = {};
5686 	struct bpf_core_cand_list *cands;
5687 	const struct btf *main_btf;
5688 	const struct btf_type *local_t;
5689 	const char *local_name;
5690 	size_t local_essent_len;
5691 	int err, i;
5692 
5693 	local_cand.btf = local_btf;
5694 	local_cand.id = local_type_id;
5695 	local_t = btf__type_by_id(local_btf, local_type_id);
5696 	if (!local_t)
5697 		return ERR_PTR(-EINVAL);
5698 
5699 	local_name = btf__name_by_offset(local_btf, local_t->name_off);
5700 	if (str_is_empty(local_name))
5701 		return ERR_PTR(-EINVAL);
5702 	local_essent_len = bpf_core_essential_name_len(local_name);
5703 
5704 	cands = calloc(1, sizeof(*cands));
5705 	if (!cands)
5706 		return ERR_PTR(-ENOMEM);
5707 
5708 	/* Attempt to find target candidates in vmlinux BTF first */
5709 	main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
5710 	err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
5711 	if (err)
5712 		goto err_out;
5713 
5714 	/* if vmlinux BTF has any candidate, don't got for module BTFs */
5715 	if (cands->len)
5716 		return cands;
5717 
5718 	/* if vmlinux BTF was overridden, don't attempt to load module BTFs */
5719 	if (obj->btf_vmlinux_override)
5720 		return cands;
5721 
5722 	/* now look through module BTFs, trying to still find candidates */
5723 	err = load_module_btfs(obj);
5724 	if (err)
5725 		goto err_out;
5726 
5727 	for (i = 0; i < obj->btf_module_cnt; i++) {
5728 		err = bpf_core_add_cands(&local_cand, local_essent_len,
5729 					 obj->btf_modules[i].btf,
5730 					 obj->btf_modules[i].name,
5731 					 btf__type_cnt(obj->btf_vmlinux),
5732 					 cands);
5733 		if (err)
5734 			goto err_out;
5735 	}
5736 
5737 	return cands;
5738 err_out:
5739 	bpf_core_free_cands(cands);
5740 	return ERR_PTR(err);
5741 }
5742 
5743 /* Check local and target types for compatibility. This check is used for
5744  * type-based CO-RE relocations and follow slightly different rules than
5745  * field-based relocations. This function assumes that root types were already
5746  * checked for name match. Beyond that initial root-level name check, names
5747  * are completely ignored. Compatibility rules are as follows:
5748  *   - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
5749  *     kind should match for local and target types (i.e., STRUCT is not
5750  *     compatible with UNION);
5751  *   - for ENUMs, the size is ignored;
5752  *   - for INT, size and signedness are ignored;
5753  *   - for ARRAY, dimensionality is ignored, element types are checked for
5754  *     compatibility recursively;
5755  *   - CONST/VOLATILE/RESTRICT modifiers are ignored;
5756  *   - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
5757  *   - FUNC_PROTOs are compatible if they have compatible signature: same
5758  *     number of input args and compatible return and argument types.
5759  * These rules are not set in stone and probably will be adjusted as we get
5760  * more experience with using BPF CO-RE relocations.
5761  */
5762 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
5763 			      const struct btf *targ_btf, __u32 targ_id)
5764 {
5765 	return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id, 32);
5766 }
5767 
5768 int bpf_core_types_match(const struct btf *local_btf, __u32 local_id,
5769 			 const struct btf *targ_btf, __u32 targ_id)
5770 {
5771 	return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false, 32);
5772 }
5773 
5774 static size_t bpf_core_hash_fn(const long key, void *ctx)
5775 {
5776 	return key;
5777 }
5778 
5779 static bool bpf_core_equal_fn(const long k1, const long k2, void *ctx)
5780 {
5781 	return k1 == k2;
5782 }
5783 
5784 static int record_relo_core(struct bpf_program *prog,
5785 			    const struct bpf_core_relo *core_relo, int insn_idx)
5786 {
5787 	struct reloc_desc *relos, *relo;
5788 
5789 	relos = libbpf_reallocarray(prog->reloc_desc,
5790 				    prog->nr_reloc + 1, sizeof(*relos));
5791 	if (!relos)
5792 		return -ENOMEM;
5793 	relo = &relos[prog->nr_reloc];
5794 	relo->type = RELO_CORE;
5795 	relo->insn_idx = insn_idx;
5796 	relo->core_relo = core_relo;
5797 	prog->reloc_desc = relos;
5798 	prog->nr_reloc++;
5799 	return 0;
5800 }
5801 
5802 static const struct bpf_core_relo *find_relo_core(struct bpf_program *prog, int insn_idx)
5803 {
5804 	struct reloc_desc *relo;
5805 	int i;
5806 
5807 	for (i = 0; i < prog->nr_reloc; i++) {
5808 		relo = &prog->reloc_desc[i];
5809 		if (relo->type != RELO_CORE || relo->insn_idx != insn_idx)
5810 			continue;
5811 
5812 		return relo->core_relo;
5813 	}
5814 
5815 	return NULL;
5816 }
5817 
5818 static int bpf_core_resolve_relo(struct bpf_program *prog,
5819 				 const struct bpf_core_relo *relo,
5820 				 int relo_idx,
5821 				 const struct btf *local_btf,
5822 				 struct hashmap *cand_cache,
5823 				 struct bpf_core_relo_res *targ_res)
5824 {
5825 	struct bpf_core_spec specs_scratch[3] = {};
5826 	struct bpf_core_cand_list *cands = NULL;
5827 	const char *prog_name = prog->name;
5828 	const struct btf_type *local_type;
5829 	const char *local_name;
5830 	__u32 local_id = relo->type_id;
5831 	int err;
5832 
5833 	local_type = btf__type_by_id(local_btf, local_id);
5834 	if (!local_type)
5835 		return -EINVAL;
5836 
5837 	local_name = btf__name_by_offset(local_btf, local_type->name_off);
5838 	if (!local_name)
5839 		return -EINVAL;
5840 
5841 	if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
5842 	    !hashmap__find(cand_cache, local_id, &cands)) {
5843 		cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
5844 		if (IS_ERR(cands)) {
5845 			pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n",
5846 				prog_name, relo_idx, local_id, btf_kind_str(local_type),
5847 				local_name, PTR_ERR(cands));
5848 			return PTR_ERR(cands);
5849 		}
5850 		err = hashmap__set(cand_cache, local_id, cands, NULL, NULL);
5851 		if (err) {
5852 			bpf_core_free_cands(cands);
5853 			return err;
5854 		}
5855 	}
5856 
5857 	return bpf_core_calc_relo_insn(prog_name, relo, relo_idx, local_btf, cands, specs_scratch,
5858 				       targ_res);
5859 }
5860 
5861 static int
5862 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
5863 {
5864 	const struct btf_ext_info_sec *sec;
5865 	struct bpf_core_relo_res targ_res;
5866 	const struct bpf_core_relo *rec;
5867 	const struct btf_ext_info *seg;
5868 	struct hashmap_entry *entry;
5869 	struct hashmap *cand_cache = NULL;
5870 	struct bpf_program *prog;
5871 	struct bpf_insn *insn;
5872 	const char *sec_name;
5873 	int i, err = 0, insn_idx, sec_idx, sec_num;
5874 
5875 	if (obj->btf_ext->core_relo_info.len == 0)
5876 		return 0;
5877 
5878 	if (targ_btf_path) {
5879 		obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
5880 		err = libbpf_get_error(obj->btf_vmlinux_override);
5881 		if (err) {
5882 			pr_warn("failed to parse target BTF: %d\n", err);
5883 			return err;
5884 		}
5885 	}
5886 
5887 	cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
5888 	if (IS_ERR(cand_cache)) {
5889 		err = PTR_ERR(cand_cache);
5890 		goto out;
5891 	}
5892 
5893 	seg = &obj->btf_ext->core_relo_info;
5894 	sec_num = 0;
5895 	for_each_btf_ext_sec(seg, sec) {
5896 		sec_idx = seg->sec_idxs[sec_num];
5897 		sec_num++;
5898 
5899 		sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
5900 		if (str_is_empty(sec_name)) {
5901 			err = -EINVAL;
5902 			goto out;
5903 		}
5904 
5905 		pr_debug("sec '%s': found %d CO-RE relocations\n", sec_name, sec->num_info);
5906 
5907 		for_each_btf_ext_rec(seg, sec, i, rec) {
5908 			if (rec->insn_off % BPF_INSN_SZ)
5909 				return -EINVAL;
5910 			insn_idx = rec->insn_off / BPF_INSN_SZ;
5911 			prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
5912 			if (!prog) {
5913 				/* When __weak subprog is "overridden" by another instance
5914 				 * of the subprog from a different object file, linker still
5915 				 * appends all the .BTF.ext info that used to belong to that
5916 				 * eliminated subprogram.
5917 				 * This is similar to what x86-64 linker does for relocations.
5918 				 * So just ignore such relocations just like we ignore
5919 				 * subprog instructions when discovering subprograms.
5920 				 */
5921 				pr_debug("sec '%s': skipping CO-RE relocation #%d for insn #%d belonging to eliminated weak subprogram\n",
5922 					 sec_name, i, insn_idx);
5923 				continue;
5924 			}
5925 			/* no need to apply CO-RE relocation if the program is
5926 			 * not going to be loaded
5927 			 */
5928 			if (!prog->autoload)
5929 				continue;
5930 
5931 			/* adjust insn_idx from section frame of reference to the local
5932 			 * program's frame of reference; (sub-)program code is not yet
5933 			 * relocated, so it's enough to just subtract in-section offset
5934 			 */
5935 			insn_idx = insn_idx - prog->sec_insn_off;
5936 			if (insn_idx >= prog->insns_cnt)
5937 				return -EINVAL;
5938 			insn = &prog->insns[insn_idx];
5939 
5940 			err = record_relo_core(prog, rec, insn_idx);
5941 			if (err) {
5942 				pr_warn("prog '%s': relo #%d: failed to record relocation: %d\n",
5943 					prog->name, i, err);
5944 				goto out;
5945 			}
5946 
5947 			if (prog->obj->gen_loader)
5948 				continue;
5949 
5950 			err = bpf_core_resolve_relo(prog, rec, i, obj->btf, cand_cache, &targ_res);
5951 			if (err) {
5952 				pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
5953 					prog->name, i, err);
5954 				goto out;
5955 			}
5956 
5957 			err = bpf_core_patch_insn(prog->name, insn, insn_idx, rec, i, &targ_res);
5958 			if (err) {
5959 				pr_warn("prog '%s': relo #%d: failed to patch insn #%u: %d\n",
5960 					prog->name, i, insn_idx, err);
5961 				goto out;
5962 			}
5963 		}
5964 	}
5965 
5966 out:
5967 	/* obj->btf_vmlinux and module BTFs are freed after object load */
5968 	btf__free(obj->btf_vmlinux_override);
5969 	obj->btf_vmlinux_override = NULL;
5970 
5971 	if (!IS_ERR_OR_NULL(cand_cache)) {
5972 		hashmap__for_each_entry(cand_cache, entry, i) {
5973 			bpf_core_free_cands(entry->pvalue);
5974 		}
5975 		hashmap__free(cand_cache);
5976 	}
5977 	return err;
5978 }
5979 
5980 /* base map load ldimm64 special constant, used also for log fixup logic */
5981 #define POISON_LDIMM64_MAP_BASE 2001000000
5982 #define POISON_LDIMM64_MAP_PFX "200100"
5983 
5984 static void poison_map_ldimm64(struct bpf_program *prog, int relo_idx,
5985 			       int insn_idx, struct bpf_insn *insn,
5986 			       int map_idx, const struct bpf_map *map)
5987 {
5988 	int i;
5989 
5990 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that loads map #%d '%s'\n",
5991 		 prog->name, relo_idx, insn_idx, map_idx, map->name);
5992 
5993 	/* we turn single ldimm64 into two identical invalid calls */
5994 	for (i = 0; i < 2; i++) {
5995 		insn->code = BPF_JMP | BPF_CALL;
5996 		insn->dst_reg = 0;
5997 		insn->src_reg = 0;
5998 		insn->off = 0;
5999 		/* if this instruction is reachable (not a dead code),
6000 		 * verifier will complain with something like:
6001 		 * invalid func unknown#2001000123
6002 		 * where lower 123 is map index into obj->maps[] array
6003 		 */
6004 		insn->imm = POISON_LDIMM64_MAP_BASE + map_idx;
6005 
6006 		insn++;
6007 	}
6008 }
6009 
6010 /* unresolved kfunc call special constant, used also for log fixup logic */
6011 #define POISON_CALL_KFUNC_BASE 2002000000
6012 #define POISON_CALL_KFUNC_PFX "2002"
6013 
6014 static void poison_kfunc_call(struct bpf_program *prog, int relo_idx,
6015 			      int insn_idx, struct bpf_insn *insn,
6016 			      int ext_idx, const struct extern_desc *ext)
6017 {
6018 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that calls kfunc '%s'\n",
6019 		 prog->name, relo_idx, insn_idx, ext->name);
6020 
6021 	/* we turn kfunc call into invalid helper call with identifiable constant */
6022 	insn->code = BPF_JMP | BPF_CALL;
6023 	insn->dst_reg = 0;
6024 	insn->src_reg = 0;
6025 	insn->off = 0;
6026 	/* if this instruction is reachable (not a dead code),
6027 	 * verifier will complain with something like:
6028 	 * invalid func unknown#2001000123
6029 	 * where lower 123 is extern index into obj->externs[] array
6030 	 */
6031 	insn->imm = POISON_CALL_KFUNC_BASE + ext_idx;
6032 }
6033 
6034 /* Relocate data references within program code:
6035  *  - map references;
6036  *  - global variable references;
6037  *  - extern references.
6038  */
6039 static int
6040 bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
6041 {
6042 	int i;
6043 
6044 	for (i = 0; i < prog->nr_reloc; i++) {
6045 		struct reloc_desc *relo = &prog->reloc_desc[i];
6046 		struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6047 		const struct bpf_map *map;
6048 		struct extern_desc *ext;
6049 
6050 		switch (relo->type) {
6051 		case RELO_LD64:
6052 			map = &obj->maps[relo->map_idx];
6053 			if (obj->gen_loader) {
6054 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
6055 				insn[0].imm = relo->map_idx;
6056 			} else if (map->autocreate) {
6057 				insn[0].src_reg = BPF_PSEUDO_MAP_FD;
6058 				insn[0].imm = map->fd;
6059 			} else {
6060 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6061 						   relo->map_idx, map);
6062 			}
6063 			break;
6064 		case RELO_DATA:
6065 			map = &obj->maps[relo->map_idx];
6066 			insn[1].imm = insn[0].imm + relo->sym_off;
6067 			if (obj->gen_loader) {
6068 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6069 				insn[0].imm = relo->map_idx;
6070 			} else if (map->autocreate) {
6071 				insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6072 				insn[0].imm = map->fd;
6073 			} else {
6074 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6075 						   relo->map_idx, map);
6076 			}
6077 			break;
6078 		case RELO_EXTERN_LD64:
6079 			ext = &obj->externs[relo->ext_idx];
6080 			if (ext->type == EXT_KCFG) {
6081 				if (obj->gen_loader) {
6082 					insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6083 					insn[0].imm = obj->kconfig_map_idx;
6084 				} else {
6085 					insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6086 					insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
6087 				}
6088 				insn[1].imm = ext->kcfg.data_off;
6089 			} else /* EXT_KSYM */ {
6090 				if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
6091 					insn[0].src_reg = BPF_PSEUDO_BTF_ID;
6092 					insn[0].imm = ext->ksym.kernel_btf_id;
6093 					insn[1].imm = ext->ksym.kernel_btf_obj_fd;
6094 				} else { /* typeless ksyms or unresolved typed ksyms */
6095 					insn[0].imm = (__u32)ext->ksym.addr;
6096 					insn[1].imm = ext->ksym.addr >> 32;
6097 				}
6098 			}
6099 			break;
6100 		case RELO_EXTERN_CALL:
6101 			ext = &obj->externs[relo->ext_idx];
6102 			insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
6103 			if (ext->is_set) {
6104 				insn[0].imm = ext->ksym.kernel_btf_id;
6105 				insn[0].off = ext->ksym.btf_fd_idx;
6106 			} else { /* unresolved weak kfunc call */
6107 				poison_kfunc_call(prog, i, relo->insn_idx, insn,
6108 						  relo->ext_idx, ext);
6109 			}
6110 			break;
6111 		case RELO_SUBPROG_ADDR:
6112 			if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
6113 				pr_warn("prog '%s': relo #%d: bad insn\n",
6114 					prog->name, i);
6115 				return -EINVAL;
6116 			}
6117 			/* handled already */
6118 			break;
6119 		case RELO_CALL:
6120 			/* handled already */
6121 			break;
6122 		case RELO_CORE:
6123 			/* will be handled by bpf_program_record_relos() */
6124 			break;
6125 		default:
6126 			pr_warn("prog '%s': relo #%d: bad relo type %d\n",
6127 				prog->name, i, relo->type);
6128 			return -EINVAL;
6129 		}
6130 	}
6131 
6132 	return 0;
6133 }
6134 
6135 static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
6136 				    const struct bpf_program *prog,
6137 				    const struct btf_ext_info *ext_info,
6138 				    void **prog_info, __u32 *prog_rec_cnt,
6139 				    __u32 *prog_rec_sz)
6140 {
6141 	void *copy_start = NULL, *copy_end = NULL;
6142 	void *rec, *rec_end, *new_prog_info;
6143 	const struct btf_ext_info_sec *sec;
6144 	size_t old_sz, new_sz;
6145 	int i, sec_num, sec_idx, off_adj;
6146 
6147 	sec_num = 0;
6148 	for_each_btf_ext_sec(ext_info, sec) {
6149 		sec_idx = ext_info->sec_idxs[sec_num];
6150 		sec_num++;
6151 		if (prog->sec_idx != sec_idx)
6152 			continue;
6153 
6154 		for_each_btf_ext_rec(ext_info, sec, i, rec) {
6155 			__u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
6156 
6157 			if (insn_off < prog->sec_insn_off)
6158 				continue;
6159 			if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
6160 				break;
6161 
6162 			if (!copy_start)
6163 				copy_start = rec;
6164 			copy_end = rec + ext_info->rec_size;
6165 		}
6166 
6167 		if (!copy_start)
6168 			return -ENOENT;
6169 
6170 		/* append func/line info of a given (sub-)program to the main
6171 		 * program func/line info
6172 		 */
6173 		old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
6174 		new_sz = old_sz + (copy_end - copy_start);
6175 		new_prog_info = realloc(*prog_info, new_sz);
6176 		if (!new_prog_info)
6177 			return -ENOMEM;
6178 		*prog_info = new_prog_info;
6179 		*prog_rec_cnt = new_sz / ext_info->rec_size;
6180 		memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
6181 
6182 		/* Kernel instruction offsets are in units of 8-byte
6183 		 * instructions, while .BTF.ext instruction offsets generated
6184 		 * by Clang are in units of bytes. So convert Clang offsets
6185 		 * into kernel offsets and adjust offset according to program
6186 		 * relocated position.
6187 		 */
6188 		off_adj = prog->sub_insn_off - prog->sec_insn_off;
6189 		rec = new_prog_info + old_sz;
6190 		rec_end = new_prog_info + new_sz;
6191 		for (; rec < rec_end; rec += ext_info->rec_size) {
6192 			__u32 *insn_off = rec;
6193 
6194 			*insn_off = *insn_off / BPF_INSN_SZ + off_adj;
6195 		}
6196 		*prog_rec_sz = ext_info->rec_size;
6197 		return 0;
6198 	}
6199 
6200 	return -ENOENT;
6201 }
6202 
6203 static int
6204 reloc_prog_func_and_line_info(const struct bpf_object *obj,
6205 			      struct bpf_program *main_prog,
6206 			      const struct bpf_program *prog)
6207 {
6208 	int err;
6209 
6210 	/* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
6211 	 * supprot func/line info
6212 	 */
6213 	if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
6214 		return 0;
6215 
6216 	/* only attempt func info relocation if main program's func_info
6217 	 * relocation was successful
6218 	 */
6219 	if (main_prog != prog && !main_prog->func_info)
6220 		goto line_info;
6221 
6222 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
6223 				       &main_prog->func_info,
6224 				       &main_prog->func_info_cnt,
6225 				       &main_prog->func_info_rec_size);
6226 	if (err) {
6227 		if (err != -ENOENT) {
6228 			pr_warn("prog '%s': error relocating .BTF.ext function info: %d\n",
6229 				prog->name, err);
6230 			return err;
6231 		}
6232 		if (main_prog->func_info) {
6233 			/*
6234 			 * Some info has already been found but has problem
6235 			 * in the last btf_ext reloc. Must have to error out.
6236 			 */
6237 			pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
6238 			return err;
6239 		}
6240 		/* Have problem loading the very first info. Ignore the rest. */
6241 		pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
6242 			prog->name);
6243 	}
6244 
6245 line_info:
6246 	/* don't relocate line info if main program's relocation failed */
6247 	if (main_prog != prog && !main_prog->line_info)
6248 		return 0;
6249 
6250 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
6251 				       &main_prog->line_info,
6252 				       &main_prog->line_info_cnt,
6253 				       &main_prog->line_info_rec_size);
6254 	if (err) {
6255 		if (err != -ENOENT) {
6256 			pr_warn("prog '%s': error relocating .BTF.ext line info: %d\n",
6257 				prog->name, err);
6258 			return err;
6259 		}
6260 		if (main_prog->line_info) {
6261 			/*
6262 			 * Some info has already been found but has problem
6263 			 * in the last btf_ext reloc. Must have to error out.
6264 			 */
6265 			pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
6266 			return err;
6267 		}
6268 		/* Have problem loading the very first info. Ignore the rest. */
6269 		pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
6270 			prog->name);
6271 	}
6272 	return 0;
6273 }
6274 
6275 static int cmp_relo_by_insn_idx(const void *key, const void *elem)
6276 {
6277 	size_t insn_idx = *(const size_t *)key;
6278 	const struct reloc_desc *relo = elem;
6279 
6280 	if (insn_idx == relo->insn_idx)
6281 		return 0;
6282 	return insn_idx < relo->insn_idx ? -1 : 1;
6283 }
6284 
6285 static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
6286 {
6287 	if (!prog->nr_reloc)
6288 		return NULL;
6289 	return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
6290 		       sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
6291 }
6292 
6293 static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
6294 {
6295 	int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
6296 	struct reloc_desc *relos;
6297 	int i;
6298 
6299 	if (main_prog == subprog)
6300 		return 0;
6301 	relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
6302 	/* if new count is zero, reallocarray can return a valid NULL result;
6303 	 * in this case the previous pointer will be freed, so we *have to*
6304 	 * reassign old pointer to the new value (even if it's NULL)
6305 	 */
6306 	if (!relos && new_cnt)
6307 		return -ENOMEM;
6308 	if (subprog->nr_reloc)
6309 		memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
6310 		       sizeof(*relos) * subprog->nr_reloc);
6311 
6312 	for (i = main_prog->nr_reloc; i < new_cnt; i++)
6313 		relos[i].insn_idx += subprog->sub_insn_off;
6314 	/* After insn_idx adjustment the 'relos' array is still sorted
6315 	 * by insn_idx and doesn't break bsearch.
6316 	 */
6317 	main_prog->reloc_desc = relos;
6318 	main_prog->nr_reloc = new_cnt;
6319 	return 0;
6320 }
6321 
6322 static int
6323 bpf_object__append_subprog_code(struct bpf_object *obj, struct bpf_program *main_prog,
6324 				struct bpf_program *subprog)
6325 {
6326        struct bpf_insn *insns;
6327        size_t new_cnt;
6328        int err;
6329 
6330        subprog->sub_insn_off = main_prog->insns_cnt;
6331 
6332        new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
6333        insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
6334        if (!insns) {
6335                pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
6336                return -ENOMEM;
6337        }
6338        main_prog->insns = insns;
6339        main_prog->insns_cnt = new_cnt;
6340 
6341        memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
6342               subprog->insns_cnt * sizeof(*insns));
6343 
6344        pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
6345                 main_prog->name, subprog->insns_cnt, subprog->name);
6346 
6347        /* The subprog insns are now appended. Append its relos too. */
6348        err = append_subprog_relos(main_prog, subprog);
6349        if (err)
6350                return err;
6351        return 0;
6352 }
6353 
6354 static int
6355 bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
6356 		       struct bpf_program *prog)
6357 {
6358 	size_t sub_insn_idx, insn_idx;
6359 	struct bpf_program *subprog;
6360 	struct reloc_desc *relo;
6361 	struct bpf_insn *insn;
6362 	int err;
6363 
6364 	err = reloc_prog_func_and_line_info(obj, main_prog, prog);
6365 	if (err)
6366 		return err;
6367 
6368 	for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
6369 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6370 		if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
6371 			continue;
6372 
6373 		relo = find_prog_insn_relo(prog, insn_idx);
6374 		if (relo && relo->type == RELO_EXTERN_CALL)
6375 			/* kfunc relocations will be handled later
6376 			 * in bpf_object__relocate_data()
6377 			 */
6378 			continue;
6379 		if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
6380 			pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
6381 				prog->name, insn_idx, relo->type);
6382 			return -LIBBPF_ERRNO__RELOC;
6383 		}
6384 		if (relo) {
6385 			/* sub-program instruction index is a combination of
6386 			 * an offset of a symbol pointed to by relocation and
6387 			 * call instruction's imm field; for global functions,
6388 			 * call always has imm = -1, but for static functions
6389 			 * relocation is against STT_SECTION and insn->imm
6390 			 * points to a start of a static function
6391 			 *
6392 			 * for subprog addr relocation, the relo->sym_off + insn->imm is
6393 			 * the byte offset in the corresponding section.
6394 			 */
6395 			if (relo->type == RELO_CALL)
6396 				sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
6397 			else
6398 				sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
6399 		} else if (insn_is_pseudo_func(insn)) {
6400 			/*
6401 			 * RELO_SUBPROG_ADDR relo is always emitted even if both
6402 			 * functions are in the same section, so it shouldn't reach here.
6403 			 */
6404 			pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
6405 				prog->name, insn_idx);
6406 			return -LIBBPF_ERRNO__RELOC;
6407 		} else {
6408 			/* if subprogram call is to a static function within
6409 			 * the same ELF section, there won't be any relocation
6410 			 * emitted, but it also means there is no additional
6411 			 * offset necessary, insns->imm is relative to
6412 			 * instruction's original position within the section
6413 			 */
6414 			sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
6415 		}
6416 
6417 		/* we enforce that sub-programs should be in .text section */
6418 		subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
6419 		if (!subprog) {
6420 			pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
6421 				prog->name);
6422 			return -LIBBPF_ERRNO__RELOC;
6423 		}
6424 
6425 		/* if it's the first call instruction calling into this
6426 		 * subprogram (meaning this subprog hasn't been processed
6427 		 * yet) within the context of current main program:
6428 		 *   - append it at the end of main program's instructions blog;
6429 		 *   - process is recursively, while current program is put on hold;
6430 		 *   - if that subprogram calls some other not yet processes
6431 		 *   subprogram, same thing will happen recursively until
6432 		 *   there are no more unprocesses subprograms left to append
6433 		 *   and relocate.
6434 		 */
6435 		if (subprog->sub_insn_off == 0) {
6436 			err = bpf_object__append_subprog_code(obj, main_prog, subprog);
6437 			if (err)
6438 				return err;
6439 			err = bpf_object__reloc_code(obj, main_prog, subprog);
6440 			if (err)
6441 				return err;
6442 		}
6443 
6444 		/* main_prog->insns memory could have been re-allocated, so
6445 		 * calculate pointer again
6446 		 */
6447 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6448 		/* calculate correct instruction position within current main
6449 		 * prog; each main prog can have a different set of
6450 		 * subprograms appended (potentially in different order as
6451 		 * well), so position of any subprog can be different for
6452 		 * different main programs
6453 		 */
6454 		insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
6455 
6456 		pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
6457 			 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
6458 	}
6459 
6460 	return 0;
6461 }
6462 
6463 /*
6464  * Relocate sub-program calls.
6465  *
6466  * Algorithm operates as follows. Each entry-point BPF program (referred to as
6467  * main prog) is processed separately. For each subprog (non-entry functions,
6468  * that can be called from either entry progs or other subprogs) gets their
6469  * sub_insn_off reset to zero. This serves as indicator that this subprogram
6470  * hasn't been yet appended and relocated within current main prog. Once its
6471  * relocated, sub_insn_off will point at the position within current main prog
6472  * where given subprog was appended. This will further be used to relocate all
6473  * the call instructions jumping into this subprog.
6474  *
6475  * We start with main program and process all call instructions. If the call
6476  * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
6477  * is zero), subprog instructions are appended at the end of main program's
6478  * instruction array. Then main program is "put on hold" while we recursively
6479  * process newly appended subprogram. If that subprogram calls into another
6480  * subprogram that hasn't been appended, new subprogram is appended again to
6481  * the *main* prog's instructions (subprog's instructions are always left
6482  * untouched, as they need to be in unmodified state for subsequent main progs
6483  * and subprog instructions are always sent only as part of a main prog) and
6484  * the process continues recursively. Once all the subprogs called from a main
6485  * prog or any of its subprogs are appended (and relocated), all their
6486  * positions within finalized instructions array are known, so it's easy to
6487  * rewrite call instructions with correct relative offsets, corresponding to
6488  * desired target subprog.
6489  *
6490  * Its important to realize that some subprogs might not be called from some
6491  * main prog and any of its called/used subprogs. Those will keep their
6492  * subprog->sub_insn_off as zero at all times and won't be appended to current
6493  * main prog and won't be relocated within the context of current main prog.
6494  * They might still be used from other main progs later.
6495  *
6496  * Visually this process can be shown as below. Suppose we have two main
6497  * programs mainA and mainB and BPF object contains three subprogs: subA,
6498  * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
6499  * subC both call subB:
6500  *
6501  *        +--------+ +-------+
6502  *        |        v v       |
6503  *     +--+---+ +--+-+-+ +---+--+
6504  *     | subA | | subB | | subC |
6505  *     +--+---+ +------+ +---+--+
6506  *        ^                  ^
6507  *        |                  |
6508  *    +---+-------+   +------+----+
6509  *    |   mainA   |   |   mainB   |
6510  *    +-----------+   +-----------+
6511  *
6512  * We'll start relocating mainA, will find subA, append it and start
6513  * processing sub A recursively:
6514  *
6515  *    +-----------+------+
6516  *    |   mainA   | subA |
6517  *    +-----------+------+
6518  *
6519  * At this point we notice that subB is used from subA, so we append it and
6520  * relocate (there are no further subcalls from subB):
6521  *
6522  *    +-----------+------+------+
6523  *    |   mainA   | subA | subB |
6524  *    +-----------+------+------+
6525  *
6526  * At this point, we relocate subA calls, then go one level up and finish with
6527  * relocatin mainA calls. mainA is done.
6528  *
6529  * For mainB process is similar but results in different order. We start with
6530  * mainB and skip subA and subB, as mainB never calls them (at least
6531  * directly), but we see subC is needed, so we append and start processing it:
6532  *
6533  *    +-----------+------+
6534  *    |   mainB   | subC |
6535  *    +-----------+------+
6536  * Now we see subC needs subB, so we go back to it, append and relocate it:
6537  *
6538  *    +-----------+------+------+
6539  *    |   mainB   | subC | subB |
6540  *    +-----------+------+------+
6541  *
6542  * At this point we unwind recursion, relocate calls in subC, then in mainB.
6543  */
6544 static int
6545 bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
6546 {
6547 	struct bpf_program *subprog;
6548 	int i, err;
6549 
6550 	/* mark all subprogs as not relocated (yet) within the context of
6551 	 * current main program
6552 	 */
6553 	for (i = 0; i < obj->nr_programs; i++) {
6554 		subprog = &obj->programs[i];
6555 		if (!prog_is_subprog(obj, subprog))
6556 			continue;
6557 
6558 		subprog->sub_insn_off = 0;
6559 	}
6560 
6561 	err = bpf_object__reloc_code(obj, prog, prog);
6562 	if (err)
6563 		return err;
6564 
6565 	return 0;
6566 }
6567 
6568 static void
6569 bpf_object__free_relocs(struct bpf_object *obj)
6570 {
6571 	struct bpf_program *prog;
6572 	int i;
6573 
6574 	/* free up relocation descriptors */
6575 	for (i = 0; i < obj->nr_programs; i++) {
6576 		prog = &obj->programs[i];
6577 		zfree(&prog->reloc_desc);
6578 		prog->nr_reloc = 0;
6579 	}
6580 }
6581 
6582 static int cmp_relocs(const void *_a, const void *_b)
6583 {
6584 	const struct reloc_desc *a = _a;
6585 	const struct reloc_desc *b = _b;
6586 
6587 	if (a->insn_idx != b->insn_idx)
6588 		return a->insn_idx < b->insn_idx ? -1 : 1;
6589 
6590 	/* no two relocations should have the same insn_idx, but ... */
6591 	if (a->type != b->type)
6592 		return a->type < b->type ? -1 : 1;
6593 
6594 	return 0;
6595 }
6596 
6597 static void bpf_object__sort_relos(struct bpf_object *obj)
6598 {
6599 	int i;
6600 
6601 	for (i = 0; i < obj->nr_programs; i++) {
6602 		struct bpf_program *p = &obj->programs[i];
6603 
6604 		if (!p->nr_reloc)
6605 			continue;
6606 
6607 		qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
6608 	}
6609 }
6610 
6611 static int
6612 bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
6613 {
6614 	struct bpf_program *prog;
6615 	size_t i, j;
6616 	int err;
6617 
6618 	if (obj->btf_ext) {
6619 		err = bpf_object__relocate_core(obj, targ_btf_path);
6620 		if (err) {
6621 			pr_warn("failed to perform CO-RE relocations: %d\n",
6622 				err);
6623 			return err;
6624 		}
6625 		bpf_object__sort_relos(obj);
6626 	}
6627 
6628 	/* Before relocating calls pre-process relocations and mark
6629 	 * few ld_imm64 instructions that points to subprogs.
6630 	 * Otherwise bpf_object__reloc_code() later would have to consider
6631 	 * all ld_imm64 insns as relocation candidates. That would
6632 	 * reduce relocation speed, since amount of find_prog_insn_relo()
6633 	 * would increase and most of them will fail to find a relo.
6634 	 */
6635 	for (i = 0; i < obj->nr_programs; i++) {
6636 		prog = &obj->programs[i];
6637 		for (j = 0; j < prog->nr_reloc; j++) {
6638 			struct reloc_desc *relo = &prog->reloc_desc[j];
6639 			struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6640 
6641 			/* mark the insn, so it's recognized by insn_is_pseudo_func() */
6642 			if (relo->type == RELO_SUBPROG_ADDR)
6643 				insn[0].src_reg = BPF_PSEUDO_FUNC;
6644 		}
6645 	}
6646 
6647 	/* relocate subprogram calls and append used subprograms to main
6648 	 * programs; each copy of subprogram code needs to be relocated
6649 	 * differently for each main program, because its code location might
6650 	 * have changed.
6651 	 * Append subprog relos to main programs to allow data relos to be
6652 	 * processed after text is completely relocated.
6653 	 */
6654 	for (i = 0; i < obj->nr_programs; i++) {
6655 		prog = &obj->programs[i];
6656 		/* sub-program's sub-calls are relocated within the context of
6657 		 * its main program only
6658 		 */
6659 		if (prog_is_subprog(obj, prog))
6660 			continue;
6661 		if (!prog->autoload)
6662 			continue;
6663 
6664 		err = bpf_object__relocate_calls(obj, prog);
6665 		if (err) {
6666 			pr_warn("prog '%s': failed to relocate calls: %d\n",
6667 				prog->name, err);
6668 			return err;
6669 		}
6670 
6671 		/* Now, also append exception callback if it has not been done already. */
6672 		if (prog->exception_cb_idx >= 0) {
6673 			struct bpf_program *subprog = &obj->programs[prog->exception_cb_idx];
6674 
6675 			/* Calling exception callback directly is disallowed, which the
6676 			 * verifier will reject later. In case it was processed already,
6677 			 * we can skip this step, otherwise for all other valid cases we
6678 			 * have to append exception callback now.
6679 			 */
6680 			if (subprog->sub_insn_off == 0) {
6681 				err = bpf_object__append_subprog_code(obj, prog, subprog);
6682 				if (err)
6683 					return err;
6684 				err = bpf_object__reloc_code(obj, prog, subprog);
6685 				if (err)
6686 					return err;
6687 			}
6688 		}
6689 	}
6690 	/* Process data relos for main programs */
6691 	for (i = 0; i < obj->nr_programs; i++) {
6692 		prog = &obj->programs[i];
6693 		if (prog_is_subprog(obj, prog))
6694 			continue;
6695 		if (!prog->autoload)
6696 			continue;
6697 		err = bpf_object__relocate_data(obj, prog);
6698 		if (err) {
6699 			pr_warn("prog '%s': failed to relocate data references: %d\n",
6700 				prog->name, err);
6701 			return err;
6702 		}
6703 	}
6704 
6705 	return 0;
6706 }
6707 
6708 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
6709 					    Elf64_Shdr *shdr, Elf_Data *data);
6710 
6711 static int bpf_object__collect_map_relos(struct bpf_object *obj,
6712 					 Elf64_Shdr *shdr, Elf_Data *data)
6713 {
6714 	const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
6715 	int i, j, nrels, new_sz;
6716 	const struct btf_var_secinfo *vi = NULL;
6717 	const struct btf_type *sec, *var, *def;
6718 	struct bpf_map *map = NULL, *targ_map = NULL;
6719 	struct bpf_program *targ_prog = NULL;
6720 	bool is_prog_array, is_map_in_map;
6721 	const struct btf_member *member;
6722 	const char *name, *mname, *type;
6723 	unsigned int moff;
6724 	Elf64_Sym *sym;
6725 	Elf64_Rel *rel;
6726 	void *tmp;
6727 
6728 	if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
6729 		return -EINVAL;
6730 	sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
6731 	if (!sec)
6732 		return -EINVAL;
6733 
6734 	nrels = shdr->sh_size / shdr->sh_entsize;
6735 	for (i = 0; i < nrels; i++) {
6736 		rel = elf_rel_by_idx(data, i);
6737 		if (!rel) {
6738 			pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
6739 			return -LIBBPF_ERRNO__FORMAT;
6740 		}
6741 
6742 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
6743 		if (!sym) {
6744 			pr_warn(".maps relo #%d: symbol %zx not found\n",
6745 				i, (size_t)ELF64_R_SYM(rel->r_info));
6746 			return -LIBBPF_ERRNO__FORMAT;
6747 		}
6748 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
6749 
6750 		pr_debug(".maps relo #%d: for %zd value %zd rel->r_offset %zu name %d ('%s')\n",
6751 			 i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
6752 			 (size_t)rel->r_offset, sym->st_name, name);
6753 
6754 		for (j = 0; j < obj->nr_maps; j++) {
6755 			map = &obj->maps[j];
6756 			if (map->sec_idx != obj->efile.btf_maps_shndx)
6757 				continue;
6758 
6759 			vi = btf_var_secinfos(sec) + map->btf_var_idx;
6760 			if (vi->offset <= rel->r_offset &&
6761 			    rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size)
6762 				break;
6763 		}
6764 		if (j == obj->nr_maps) {
6765 			pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
6766 				i, name, (size_t)rel->r_offset);
6767 			return -EINVAL;
6768 		}
6769 
6770 		is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
6771 		is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
6772 		type = is_map_in_map ? "map" : "prog";
6773 		if (is_map_in_map) {
6774 			if (sym->st_shndx != obj->efile.btf_maps_shndx) {
6775 				pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
6776 					i, name);
6777 				return -LIBBPF_ERRNO__RELOC;
6778 			}
6779 			if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
6780 			    map->def.key_size != sizeof(int)) {
6781 				pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
6782 					i, map->name, sizeof(int));
6783 				return -EINVAL;
6784 			}
6785 			targ_map = bpf_object__find_map_by_name(obj, name);
6786 			if (!targ_map) {
6787 				pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
6788 					i, name);
6789 				return -ESRCH;
6790 			}
6791 		} else if (is_prog_array) {
6792 			targ_prog = bpf_object__find_program_by_name(obj, name);
6793 			if (!targ_prog) {
6794 				pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
6795 					i, name);
6796 				return -ESRCH;
6797 			}
6798 			if (targ_prog->sec_idx != sym->st_shndx ||
6799 			    targ_prog->sec_insn_off * 8 != sym->st_value ||
6800 			    prog_is_subprog(obj, targ_prog)) {
6801 				pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
6802 					i, name);
6803 				return -LIBBPF_ERRNO__RELOC;
6804 			}
6805 		} else {
6806 			return -EINVAL;
6807 		}
6808 
6809 		var = btf__type_by_id(obj->btf, vi->type);
6810 		def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
6811 		if (btf_vlen(def) == 0)
6812 			return -EINVAL;
6813 		member = btf_members(def) + btf_vlen(def) - 1;
6814 		mname = btf__name_by_offset(obj->btf, member->name_off);
6815 		if (strcmp(mname, "values"))
6816 			return -EINVAL;
6817 
6818 		moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
6819 		if (rel->r_offset - vi->offset < moff)
6820 			return -EINVAL;
6821 
6822 		moff = rel->r_offset - vi->offset - moff;
6823 		/* here we use BPF pointer size, which is always 64 bit, as we
6824 		 * are parsing ELF that was built for BPF target
6825 		 */
6826 		if (moff % bpf_ptr_sz)
6827 			return -EINVAL;
6828 		moff /= bpf_ptr_sz;
6829 		if (moff >= map->init_slots_sz) {
6830 			new_sz = moff + 1;
6831 			tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
6832 			if (!tmp)
6833 				return -ENOMEM;
6834 			map->init_slots = tmp;
6835 			memset(map->init_slots + map->init_slots_sz, 0,
6836 			       (new_sz - map->init_slots_sz) * host_ptr_sz);
6837 			map->init_slots_sz = new_sz;
6838 		}
6839 		map->init_slots[moff] = is_map_in_map ? (void *)targ_map : (void *)targ_prog;
6840 
6841 		pr_debug(".maps relo #%d: map '%s' slot [%d] points to %s '%s'\n",
6842 			 i, map->name, moff, type, name);
6843 	}
6844 
6845 	return 0;
6846 }
6847 
6848 static int bpf_object__collect_relos(struct bpf_object *obj)
6849 {
6850 	int i, err;
6851 
6852 	for (i = 0; i < obj->efile.sec_cnt; i++) {
6853 		struct elf_sec_desc *sec_desc = &obj->efile.secs[i];
6854 		Elf64_Shdr *shdr;
6855 		Elf_Data *data;
6856 		int idx;
6857 
6858 		if (sec_desc->sec_type != SEC_RELO)
6859 			continue;
6860 
6861 		shdr = sec_desc->shdr;
6862 		data = sec_desc->data;
6863 		idx = shdr->sh_info;
6864 
6865 		if (shdr->sh_type != SHT_REL) {
6866 			pr_warn("internal error at %d\n", __LINE__);
6867 			return -LIBBPF_ERRNO__INTERNAL;
6868 		}
6869 
6870 		if (idx == obj->efile.st_ops_shndx || idx == obj->efile.st_ops_link_shndx)
6871 			err = bpf_object__collect_st_ops_relos(obj, shdr, data);
6872 		else if (idx == obj->efile.btf_maps_shndx)
6873 			err = bpf_object__collect_map_relos(obj, shdr, data);
6874 		else
6875 			err = bpf_object__collect_prog_relos(obj, shdr, data);
6876 		if (err)
6877 			return err;
6878 	}
6879 
6880 	bpf_object__sort_relos(obj);
6881 	return 0;
6882 }
6883 
6884 static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
6885 {
6886 	if (BPF_CLASS(insn->code) == BPF_JMP &&
6887 	    BPF_OP(insn->code) == BPF_CALL &&
6888 	    BPF_SRC(insn->code) == BPF_K &&
6889 	    insn->src_reg == 0 &&
6890 	    insn->dst_reg == 0) {
6891 		    *func_id = insn->imm;
6892 		    return true;
6893 	}
6894 	return false;
6895 }
6896 
6897 static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
6898 {
6899 	struct bpf_insn *insn = prog->insns;
6900 	enum bpf_func_id func_id;
6901 	int i;
6902 
6903 	if (obj->gen_loader)
6904 		return 0;
6905 
6906 	for (i = 0; i < prog->insns_cnt; i++, insn++) {
6907 		if (!insn_is_helper_call(insn, &func_id))
6908 			continue;
6909 
6910 		/* on kernels that don't yet support
6911 		 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
6912 		 * to bpf_probe_read() which works well for old kernels
6913 		 */
6914 		switch (func_id) {
6915 		case BPF_FUNC_probe_read_kernel:
6916 		case BPF_FUNC_probe_read_user:
6917 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6918 				insn->imm = BPF_FUNC_probe_read;
6919 			break;
6920 		case BPF_FUNC_probe_read_kernel_str:
6921 		case BPF_FUNC_probe_read_user_str:
6922 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6923 				insn->imm = BPF_FUNC_probe_read_str;
6924 			break;
6925 		default:
6926 			break;
6927 		}
6928 	}
6929 	return 0;
6930 }
6931 
6932 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
6933 				     int *btf_obj_fd, int *btf_type_id);
6934 
6935 /* this is called as prog->sec_def->prog_prepare_load_fn for libbpf-supported sec_defs */
6936 static int libbpf_prepare_prog_load(struct bpf_program *prog,
6937 				    struct bpf_prog_load_opts *opts, long cookie)
6938 {
6939 	enum sec_def_flags def = cookie;
6940 
6941 	/* old kernels might not support specifying expected_attach_type */
6942 	if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
6943 		opts->expected_attach_type = 0;
6944 
6945 	if (def & SEC_SLEEPABLE)
6946 		opts->prog_flags |= BPF_F_SLEEPABLE;
6947 
6948 	if (prog->type == BPF_PROG_TYPE_XDP && (def & SEC_XDP_FRAGS))
6949 		opts->prog_flags |= BPF_F_XDP_HAS_FRAGS;
6950 
6951 	/* special check for usdt to use uprobe_multi link */
6952 	if ((def & SEC_USDT) && kernel_supports(prog->obj, FEAT_UPROBE_MULTI_LINK))
6953 		prog->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
6954 
6955 	if ((def & SEC_ATTACH_BTF) && !prog->attach_btf_id) {
6956 		int btf_obj_fd = 0, btf_type_id = 0, err;
6957 		const char *attach_name;
6958 
6959 		attach_name = strchr(prog->sec_name, '/');
6960 		if (!attach_name) {
6961 			/* if BPF program is annotated with just SEC("fentry")
6962 			 * (or similar) without declaratively specifying
6963 			 * target, then it is expected that target will be
6964 			 * specified with bpf_program__set_attach_target() at
6965 			 * runtime before BPF object load step. If not, then
6966 			 * there is nothing to load into the kernel as BPF
6967 			 * verifier won't be able to validate BPF program
6968 			 * correctness anyways.
6969 			 */
6970 			pr_warn("prog '%s': no BTF-based attach target is specified, use bpf_program__set_attach_target()\n",
6971 				prog->name);
6972 			return -EINVAL;
6973 		}
6974 		attach_name++; /* skip over / */
6975 
6976 		err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
6977 		if (err)
6978 			return err;
6979 
6980 		/* cache resolved BTF FD and BTF type ID in the prog */
6981 		prog->attach_btf_obj_fd = btf_obj_fd;
6982 		prog->attach_btf_id = btf_type_id;
6983 
6984 		/* but by now libbpf common logic is not utilizing
6985 		 * prog->atach_btf_obj_fd/prog->attach_btf_id anymore because
6986 		 * this callback is called after opts were populated by
6987 		 * libbpf, so this callback has to update opts explicitly here
6988 		 */
6989 		opts->attach_btf_obj_fd = btf_obj_fd;
6990 		opts->attach_btf_id = btf_type_id;
6991 	}
6992 	return 0;
6993 }
6994 
6995 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz);
6996 
6997 static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
6998 				struct bpf_insn *insns, int insns_cnt,
6999 				const char *license, __u32 kern_version, int *prog_fd)
7000 {
7001 	LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
7002 	const char *prog_name = NULL;
7003 	char *cp, errmsg[STRERR_BUFSIZE];
7004 	size_t log_buf_size = 0;
7005 	char *log_buf = NULL, *tmp;
7006 	int btf_fd, ret, err;
7007 	bool own_log_buf = true;
7008 	__u32 log_level = prog->log_level;
7009 
7010 	if (prog->type == BPF_PROG_TYPE_UNSPEC) {
7011 		/*
7012 		 * The program type must be set.  Most likely we couldn't find a proper
7013 		 * section definition at load time, and thus we didn't infer the type.
7014 		 */
7015 		pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
7016 			prog->name, prog->sec_name);
7017 		return -EINVAL;
7018 	}
7019 
7020 	if (!insns || !insns_cnt)
7021 		return -EINVAL;
7022 
7023 	if (kernel_supports(obj, FEAT_PROG_NAME))
7024 		prog_name = prog->name;
7025 	load_attr.attach_prog_fd = prog->attach_prog_fd;
7026 	load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
7027 	load_attr.attach_btf_id = prog->attach_btf_id;
7028 	load_attr.kern_version = kern_version;
7029 	load_attr.prog_ifindex = prog->prog_ifindex;
7030 
7031 	/* specify func_info/line_info only if kernel supports them */
7032 	btf_fd = bpf_object__btf_fd(obj);
7033 	if (btf_fd >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
7034 		load_attr.prog_btf_fd = btf_fd;
7035 		load_attr.func_info = prog->func_info;
7036 		load_attr.func_info_rec_size = prog->func_info_rec_size;
7037 		load_attr.func_info_cnt = prog->func_info_cnt;
7038 		load_attr.line_info = prog->line_info;
7039 		load_attr.line_info_rec_size = prog->line_info_rec_size;
7040 		load_attr.line_info_cnt = prog->line_info_cnt;
7041 	}
7042 	load_attr.log_level = log_level;
7043 	load_attr.prog_flags = prog->prog_flags;
7044 	load_attr.fd_array = obj->fd_array;
7045 
7046 	/* adjust load_attr if sec_def provides custom preload callback */
7047 	if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
7048 		err = prog->sec_def->prog_prepare_load_fn(prog, &load_attr, prog->sec_def->cookie);
7049 		if (err < 0) {
7050 			pr_warn("prog '%s': failed to prepare load attributes: %d\n",
7051 				prog->name, err);
7052 			return err;
7053 		}
7054 		insns = prog->insns;
7055 		insns_cnt = prog->insns_cnt;
7056 	}
7057 
7058 	/* allow prog_prepare_load_fn to change expected_attach_type */
7059 	load_attr.expected_attach_type = prog->expected_attach_type;
7060 
7061 	if (obj->gen_loader) {
7062 		bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
7063 				   license, insns, insns_cnt, &load_attr,
7064 				   prog - obj->programs);
7065 		*prog_fd = -1;
7066 		return 0;
7067 	}
7068 
7069 retry_load:
7070 	/* if log_level is zero, we don't request logs initially even if
7071 	 * custom log_buf is specified; if the program load fails, then we'll
7072 	 * bump log_level to 1 and use either custom log_buf or we'll allocate
7073 	 * our own and retry the load to get details on what failed
7074 	 */
7075 	if (log_level) {
7076 		if (prog->log_buf) {
7077 			log_buf = prog->log_buf;
7078 			log_buf_size = prog->log_size;
7079 			own_log_buf = false;
7080 		} else if (obj->log_buf) {
7081 			log_buf = obj->log_buf;
7082 			log_buf_size = obj->log_size;
7083 			own_log_buf = false;
7084 		} else {
7085 			log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
7086 			tmp = realloc(log_buf, log_buf_size);
7087 			if (!tmp) {
7088 				ret = -ENOMEM;
7089 				goto out;
7090 			}
7091 			log_buf = tmp;
7092 			log_buf[0] = '\0';
7093 			own_log_buf = true;
7094 		}
7095 	}
7096 
7097 	load_attr.log_buf = log_buf;
7098 	load_attr.log_size = log_buf_size;
7099 	load_attr.log_level = log_level;
7100 
7101 	ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
7102 	if (ret >= 0) {
7103 		if (log_level && own_log_buf) {
7104 			pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
7105 				 prog->name, log_buf);
7106 		}
7107 
7108 		if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
7109 			struct bpf_map *map;
7110 			int i;
7111 
7112 			for (i = 0; i < obj->nr_maps; i++) {
7113 				map = &prog->obj->maps[i];
7114 				if (map->libbpf_type != LIBBPF_MAP_RODATA)
7115 					continue;
7116 
7117 				if (bpf_prog_bind_map(ret, bpf_map__fd(map), NULL)) {
7118 					cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
7119 					pr_warn("prog '%s': failed to bind map '%s': %s\n",
7120 						prog->name, map->real_name, cp);
7121 					/* Don't fail hard if can't bind rodata. */
7122 				}
7123 			}
7124 		}
7125 
7126 		*prog_fd = ret;
7127 		ret = 0;
7128 		goto out;
7129 	}
7130 
7131 	if (log_level == 0) {
7132 		log_level = 1;
7133 		goto retry_load;
7134 	}
7135 	/* On ENOSPC, increase log buffer size and retry, unless custom
7136 	 * log_buf is specified.
7137 	 * Be careful to not overflow u32, though. Kernel's log buf size limit
7138 	 * isn't part of UAPI so it can always be bumped to full 4GB. So don't
7139 	 * multiply by 2 unless we are sure we'll fit within 32 bits.
7140 	 * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
7141 	 */
7142 	if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
7143 		goto retry_load;
7144 
7145 	ret = -errno;
7146 
7147 	/* post-process verifier log to improve error descriptions */
7148 	fixup_verifier_log(prog, log_buf, log_buf_size);
7149 
7150 	cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
7151 	pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, cp);
7152 	pr_perm_msg(ret);
7153 
7154 	if (own_log_buf && log_buf && log_buf[0] != '\0') {
7155 		pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
7156 			prog->name, log_buf);
7157 	}
7158 
7159 out:
7160 	if (own_log_buf)
7161 		free(log_buf);
7162 	return ret;
7163 }
7164 
7165 static char *find_prev_line(char *buf, char *cur)
7166 {
7167 	char *p;
7168 
7169 	if (cur == buf) /* end of a log buf */
7170 		return NULL;
7171 
7172 	p = cur - 1;
7173 	while (p - 1 >= buf && *(p - 1) != '\n')
7174 		p--;
7175 
7176 	return p;
7177 }
7178 
7179 static void patch_log(char *buf, size_t buf_sz, size_t log_sz,
7180 		      char *orig, size_t orig_sz, const char *patch)
7181 {
7182 	/* size of the remaining log content to the right from the to-be-replaced part */
7183 	size_t rem_sz = (buf + log_sz) - (orig + orig_sz);
7184 	size_t patch_sz = strlen(patch);
7185 
7186 	if (patch_sz != orig_sz) {
7187 		/* If patch line(s) are longer than original piece of verifier log,
7188 		 * shift log contents by (patch_sz - orig_sz) bytes to the right
7189 		 * starting from after to-be-replaced part of the log.
7190 		 *
7191 		 * If patch line(s) are shorter than original piece of verifier log,
7192 		 * shift log contents by (orig_sz - patch_sz) bytes to the left
7193 		 * starting from after to-be-replaced part of the log
7194 		 *
7195 		 * We need to be careful about not overflowing available
7196 		 * buf_sz capacity. If that's the case, we'll truncate the end
7197 		 * of the original log, as necessary.
7198 		 */
7199 		if (patch_sz > orig_sz) {
7200 			if (orig + patch_sz >= buf + buf_sz) {
7201 				/* patch is big enough to cover remaining space completely */
7202 				patch_sz -= (orig + patch_sz) - (buf + buf_sz) + 1;
7203 				rem_sz = 0;
7204 			} else if (patch_sz - orig_sz > buf_sz - log_sz) {
7205 				/* patch causes part of remaining log to be truncated */
7206 				rem_sz -= (patch_sz - orig_sz) - (buf_sz - log_sz);
7207 			}
7208 		}
7209 		/* shift remaining log to the right by calculated amount */
7210 		memmove(orig + patch_sz, orig + orig_sz, rem_sz);
7211 	}
7212 
7213 	memcpy(orig, patch, patch_sz);
7214 }
7215 
7216 static void fixup_log_failed_core_relo(struct bpf_program *prog,
7217 				       char *buf, size_t buf_sz, size_t log_sz,
7218 				       char *line1, char *line2, char *line3)
7219 {
7220 	/* Expected log for failed and not properly guarded CO-RE relocation:
7221 	 * line1 -> 123: (85) call unknown#195896080
7222 	 * line2 -> invalid func unknown#195896080
7223 	 * line3 -> <anything else or end of buffer>
7224 	 *
7225 	 * "123" is the index of the instruction that was poisoned. We extract
7226 	 * instruction index to find corresponding CO-RE relocation and
7227 	 * replace this part of the log with more relevant information about
7228 	 * failed CO-RE relocation.
7229 	 */
7230 	const struct bpf_core_relo *relo;
7231 	struct bpf_core_spec spec;
7232 	char patch[512], spec_buf[256];
7233 	int insn_idx, err, spec_len;
7234 
7235 	if (sscanf(line1, "%d: (%*d) call unknown#195896080\n", &insn_idx) != 1)
7236 		return;
7237 
7238 	relo = find_relo_core(prog, insn_idx);
7239 	if (!relo)
7240 		return;
7241 
7242 	err = bpf_core_parse_spec(prog->name, prog->obj->btf, relo, &spec);
7243 	if (err)
7244 		return;
7245 
7246 	spec_len = bpf_core_format_spec(spec_buf, sizeof(spec_buf), &spec);
7247 	snprintf(patch, sizeof(patch),
7248 		 "%d: <invalid CO-RE relocation>\n"
7249 		 "failed to resolve CO-RE relocation %s%s\n",
7250 		 insn_idx, spec_buf, spec_len >= sizeof(spec_buf) ? "..." : "");
7251 
7252 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7253 }
7254 
7255 static void fixup_log_missing_map_load(struct bpf_program *prog,
7256 				       char *buf, size_t buf_sz, size_t log_sz,
7257 				       char *line1, char *line2, char *line3)
7258 {
7259 	/* Expected log for failed and not properly guarded map reference:
7260 	 * line1 -> 123: (85) call unknown#2001000345
7261 	 * line2 -> invalid func unknown#2001000345
7262 	 * line3 -> <anything else or end of buffer>
7263 	 *
7264 	 * "123" is the index of the instruction that was poisoned.
7265 	 * "345" in "2001000345" is a map index in obj->maps to fetch map name.
7266 	 */
7267 	struct bpf_object *obj = prog->obj;
7268 	const struct bpf_map *map;
7269 	int insn_idx, map_idx;
7270 	char patch[128];
7271 
7272 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &map_idx) != 2)
7273 		return;
7274 
7275 	map_idx -= POISON_LDIMM64_MAP_BASE;
7276 	if (map_idx < 0 || map_idx >= obj->nr_maps)
7277 		return;
7278 	map = &obj->maps[map_idx];
7279 
7280 	snprintf(patch, sizeof(patch),
7281 		 "%d: <invalid BPF map reference>\n"
7282 		 "BPF map '%s' is referenced but wasn't created\n",
7283 		 insn_idx, map->name);
7284 
7285 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7286 }
7287 
7288 static void fixup_log_missing_kfunc_call(struct bpf_program *prog,
7289 					 char *buf, size_t buf_sz, size_t log_sz,
7290 					 char *line1, char *line2, char *line3)
7291 {
7292 	/* Expected log for failed and not properly guarded kfunc call:
7293 	 * line1 -> 123: (85) call unknown#2002000345
7294 	 * line2 -> invalid func unknown#2002000345
7295 	 * line3 -> <anything else or end of buffer>
7296 	 *
7297 	 * "123" is the index of the instruction that was poisoned.
7298 	 * "345" in "2002000345" is an extern index in obj->externs to fetch kfunc name.
7299 	 */
7300 	struct bpf_object *obj = prog->obj;
7301 	const struct extern_desc *ext;
7302 	int insn_idx, ext_idx;
7303 	char patch[128];
7304 
7305 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &ext_idx) != 2)
7306 		return;
7307 
7308 	ext_idx -= POISON_CALL_KFUNC_BASE;
7309 	if (ext_idx < 0 || ext_idx >= obj->nr_extern)
7310 		return;
7311 	ext = &obj->externs[ext_idx];
7312 
7313 	snprintf(patch, sizeof(patch),
7314 		 "%d: <invalid kfunc call>\n"
7315 		 "kfunc '%s' is referenced but wasn't resolved\n",
7316 		 insn_idx, ext->name);
7317 
7318 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7319 }
7320 
7321 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz)
7322 {
7323 	/* look for familiar error patterns in last N lines of the log */
7324 	const size_t max_last_line_cnt = 10;
7325 	char *prev_line, *cur_line, *next_line;
7326 	size_t log_sz;
7327 	int i;
7328 
7329 	if (!buf)
7330 		return;
7331 
7332 	log_sz = strlen(buf) + 1;
7333 	next_line = buf + log_sz - 1;
7334 
7335 	for (i = 0; i < max_last_line_cnt; i++, next_line = cur_line) {
7336 		cur_line = find_prev_line(buf, next_line);
7337 		if (!cur_line)
7338 			return;
7339 
7340 		if (str_has_pfx(cur_line, "invalid func unknown#195896080\n")) {
7341 			prev_line = find_prev_line(buf, cur_line);
7342 			if (!prev_line)
7343 				continue;
7344 
7345 			/* failed CO-RE relocation case */
7346 			fixup_log_failed_core_relo(prog, buf, buf_sz, log_sz,
7347 						   prev_line, cur_line, next_line);
7348 			return;
7349 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_LDIMM64_MAP_PFX)) {
7350 			prev_line = find_prev_line(buf, cur_line);
7351 			if (!prev_line)
7352 				continue;
7353 
7354 			/* reference to uncreated BPF map */
7355 			fixup_log_missing_map_load(prog, buf, buf_sz, log_sz,
7356 						   prev_line, cur_line, next_line);
7357 			return;
7358 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_CALL_KFUNC_PFX)) {
7359 			prev_line = find_prev_line(buf, cur_line);
7360 			if (!prev_line)
7361 				continue;
7362 
7363 			/* reference to unresolved kfunc */
7364 			fixup_log_missing_kfunc_call(prog, buf, buf_sz, log_sz,
7365 						     prev_line, cur_line, next_line);
7366 			return;
7367 		}
7368 	}
7369 }
7370 
7371 static int bpf_program_record_relos(struct bpf_program *prog)
7372 {
7373 	struct bpf_object *obj = prog->obj;
7374 	int i;
7375 
7376 	for (i = 0; i < prog->nr_reloc; i++) {
7377 		struct reloc_desc *relo = &prog->reloc_desc[i];
7378 		struct extern_desc *ext = &obj->externs[relo->ext_idx];
7379 		int kind;
7380 
7381 		switch (relo->type) {
7382 		case RELO_EXTERN_LD64:
7383 			if (ext->type != EXT_KSYM)
7384 				continue;
7385 			kind = btf_is_var(btf__type_by_id(obj->btf, ext->btf_id)) ?
7386 				BTF_KIND_VAR : BTF_KIND_FUNC;
7387 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7388 					       ext->is_weak, !ext->ksym.type_id,
7389 					       true, kind, relo->insn_idx);
7390 			break;
7391 		case RELO_EXTERN_CALL:
7392 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7393 					       ext->is_weak, false, false, BTF_KIND_FUNC,
7394 					       relo->insn_idx);
7395 			break;
7396 		case RELO_CORE: {
7397 			struct bpf_core_relo cr = {
7398 				.insn_off = relo->insn_idx * 8,
7399 				.type_id = relo->core_relo->type_id,
7400 				.access_str_off = relo->core_relo->access_str_off,
7401 				.kind = relo->core_relo->kind,
7402 			};
7403 
7404 			bpf_gen__record_relo_core(obj->gen_loader, &cr);
7405 			break;
7406 		}
7407 		default:
7408 			continue;
7409 		}
7410 	}
7411 	return 0;
7412 }
7413 
7414 static int
7415 bpf_object__load_progs(struct bpf_object *obj, int log_level)
7416 {
7417 	struct bpf_program *prog;
7418 	size_t i;
7419 	int err;
7420 
7421 	for (i = 0; i < obj->nr_programs; i++) {
7422 		prog = &obj->programs[i];
7423 		err = bpf_object__sanitize_prog(obj, prog);
7424 		if (err)
7425 			return err;
7426 	}
7427 
7428 	for (i = 0; i < obj->nr_programs; i++) {
7429 		prog = &obj->programs[i];
7430 		if (prog_is_subprog(obj, prog))
7431 			continue;
7432 		if (!prog->autoload) {
7433 			pr_debug("prog '%s': skipped loading\n", prog->name);
7434 			continue;
7435 		}
7436 		prog->log_level |= log_level;
7437 
7438 		if (obj->gen_loader)
7439 			bpf_program_record_relos(prog);
7440 
7441 		err = bpf_object_load_prog(obj, prog, prog->insns, prog->insns_cnt,
7442 					   obj->license, obj->kern_version, &prog->fd);
7443 		if (err) {
7444 			pr_warn("prog '%s': failed to load: %d\n", prog->name, err);
7445 			return err;
7446 		}
7447 	}
7448 
7449 	bpf_object__free_relocs(obj);
7450 	return 0;
7451 }
7452 
7453 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
7454 
7455 static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
7456 {
7457 	struct bpf_program *prog;
7458 	int err;
7459 
7460 	bpf_object__for_each_program(prog, obj) {
7461 		prog->sec_def = find_sec_def(prog->sec_name);
7462 		if (!prog->sec_def) {
7463 			/* couldn't guess, but user might manually specify */
7464 			pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
7465 				prog->name, prog->sec_name);
7466 			continue;
7467 		}
7468 
7469 		prog->type = prog->sec_def->prog_type;
7470 		prog->expected_attach_type = prog->sec_def->expected_attach_type;
7471 
7472 		/* sec_def can have custom callback which should be called
7473 		 * after bpf_program is initialized to adjust its properties
7474 		 */
7475 		if (prog->sec_def->prog_setup_fn) {
7476 			err = prog->sec_def->prog_setup_fn(prog, prog->sec_def->cookie);
7477 			if (err < 0) {
7478 				pr_warn("prog '%s': failed to initialize: %d\n",
7479 					prog->name, err);
7480 				return err;
7481 			}
7482 		}
7483 	}
7484 
7485 	return 0;
7486 }
7487 
7488 static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
7489 					  const struct bpf_object_open_opts *opts)
7490 {
7491 	const char *obj_name, *kconfig, *btf_tmp_path;
7492 	struct bpf_object *obj;
7493 	char tmp_name[64];
7494 	int err;
7495 	char *log_buf;
7496 	size_t log_size;
7497 	__u32 log_level;
7498 
7499 	if (elf_version(EV_CURRENT) == EV_NONE) {
7500 		pr_warn("failed to init libelf for %s\n",
7501 			path ? : "(mem buf)");
7502 		return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
7503 	}
7504 
7505 	if (!OPTS_VALID(opts, bpf_object_open_opts))
7506 		return ERR_PTR(-EINVAL);
7507 
7508 	obj_name = OPTS_GET(opts, object_name, NULL);
7509 	if (obj_buf) {
7510 		if (!obj_name) {
7511 			snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
7512 				 (unsigned long)obj_buf,
7513 				 (unsigned long)obj_buf_sz);
7514 			obj_name = tmp_name;
7515 		}
7516 		path = obj_name;
7517 		pr_debug("loading object '%s' from buffer\n", obj_name);
7518 	}
7519 
7520 	log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
7521 	log_size = OPTS_GET(opts, kernel_log_size, 0);
7522 	log_level = OPTS_GET(opts, kernel_log_level, 0);
7523 	if (log_size > UINT_MAX)
7524 		return ERR_PTR(-EINVAL);
7525 	if (log_size && !log_buf)
7526 		return ERR_PTR(-EINVAL);
7527 
7528 	obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
7529 	if (IS_ERR(obj))
7530 		return obj;
7531 
7532 	obj->log_buf = log_buf;
7533 	obj->log_size = log_size;
7534 	obj->log_level = log_level;
7535 
7536 	btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
7537 	if (btf_tmp_path) {
7538 		if (strlen(btf_tmp_path) >= PATH_MAX) {
7539 			err = -ENAMETOOLONG;
7540 			goto out;
7541 		}
7542 		obj->btf_custom_path = strdup(btf_tmp_path);
7543 		if (!obj->btf_custom_path) {
7544 			err = -ENOMEM;
7545 			goto out;
7546 		}
7547 	}
7548 
7549 	kconfig = OPTS_GET(opts, kconfig, NULL);
7550 	if (kconfig) {
7551 		obj->kconfig = strdup(kconfig);
7552 		if (!obj->kconfig) {
7553 			err = -ENOMEM;
7554 			goto out;
7555 		}
7556 	}
7557 
7558 	err = bpf_object__elf_init(obj);
7559 	err = err ? : bpf_object__check_endianness(obj);
7560 	err = err ? : bpf_object__elf_collect(obj);
7561 	err = err ? : bpf_object__collect_externs(obj);
7562 	err = err ? : bpf_object_fixup_btf(obj);
7563 	err = err ? : bpf_object__init_maps(obj, opts);
7564 	err = err ? : bpf_object_init_progs(obj, opts);
7565 	err = err ? : bpf_object__collect_relos(obj);
7566 	if (err)
7567 		goto out;
7568 
7569 	bpf_object__elf_finish(obj);
7570 
7571 	return obj;
7572 out:
7573 	bpf_object__close(obj);
7574 	return ERR_PTR(err);
7575 }
7576 
7577 struct bpf_object *
7578 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
7579 {
7580 	if (!path)
7581 		return libbpf_err_ptr(-EINVAL);
7582 
7583 	pr_debug("loading %s\n", path);
7584 
7585 	return libbpf_ptr(bpf_object_open(path, NULL, 0, opts));
7586 }
7587 
7588 struct bpf_object *bpf_object__open(const char *path)
7589 {
7590 	return bpf_object__open_file(path, NULL);
7591 }
7592 
7593 struct bpf_object *
7594 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
7595 		     const struct bpf_object_open_opts *opts)
7596 {
7597 	if (!obj_buf || obj_buf_sz == 0)
7598 		return libbpf_err_ptr(-EINVAL);
7599 
7600 	return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, opts));
7601 }
7602 
7603 static int bpf_object_unload(struct bpf_object *obj)
7604 {
7605 	size_t i;
7606 
7607 	if (!obj)
7608 		return libbpf_err(-EINVAL);
7609 
7610 	for (i = 0; i < obj->nr_maps; i++) {
7611 		zclose(obj->maps[i].fd);
7612 		if (obj->maps[i].st_ops)
7613 			zfree(&obj->maps[i].st_ops->kern_vdata);
7614 	}
7615 
7616 	for (i = 0; i < obj->nr_programs; i++)
7617 		bpf_program__unload(&obj->programs[i]);
7618 
7619 	return 0;
7620 }
7621 
7622 static int bpf_object__sanitize_maps(struct bpf_object *obj)
7623 {
7624 	struct bpf_map *m;
7625 
7626 	bpf_object__for_each_map(m, obj) {
7627 		if (!bpf_map__is_internal(m))
7628 			continue;
7629 		if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
7630 			m->def.map_flags &= ~BPF_F_MMAPABLE;
7631 	}
7632 
7633 	return 0;
7634 }
7635 
7636 int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
7637 {
7638 	char sym_type, sym_name[500];
7639 	unsigned long long sym_addr;
7640 	int ret, err = 0;
7641 	FILE *f;
7642 
7643 	f = fopen("/proc/kallsyms", "re");
7644 	if (!f) {
7645 		err = -errno;
7646 		pr_warn("failed to open /proc/kallsyms: %d\n", err);
7647 		return err;
7648 	}
7649 
7650 	while (true) {
7651 		ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
7652 			     &sym_addr, &sym_type, sym_name);
7653 		if (ret == EOF && feof(f))
7654 			break;
7655 		if (ret != 3) {
7656 			pr_warn("failed to read kallsyms entry: %d\n", ret);
7657 			err = -EINVAL;
7658 			break;
7659 		}
7660 
7661 		err = cb(sym_addr, sym_type, sym_name, ctx);
7662 		if (err)
7663 			break;
7664 	}
7665 
7666 	fclose(f);
7667 	return err;
7668 }
7669 
7670 static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
7671 		       const char *sym_name, void *ctx)
7672 {
7673 	struct bpf_object *obj = ctx;
7674 	const struct btf_type *t;
7675 	struct extern_desc *ext;
7676 
7677 	ext = find_extern_by_name(obj, sym_name);
7678 	if (!ext || ext->type != EXT_KSYM)
7679 		return 0;
7680 
7681 	t = btf__type_by_id(obj->btf, ext->btf_id);
7682 	if (!btf_is_var(t))
7683 		return 0;
7684 
7685 	if (ext->is_set && ext->ksym.addr != sym_addr) {
7686 		pr_warn("extern (ksym) '%s': resolution is ambiguous: 0x%llx or 0x%llx\n",
7687 			sym_name, ext->ksym.addr, sym_addr);
7688 		return -EINVAL;
7689 	}
7690 	if (!ext->is_set) {
7691 		ext->is_set = true;
7692 		ext->ksym.addr = sym_addr;
7693 		pr_debug("extern (ksym) '%s': set to 0x%llx\n", sym_name, sym_addr);
7694 	}
7695 	return 0;
7696 }
7697 
7698 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
7699 {
7700 	return libbpf_kallsyms_parse(kallsyms_cb, obj);
7701 }
7702 
7703 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
7704 			    __u16 kind, struct btf **res_btf,
7705 			    struct module_btf **res_mod_btf)
7706 {
7707 	struct module_btf *mod_btf;
7708 	struct btf *btf;
7709 	int i, id, err;
7710 
7711 	btf = obj->btf_vmlinux;
7712 	mod_btf = NULL;
7713 	id = btf__find_by_name_kind(btf, ksym_name, kind);
7714 
7715 	if (id == -ENOENT) {
7716 		err = load_module_btfs(obj);
7717 		if (err)
7718 			return err;
7719 
7720 		for (i = 0; i < obj->btf_module_cnt; i++) {
7721 			/* we assume module_btf's BTF FD is always >0 */
7722 			mod_btf = &obj->btf_modules[i];
7723 			btf = mod_btf->btf;
7724 			id = btf__find_by_name_kind_own(btf, ksym_name, kind);
7725 			if (id != -ENOENT)
7726 				break;
7727 		}
7728 	}
7729 	if (id <= 0)
7730 		return -ESRCH;
7731 
7732 	*res_btf = btf;
7733 	*res_mod_btf = mod_btf;
7734 	return id;
7735 }
7736 
7737 static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
7738 					       struct extern_desc *ext)
7739 {
7740 	const struct btf_type *targ_var, *targ_type;
7741 	__u32 targ_type_id, local_type_id;
7742 	struct module_btf *mod_btf = NULL;
7743 	const char *targ_var_name;
7744 	struct btf *btf = NULL;
7745 	int id, err;
7746 
7747 	id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
7748 	if (id < 0) {
7749 		if (id == -ESRCH && ext->is_weak)
7750 			return 0;
7751 		pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
7752 			ext->name);
7753 		return id;
7754 	}
7755 
7756 	/* find local type_id */
7757 	local_type_id = ext->ksym.type_id;
7758 
7759 	/* find target type_id */
7760 	targ_var = btf__type_by_id(btf, id);
7761 	targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
7762 	targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
7763 
7764 	err = bpf_core_types_are_compat(obj->btf, local_type_id,
7765 					btf, targ_type_id);
7766 	if (err <= 0) {
7767 		const struct btf_type *local_type;
7768 		const char *targ_name, *local_name;
7769 
7770 		local_type = btf__type_by_id(obj->btf, local_type_id);
7771 		local_name = btf__name_by_offset(obj->btf, local_type->name_off);
7772 		targ_name = btf__name_by_offset(btf, targ_type->name_off);
7773 
7774 		pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
7775 			ext->name, local_type_id,
7776 			btf_kind_str(local_type), local_name, targ_type_id,
7777 			btf_kind_str(targ_type), targ_name);
7778 		return -EINVAL;
7779 	}
7780 
7781 	ext->is_set = true;
7782 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
7783 	ext->ksym.kernel_btf_id = id;
7784 	pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
7785 		 ext->name, id, btf_kind_str(targ_var), targ_var_name);
7786 
7787 	return 0;
7788 }
7789 
7790 static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
7791 						struct extern_desc *ext)
7792 {
7793 	int local_func_proto_id, kfunc_proto_id, kfunc_id;
7794 	struct module_btf *mod_btf = NULL;
7795 	const struct btf_type *kern_func;
7796 	struct btf *kern_btf = NULL;
7797 	int ret;
7798 
7799 	local_func_proto_id = ext->ksym.type_id;
7800 
7801 	kfunc_id = find_ksym_btf_id(obj, ext->essent_name ?: ext->name, BTF_KIND_FUNC, &kern_btf,
7802 				    &mod_btf);
7803 	if (kfunc_id < 0) {
7804 		if (kfunc_id == -ESRCH && ext->is_weak)
7805 			return 0;
7806 		pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
7807 			ext->name);
7808 		return kfunc_id;
7809 	}
7810 
7811 	kern_func = btf__type_by_id(kern_btf, kfunc_id);
7812 	kfunc_proto_id = kern_func->type;
7813 
7814 	ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
7815 					kern_btf, kfunc_proto_id);
7816 	if (ret <= 0) {
7817 		if (ext->is_weak)
7818 			return 0;
7819 
7820 		pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with %s [%d]\n",
7821 			ext->name, local_func_proto_id,
7822 			mod_btf ? mod_btf->name : "vmlinux", kfunc_proto_id);
7823 		return -EINVAL;
7824 	}
7825 
7826 	/* set index for module BTF fd in fd_array, if unset */
7827 	if (mod_btf && !mod_btf->fd_array_idx) {
7828 		/* insn->off is s16 */
7829 		if (obj->fd_array_cnt == INT16_MAX) {
7830 			pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
7831 				ext->name, mod_btf->fd_array_idx);
7832 			return -E2BIG;
7833 		}
7834 		/* Cannot use index 0 for module BTF fd */
7835 		if (!obj->fd_array_cnt)
7836 			obj->fd_array_cnt = 1;
7837 
7838 		ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
7839 					obj->fd_array_cnt + 1);
7840 		if (ret)
7841 			return ret;
7842 		mod_btf->fd_array_idx = obj->fd_array_cnt;
7843 		/* we assume module BTF FD is always >0 */
7844 		obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
7845 	}
7846 
7847 	ext->is_set = true;
7848 	ext->ksym.kernel_btf_id = kfunc_id;
7849 	ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
7850 	/* Also set kernel_btf_obj_fd to make sure that bpf_object__relocate_data()
7851 	 * populates FD into ld_imm64 insn when it's used to point to kfunc.
7852 	 * {kernel_btf_id, btf_fd_idx} -> fixup bpf_call.
7853 	 * {kernel_btf_id, kernel_btf_obj_fd} -> fixup ld_imm64.
7854 	 */
7855 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
7856 	pr_debug("extern (func ksym) '%s': resolved to %s [%d]\n",
7857 		 ext->name, mod_btf ? mod_btf->name : "vmlinux", kfunc_id);
7858 
7859 	return 0;
7860 }
7861 
7862 static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
7863 {
7864 	const struct btf_type *t;
7865 	struct extern_desc *ext;
7866 	int i, err;
7867 
7868 	for (i = 0; i < obj->nr_extern; i++) {
7869 		ext = &obj->externs[i];
7870 		if (ext->type != EXT_KSYM || !ext->ksym.type_id)
7871 			continue;
7872 
7873 		if (obj->gen_loader) {
7874 			ext->is_set = true;
7875 			ext->ksym.kernel_btf_obj_fd = 0;
7876 			ext->ksym.kernel_btf_id = 0;
7877 			continue;
7878 		}
7879 		t = btf__type_by_id(obj->btf, ext->btf_id);
7880 		if (btf_is_var(t))
7881 			err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
7882 		else
7883 			err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
7884 		if (err)
7885 			return err;
7886 	}
7887 	return 0;
7888 }
7889 
7890 static int bpf_object__resolve_externs(struct bpf_object *obj,
7891 				       const char *extra_kconfig)
7892 {
7893 	bool need_config = false, need_kallsyms = false;
7894 	bool need_vmlinux_btf = false;
7895 	struct extern_desc *ext;
7896 	void *kcfg_data = NULL;
7897 	int err, i;
7898 
7899 	if (obj->nr_extern == 0)
7900 		return 0;
7901 
7902 	if (obj->kconfig_map_idx >= 0)
7903 		kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
7904 
7905 	for (i = 0; i < obj->nr_extern; i++) {
7906 		ext = &obj->externs[i];
7907 
7908 		if (ext->type == EXT_KSYM) {
7909 			if (ext->ksym.type_id)
7910 				need_vmlinux_btf = true;
7911 			else
7912 				need_kallsyms = true;
7913 			continue;
7914 		} else if (ext->type == EXT_KCFG) {
7915 			void *ext_ptr = kcfg_data + ext->kcfg.data_off;
7916 			__u64 value = 0;
7917 
7918 			/* Kconfig externs need actual /proc/config.gz */
7919 			if (str_has_pfx(ext->name, "CONFIG_")) {
7920 				need_config = true;
7921 				continue;
7922 			}
7923 
7924 			/* Virtual kcfg externs are customly handled by libbpf */
7925 			if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
7926 				value = get_kernel_version();
7927 				if (!value) {
7928 					pr_warn("extern (kcfg) '%s': failed to get kernel version\n", ext->name);
7929 					return -EINVAL;
7930 				}
7931 			} else if (strcmp(ext->name, "LINUX_HAS_BPF_COOKIE") == 0) {
7932 				value = kernel_supports(obj, FEAT_BPF_COOKIE);
7933 			} else if (strcmp(ext->name, "LINUX_HAS_SYSCALL_WRAPPER") == 0) {
7934 				value = kernel_supports(obj, FEAT_SYSCALL_WRAPPER);
7935 			} else if (!str_has_pfx(ext->name, "LINUX_") || !ext->is_weak) {
7936 				/* Currently libbpf supports only CONFIG_ and LINUX_ prefixed
7937 				 * __kconfig externs, where LINUX_ ones are virtual and filled out
7938 				 * customly by libbpf (their values don't come from Kconfig).
7939 				 * If LINUX_xxx variable is not recognized by libbpf, but is marked
7940 				 * __weak, it defaults to zero value, just like for CONFIG_xxx
7941 				 * externs.
7942 				 */
7943 				pr_warn("extern (kcfg) '%s': unrecognized virtual extern\n", ext->name);
7944 				return -EINVAL;
7945 			}
7946 
7947 			err = set_kcfg_value_num(ext, ext_ptr, value);
7948 			if (err)
7949 				return err;
7950 			pr_debug("extern (kcfg) '%s': set to 0x%llx\n",
7951 				 ext->name, (long long)value);
7952 		} else {
7953 			pr_warn("extern '%s': unrecognized extern kind\n", ext->name);
7954 			return -EINVAL;
7955 		}
7956 	}
7957 	if (need_config && extra_kconfig) {
7958 		err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
7959 		if (err)
7960 			return -EINVAL;
7961 		need_config = false;
7962 		for (i = 0; i < obj->nr_extern; i++) {
7963 			ext = &obj->externs[i];
7964 			if (ext->type == EXT_KCFG && !ext->is_set) {
7965 				need_config = true;
7966 				break;
7967 			}
7968 		}
7969 	}
7970 	if (need_config) {
7971 		err = bpf_object__read_kconfig_file(obj, kcfg_data);
7972 		if (err)
7973 			return -EINVAL;
7974 	}
7975 	if (need_kallsyms) {
7976 		err = bpf_object__read_kallsyms_file(obj);
7977 		if (err)
7978 			return -EINVAL;
7979 	}
7980 	if (need_vmlinux_btf) {
7981 		err = bpf_object__resolve_ksyms_btf_id(obj);
7982 		if (err)
7983 			return -EINVAL;
7984 	}
7985 	for (i = 0; i < obj->nr_extern; i++) {
7986 		ext = &obj->externs[i];
7987 
7988 		if (!ext->is_set && !ext->is_weak) {
7989 			pr_warn("extern '%s' (strong): not resolved\n", ext->name);
7990 			return -ESRCH;
7991 		} else if (!ext->is_set) {
7992 			pr_debug("extern '%s' (weak): not resolved, defaulting to zero\n",
7993 				 ext->name);
7994 		}
7995 	}
7996 
7997 	return 0;
7998 }
7999 
8000 static void bpf_map_prepare_vdata(const struct bpf_map *map)
8001 {
8002 	struct bpf_struct_ops *st_ops;
8003 	__u32 i;
8004 
8005 	st_ops = map->st_ops;
8006 	for (i = 0; i < btf_vlen(st_ops->type); i++) {
8007 		struct bpf_program *prog = st_ops->progs[i];
8008 		void *kern_data;
8009 		int prog_fd;
8010 
8011 		if (!prog)
8012 			continue;
8013 
8014 		prog_fd = bpf_program__fd(prog);
8015 		kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
8016 		*(unsigned long *)kern_data = prog_fd;
8017 	}
8018 }
8019 
8020 static int bpf_object_prepare_struct_ops(struct bpf_object *obj)
8021 {
8022 	int i;
8023 
8024 	for (i = 0; i < obj->nr_maps; i++)
8025 		if (bpf_map__is_struct_ops(&obj->maps[i]))
8026 			bpf_map_prepare_vdata(&obj->maps[i]);
8027 
8028 	return 0;
8029 }
8030 
8031 static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
8032 {
8033 	int err, i;
8034 
8035 	if (!obj)
8036 		return libbpf_err(-EINVAL);
8037 
8038 	if (obj->loaded) {
8039 		pr_warn("object '%s': load can't be attempted twice\n", obj->name);
8040 		return libbpf_err(-EINVAL);
8041 	}
8042 
8043 	if (obj->gen_loader)
8044 		bpf_gen__init(obj->gen_loader, extra_log_level, obj->nr_programs, obj->nr_maps);
8045 
8046 	err = bpf_object__probe_loading(obj);
8047 	err = err ? : bpf_object__load_vmlinux_btf(obj, false);
8048 	err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
8049 	err = err ? : bpf_object__sanitize_and_load_btf(obj);
8050 	err = err ? : bpf_object__sanitize_maps(obj);
8051 	err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
8052 	err = err ? : bpf_object__create_maps(obj);
8053 	err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
8054 	err = err ? : bpf_object__load_progs(obj, extra_log_level);
8055 	err = err ? : bpf_object_init_prog_arrays(obj);
8056 	err = err ? : bpf_object_prepare_struct_ops(obj);
8057 
8058 	if (obj->gen_loader) {
8059 		/* reset FDs */
8060 		if (obj->btf)
8061 			btf__set_fd(obj->btf, -1);
8062 		for (i = 0; i < obj->nr_maps; i++)
8063 			obj->maps[i].fd = -1;
8064 		if (!err)
8065 			err = bpf_gen__finish(obj->gen_loader, obj->nr_programs, obj->nr_maps);
8066 	}
8067 
8068 	/* clean up fd_array */
8069 	zfree(&obj->fd_array);
8070 
8071 	/* clean up module BTFs */
8072 	for (i = 0; i < obj->btf_module_cnt; i++) {
8073 		close(obj->btf_modules[i].fd);
8074 		btf__free(obj->btf_modules[i].btf);
8075 		free(obj->btf_modules[i].name);
8076 	}
8077 	free(obj->btf_modules);
8078 
8079 	/* clean up vmlinux BTF */
8080 	btf__free(obj->btf_vmlinux);
8081 	obj->btf_vmlinux = NULL;
8082 
8083 	obj->loaded = true; /* doesn't matter if successfully or not */
8084 
8085 	if (err)
8086 		goto out;
8087 
8088 	return 0;
8089 out:
8090 	/* unpin any maps that were auto-pinned during load */
8091 	for (i = 0; i < obj->nr_maps; i++)
8092 		if (obj->maps[i].pinned && !obj->maps[i].reused)
8093 			bpf_map__unpin(&obj->maps[i], NULL);
8094 
8095 	bpf_object_unload(obj);
8096 	pr_warn("failed to load object '%s'\n", obj->path);
8097 	return libbpf_err(err);
8098 }
8099 
8100 int bpf_object__load(struct bpf_object *obj)
8101 {
8102 	return bpf_object_load(obj, 0, NULL);
8103 }
8104 
8105 static int make_parent_dir(const char *path)
8106 {
8107 	char *cp, errmsg[STRERR_BUFSIZE];
8108 	char *dname, *dir;
8109 	int err = 0;
8110 
8111 	dname = strdup(path);
8112 	if (dname == NULL)
8113 		return -ENOMEM;
8114 
8115 	dir = dirname(dname);
8116 	if (mkdir(dir, 0700) && errno != EEXIST)
8117 		err = -errno;
8118 
8119 	free(dname);
8120 	if (err) {
8121 		cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
8122 		pr_warn("failed to mkdir %s: %s\n", path, cp);
8123 	}
8124 	return err;
8125 }
8126 
8127 static int check_path(const char *path)
8128 {
8129 	char *cp, errmsg[STRERR_BUFSIZE];
8130 	struct statfs st_fs;
8131 	char *dname, *dir;
8132 	int err = 0;
8133 
8134 	if (path == NULL)
8135 		return -EINVAL;
8136 
8137 	dname = strdup(path);
8138 	if (dname == NULL)
8139 		return -ENOMEM;
8140 
8141 	dir = dirname(dname);
8142 	if (statfs(dir, &st_fs)) {
8143 		cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
8144 		pr_warn("failed to statfs %s: %s\n", dir, cp);
8145 		err = -errno;
8146 	}
8147 	free(dname);
8148 
8149 	if (!err && st_fs.f_type != BPF_FS_MAGIC) {
8150 		pr_warn("specified path %s is not on BPF FS\n", path);
8151 		err = -EINVAL;
8152 	}
8153 
8154 	return err;
8155 }
8156 
8157 int bpf_program__pin(struct bpf_program *prog, const char *path)
8158 {
8159 	char *cp, errmsg[STRERR_BUFSIZE];
8160 	int err;
8161 
8162 	if (prog->fd < 0) {
8163 		pr_warn("prog '%s': can't pin program that wasn't loaded\n", prog->name);
8164 		return libbpf_err(-EINVAL);
8165 	}
8166 
8167 	err = make_parent_dir(path);
8168 	if (err)
8169 		return libbpf_err(err);
8170 
8171 	err = check_path(path);
8172 	if (err)
8173 		return libbpf_err(err);
8174 
8175 	if (bpf_obj_pin(prog->fd, path)) {
8176 		err = -errno;
8177 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
8178 		pr_warn("prog '%s': failed to pin at '%s': %s\n", prog->name, path, cp);
8179 		return libbpf_err(err);
8180 	}
8181 
8182 	pr_debug("prog '%s': pinned at '%s'\n", prog->name, path);
8183 	return 0;
8184 }
8185 
8186 int bpf_program__unpin(struct bpf_program *prog, const char *path)
8187 {
8188 	int err;
8189 
8190 	if (prog->fd < 0) {
8191 		pr_warn("prog '%s': can't unpin program that wasn't loaded\n", prog->name);
8192 		return libbpf_err(-EINVAL);
8193 	}
8194 
8195 	err = check_path(path);
8196 	if (err)
8197 		return libbpf_err(err);
8198 
8199 	err = unlink(path);
8200 	if (err)
8201 		return libbpf_err(-errno);
8202 
8203 	pr_debug("prog '%s': unpinned from '%s'\n", prog->name, path);
8204 	return 0;
8205 }
8206 
8207 int bpf_map__pin(struct bpf_map *map, const char *path)
8208 {
8209 	char *cp, errmsg[STRERR_BUFSIZE];
8210 	int err;
8211 
8212 	if (map == NULL) {
8213 		pr_warn("invalid map pointer\n");
8214 		return libbpf_err(-EINVAL);
8215 	}
8216 
8217 	if (map->pin_path) {
8218 		if (path && strcmp(path, map->pin_path)) {
8219 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8220 				bpf_map__name(map), map->pin_path, path);
8221 			return libbpf_err(-EINVAL);
8222 		} else if (map->pinned) {
8223 			pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
8224 				 bpf_map__name(map), map->pin_path);
8225 			return 0;
8226 		}
8227 	} else {
8228 		if (!path) {
8229 			pr_warn("missing a path to pin map '%s' at\n",
8230 				bpf_map__name(map));
8231 			return libbpf_err(-EINVAL);
8232 		} else if (map->pinned) {
8233 			pr_warn("map '%s' already pinned\n", bpf_map__name(map));
8234 			return libbpf_err(-EEXIST);
8235 		}
8236 
8237 		map->pin_path = strdup(path);
8238 		if (!map->pin_path) {
8239 			err = -errno;
8240 			goto out_err;
8241 		}
8242 	}
8243 
8244 	err = make_parent_dir(map->pin_path);
8245 	if (err)
8246 		return libbpf_err(err);
8247 
8248 	err = check_path(map->pin_path);
8249 	if (err)
8250 		return libbpf_err(err);
8251 
8252 	if (bpf_obj_pin(map->fd, map->pin_path)) {
8253 		err = -errno;
8254 		goto out_err;
8255 	}
8256 
8257 	map->pinned = true;
8258 	pr_debug("pinned map '%s'\n", map->pin_path);
8259 
8260 	return 0;
8261 
8262 out_err:
8263 	cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
8264 	pr_warn("failed to pin map: %s\n", cp);
8265 	return libbpf_err(err);
8266 }
8267 
8268 int bpf_map__unpin(struct bpf_map *map, const char *path)
8269 {
8270 	int err;
8271 
8272 	if (map == NULL) {
8273 		pr_warn("invalid map pointer\n");
8274 		return libbpf_err(-EINVAL);
8275 	}
8276 
8277 	if (map->pin_path) {
8278 		if (path && strcmp(path, map->pin_path)) {
8279 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8280 				bpf_map__name(map), map->pin_path, path);
8281 			return libbpf_err(-EINVAL);
8282 		}
8283 		path = map->pin_path;
8284 	} else if (!path) {
8285 		pr_warn("no path to unpin map '%s' from\n",
8286 			bpf_map__name(map));
8287 		return libbpf_err(-EINVAL);
8288 	}
8289 
8290 	err = check_path(path);
8291 	if (err)
8292 		return libbpf_err(err);
8293 
8294 	err = unlink(path);
8295 	if (err != 0)
8296 		return libbpf_err(-errno);
8297 
8298 	map->pinned = false;
8299 	pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
8300 
8301 	return 0;
8302 }
8303 
8304 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
8305 {
8306 	char *new = NULL;
8307 
8308 	if (path) {
8309 		new = strdup(path);
8310 		if (!new)
8311 			return libbpf_err(-errno);
8312 	}
8313 
8314 	free(map->pin_path);
8315 	map->pin_path = new;
8316 	return 0;
8317 }
8318 
8319 __alias(bpf_map__pin_path)
8320 const char *bpf_map__get_pin_path(const struct bpf_map *map);
8321 
8322 const char *bpf_map__pin_path(const struct bpf_map *map)
8323 {
8324 	return map->pin_path;
8325 }
8326 
8327 bool bpf_map__is_pinned(const struct bpf_map *map)
8328 {
8329 	return map->pinned;
8330 }
8331 
8332 static void sanitize_pin_path(char *s)
8333 {
8334 	/* bpffs disallows periods in path names */
8335 	while (*s) {
8336 		if (*s == '.')
8337 			*s = '_';
8338 		s++;
8339 	}
8340 }
8341 
8342 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
8343 {
8344 	struct bpf_map *map;
8345 	int err;
8346 
8347 	if (!obj)
8348 		return libbpf_err(-ENOENT);
8349 
8350 	if (!obj->loaded) {
8351 		pr_warn("object not yet loaded; load it first\n");
8352 		return libbpf_err(-ENOENT);
8353 	}
8354 
8355 	bpf_object__for_each_map(map, obj) {
8356 		char *pin_path = NULL;
8357 		char buf[PATH_MAX];
8358 
8359 		if (!map->autocreate)
8360 			continue;
8361 
8362 		if (path) {
8363 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8364 			if (err)
8365 				goto err_unpin_maps;
8366 			sanitize_pin_path(buf);
8367 			pin_path = buf;
8368 		} else if (!map->pin_path) {
8369 			continue;
8370 		}
8371 
8372 		err = bpf_map__pin(map, pin_path);
8373 		if (err)
8374 			goto err_unpin_maps;
8375 	}
8376 
8377 	return 0;
8378 
8379 err_unpin_maps:
8380 	while ((map = bpf_object__prev_map(obj, map))) {
8381 		if (!map->pin_path)
8382 			continue;
8383 
8384 		bpf_map__unpin(map, NULL);
8385 	}
8386 
8387 	return libbpf_err(err);
8388 }
8389 
8390 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
8391 {
8392 	struct bpf_map *map;
8393 	int err;
8394 
8395 	if (!obj)
8396 		return libbpf_err(-ENOENT);
8397 
8398 	bpf_object__for_each_map(map, obj) {
8399 		char *pin_path = NULL;
8400 		char buf[PATH_MAX];
8401 
8402 		if (path) {
8403 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8404 			if (err)
8405 				return libbpf_err(err);
8406 			sanitize_pin_path(buf);
8407 			pin_path = buf;
8408 		} else if (!map->pin_path) {
8409 			continue;
8410 		}
8411 
8412 		err = bpf_map__unpin(map, pin_path);
8413 		if (err)
8414 			return libbpf_err(err);
8415 	}
8416 
8417 	return 0;
8418 }
8419 
8420 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
8421 {
8422 	struct bpf_program *prog;
8423 	char buf[PATH_MAX];
8424 	int err;
8425 
8426 	if (!obj)
8427 		return libbpf_err(-ENOENT);
8428 
8429 	if (!obj->loaded) {
8430 		pr_warn("object not yet loaded; load it first\n");
8431 		return libbpf_err(-ENOENT);
8432 	}
8433 
8434 	bpf_object__for_each_program(prog, obj) {
8435 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
8436 		if (err)
8437 			goto err_unpin_programs;
8438 
8439 		err = bpf_program__pin(prog, buf);
8440 		if (err)
8441 			goto err_unpin_programs;
8442 	}
8443 
8444 	return 0;
8445 
8446 err_unpin_programs:
8447 	while ((prog = bpf_object__prev_program(obj, prog))) {
8448 		if (pathname_concat(buf, sizeof(buf), path, prog->name))
8449 			continue;
8450 
8451 		bpf_program__unpin(prog, buf);
8452 	}
8453 
8454 	return libbpf_err(err);
8455 }
8456 
8457 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
8458 {
8459 	struct bpf_program *prog;
8460 	int err;
8461 
8462 	if (!obj)
8463 		return libbpf_err(-ENOENT);
8464 
8465 	bpf_object__for_each_program(prog, obj) {
8466 		char buf[PATH_MAX];
8467 
8468 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
8469 		if (err)
8470 			return libbpf_err(err);
8471 
8472 		err = bpf_program__unpin(prog, buf);
8473 		if (err)
8474 			return libbpf_err(err);
8475 	}
8476 
8477 	return 0;
8478 }
8479 
8480 int bpf_object__pin(struct bpf_object *obj, const char *path)
8481 {
8482 	int err;
8483 
8484 	err = bpf_object__pin_maps(obj, path);
8485 	if (err)
8486 		return libbpf_err(err);
8487 
8488 	err = bpf_object__pin_programs(obj, path);
8489 	if (err) {
8490 		bpf_object__unpin_maps(obj, path);
8491 		return libbpf_err(err);
8492 	}
8493 
8494 	return 0;
8495 }
8496 
8497 int bpf_object__unpin(struct bpf_object *obj, const char *path)
8498 {
8499 	int err;
8500 
8501 	err = bpf_object__unpin_programs(obj, path);
8502 	if (err)
8503 		return libbpf_err(err);
8504 
8505 	err = bpf_object__unpin_maps(obj, path);
8506 	if (err)
8507 		return libbpf_err(err);
8508 
8509 	return 0;
8510 }
8511 
8512 static void bpf_map__destroy(struct bpf_map *map)
8513 {
8514 	if (map->inner_map) {
8515 		bpf_map__destroy(map->inner_map);
8516 		zfree(&map->inner_map);
8517 	}
8518 
8519 	zfree(&map->init_slots);
8520 	map->init_slots_sz = 0;
8521 
8522 	if (map->mmaped) {
8523 		size_t mmap_sz;
8524 
8525 		mmap_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
8526 		munmap(map->mmaped, mmap_sz);
8527 		map->mmaped = NULL;
8528 	}
8529 
8530 	if (map->st_ops) {
8531 		zfree(&map->st_ops->data);
8532 		zfree(&map->st_ops->progs);
8533 		zfree(&map->st_ops->kern_func_off);
8534 		zfree(&map->st_ops);
8535 	}
8536 
8537 	zfree(&map->name);
8538 	zfree(&map->real_name);
8539 	zfree(&map->pin_path);
8540 
8541 	if (map->fd >= 0)
8542 		zclose(map->fd);
8543 }
8544 
8545 void bpf_object__close(struct bpf_object *obj)
8546 {
8547 	size_t i;
8548 
8549 	if (IS_ERR_OR_NULL(obj))
8550 		return;
8551 
8552 	usdt_manager_free(obj->usdt_man);
8553 	obj->usdt_man = NULL;
8554 
8555 	bpf_gen__free(obj->gen_loader);
8556 	bpf_object__elf_finish(obj);
8557 	bpf_object_unload(obj);
8558 	btf__free(obj->btf);
8559 	btf__free(obj->btf_vmlinux);
8560 	btf_ext__free(obj->btf_ext);
8561 
8562 	for (i = 0; i < obj->nr_maps; i++)
8563 		bpf_map__destroy(&obj->maps[i]);
8564 
8565 	zfree(&obj->btf_custom_path);
8566 	zfree(&obj->kconfig);
8567 
8568 	for (i = 0; i < obj->nr_extern; i++)
8569 		zfree(&obj->externs[i].essent_name);
8570 
8571 	zfree(&obj->externs);
8572 	obj->nr_extern = 0;
8573 
8574 	zfree(&obj->maps);
8575 	obj->nr_maps = 0;
8576 
8577 	if (obj->programs && obj->nr_programs) {
8578 		for (i = 0; i < obj->nr_programs; i++)
8579 			bpf_program__exit(&obj->programs[i]);
8580 	}
8581 	zfree(&obj->programs);
8582 
8583 	free(obj);
8584 }
8585 
8586 const char *bpf_object__name(const struct bpf_object *obj)
8587 {
8588 	return obj ? obj->name : libbpf_err_ptr(-EINVAL);
8589 }
8590 
8591 unsigned int bpf_object__kversion(const struct bpf_object *obj)
8592 {
8593 	return obj ? obj->kern_version : 0;
8594 }
8595 
8596 struct btf *bpf_object__btf(const struct bpf_object *obj)
8597 {
8598 	return obj ? obj->btf : NULL;
8599 }
8600 
8601 int bpf_object__btf_fd(const struct bpf_object *obj)
8602 {
8603 	return obj->btf ? btf__fd(obj->btf) : -1;
8604 }
8605 
8606 int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
8607 {
8608 	if (obj->loaded)
8609 		return libbpf_err(-EINVAL);
8610 
8611 	obj->kern_version = kern_version;
8612 
8613 	return 0;
8614 }
8615 
8616 int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
8617 {
8618 	struct bpf_gen *gen;
8619 
8620 	if (!opts)
8621 		return -EFAULT;
8622 	if (!OPTS_VALID(opts, gen_loader_opts))
8623 		return -EINVAL;
8624 	gen = calloc(sizeof(*gen), 1);
8625 	if (!gen)
8626 		return -ENOMEM;
8627 	gen->opts = opts;
8628 	obj->gen_loader = gen;
8629 	return 0;
8630 }
8631 
8632 static struct bpf_program *
8633 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
8634 		    bool forward)
8635 {
8636 	size_t nr_programs = obj->nr_programs;
8637 	ssize_t idx;
8638 
8639 	if (!nr_programs)
8640 		return NULL;
8641 
8642 	if (!p)
8643 		/* Iter from the beginning */
8644 		return forward ? &obj->programs[0] :
8645 			&obj->programs[nr_programs - 1];
8646 
8647 	if (p->obj != obj) {
8648 		pr_warn("error: program handler doesn't match object\n");
8649 		return errno = EINVAL, NULL;
8650 	}
8651 
8652 	idx = (p - obj->programs) + (forward ? 1 : -1);
8653 	if (idx >= obj->nr_programs || idx < 0)
8654 		return NULL;
8655 	return &obj->programs[idx];
8656 }
8657 
8658 struct bpf_program *
8659 bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
8660 {
8661 	struct bpf_program *prog = prev;
8662 
8663 	do {
8664 		prog = __bpf_program__iter(prog, obj, true);
8665 	} while (prog && prog_is_subprog(obj, prog));
8666 
8667 	return prog;
8668 }
8669 
8670 struct bpf_program *
8671 bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
8672 {
8673 	struct bpf_program *prog = next;
8674 
8675 	do {
8676 		prog = __bpf_program__iter(prog, obj, false);
8677 	} while (prog && prog_is_subprog(obj, prog));
8678 
8679 	return prog;
8680 }
8681 
8682 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
8683 {
8684 	prog->prog_ifindex = ifindex;
8685 }
8686 
8687 const char *bpf_program__name(const struct bpf_program *prog)
8688 {
8689 	return prog->name;
8690 }
8691 
8692 const char *bpf_program__section_name(const struct bpf_program *prog)
8693 {
8694 	return prog->sec_name;
8695 }
8696 
8697 bool bpf_program__autoload(const struct bpf_program *prog)
8698 {
8699 	return prog->autoload;
8700 }
8701 
8702 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
8703 {
8704 	if (prog->obj->loaded)
8705 		return libbpf_err(-EINVAL);
8706 
8707 	prog->autoload = autoload;
8708 	return 0;
8709 }
8710 
8711 bool bpf_program__autoattach(const struct bpf_program *prog)
8712 {
8713 	return prog->autoattach;
8714 }
8715 
8716 void bpf_program__set_autoattach(struct bpf_program *prog, bool autoattach)
8717 {
8718 	prog->autoattach = autoattach;
8719 }
8720 
8721 const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
8722 {
8723 	return prog->insns;
8724 }
8725 
8726 size_t bpf_program__insn_cnt(const struct bpf_program *prog)
8727 {
8728 	return prog->insns_cnt;
8729 }
8730 
8731 int bpf_program__set_insns(struct bpf_program *prog,
8732 			   struct bpf_insn *new_insns, size_t new_insn_cnt)
8733 {
8734 	struct bpf_insn *insns;
8735 
8736 	if (prog->obj->loaded)
8737 		return -EBUSY;
8738 
8739 	insns = libbpf_reallocarray(prog->insns, new_insn_cnt, sizeof(*insns));
8740 	/* NULL is a valid return from reallocarray if the new count is zero */
8741 	if (!insns && new_insn_cnt) {
8742 		pr_warn("prog '%s': failed to realloc prog code\n", prog->name);
8743 		return -ENOMEM;
8744 	}
8745 	memcpy(insns, new_insns, new_insn_cnt * sizeof(*insns));
8746 
8747 	prog->insns = insns;
8748 	prog->insns_cnt = new_insn_cnt;
8749 	return 0;
8750 }
8751 
8752 int bpf_program__fd(const struct bpf_program *prog)
8753 {
8754 	if (!prog)
8755 		return libbpf_err(-EINVAL);
8756 
8757 	if (prog->fd < 0)
8758 		return libbpf_err(-ENOENT);
8759 
8760 	return prog->fd;
8761 }
8762 
8763 __alias(bpf_program__type)
8764 enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog);
8765 
8766 enum bpf_prog_type bpf_program__type(const struct bpf_program *prog)
8767 {
8768 	return prog->type;
8769 }
8770 
8771 static size_t custom_sec_def_cnt;
8772 static struct bpf_sec_def *custom_sec_defs;
8773 static struct bpf_sec_def custom_fallback_def;
8774 static bool has_custom_fallback_def;
8775 static int last_custom_sec_def_handler_id;
8776 
8777 int bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
8778 {
8779 	if (prog->obj->loaded)
8780 		return libbpf_err(-EBUSY);
8781 
8782 	/* if type is not changed, do nothing */
8783 	if (prog->type == type)
8784 		return 0;
8785 
8786 	prog->type = type;
8787 
8788 	/* If a program type was changed, we need to reset associated SEC()
8789 	 * handler, as it will be invalid now. The only exception is a generic
8790 	 * fallback handler, which by definition is program type-agnostic and
8791 	 * is a catch-all custom handler, optionally set by the application,
8792 	 * so should be able to handle any type of BPF program.
8793 	 */
8794 	if (prog->sec_def != &custom_fallback_def)
8795 		prog->sec_def = NULL;
8796 	return 0;
8797 }
8798 
8799 __alias(bpf_program__expected_attach_type)
8800 enum bpf_attach_type bpf_program__get_expected_attach_type(const struct bpf_program *prog);
8801 
8802 enum bpf_attach_type bpf_program__expected_attach_type(const struct bpf_program *prog)
8803 {
8804 	return prog->expected_attach_type;
8805 }
8806 
8807 int bpf_program__set_expected_attach_type(struct bpf_program *prog,
8808 					   enum bpf_attach_type type)
8809 {
8810 	if (prog->obj->loaded)
8811 		return libbpf_err(-EBUSY);
8812 
8813 	prog->expected_attach_type = type;
8814 	return 0;
8815 }
8816 
8817 __u32 bpf_program__flags(const struct bpf_program *prog)
8818 {
8819 	return prog->prog_flags;
8820 }
8821 
8822 int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
8823 {
8824 	if (prog->obj->loaded)
8825 		return libbpf_err(-EBUSY);
8826 
8827 	prog->prog_flags = flags;
8828 	return 0;
8829 }
8830 
8831 __u32 bpf_program__log_level(const struct bpf_program *prog)
8832 {
8833 	return prog->log_level;
8834 }
8835 
8836 int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
8837 {
8838 	if (prog->obj->loaded)
8839 		return libbpf_err(-EBUSY);
8840 
8841 	prog->log_level = log_level;
8842 	return 0;
8843 }
8844 
8845 const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
8846 {
8847 	*log_size = prog->log_size;
8848 	return prog->log_buf;
8849 }
8850 
8851 int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
8852 {
8853 	if (log_size && !log_buf)
8854 		return -EINVAL;
8855 	if (prog->log_size > UINT_MAX)
8856 		return -EINVAL;
8857 	if (prog->obj->loaded)
8858 		return -EBUSY;
8859 
8860 	prog->log_buf = log_buf;
8861 	prog->log_size = log_size;
8862 	return 0;
8863 }
8864 
8865 #define SEC_DEF(sec_pfx, ptype, atype, flags, ...) {			    \
8866 	.sec = (char *)sec_pfx,						    \
8867 	.prog_type = BPF_PROG_TYPE_##ptype,				    \
8868 	.expected_attach_type = atype,					    \
8869 	.cookie = (long)(flags),					    \
8870 	.prog_prepare_load_fn = libbpf_prepare_prog_load,		    \
8871 	__VA_ARGS__							    \
8872 }
8873 
8874 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8875 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8876 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8877 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8878 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8879 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8880 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8881 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8882 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8883 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8884 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8885 
8886 static const struct bpf_sec_def section_defs[] = {
8887 	SEC_DEF("socket",		SOCKET_FILTER, 0, SEC_NONE),
8888 	SEC_DEF("sk_reuseport/migrate",	SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE),
8889 	SEC_DEF("sk_reuseport",		SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE),
8890 	SEC_DEF("kprobe+",		KPROBE,	0, SEC_NONE, attach_kprobe),
8891 	SEC_DEF("uprobe+",		KPROBE,	0, SEC_NONE, attach_uprobe),
8892 	SEC_DEF("uprobe.s+",		KPROBE,	0, SEC_SLEEPABLE, attach_uprobe),
8893 	SEC_DEF("kretprobe+",		KPROBE, 0, SEC_NONE, attach_kprobe),
8894 	SEC_DEF("uretprobe+",		KPROBE, 0, SEC_NONE, attach_uprobe),
8895 	SEC_DEF("uretprobe.s+",		KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
8896 	SEC_DEF("kprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
8897 	SEC_DEF("kretprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
8898 	SEC_DEF("uprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
8899 	SEC_DEF("uretprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
8900 	SEC_DEF("uprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
8901 	SEC_DEF("uretprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
8902 	SEC_DEF("ksyscall+",		KPROBE,	0, SEC_NONE, attach_ksyscall),
8903 	SEC_DEF("kretsyscall+",		KPROBE, 0, SEC_NONE, attach_ksyscall),
8904 	SEC_DEF("usdt+",		KPROBE,	0, SEC_USDT, attach_usdt),
8905 	SEC_DEF("usdt.s+",		KPROBE,	0, SEC_USDT | SEC_SLEEPABLE, attach_usdt),
8906 	SEC_DEF("tc/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE), /* alias for tcx */
8907 	SEC_DEF("tc/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),  /* alias for tcx */
8908 	SEC_DEF("tcx/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE),
8909 	SEC_DEF("tcx/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),
8910 	SEC_DEF("tc",			SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
8911 	SEC_DEF("classifier",		SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
8912 	SEC_DEF("action",		SCHED_ACT, 0, SEC_NONE), /* deprecated / legacy, use tcx */
8913 	SEC_DEF("tracepoint+",		TRACEPOINT, 0, SEC_NONE, attach_tp),
8914 	SEC_DEF("tp+",			TRACEPOINT, 0, SEC_NONE, attach_tp),
8915 	SEC_DEF("raw_tracepoint+",	RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
8916 	SEC_DEF("raw_tp+",		RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
8917 	SEC_DEF("raw_tracepoint.w+",	RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
8918 	SEC_DEF("raw_tp.w+",		RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
8919 	SEC_DEF("tp_btf+",		TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
8920 	SEC_DEF("fentry+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
8921 	SEC_DEF("fmod_ret+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
8922 	SEC_DEF("fexit+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
8923 	SEC_DEF("fentry.s+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8924 	SEC_DEF("fmod_ret.s+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8925 	SEC_DEF("fexit.s+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8926 	SEC_DEF("freplace+",		EXT, 0, SEC_ATTACH_BTF, attach_trace),
8927 	SEC_DEF("lsm+",			LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
8928 	SEC_DEF("lsm.s+",		LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
8929 	SEC_DEF("lsm_cgroup+",		LSM, BPF_LSM_CGROUP, SEC_ATTACH_BTF),
8930 	SEC_DEF("iter+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
8931 	SEC_DEF("iter.s+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_iter),
8932 	SEC_DEF("syscall",		SYSCALL, 0, SEC_SLEEPABLE),
8933 	SEC_DEF("xdp.frags/devmap",	XDP, BPF_XDP_DEVMAP, SEC_XDP_FRAGS),
8934 	SEC_DEF("xdp/devmap",		XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
8935 	SEC_DEF("xdp.frags/cpumap",	XDP, BPF_XDP_CPUMAP, SEC_XDP_FRAGS),
8936 	SEC_DEF("xdp/cpumap",		XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
8937 	SEC_DEF("xdp.frags",		XDP, BPF_XDP, SEC_XDP_FRAGS),
8938 	SEC_DEF("xdp",			XDP, BPF_XDP, SEC_ATTACHABLE_OPT),
8939 	SEC_DEF("perf_event",		PERF_EVENT, 0, SEC_NONE),
8940 	SEC_DEF("lwt_in",		LWT_IN, 0, SEC_NONE),
8941 	SEC_DEF("lwt_out",		LWT_OUT, 0, SEC_NONE),
8942 	SEC_DEF("lwt_xmit",		LWT_XMIT, 0, SEC_NONE),
8943 	SEC_DEF("lwt_seg6local",	LWT_SEG6LOCAL, 0, SEC_NONE),
8944 	SEC_DEF("sockops",		SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT),
8945 	SEC_DEF("sk_skb/stream_parser",	SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT),
8946 	SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT),
8947 	SEC_DEF("sk_skb",		SK_SKB, 0, SEC_NONE),
8948 	SEC_DEF("sk_msg",		SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT),
8949 	SEC_DEF("lirc_mode2",		LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT),
8950 	SEC_DEF("flow_dissector",	FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT),
8951 	SEC_DEF("cgroup_skb/ingress",	CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT),
8952 	SEC_DEF("cgroup_skb/egress",	CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT),
8953 	SEC_DEF("cgroup/skb",		CGROUP_SKB, 0, SEC_NONE),
8954 	SEC_DEF("cgroup/sock_create",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE),
8955 	SEC_DEF("cgroup/sock_release",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE),
8956 	SEC_DEF("cgroup/sock",		CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT),
8957 	SEC_DEF("cgroup/post_bind4",	CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE),
8958 	SEC_DEF("cgroup/post_bind6",	CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE),
8959 	SEC_DEF("cgroup/bind4",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE),
8960 	SEC_DEF("cgroup/bind6",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE),
8961 	SEC_DEF("cgroup/connect4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE),
8962 	SEC_DEF("cgroup/connect6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE),
8963 	SEC_DEF("cgroup/sendmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE),
8964 	SEC_DEF("cgroup/sendmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE),
8965 	SEC_DEF("cgroup/recvmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE),
8966 	SEC_DEF("cgroup/recvmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE),
8967 	SEC_DEF("cgroup/getpeername4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE),
8968 	SEC_DEF("cgroup/getpeername6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE),
8969 	SEC_DEF("cgroup/getsockname4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE),
8970 	SEC_DEF("cgroup/getsockname6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE),
8971 	SEC_DEF("cgroup/sysctl",	CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE),
8972 	SEC_DEF("cgroup/getsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE),
8973 	SEC_DEF("cgroup/setsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE),
8974 	SEC_DEF("cgroup/dev",		CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT),
8975 	SEC_DEF("struct_ops+",		STRUCT_OPS, 0, SEC_NONE),
8976 	SEC_DEF("struct_ops.s+",	STRUCT_OPS, 0, SEC_SLEEPABLE),
8977 	SEC_DEF("sk_lookup",		SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE),
8978 	SEC_DEF("netfilter",		NETFILTER, BPF_NETFILTER, SEC_NONE),
8979 };
8980 
8981 int libbpf_register_prog_handler(const char *sec,
8982 				 enum bpf_prog_type prog_type,
8983 				 enum bpf_attach_type exp_attach_type,
8984 				 const struct libbpf_prog_handler_opts *opts)
8985 {
8986 	struct bpf_sec_def *sec_def;
8987 
8988 	if (!OPTS_VALID(opts, libbpf_prog_handler_opts))
8989 		return libbpf_err(-EINVAL);
8990 
8991 	if (last_custom_sec_def_handler_id == INT_MAX) /* prevent overflow */
8992 		return libbpf_err(-E2BIG);
8993 
8994 	if (sec) {
8995 		sec_def = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt + 1,
8996 					      sizeof(*sec_def));
8997 		if (!sec_def)
8998 			return libbpf_err(-ENOMEM);
8999 
9000 		custom_sec_defs = sec_def;
9001 		sec_def = &custom_sec_defs[custom_sec_def_cnt];
9002 	} else {
9003 		if (has_custom_fallback_def)
9004 			return libbpf_err(-EBUSY);
9005 
9006 		sec_def = &custom_fallback_def;
9007 	}
9008 
9009 	sec_def->sec = sec ? strdup(sec) : NULL;
9010 	if (sec && !sec_def->sec)
9011 		return libbpf_err(-ENOMEM);
9012 
9013 	sec_def->prog_type = prog_type;
9014 	sec_def->expected_attach_type = exp_attach_type;
9015 	sec_def->cookie = OPTS_GET(opts, cookie, 0);
9016 
9017 	sec_def->prog_setup_fn = OPTS_GET(opts, prog_setup_fn, NULL);
9018 	sec_def->prog_prepare_load_fn = OPTS_GET(opts, prog_prepare_load_fn, NULL);
9019 	sec_def->prog_attach_fn = OPTS_GET(opts, prog_attach_fn, NULL);
9020 
9021 	sec_def->handler_id = ++last_custom_sec_def_handler_id;
9022 
9023 	if (sec)
9024 		custom_sec_def_cnt++;
9025 	else
9026 		has_custom_fallback_def = true;
9027 
9028 	return sec_def->handler_id;
9029 }
9030 
9031 int libbpf_unregister_prog_handler(int handler_id)
9032 {
9033 	struct bpf_sec_def *sec_defs;
9034 	int i;
9035 
9036 	if (handler_id <= 0)
9037 		return libbpf_err(-EINVAL);
9038 
9039 	if (has_custom_fallback_def && custom_fallback_def.handler_id == handler_id) {
9040 		memset(&custom_fallback_def, 0, sizeof(custom_fallback_def));
9041 		has_custom_fallback_def = false;
9042 		return 0;
9043 	}
9044 
9045 	for (i = 0; i < custom_sec_def_cnt; i++) {
9046 		if (custom_sec_defs[i].handler_id == handler_id)
9047 			break;
9048 	}
9049 
9050 	if (i == custom_sec_def_cnt)
9051 		return libbpf_err(-ENOENT);
9052 
9053 	free(custom_sec_defs[i].sec);
9054 	for (i = i + 1; i < custom_sec_def_cnt; i++)
9055 		custom_sec_defs[i - 1] = custom_sec_defs[i];
9056 	custom_sec_def_cnt--;
9057 
9058 	/* try to shrink the array, but it's ok if we couldn't */
9059 	sec_defs = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt, sizeof(*sec_defs));
9060 	/* if new count is zero, reallocarray can return a valid NULL result;
9061 	 * in this case the previous pointer will be freed, so we *have to*
9062 	 * reassign old pointer to the new value (even if it's NULL)
9063 	 */
9064 	if (sec_defs || custom_sec_def_cnt == 0)
9065 		custom_sec_defs = sec_defs;
9066 
9067 	return 0;
9068 }
9069 
9070 static bool sec_def_matches(const struct bpf_sec_def *sec_def, const char *sec_name)
9071 {
9072 	size_t len = strlen(sec_def->sec);
9073 
9074 	/* "type/" always has to have proper SEC("type/extras") form */
9075 	if (sec_def->sec[len - 1] == '/') {
9076 		if (str_has_pfx(sec_name, sec_def->sec))
9077 			return true;
9078 		return false;
9079 	}
9080 
9081 	/* "type+" means it can be either exact SEC("type") or
9082 	 * well-formed SEC("type/extras") with proper '/' separator
9083 	 */
9084 	if (sec_def->sec[len - 1] == '+') {
9085 		len--;
9086 		/* not even a prefix */
9087 		if (strncmp(sec_name, sec_def->sec, len) != 0)
9088 			return false;
9089 		/* exact match or has '/' separator */
9090 		if (sec_name[len] == '\0' || sec_name[len] == '/')
9091 			return true;
9092 		return false;
9093 	}
9094 
9095 	return strcmp(sec_name, sec_def->sec) == 0;
9096 }
9097 
9098 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
9099 {
9100 	const struct bpf_sec_def *sec_def;
9101 	int i, n;
9102 
9103 	n = custom_sec_def_cnt;
9104 	for (i = 0; i < n; i++) {
9105 		sec_def = &custom_sec_defs[i];
9106 		if (sec_def_matches(sec_def, sec_name))
9107 			return sec_def;
9108 	}
9109 
9110 	n = ARRAY_SIZE(section_defs);
9111 	for (i = 0; i < n; i++) {
9112 		sec_def = &section_defs[i];
9113 		if (sec_def_matches(sec_def, sec_name))
9114 			return sec_def;
9115 	}
9116 
9117 	if (has_custom_fallback_def)
9118 		return &custom_fallback_def;
9119 
9120 	return NULL;
9121 }
9122 
9123 #define MAX_TYPE_NAME_SIZE 32
9124 
9125 static char *libbpf_get_type_names(bool attach_type)
9126 {
9127 	int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
9128 	char *buf;
9129 
9130 	buf = malloc(len);
9131 	if (!buf)
9132 		return NULL;
9133 
9134 	buf[0] = '\0';
9135 	/* Forge string buf with all available names */
9136 	for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
9137 		const struct bpf_sec_def *sec_def = &section_defs[i];
9138 
9139 		if (attach_type) {
9140 			if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
9141 				continue;
9142 
9143 			if (!(sec_def->cookie & SEC_ATTACHABLE))
9144 				continue;
9145 		}
9146 
9147 		if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
9148 			free(buf);
9149 			return NULL;
9150 		}
9151 		strcat(buf, " ");
9152 		strcat(buf, section_defs[i].sec);
9153 	}
9154 
9155 	return buf;
9156 }
9157 
9158 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
9159 			     enum bpf_attach_type *expected_attach_type)
9160 {
9161 	const struct bpf_sec_def *sec_def;
9162 	char *type_names;
9163 
9164 	if (!name)
9165 		return libbpf_err(-EINVAL);
9166 
9167 	sec_def = find_sec_def(name);
9168 	if (sec_def) {
9169 		*prog_type = sec_def->prog_type;
9170 		*expected_attach_type = sec_def->expected_attach_type;
9171 		return 0;
9172 	}
9173 
9174 	pr_debug("failed to guess program type from ELF section '%s'\n", name);
9175 	type_names = libbpf_get_type_names(false);
9176 	if (type_names != NULL) {
9177 		pr_debug("supported section(type) names are:%s\n", type_names);
9178 		free(type_names);
9179 	}
9180 
9181 	return libbpf_err(-ESRCH);
9182 }
9183 
9184 const char *libbpf_bpf_attach_type_str(enum bpf_attach_type t)
9185 {
9186 	if (t < 0 || t >= ARRAY_SIZE(attach_type_name))
9187 		return NULL;
9188 
9189 	return attach_type_name[t];
9190 }
9191 
9192 const char *libbpf_bpf_link_type_str(enum bpf_link_type t)
9193 {
9194 	if (t < 0 || t >= ARRAY_SIZE(link_type_name))
9195 		return NULL;
9196 
9197 	return link_type_name[t];
9198 }
9199 
9200 const char *libbpf_bpf_map_type_str(enum bpf_map_type t)
9201 {
9202 	if (t < 0 || t >= ARRAY_SIZE(map_type_name))
9203 		return NULL;
9204 
9205 	return map_type_name[t];
9206 }
9207 
9208 const char *libbpf_bpf_prog_type_str(enum bpf_prog_type t)
9209 {
9210 	if (t < 0 || t >= ARRAY_SIZE(prog_type_name))
9211 		return NULL;
9212 
9213 	return prog_type_name[t];
9214 }
9215 
9216 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
9217 						     int sec_idx,
9218 						     size_t offset)
9219 {
9220 	struct bpf_map *map;
9221 	size_t i;
9222 
9223 	for (i = 0; i < obj->nr_maps; i++) {
9224 		map = &obj->maps[i];
9225 		if (!bpf_map__is_struct_ops(map))
9226 			continue;
9227 		if (map->sec_idx == sec_idx &&
9228 		    map->sec_offset <= offset &&
9229 		    offset - map->sec_offset < map->def.value_size)
9230 			return map;
9231 	}
9232 
9233 	return NULL;
9234 }
9235 
9236 /* Collect the reloc from ELF and populate the st_ops->progs[] */
9237 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
9238 					    Elf64_Shdr *shdr, Elf_Data *data)
9239 {
9240 	const struct btf_member *member;
9241 	struct bpf_struct_ops *st_ops;
9242 	struct bpf_program *prog;
9243 	unsigned int shdr_idx;
9244 	const struct btf *btf;
9245 	struct bpf_map *map;
9246 	unsigned int moff, insn_idx;
9247 	const char *name;
9248 	__u32 member_idx;
9249 	Elf64_Sym *sym;
9250 	Elf64_Rel *rel;
9251 	int i, nrels;
9252 
9253 	btf = obj->btf;
9254 	nrels = shdr->sh_size / shdr->sh_entsize;
9255 	for (i = 0; i < nrels; i++) {
9256 		rel = elf_rel_by_idx(data, i);
9257 		if (!rel) {
9258 			pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
9259 			return -LIBBPF_ERRNO__FORMAT;
9260 		}
9261 
9262 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
9263 		if (!sym) {
9264 			pr_warn("struct_ops reloc: symbol %zx not found\n",
9265 				(size_t)ELF64_R_SYM(rel->r_info));
9266 			return -LIBBPF_ERRNO__FORMAT;
9267 		}
9268 
9269 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
9270 		map = find_struct_ops_map_by_offset(obj, shdr->sh_info, rel->r_offset);
9271 		if (!map) {
9272 			pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
9273 				(size_t)rel->r_offset);
9274 			return -EINVAL;
9275 		}
9276 
9277 		moff = rel->r_offset - map->sec_offset;
9278 		shdr_idx = sym->st_shndx;
9279 		st_ops = map->st_ops;
9280 		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",
9281 			 map->name,
9282 			 (long long)(rel->r_info >> 32),
9283 			 (long long)sym->st_value,
9284 			 shdr_idx, (size_t)rel->r_offset,
9285 			 map->sec_offset, sym->st_name, name);
9286 
9287 		if (shdr_idx >= SHN_LORESERVE) {
9288 			pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
9289 				map->name, (size_t)rel->r_offset, shdr_idx);
9290 			return -LIBBPF_ERRNO__RELOC;
9291 		}
9292 		if (sym->st_value % BPF_INSN_SZ) {
9293 			pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
9294 				map->name, (unsigned long long)sym->st_value);
9295 			return -LIBBPF_ERRNO__FORMAT;
9296 		}
9297 		insn_idx = sym->st_value / BPF_INSN_SZ;
9298 
9299 		member = find_member_by_offset(st_ops->type, moff * 8);
9300 		if (!member) {
9301 			pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
9302 				map->name, moff);
9303 			return -EINVAL;
9304 		}
9305 		member_idx = member - btf_members(st_ops->type);
9306 		name = btf__name_by_offset(btf, member->name_off);
9307 
9308 		if (!resolve_func_ptr(btf, member->type, NULL)) {
9309 			pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
9310 				map->name, name);
9311 			return -EINVAL;
9312 		}
9313 
9314 		prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
9315 		if (!prog) {
9316 			pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
9317 				map->name, shdr_idx, name);
9318 			return -EINVAL;
9319 		}
9320 
9321 		/* prevent the use of BPF prog with invalid type */
9322 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
9323 			pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
9324 				map->name, prog->name);
9325 			return -EINVAL;
9326 		}
9327 
9328 		/* if we haven't yet processed this BPF program, record proper
9329 		 * attach_btf_id and member_idx
9330 		 */
9331 		if (!prog->attach_btf_id) {
9332 			prog->attach_btf_id = st_ops->type_id;
9333 			prog->expected_attach_type = member_idx;
9334 		}
9335 
9336 		/* struct_ops BPF prog can be re-used between multiple
9337 		 * .struct_ops & .struct_ops.link as long as it's the
9338 		 * same struct_ops struct definition and the same
9339 		 * function pointer field
9340 		 */
9341 		if (prog->attach_btf_id != st_ops->type_id ||
9342 		    prog->expected_attach_type != member_idx) {
9343 			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",
9344 				map->name, prog->name, prog->sec_name, prog->type,
9345 				prog->attach_btf_id, prog->expected_attach_type, name);
9346 			return -EINVAL;
9347 		}
9348 
9349 		st_ops->progs[member_idx] = prog;
9350 	}
9351 
9352 	return 0;
9353 }
9354 
9355 #define BTF_TRACE_PREFIX "btf_trace_"
9356 #define BTF_LSM_PREFIX "bpf_lsm_"
9357 #define BTF_ITER_PREFIX "bpf_iter_"
9358 #define BTF_MAX_NAME_SIZE 128
9359 
9360 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
9361 				const char **prefix, int *kind)
9362 {
9363 	switch (attach_type) {
9364 	case BPF_TRACE_RAW_TP:
9365 		*prefix = BTF_TRACE_PREFIX;
9366 		*kind = BTF_KIND_TYPEDEF;
9367 		break;
9368 	case BPF_LSM_MAC:
9369 	case BPF_LSM_CGROUP:
9370 		*prefix = BTF_LSM_PREFIX;
9371 		*kind = BTF_KIND_FUNC;
9372 		break;
9373 	case BPF_TRACE_ITER:
9374 		*prefix = BTF_ITER_PREFIX;
9375 		*kind = BTF_KIND_FUNC;
9376 		break;
9377 	default:
9378 		*prefix = "";
9379 		*kind = BTF_KIND_FUNC;
9380 	}
9381 }
9382 
9383 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
9384 				   const char *name, __u32 kind)
9385 {
9386 	char btf_type_name[BTF_MAX_NAME_SIZE];
9387 	int ret;
9388 
9389 	ret = snprintf(btf_type_name, sizeof(btf_type_name),
9390 		       "%s%s", prefix, name);
9391 	/* snprintf returns the number of characters written excluding the
9392 	 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
9393 	 * indicates truncation.
9394 	 */
9395 	if (ret < 0 || ret >= sizeof(btf_type_name))
9396 		return -ENAMETOOLONG;
9397 	return btf__find_by_name_kind(btf, btf_type_name, kind);
9398 }
9399 
9400 static inline int find_attach_btf_id(struct btf *btf, const char *name,
9401 				     enum bpf_attach_type attach_type)
9402 {
9403 	const char *prefix;
9404 	int kind;
9405 
9406 	btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
9407 	return find_btf_by_prefix_kind(btf, prefix, name, kind);
9408 }
9409 
9410 int libbpf_find_vmlinux_btf_id(const char *name,
9411 			       enum bpf_attach_type attach_type)
9412 {
9413 	struct btf *btf;
9414 	int err;
9415 
9416 	btf = btf__load_vmlinux_btf();
9417 	err = libbpf_get_error(btf);
9418 	if (err) {
9419 		pr_warn("vmlinux BTF is not found\n");
9420 		return libbpf_err(err);
9421 	}
9422 
9423 	err = find_attach_btf_id(btf, name, attach_type);
9424 	if (err <= 0)
9425 		pr_warn("%s is not found in vmlinux BTF\n", name);
9426 
9427 	btf__free(btf);
9428 	return libbpf_err(err);
9429 }
9430 
9431 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
9432 {
9433 	struct bpf_prog_info info;
9434 	__u32 info_len = sizeof(info);
9435 	struct btf *btf;
9436 	int err;
9437 
9438 	memset(&info, 0, info_len);
9439 	err = bpf_prog_get_info_by_fd(attach_prog_fd, &info, &info_len);
9440 	if (err) {
9441 		pr_warn("failed bpf_prog_get_info_by_fd for FD %d: %d\n",
9442 			attach_prog_fd, err);
9443 		return err;
9444 	}
9445 
9446 	err = -EINVAL;
9447 	if (!info.btf_id) {
9448 		pr_warn("The target program doesn't have BTF\n");
9449 		goto out;
9450 	}
9451 	btf = btf__load_from_kernel_by_id(info.btf_id);
9452 	err = libbpf_get_error(btf);
9453 	if (err) {
9454 		pr_warn("Failed to get BTF %d of the program: %d\n", info.btf_id, err);
9455 		goto out;
9456 	}
9457 	err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
9458 	btf__free(btf);
9459 	if (err <= 0) {
9460 		pr_warn("%s is not found in prog's BTF\n", name);
9461 		goto out;
9462 	}
9463 out:
9464 	return err;
9465 }
9466 
9467 static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
9468 			      enum bpf_attach_type attach_type,
9469 			      int *btf_obj_fd, int *btf_type_id)
9470 {
9471 	int ret, i;
9472 
9473 	ret = find_attach_btf_id(obj->btf_vmlinux, attach_name, attach_type);
9474 	if (ret > 0) {
9475 		*btf_obj_fd = 0; /* vmlinux BTF */
9476 		*btf_type_id = ret;
9477 		return 0;
9478 	}
9479 	if (ret != -ENOENT)
9480 		return ret;
9481 
9482 	ret = load_module_btfs(obj);
9483 	if (ret)
9484 		return ret;
9485 
9486 	for (i = 0; i < obj->btf_module_cnt; i++) {
9487 		const struct module_btf *mod = &obj->btf_modules[i];
9488 
9489 		ret = find_attach_btf_id(mod->btf, attach_name, attach_type);
9490 		if (ret > 0) {
9491 			*btf_obj_fd = mod->fd;
9492 			*btf_type_id = ret;
9493 			return 0;
9494 		}
9495 		if (ret == -ENOENT)
9496 			continue;
9497 
9498 		return ret;
9499 	}
9500 
9501 	return -ESRCH;
9502 }
9503 
9504 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
9505 				     int *btf_obj_fd, int *btf_type_id)
9506 {
9507 	enum bpf_attach_type attach_type = prog->expected_attach_type;
9508 	__u32 attach_prog_fd = prog->attach_prog_fd;
9509 	int err = 0;
9510 
9511 	/* BPF program's BTF ID */
9512 	if (prog->type == BPF_PROG_TYPE_EXT || attach_prog_fd) {
9513 		if (!attach_prog_fd) {
9514 			pr_warn("prog '%s': attach program FD is not set\n", prog->name);
9515 			return -EINVAL;
9516 		}
9517 		err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd);
9518 		if (err < 0) {
9519 			pr_warn("prog '%s': failed to find BPF program (FD %d) BTF ID for '%s': %d\n",
9520 				 prog->name, attach_prog_fd, attach_name, err);
9521 			return err;
9522 		}
9523 		*btf_obj_fd = 0;
9524 		*btf_type_id = err;
9525 		return 0;
9526 	}
9527 
9528 	/* kernel/module BTF ID */
9529 	if (prog->obj->gen_loader) {
9530 		bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
9531 		*btf_obj_fd = 0;
9532 		*btf_type_id = 1;
9533 	} else {
9534 		err = find_kernel_btf_id(prog->obj, attach_name, attach_type, btf_obj_fd, btf_type_id);
9535 	}
9536 	if (err) {
9537 		pr_warn("prog '%s': failed to find kernel BTF type ID of '%s': %d\n",
9538 			prog->name, attach_name, err);
9539 		return err;
9540 	}
9541 	return 0;
9542 }
9543 
9544 int libbpf_attach_type_by_name(const char *name,
9545 			       enum bpf_attach_type *attach_type)
9546 {
9547 	char *type_names;
9548 	const struct bpf_sec_def *sec_def;
9549 
9550 	if (!name)
9551 		return libbpf_err(-EINVAL);
9552 
9553 	sec_def = find_sec_def(name);
9554 	if (!sec_def) {
9555 		pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
9556 		type_names = libbpf_get_type_names(true);
9557 		if (type_names != NULL) {
9558 			pr_debug("attachable section(type) names are:%s\n", type_names);
9559 			free(type_names);
9560 		}
9561 
9562 		return libbpf_err(-EINVAL);
9563 	}
9564 
9565 	if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
9566 		return libbpf_err(-EINVAL);
9567 	if (!(sec_def->cookie & SEC_ATTACHABLE))
9568 		return libbpf_err(-EINVAL);
9569 
9570 	*attach_type = sec_def->expected_attach_type;
9571 	return 0;
9572 }
9573 
9574 int bpf_map__fd(const struct bpf_map *map)
9575 {
9576 	return map ? map->fd : libbpf_err(-EINVAL);
9577 }
9578 
9579 static bool map_uses_real_name(const struct bpf_map *map)
9580 {
9581 	/* Since libbpf started to support custom .data.* and .rodata.* maps,
9582 	 * their user-visible name differs from kernel-visible name. Users see
9583 	 * such map's corresponding ELF section name as a map name.
9584 	 * This check distinguishes .data/.rodata from .data.* and .rodata.*
9585 	 * maps to know which name has to be returned to the user.
9586 	 */
9587 	if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
9588 		return true;
9589 	if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
9590 		return true;
9591 	return false;
9592 }
9593 
9594 const char *bpf_map__name(const struct bpf_map *map)
9595 {
9596 	if (!map)
9597 		return NULL;
9598 
9599 	if (map_uses_real_name(map))
9600 		return map->real_name;
9601 
9602 	return map->name;
9603 }
9604 
9605 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
9606 {
9607 	return map->def.type;
9608 }
9609 
9610 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
9611 {
9612 	if (map->fd >= 0)
9613 		return libbpf_err(-EBUSY);
9614 	map->def.type = type;
9615 	return 0;
9616 }
9617 
9618 __u32 bpf_map__map_flags(const struct bpf_map *map)
9619 {
9620 	return map->def.map_flags;
9621 }
9622 
9623 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
9624 {
9625 	if (map->fd >= 0)
9626 		return libbpf_err(-EBUSY);
9627 	map->def.map_flags = flags;
9628 	return 0;
9629 }
9630 
9631 __u64 bpf_map__map_extra(const struct bpf_map *map)
9632 {
9633 	return map->map_extra;
9634 }
9635 
9636 int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
9637 {
9638 	if (map->fd >= 0)
9639 		return libbpf_err(-EBUSY);
9640 	map->map_extra = map_extra;
9641 	return 0;
9642 }
9643 
9644 __u32 bpf_map__numa_node(const struct bpf_map *map)
9645 {
9646 	return map->numa_node;
9647 }
9648 
9649 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
9650 {
9651 	if (map->fd >= 0)
9652 		return libbpf_err(-EBUSY);
9653 	map->numa_node = numa_node;
9654 	return 0;
9655 }
9656 
9657 __u32 bpf_map__key_size(const struct bpf_map *map)
9658 {
9659 	return map->def.key_size;
9660 }
9661 
9662 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
9663 {
9664 	if (map->fd >= 0)
9665 		return libbpf_err(-EBUSY);
9666 	map->def.key_size = size;
9667 	return 0;
9668 }
9669 
9670 __u32 bpf_map__value_size(const struct bpf_map *map)
9671 {
9672 	return map->def.value_size;
9673 }
9674 
9675 static int map_btf_datasec_resize(struct bpf_map *map, __u32 size)
9676 {
9677 	struct btf *btf;
9678 	struct btf_type *datasec_type, *var_type;
9679 	struct btf_var_secinfo *var;
9680 	const struct btf_type *array_type;
9681 	const struct btf_array *array;
9682 	int vlen, element_sz, new_array_id;
9683 	__u32 nr_elements;
9684 
9685 	/* check btf existence */
9686 	btf = bpf_object__btf(map->obj);
9687 	if (!btf)
9688 		return -ENOENT;
9689 
9690 	/* verify map is datasec */
9691 	datasec_type = btf_type_by_id(btf, bpf_map__btf_value_type_id(map));
9692 	if (!btf_is_datasec(datasec_type)) {
9693 		pr_warn("map '%s': cannot be resized, map value type is not a datasec\n",
9694 			bpf_map__name(map));
9695 		return -EINVAL;
9696 	}
9697 
9698 	/* verify datasec has at least one var */
9699 	vlen = btf_vlen(datasec_type);
9700 	if (vlen == 0) {
9701 		pr_warn("map '%s': cannot be resized, map value datasec is empty\n",
9702 			bpf_map__name(map));
9703 		return -EINVAL;
9704 	}
9705 
9706 	/* verify last var in the datasec is an array */
9707 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
9708 	var_type = btf_type_by_id(btf, var->type);
9709 	array_type = skip_mods_and_typedefs(btf, var_type->type, NULL);
9710 	if (!btf_is_array(array_type)) {
9711 		pr_warn("map '%s': cannot be resized, last var must be an array\n",
9712 			bpf_map__name(map));
9713 		return -EINVAL;
9714 	}
9715 
9716 	/* verify request size aligns with array */
9717 	array = btf_array(array_type);
9718 	element_sz = btf__resolve_size(btf, array->type);
9719 	if (element_sz <= 0 || (size - var->offset) % element_sz != 0) {
9720 		pr_warn("map '%s': cannot be resized, element size (%d) doesn't align with new total size (%u)\n",
9721 			bpf_map__name(map), element_sz, size);
9722 		return -EINVAL;
9723 	}
9724 
9725 	/* create a new array based on the existing array, but with new length */
9726 	nr_elements = (size - var->offset) / element_sz;
9727 	new_array_id = btf__add_array(btf, array->index_type, array->type, nr_elements);
9728 	if (new_array_id < 0)
9729 		return new_array_id;
9730 
9731 	/* adding a new btf type invalidates existing pointers to btf objects,
9732 	 * so refresh pointers before proceeding
9733 	 */
9734 	datasec_type = btf_type_by_id(btf, map->btf_value_type_id);
9735 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
9736 	var_type = btf_type_by_id(btf, var->type);
9737 
9738 	/* finally update btf info */
9739 	datasec_type->size = size;
9740 	var->size = size - var->offset;
9741 	var_type->type = new_array_id;
9742 
9743 	return 0;
9744 }
9745 
9746 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
9747 {
9748 	if (map->fd >= 0)
9749 		return libbpf_err(-EBUSY);
9750 
9751 	if (map->mmaped) {
9752 		int err;
9753 		size_t mmap_old_sz, mmap_new_sz;
9754 
9755 		mmap_old_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
9756 		mmap_new_sz = bpf_map_mmap_sz(size, map->def.max_entries);
9757 		err = bpf_map_mmap_resize(map, mmap_old_sz, mmap_new_sz);
9758 		if (err) {
9759 			pr_warn("map '%s': failed to resize memory-mapped region: %d\n",
9760 				bpf_map__name(map), err);
9761 			return err;
9762 		}
9763 		err = map_btf_datasec_resize(map, size);
9764 		if (err && err != -ENOENT) {
9765 			pr_warn("map '%s': failed to adjust resized BTF, clearing BTF key/value info: %d\n",
9766 				bpf_map__name(map), err);
9767 			map->btf_value_type_id = 0;
9768 			map->btf_key_type_id = 0;
9769 		}
9770 	}
9771 
9772 	map->def.value_size = size;
9773 	return 0;
9774 }
9775 
9776 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
9777 {
9778 	return map ? map->btf_key_type_id : 0;
9779 }
9780 
9781 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
9782 {
9783 	return map ? map->btf_value_type_id : 0;
9784 }
9785 
9786 int bpf_map__set_initial_value(struct bpf_map *map,
9787 			       const void *data, size_t size)
9788 {
9789 	if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG ||
9790 	    size != map->def.value_size || map->fd >= 0)
9791 		return libbpf_err(-EINVAL);
9792 
9793 	memcpy(map->mmaped, data, size);
9794 	return 0;
9795 }
9796 
9797 void *bpf_map__initial_value(struct bpf_map *map, size_t *psize)
9798 {
9799 	if (!map->mmaped)
9800 		return NULL;
9801 	*psize = map->def.value_size;
9802 	return map->mmaped;
9803 }
9804 
9805 bool bpf_map__is_internal(const struct bpf_map *map)
9806 {
9807 	return map->libbpf_type != LIBBPF_MAP_UNSPEC;
9808 }
9809 
9810 __u32 bpf_map__ifindex(const struct bpf_map *map)
9811 {
9812 	return map->map_ifindex;
9813 }
9814 
9815 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
9816 {
9817 	if (map->fd >= 0)
9818 		return libbpf_err(-EBUSY);
9819 	map->map_ifindex = ifindex;
9820 	return 0;
9821 }
9822 
9823 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
9824 {
9825 	if (!bpf_map_type__is_map_in_map(map->def.type)) {
9826 		pr_warn("error: unsupported map type\n");
9827 		return libbpf_err(-EINVAL);
9828 	}
9829 	if (map->inner_map_fd != -1) {
9830 		pr_warn("error: inner_map_fd already specified\n");
9831 		return libbpf_err(-EINVAL);
9832 	}
9833 	if (map->inner_map) {
9834 		bpf_map__destroy(map->inner_map);
9835 		zfree(&map->inner_map);
9836 	}
9837 	map->inner_map_fd = fd;
9838 	return 0;
9839 }
9840 
9841 static struct bpf_map *
9842 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
9843 {
9844 	ssize_t idx;
9845 	struct bpf_map *s, *e;
9846 
9847 	if (!obj || !obj->maps)
9848 		return errno = EINVAL, NULL;
9849 
9850 	s = obj->maps;
9851 	e = obj->maps + obj->nr_maps;
9852 
9853 	if ((m < s) || (m >= e)) {
9854 		pr_warn("error in %s: map handler doesn't belong to object\n",
9855 			 __func__);
9856 		return errno = EINVAL, NULL;
9857 	}
9858 
9859 	idx = (m - obj->maps) + i;
9860 	if (idx >= obj->nr_maps || idx < 0)
9861 		return NULL;
9862 	return &obj->maps[idx];
9863 }
9864 
9865 struct bpf_map *
9866 bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
9867 {
9868 	if (prev == NULL)
9869 		return obj->maps;
9870 
9871 	return __bpf_map__iter(prev, obj, 1);
9872 }
9873 
9874 struct bpf_map *
9875 bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
9876 {
9877 	if (next == NULL) {
9878 		if (!obj->nr_maps)
9879 			return NULL;
9880 		return obj->maps + obj->nr_maps - 1;
9881 	}
9882 
9883 	return __bpf_map__iter(next, obj, -1);
9884 }
9885 
9886 struct bpf_map *
9887 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
9888 {
9889 	struct bpf_map *pos;
9890 
9891 	bpf_object__for_each_map(pos, obj) {
9892 		/* if it's a special internal map name (which always starts
9893 		 * with dot) then check if that special name matches the
9894 		 * real map name (ELF section name)
9895 		 */
9896 		if (name[0] == '.') {
9897 			if (pos->real_name && strcmp(pos->real_name, name) == 0)
9898 				return pos;
9899 			continue;
9900 		}
9901 		/* otherwise map name has to be an exact match */
9902 		if (map_uses_real_name(pos)) {
9903 			if (strcmp(pos->real_name, name) == 0)
9904 				return pos;
9905 			continue;
9906 		}
9907 		if (strcmp(pos->name, name) == 0)
9908 			return pos;
9909 	}
9910 	return errno = ENOENT, NULL;
9911 }
9912 
9913 int
9914 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
9915 {
9916 	return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
9917 }
9918 
9919 static int validate_map_op(const struct bpf_map *map, size_t key_sz,
9920 			   size_t value_sz, bool check_value_sz)
9921 {
9922 	if (map->fd <= 0)
9923 		return -ENOENT;
9924 
9925 	if (map->def.key_size != key_sz) {
9926 		pr_warn("map '%s': unexpected key size %zu provided, expected %u\n",
9927 			map->name, key_sz, map->def.key_size);
9928 		return -EINVAL;
9929 	}
9930 
9931 	if (!check_value_sz)
9932 		return 0;
9933 
9934 	switch (map->def.type) {
9935 	case BPF_MAP_TYPE_PERCPU_ARRAY:
9936 	case BPF_MAP_TYPE_PERCPU_HASH:
9937 	case BPF_MAP_TYPE_LRU_PERCPU_HASH:
9938 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: {
9939 		int num_cpu = libbpf_num_possible_cpus();
9940 		size_t elem_sz = roundup(map->def.value_size, 8);
9941 
9942 		if (value_sz != num_cpu * elem_sz) {
9943 			pr_warn("map '%s': unexpected value size %zu provided for per-CPU map, expected %d * %zu = %zd\n",
9944 				map->name, value_sz, num_cpu, elem_sz, num_cpu * elem_sz);
9945 			return -EINVAL;
9946 		}
9947 		break;
9948 	}
9949 	default:
9950 		if (map->def.value_size != value_sz) {
9951 			pr_warn("map '%s': unexpected value size %zu provided, expected %u\n",
9952 				map->name, value_sz, map->def.value_size);
9953 			return -EINVAL;
9954 		}
9955 		break;
9956 	}
9957 	return 0;
9958 }
9959 
9960 int bpf_map__lookup_elem(const struct bpf_map *map,
9961 			 const void *key, size_t key_sz,
9962 			 void *value, size_t value_sz, __u64 flags)
9963 {
9964 	int err;
9965 
9966 	err = validate_map_op(map, key_sz, value_sz, true);
9967 	if (err)
9968 		return libbpf_err(err);
9969 
9970 	return bpf_map_lookup_elem_flags(map->fd, key, value, flags);
9971 }
9972 
9973 int bpf_map__update_elem(const struct bpf_map *map,
9974 			 const void *key, size_t key_sz,
9975 			 const void *value, size_t value_sz, __u64 flags)
9976 {
9977 	int err;
9978 
9979 	err = validate_map_op(map, key_sz, value_sz, true);
9980 	if (err)
9981 		return libbpf_err(err);
9982 
9983 	return bpf_map_update_elem(map->fd, key, value, flags);
9984 }
9985 
9986 int bpf_map__delete_elem(const struct bpf_map *map,
9987 			 const void *key, size_t key_sz, __u64 flags)
9988 {
9989 	int err;
9990 
9991 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
9992 	if (err)
9993 		return libbpf_err(err);
9994 
9995 	return bpf_map_delete_elem_flags(map->fd, key, flags);
9996 }
9997 
9998 int bpf_map__lookup_and_delete_elem(const struct bpf_map *map,
9999 				    const void *key, size_t key_sz,
10000 				    void *value, size_t value_sz, __u64 flags)
10001 {
10002 	int err;
10003 
10004 	err = validate_map_op(map, key_sz, value_sz, true);
10005 	if (err)
10006 		return libbpf_err(err);
10007 
10008 	return bpf_map_lookup_and_delete_elem_flags(map->fd, key, value, flags);
10009 }
10010 
10011 int bpf_map__get_next_key(const struct bpf_map *map,
10012 			  const void *cur_key, void *next_key, size_t key_sz)
10013 {
10014 	int err;
10015 
10016 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
10017 	if (err)
10018 		return libbpf_err(err);
10019 
10020 	return bpf_map_get_next_key(map->fd, cur_key, next_key);
10021 }
10022 
10023 long libbpf_get_error(const void *ptr)
10024 {
10025 	if (!IS_ERR_OR_NULL(ptr))
10026 		return 0;
10027 
10028 	if (IS_ERR(ptr))
10029 		errno = -PTR_ERR(ptr);
10030 
10031 	/* If ptr == NULL, then errno should be already set by the failing
10032 	 * API, because libbpf never returns NULL on success and it now always
10033 	 * sets errno on error. So no extra errno handling for ptr == NULL
10034 	 * case.
10035 	 */
10036 	return -errno;
10037 }
10038 
10039 /* Replace link's underlying BPF program with the new one */
10040 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
10041 {
10042 	int ret;
10043 
10044 	ret = bpf_link_update(bpf_link__fd(link), bpf_program__fd(prog), NULL);
10045 	return libbpf_err_errno(ret);
10046 }
10047 
10048 /* Release "ownership" of underlying BPF resource (typically, BPF program
10049  * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
10050  * link, when destructed through bpf_link__destroy() call won't attempt to
10051  * detach/unregisted that BPF resource. This is useful in situations where,
10052  * say, attached BPF program has to outlive userspace program that attached it
10053  * in the system. Depending on type of BPF program, though, there might be
10054  * additional steps (like pinning BPF program in BPF FS) necessary to ensure
10055  * exit of userspace program doesn't trigger automatic detachment and clean up
10056  * inside the kernel.
10057  */
10058 void bpf_link__disconnect(struct bpf_link *link)
10059 {
10060 	link->disconnected = true;
10061 }
10062 
10063 int bpf_link__destroy(struct bpf_link *link)
10064 {
10065 	int err = 0;
10066 
10067 	if (IS_ERR_OR_NULL(link))
10068 		return 0;
10069 
10070 	if (!link->disconnected && link->detach)
10071 		err = link->detach(link);
10072 	if (link->pin_path)
10073 		free(link->pin_path);
10074 	if (link->dealloc)
10075 		link->dealloc(link);
10076 	else
10077 		free(link);
10078 
10079 	return libbpf_err(err);
10080 }
10081 
10082 int bpf_link__fd(const struct bpf_link *link)
10083 {
10084 	return link->fd;
10085 }
10086 
10087 const char *bpf_link__pin_path(const struct bpf_link *link)
10088 {
10089 	return link->pin_path;
10090 }
10091 
10092 static int bpf_link__detach_fd(struct bpf_link *link)
10093 {
10094 	return libbpf_err_errno(close(link->fd));
10095 }
10096 
10097 struct bpf_link *bpf_link__open(const char *path)
10098 {
10099 	struct bpf_link *link;
10100 	int fd;
10101 
10102 	fd = bpf_obj_get(path);
10103 	if (fd < 0) {
10104 		fd = -errno;
10105 		pr_warn("failed to open link at %s: %d\n", path, fd);
10106 		return libbpf_err_ptr(fd);
10107 	}
10108 
10109 	link = calloc(1, sizeof(*link));
10110 	if (!link) {
10111 		close(fd);
10112 		return libbpf_err_ptr(-ENOMEM);
10113 	}
10114 	link->detach = &bpf_link__detach_fd;
10115 	link->fd = fd;
10116 
10117 	link->pin_path = strdup(path);
10118 	if (!link->pin_path) {
10119 		bpf_link__destroy(link);
10120 		return libbpf_err_ptr(-ENOMEM);
10121 	}
10122 
10123 	return link;
10124 }
10125 
10126 int bpf_link__detach(struct bpf_link *link)
10127 {
10128 	return bpf_link_detach(link->fd) ? -errno : 0;
10129 }
10130 
10131 int bpf_link__pin(struct bpf_link *link, const char *path)
10132 {
10133 	int err;
10134 
10135 	if (link->pin_path)
10136 		return libbpf_err(-EBUSY);
10137 	err = make_parent_dir(path);
10138 	if (err)
10139 		return libbpf_err(err);
10140 	err = check_path(path);
10141 	if (err)
10142 		return libbpf_err(err);
10143 
10144 	link->pin_path = strdup(path);
10145 	if (!link->pin_path)
10146 		return libbpf_err(-ENOMEM);
10147 
10148 	if (bpf_obj_pin(link->fd, link->pin_path)) {
10149 		err = -errno;
10150 		zfree(&link->pin_path);
10151 		return libbpf_err(err);
10152 	}
10153 
10154 	pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
10155 	return 0;
10156 }
10157 
10158 int bpf_link__unpin(struct bpf_link *link)
10159 {
10160 	int err;
10161 
10162 	if (!link->pin_path)
10163 		return libbpf_err(-EINVAL);
10164 
10165 	err = unlink(link->pin_path);
10166 	if (err != 0)
10167 		return -errno;
10168 
10169 	pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
10170 	zfree(&link->pin_path);
10171 	return 0;
10172 }
10173 
10174 struct bpf_link_perf {
10175 	struct bpf_link link;
10176 	int perf_event_fd;
10177 	/* legacy kprobe support: keep track of probe identifier and type */
10178 	char *legacy_probe_name;
10179 	bool legacy_is_kprobe;
10180 	bool legacy_is_retprobe;
10181 };
10182 
10183 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
10184 static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
10185 
10186 static int bpf_link_perf_detach(struct bpf_link *link)
10187 {
10188 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10189 	int err = 0;
10190 
10191 	if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
10192 		err = -errno;
10193 
10194 	if (perf_link->perf_event_fd != link->fd)
10195 		close(perf_link->perf_event_fd);
10196 	close(link->fd);
10197 
10198 	/* legacy uprobe/kprobe needs to be removed after perf event fd closure */
10199 	if (perf_link->legacy_probe_name) {
10200 		if (perf_link->legacy_is_kprobe) {
10201 			err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
10202 							 perf_link->legacy_is_retprobe);
10203 		} else {
10204 			err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
10205 							 perf_link->legacy_is_retprobe);
10206 		}
10207 	}
10208 
10209 	return err;
10210 }
10211 
10212 static void bpf_link_perf_dealloc(struct bpf_link *link)
10213 {
10214 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10215 
10216 	free(perf_link->legacy_probe_name);
10217 	free(perf_link);
10218 }
10219 
10220 struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
10221 						     const struct bpf_perf_event_opts *opts)
10222 {
10223 	char errmsg[STRERR_BUFSIZE];
10224 	struct bpf_link_perf *link;
10225 	int prog_fd, link_fd = -1, err;
10226 	bool force_ioctl_attach;
10227 
10228 	if (!OPTS_VALID(opts, bpf_perf_event_opts))
10229 		return libbpf_err_ptr(-EINVAL);
10230 
10231 	if (pfd < 0) {
10232 		pr_warn("prog '%s': invalid perf event FD %d\n",
10233 			prog->name, pfd);
10234 		return libbpf_err_ptr(-EINVAL);
10235 	}
10236 	prog_fd = bpf_program__fd(prog);
10237 	if (prog_fd < 0) {
10238 		pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
10239 			prog->name);
10240 		return libbpf_err_ptr(-EINVAL);
10241 	}
10242 
10243 	link = calloc(1, sizeof(*link));
10244 	if (!link)
10245 		return libbpf_err_ptr(-ENOMEM);
10246 	link->link.detach = &bpf_link_perf_detach;
10247 	link->link.dealloc = &bpf_link_perf_dealloc;
10248 	link->perf_event_fd = pfd;
10249 
10250 	force_ioctl_attach = OPTS_GET(opts, force_ioctl_attach, false);
10251 	if (kernel_supports(prog->obj, FEAT_PERF_LINK) && !force_ioctl_attach) {
10252 		DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
10253 			.perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
10254 
10255 		link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
10256 		if (link_fd < 0) {
10257 			err = -errno;
10258 			pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %d (%s)\n",
10259 				prog->name, pfd,
10260 				err, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10261 			goto err_out;
10262 		}
10263 		link->link.fd = link_fd;
10264 	} else {
10265 		if (OPTS_GET(opts, bpf_cookie, 0)) {
10266 			pr_warn("prog '%s': user context value is not supported\n", prog->name);
10267 			err = -EOPNOTSUPP;
10268 			goto err_out;
10269 		}
10270 
10271 		if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
10272 			err = -errno;
10273 			pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
10274 				prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10275 			if (err == -EPROTO)
10276 				pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
10277 					prog->name, pfd);
10278 			goto err_out;
10279 		}
10280 		link->link.fd = pfd;
10281 	}
10282 	if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
10283 		err = -errno;
10284 		pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
10285 			prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10286 		goto err_out;
10287 	}
10288 
10289 	return &link->link;
10290 err_out:
10291 	if (link_fd >= 0)
10292 		close(link_fd);
10293 	free(link);
10294 	return libbpf_err_ptr(err);
10295 }
10296 
10297 struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
10298 {
10299 	return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
10300 }
10301 
10302 /*
10303  * this function is expected to parse integer in the range of [0, 2^31-1] from
10304  * given file using scanf format string fmt. If actual parsed value is
10305  * negative, the result might be indistinguishable from error
10306  */
10307 static int parse_uint_from_file(const char *file, const char *fmt)
10308 {
10309 	char buf[STRERR_BUFSIZE];
10310 	int err, ret;
10311 	FILE *f;
10312 
10313 	f = fopen(file, "re");
10314 	if (!f) {
10315 		err = -errno;
10316 		pr_debug("failed to open '%s': %s\n", file,
10317 			 libbpf_strerror_r(err, buf, sizeof(buf)));
10318 		return err;
10319 	}
10320 	err = fscanf(f, fmt, &ret);
10321 	if (err != 1) {
10322 		err = err == EOF ? -EIO : -errno;
10323 		pr_debug("failed to parse '%s': %s\n", file,
10324 			libbpf_strerror_r(err, buf, sizeof(buf)));
10325 		fclose(f);
10326 		return err;
10327 	}
10328 	fclose(f);
10329 	return ret;
10330 }
10331 
10332 static int determine_kprobe_perf_type(void)
10333 {
10334 	const char *file = "/sys/bus/event_source/devices/kprobe/type";
10335 
10336 	return parse_uint_from_file(file, "%d\n");
10337 }
10338 
10339 static int determine_uprobe_perf_type(void)
10340 {
10341 	const char *file = "/sys/bus/event_source/devices/uprobe/type";
10342 
10343 	return parse_uint_from_file(file, "%d\n");
10344 }
10345 
10346 static int determine_kprobe_retprobe_bit(void)
10347 {
10348 	const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
10349 
10350 	return parse_uint_from_file(file, "config:%d\n");
10351 }
10352 
10353 static int determine_uprobe_retprobe_bit(void)
10354 {
10355 	const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
10356 
10357 	return parse_uint_from_file(file, "config:%d\n");
10358 }
10359 
10360 #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
10361 #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
10362 
10363 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
10364 				 uint64_t offset, int pid, size_t ref_ctr_off)
10365 {
10366 	const size_t attr_sz = sizeof(struct perf_event_attr);
10367 	struct perf_event_attr attr;
10368 	char errmsg[STRERR_BUFSIZE];
10369 	int type, pfd;
10370 
10371 	if ((__u64)ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
10372 		return -EINVAL;
10373 
10374 	memset(&attr, 0, attr_sz);
10375 
10376 	type = uprobe ? determine_uprobe_perf_type()
10377 		      : determine_kprobe_perf_type();
10378 	if (type < 0) {
10379 		pr_warn("failed to determine %s perf type: %s\n",
10380 			uprobe ? "uprobe" : "kprobe",
10381 			libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
10382 		return type;
10383 	}
10384 	if (retprobe) {
10385 		int bit = uprobe ? determine_uprobe_retprobe_bit()
10386 				 : determine_kprobe_retprobe_bit();
10387 
10388 		if (bit < 0) {
10389 			pr_warn("failed to determine %s retprobe bit: %s\n",
10390 				uprobe ? "uprobe" : "kprobe",
10391 				libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
10392 			return bit;
10393 		}
10394 		attr.config |= 1 << bit;
10395 	}
10396 	attr.size = attr_sz;
10397 	attr.type = type;
10398 	attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
10399 	attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
10400 	attr.config2 = offset;		 /* kprobe_addr or probe_offset */
10401 
10402 	/* pid filter is meaningful only for uprobes */
10403 	pfd = syscall(__NR_perf_event_open, &attr,
10404 		      pid < 0 ? -1 : pid /* pid */,
10405 		      pid == -1 ? 0 : -1 /* cpu */,
10406 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
10407 	return pfd >= 0 ? pfd : -errno;
10408 }
10409 
10410 static int append_to_file(const char *file, const char *fmt, ...)
10411 {
10412 	int fd, n, err = 0;
10413 	va_list ap;
10414 	char buf[1024];
10415 
10416 	va_start(ap, fmt);
10417 	n = vsnprintf(buf, sizeof(buf), fmt, ap);
10418 	va_end(ap);
10419 
10420 	if (n < 0 || n >= sizeof(buf))
10421 		return -EINVAL;
10422 
10423 	fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
10424 	if (fd < 0)
10425 		return -errno;
10426 
10427 	if (write(fd, buf, n) < 0)
10428 		err = -errno;
10429 
10430 	close(fd);
10431 	return err;
10432 }
10433 
10434 #define DEBUGFS "/sys/kernel/debug/tracing"
10435 #define TRACEFS "/sys/kernel/tracing"
10436 
10437 static bool use_debugfs(void)
10438 {
10439 	static int has_debugfs = -1;
10440 
10441 	if (has_debugfs < 0)
10442 		has_debugfs = faccessat(AT_FDCWD, DEBUGFS, F_OK, AT_EACCESS) == 0;
10443 
10444 	return has_debugfs == 1;
10445 }
10446 
10447 static const char *tracefs_path(void)
10448 {
10449 	return use_debugfs() ? DEBUGFS : TRACEFS;
10450 }
10451 
10452 static const char *tracefs_kprobe_events(void)
10453 {
10454 	return use_debugfs() ? DEBUGFS"/kprobe_events" : TRACEFS"/kprobe_events";
10455 }
10456 
10457 static const char *tracefs_uprobe_events(void)
10458 {
10459 	return use_debugfs() ? DEBUGFS"/uprobe_events" : TRACEFS"/uprobe_events";
10460 }
10461 
10462 static const char *tracefs_available_filter_functions(void)
10463 {
10464 	return use_debugfs() ? DEBUGFS"/available_filter_functions"
10465 			     : TRACEFS"/available_filter_functions";
10466 }
10467 
10468 static const char *tracefs_available_filter_functions_addrs(void)
10469 {
10470 	return use_debugfs() ? DEBUGFS"/available_filter_functions_addrs"
10471 			     : TRACEFS"/available_filter_functions_addrs";
10472 }
10473 
10474 static void gen_kprobe_legacy_event_name(char *buf, size_t buf_sz,
10475 					 const char *kfunc_name, size_t offset)
10476 {
10477 	static int index = 0;
10478 	int i;
10479 
10480 	snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx_%d", getpid(), kfunc_name, offset,
10481 		 __sync_fetch_and_add(&index, 1));
10482 
10483 	/* sanitize binary_path in the probe name */
10484 	for (i = 0; buf[i]; i++) {
10485 		if (!isalnum(buf[i]))
10486 			buf[i] = '_';
10487 	}
10488 }
10489 
10490 static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
10491 				   const char *kfunc_name, size_t offset)
10492 {
10493 	return append_to_file(tracefs_kprobe_events(), "%c:%s/%s %s+0x%zx",
10494 			      retprobe ? 'r' : 'p',
10495 			      retprobe ? "kretprobes" : "kprobes",
10496 			      probe_name, kfunc_name, offset);
10497 }
10498 
10499 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
10500 {
10501 	return append_to_file(tracefs_kprobe_events(), "-:%s/%s",
10502 			      retprobe ? "kretprobes" : "kprobes", probe_name);
10503 }
10504 
10505 static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
10506 {
10507 	char file[256];
10508 
10509 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
10510 		 tracefs_path(), retprobe ? "kretprobes" : "kprobes", probe_name);
10511 
10512 	return parse_uint_from_file(file, "%d\n");
10513 }
10514 
10515 static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
10516 					 const char *kfunc_name, size_t offset, int pid)
10517 {
10518 	const size_t attr_sz = sizeof(struct perf_event_attr);
10519 	struct perf_event_attr attr;
10520 	char errmsg[STRERR_BUFSIZE];
10521 	int type, pfd, err;
10522 
10523 	err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
10524 	if (err < 0) {
10525 		pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
10526 			kfunc_name, offset,
10527 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10528 		return err;
10529 	}
10530 	type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
10531 	if (type < 0) {
10532 		err = type;
10533 		pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
10534 			kfunc_name, offset,
10535 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10536 		goto err_clean_legacy;
10537 	}
10538 
10539 	memset(&attr, 0, attr_sz);
10540 	attr.size = attr_sz;
10541 	attr.config = type;
10542 	attr.type = PERF_TYPE_TRACEPOINT;
10543 
10544 	pfd = syscall(__NR_perf_event_open, &attr,
10545 		      pid < 0 ? -1 : pid, /* pid */
10546 		      pid == -1 ? 0 : -1, /* cpu */
10547 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
10548 	if (pfd < 0) {
10549 		err = -errno;
10550 		pr_warn("legacy kprobe perf_event_open() failed: %s\n",
10551 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10552 		goto err_clean_legacy;
10553 	}
10554 	return pfd;
10555 
10556 err_clean_legacy:
10557 	/* Clear the newly added legacy kprobe_event */
10558 	remove_kprobe_event_legacy(probe_name, retprobe);
10559 	return err;
10560 }
10561 
10562 static const char *arch_specific_syscall_pfx(void)
10563 {
10564 #if defined(__x86_64__)
10565 	return "x64";
10566 #elif defined(__i386__)
10567 	return "ia32";
10568 #elif defined(__s390x__)
10569 	return "s390x";
10570 #elif defined(__s390__)
10571 	return "s390";
10572 #elif defined(__arm__)
10573 	return "arm";
10574 #elif defined(__aarch64__)
10575 	return "arm64";
10576 #elif defined(__mips__)
10577 	return "mips";
10578 #elif defined(__riscv)
10579 	return "riscv";
10580 #elif defined(__powerpc__)
10581 	return "powerpc";
10582 #elif defined(__powerpc64__)
10583 	return "powerpc64";
10584 #else
10585 	return NULL;
10586 #endif
10587 }
10588 
10589 static int probe_kern_syscall_wrapper(void)
10590 {
10591 	char syscall_name[64];
10592 	const char *ksys_pfx;
10593 
10594 	ksys_pfx = arch_specific_syscall_pfx();
10595 	if (!ksys_pfx)
10596 		return 0;
10597 
10598 	snprintf(syscall_name, sizeof(syscall_name), "__%s_sys_bpf", ksys_pfx);
10599 
10600 	if (determine_kprobe_perf_type() >= 0) {
10601 		int pfd;
10602 
10603 		pfd = perf_event_open_probe(false, false, syscall_name, 0, getpid(), 0);
10604 		if (pfd >= 0)
10605 			close(pfd);
10606 
10607 		return pfd >= 0 ? 1 : 0;
10608 	} else { /* legacy mode */
10609 		char probe_name[128];
10610 
10611 		gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name), syscall_name, 0);
10612 		if (add_kprobe_event_legacy(probe_name, false, syscall_name, 0) < 0)
10613 			return 0;
10614 
10615 		(void)remove_kprobe_event_legacy(probe_name, false);
10616 		return 1;
10617 	}
10618 }
10619 
10620 struct bpf_link *
10621 bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
10622 				const char *func_name,
10623 				const struct bpf_kprobe_opts *opts)
10624 {
10625 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
10626 	enum probe_attach_mode attach_mode;
10627 	char errmsg[STRERR_BUFSIZE];
10628 	char *legacy_probe = NULL;
10629 	struct bpf_link *link;
10630 	size_t offset;
10631 	bool retprobe, legacy;
10632 	int pfd, err;
10633 
10634 	if (!OPTS_VALID(opts, bpf_kprobe_opts))
10635 		return libbpf_err_ptr(-EINVAL);
10636 
10637 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
10638 	retprobe = OPTS_GET(opts, retprobe, false);
10639 	offset = OPTS_GET(opts, offset, 0);
10640 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10641 
10642 	legacy = determine_kprobe_perf_type() < 0;
10643 	switch (attach_mode) {
10644 	case PROBE_ATTACH_MODE_LEGACY:
10645 		legacy = true;
10646 		pe_opts.force_ioctl_attach = true;
10647 		break;
10648 	case PROBE_ATTACH_MODE_PERF:
10649 		if (legacy)
10650 			return libbpf_err_ptr(-ENOTSUP);
10651 		pe_opts.force_ioctl_attach = true;
10652 		break;
10653 	case PROBE_ATTACH_MODE_LINK:
10654 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
10655 			return libbpf_err_ptr(-ENOTSUP);
10656 		break;
10657 	case PROBE_ATTACH_MODE_DEFAULT:
10658 		break;
10659 	default:
10660 		return libbpf_err_ptr(-EINVAL);
10661 	}
10662 
10663 	if (!legacy) {
10664 		pfd = perf_event_open_probe(false /* uprobe */, retprobe,
10665 					    func_name, offset,
10666 					    -1 /* pid */, 0 /* ref_ctr_off */);
10667 	} else {
10668 		char probe_name[256];
10669 
10670 		gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name),
10671 					     func_name, offset);
10672 
10673 		legacy_probe = strdup(probe_name);
10674 		if (!legacy_probe)
10675 			return libbpf_err_ptr(-ENOMEM);
10676 
10677 		pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
10678 						    offset, -1 /* pid */);
10679 	}
10680 	if (pfd < 0) {
10681 		err = -errno;
10682 		pr_warn("prog '%s': failed to create %s '%s+0x%zx' perf event: %s\n",
10683 			prog->name, retprobe ? "kretprobe" : "kprobe",
10684 			func_name, offset,
10685 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10686 		goto err_out;
10687 	}
10688 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
10689 	err = libbpf_get_error(link);
10690 	if (err) {
10691 		close(pfd);
10692 		pr_warn("prog '%s': failed to attach to %s '%s+0x%zx': %s\n",
10693 			prog->name, retprobe ? "kretprobe" : "kprobe",
10694 			func_name, offset,
10695 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10696 		goto err_clean_legacy;
10697 	}
10698 	if (legacy) {
10699 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10700 
10701 		perf_link->legacy_probe_name = legacy_probe;
10702 		perf_link->legacy_is_kprobe = true;
10703 		perf_link->legacy_is_retprobe = retprobe;
10704 	}
10705 
10706 	return link;
10707 
10708 err_clean_legacy:
10709 	if (legacy)
10710 		remove_kprobe_event_legacy(legacy_probe, retprobe);
10711 err_out:
10712 	free(legacy_probe);
10713 	return libbpf_err_ptr(err);
10714 }
10715 
10716 struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
10717 					    bool retprobe,
10718 					    const char *func_name)
10719 {
10720 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
10721 		.retprobe = retprobe,
10722 	);
10723 
10724 	return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
10725 }
10726 
10727 struct bpf_link *bpf_program__attach_ksyscall(const struct bpf_program *prog,
10728 					      const char *syscall_name,
10729 					      const struct bpf_ksyscall_opts *opts)
10730 {
10731 	LIBBPF_OPTS(bpf_kprobe_opts, kprobe_opts);
10732 	char func_name[128];
10733 
10734 	if (!OPTS_VALID(opts, bpf_ksyscall_opts))
10735 		return libbpf_err_ptr(-EINVAL);
10736 
10737 	if (kernel_supports(prog->obj, FEAT_SYSCALL_WRAPPER)) {
10738 		/* arch_specific_syscall_pfx() should never return NULL here
10739 		 * because it is guarded by kernel_supports(). However, since
10740 		 * compiler does not know that we have an explicit conditional
10741 		 * as well.
10742 		 */
10743 		snprintf(func_name, sizeof(func_name), "__%s_sys_%s",
10744 			 arch_specific_syscall_pfx() ? : "", syscall_name);
10745 	} else {
10746 		snprintf(func_name, sizeof(func_name), "__se_sys_%s", syscall_name);
10747 	}
10748 
10749 	kprobe_opts.retprobe = OPTS_GET(opts, retprobe, false);
10750 	kprobe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10751 
10752 	return bpf_program__attach_kprobe_opts(prog, func_name, &kprobe_opts);
10753 }
10754 
10755 /* Adapted from perf/util/string.c */
10756 bool glob_match(const char *str, const char *pat)
10757 {
10758 	while (*str && *pat && *pat != '*') {
10759 		if (*pat == '?') {      /* Matches any single character */
10760 			str++;
10761 			pat++;
10762 			continue;
10763 		}
10764 		if (*str != *pat)
10765 			return false;
10766 		str++;
10767 		pat++;
10768 	}
10769 	/* Check wild card */
10770 	if (*pat == '*') {
10771 		while (*pat == '*')
10772 			pat++;
10773 		if (!*pat) /* Tail wild card matches all */
10774 			return true;
10775 		while (*str)
10776 			if (glob_match(str++, pat))
10777 				return true;
10778 	}
10779 	return !*str && !*pat;
10780 }
10781 
10782 struct kprobe_multi_resolve {
10783 	const char *pattern;
10784 	unsigned long *addrs;
10785 	size_t cap;
10786 	size_t cnt;
10787 };
10788 
10789 struct avail_kallsyms_data {
10790 	char **syms;
10791 	size_t cnt;
10792 	struct kprobe_multi_resolve *res;
10793 };
10794 
10795 static int avail_func_cmp(const void *a, const void *b)
10796 {
10797 	return strcmp(*(const char **)a, *(const char **)b);
10798 }
10799 
10800 static int avail_kallsyms_cb(unsigned long long sym_addr, char sym_type,
10801 			     const char *sym_name, void *ctx)
10802 {
10803 	struct avail_kallsyms_data *data = ctx;
10804 	struct kprobe_multi_resolve *res = data->res;
10805 	int err;
10806 
10807 	if (!bsearch(&sym_name, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp))
10808 		return 0;
10809 
10810 	err = libbpf_ensure_mem((void **)&res->addrs, &res->cap, sizeof(*res->addrs), res->cnt + 1);
10811 	if (err)
10812 		return err;
10813 
10814 	res->addrs[res->cnt++] = (unsigned long)sym_addr;
10815 	return 0;
10816 }
10817 
10818 static int libbpf_available_kallsyms_parse(struct kprobe_multi_resolve *res)
10819 {
10820 	const char *available_functions_file = tracefs_available_filter_functions();
10821 	struct avail_kallsyms_data data;
10822 	char sym_name[500];
10823 	FILE *f;
10824 	int err = 0, ret, i;
10825 	char **syms = NULL;
10826 	size_t cap = 0, cnt = 0;
10827 
10828 	f = fopen(available_functions_file, "re");
10829 	if (!f) {
10830 		err = -errno;
10831 		pr_warn("failed to open %s: %d\n", available_functions_file, err);
10832 		return err;
10833 	}
10834 
10835 	while (true) {
10836 		char *name;
10837 
10838 		ret = fscanf(f, "%499s%*[^\n]\n", sym_name);
10839 		if (ret == EOF && feof(f))
10840 			break;
10841 
10842 		if (ret != 1) {
10843 			pr_warn("failed to parse available_filter_functions entry: %d\n", ret);
10844 			err = -EINVAL;
10845 			goto cleanup;
10846 		}
10847 
10848 		if (!glob_match(sym_name, res->pattern))
10849 			continue;
10850 
10851 		err = libbpf_ensure_mem((void **)&syms, &cap, sizeof(*syms), cnt + 1);
10852 		if (err)
10853 			goto cleanup;
10854 
10855 		name = strdup(sym_name);
10856 		if (!name) {
10857 			err = -errno;
10858 			goto cleanup;
10859 		}
10860 
10861 		syms[cnt++] = name;
10862 	}
10863 
10864 	/* no entries found, bail out */
10865 	if (cnt == 0) {
10866 		err = -ENOENT;
10867 		goto cleanup;
10868 	}
10869 
10870 	/* sort available functions */
10871 	qsort(syms, cnt, sizeof(*syms), avail_func_cmp);
10872 
10873 	data.syms = syms;
10874 	data.res = res;
10875 	data.cnt = cnt;
10876 	libbpf_kallsyms_parse(avail_kallsyms_cb, &data);
10877 
10878 	if (res->cnt == 0)
10879 		err = -ENOENT;
10880 
10881 cleanup:
10882 	for (i = 0; i < cnt; i++)
10883 		free((char *)syms[i]);
10884 	free(syms);
10885 
10886 	fclose(f);
10887 	return err;
10888 }
10889 
10890 static bool has_available_filter_functions_addrs(void)
10891 {
10892 	return access(tracefs_available_filter_functions_addrs(), R_OK) != -1;
10893 }
10894 
10895 static int libbpf_available_kprobes_parse(struct kprobe_multi_resolve *res)
10896 {
10897 	const char *available_path = tracefs_available_filter_functions_addrs();
10898 	char sym_name[500];
10899 	FILE *f;
10900 	int ret, err = 0;
10901 	unsigned long long sym_addr;
10902 
10903 	f = fopen(available_path, "re");
10904 	if (!f) {
10905 		err = -errno;
10906 		pr_warn("failed to open %s: %d\n", available_path, err);
10907 		return err;
10908 	}
10909 
10910 	while (true) {
10911 		ret = fscanf(f, "%llx %499s%*[^\n]\n", &sym_addr, sym_name);
10912 		if (ret == EOF && feof(f))
10913 			break;
10914 
10915 		if (ret != 2) {
10916 			pr_warn("failed to parse available_filter_functions_addrs entry: %d\n",
10917 				ret);
10918 			err = -EINVAL;
10919 			goto cleanup;
10920 		}
10921 
10922 		if (!glob_match(sym_name, res->pattern))
10923 			continue;
10924 
10925 		err = libbpf_ensure_mem((void **)&res->addrs, &res->cap,
10926 					sizeof(*res->addrs), res->cnt + 1);
10927 		if (err)
10928 			goto cleanup;
10929 
10930 		res->addrs[res->cnt++] = (unsigned long)sym_addr;
10931 	}
10932 
10933 	if (res->cnt == 0)
10934 		err = -ENOENT;
10935 
10936 cleanup:
10937 	fclose(f);
10938 	return err;
10939 }
10940 
10941 struct bpf_link *
10942 bpf_program__attach_kprobe_multi_opts(const struct bpf_program *prog,
10943 				      const char *pattern,
10944 				      const struct bpf_kprobe_multi_opts *opts)
10945 {
10946 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
10947 	struct kprobe_multi_resolve res = {
10948 		.pattern = pattern,
10949 	};
10950 	struct bpf_link *link = NULL;
10951 	char errmsg[STRERR_BUFSIZE];
10952 	const unsigned long *addrs;
10953 	int err, link_fd, prog_fd;
10954 	const __u64 *cookies;
10955 	const char **syms;
10956 	bool retprobe;
10957 	size_t cnt;
10958 
10959 	if (!OPTS_VALID(opts, bpf_kprobe_multi_opts))
10960 		return libbpf_err_ptr(-EINVAL);
10961 
10962 	syms    = OPTS_GET(opts, syms, false);
10963 	addrs   = OPTS_GET(opts, addrs, false);
10964 	cnt     = OPTS_GET(opts, cnt, false);
10965 	cookies = OPTS_GET(opts, cookies, false);
10966 
10967 	if (!pattern && !addrs && !syms)
10968 		return libbpf_err_ptr(-EINVAL);
10969 	if (pattern && (addrs || syms || cookies || cnt))
10970 		return libbpf_err_ptr(-EINVAL);
10971 	if (!pattern && !cnt)
10972 		return libbpf_err_ptr(-EINVAL);
10973 	if (addrs && syms)
10974 		return libbpf_err_ptr(-EINVAL);
10975 
10976 	if (pattern) {
10977 		if (has_available_filter_functions_addrs())
10978 			err = libbpf_available_kprobes_parse(&res);
10979 		else
10980 			err = libbpf_available_kallsyms_parse(&res);
10981 		if (err)
10982 			goto error;
10983 		addrs = res.addrs;
10984 		cnt = res.cnt;
10985 	}
10986 
10987 	retprobe = OPTS_GET(opts, retprobe, false);
10988 
10989 	lopts.kprobe_multi.syms = syms;
10990 	lopts.kprobe_multi.addrs = addrs;
10991 	lopts.kprobe_multi.cookies = cookies;
10992 	lopts.kprobe_multi.cnt = cnt;
10993 	lopts.kprobe_multi.flags = retprobe ? BPF_F_KPROBE_MULTI_RETURN : 0;
10994 
10995 	link = calloc(1, sizeof(*link));
10996 	if (!link) {
10997 		err = -ENOMEM;
10998 		goto error;
10999 	}
11000 	link->detach = &bpf_link__detach_fd;
11001 
11002 	prog_fd = bpf_program__fd(prog);
11003 	link_fd = bpf_link_create(prog_fd, 0, BPF_TRACE_KPROBE_MULTI, &lopts);
11004 	if (link_fd < 0) {
11005 		err = -errno;
11006 		pr_warn("prog '%s': failed to attach: %s\n",
11007 			prog->name, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11008 		goto error;
11009 	}
11010 	link->fd = link_fd;
11011 	free(res.addrs);
11012 	return link;
11013 
11014 error:
11015 	free(link);
11016 	free(res.addrs);
11017 	return libbpf_err_ptr(err);
11018 }
11019 
11020 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11021 {
11022 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
11023 	unsigned long offset = 0;
11024 	const char *func_name;
11025 	char *func;
11026 	int n;
11027 
11028 	*link = NULL;
11029 
11030 	/* no auto-attach for SEC("kprobe") and SEC("kretprobe") */
11031 	if (strcmp(prog->sec_name, "kprobe") == 0 || strcmp(prog->sec_name, "kretprobe") == 0)
11032 		return 0;
11033 
11034 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
11035 	if (opts.retprobe)
11036 		func_name = prog->sec_name + sizeof("kretprobe/") - 1;
11037 	else
11038 		func_name = prog->sec_name + sizeof("kprobe/") - 1;
11039 
11040 	n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
11041 	if (n < 1) {
11042 		pr_warn("kprobe name is invalid: %s\n", func_name);
11043 		return -EINVAL;
11044 	}
11045 	if (opts.retprobe && offset != 0) {
11046 		free(func);
11047 		pr_warn("kretprobes do not support offset specification\n");
11048 		return -EINVAL;
11049 	}
11050 
11051 	opts.offset = offset;
11052 	*link = bpf_program__attach_kprobe_opts(prog, func, &opts);
11053 	free(func);
11054 	return libbpf_get_error(*link);
11055 }
11056 
11057 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11058 {
11059 	LIBBPF_OPTS(bpf_ksyscall_opts, opts);
11060 	const char *syscall_name;
11061 
11062 	*link = NULL;
11063 
11064 	/* no auto-attach for SEC("ksyscall") and SEC("kretsyscall") */
11065 	if (strcmp(prog->sec_name, "ksyscall") == 0 || strcmp(prog->sec_name, "kretsyscall") == 0)
11066 		return 0;
11067 
11068 	opts.retprobe = str_has_pfx(prog->sec_name, "kretsyscall/");
11069 	if (opts.retprobe)
11070 		syscall_name = prog->sec_name + sizeof("kretsyscall/") - 1;
11071 	else
11072 		syscall_name = prog->sec_name + sizeof("ksyscall/") - 1;
11073 
11074 	*link = bpf_program__attach_ksyscall(prog, syscall_name, &opts);
11075 	return *link ? 0 : -errno;
11076 }
11077 
11078 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11079 {
11080 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts);
11081 	const char *spec;
11082 	char *pattern;
11083 	int n;
11084 
11085 	*link = NULL;
11086 
11087 	/* no auto-attach for SEC("kprobe.multi") and SEC("kretprobe.multi") */
11088 	if (strcmp(prog->sec_name, "kprobe.multi") == 0 ||
11089 	    strcmp(prog->sec_name, "kretprobe.multi") == 0)
11090 		return 0;
11091 
11092 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe.multi/");
11093 	if (opts.retprobe)
11094 		spec = prog->sec_name + sizeof("kretprobe.multi/") - 1;
11095 	else
11096 		spec = prog->sec_name + sizeof("kprobe.multi/") - 1;
11097 
11098 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
11099 	if (n < 1) {
11100 		pr_warn("kprobe multi pattern is invalid: %s\n", pattern);
11101 		return -EINVAL;
11102 	}
11103 
11104 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
11105 	free(pattern);
11106 	return libbpf_get_error(*link);
11107 }
11108 
11109 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11110 {
11111 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
11112 	LIBBPF_OPTS(bpf_uprobe_multi_opts, opts);
11113 	int n, ret = -EINVAL;
11114 
11115 	*link = NULL;
11116 
11117 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%ms",
11118 		   &probe_type, &binary_path, &func_name);
11119 	switch (n) {
11120 	case 1:
11121 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
11122 		ret = 0;
11123 		break;
11124 	case 3:
11125 		opts.retprobe = strcmp(probe_type, "uretprobe.multi") == 0;
11126 		*link = bpf_program__attach_uprobe_multi(prog, -1, binary_path, func_name, &opts);
11127 		ret = libbpf_get_error(*link);
11128 		break;
11129 	default:
11130 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
11131 			prog->sec_name);
11132 		break;
11133 	}
11134 	free(probe_type);
11135 	free(binary_path);
11136 	free(func_name);
11137 	return ret;
11138 }
11139 
11140 static void gen_uprobe_legacy_event_name(char *buf, size_t buf_sz,
11141 					 const char *binary_path, uint64_t offset)
11142 {
11143 	int i;
11144 
11145 	snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx", getpid(), binary_path, (size_t)offset);
11146 
11147 	/* sanitize binary_path in the probe name */
11148 	for (i = 0; buf[i]; i++) {
11149 		if (!isalnum(buf[i]))
11150 			buf[i] = '_';
11151 	}
11152 }
11153 
11154 static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
11155 					  const char *binary_path, size_t offset)
11156 {
11157 	return append_to_file(tracefs_uprobe_events(), "%c:%s/%s %s:0x%zx",
11158 			      retprobe ? 'r' : 'p',
11159 			      retprobe ? "uretprobes" : "uprobes",
11160 			      probe_name, binary_path, offset);
11161 }
11162 
11163 static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
11164 {
11165 	return append_to_file(tracefs_uprobe_events(), "-:%s/%s",
11166 			      retprobe ? "uretprobes" : "uprobes", probe_name);
11167 }
11168 
11169 static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
11170 {
11171 	char file[512];
11172 
11173 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11174 		 tracefs_path(), retprobe ? "uretprobes" : "uprobes", probe_name);
11175 
11176 	return parse_uint_from_file(file, "%d\n");
11177 }
11178 
11179 static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
11180 					 const char *binary_path, size_t offset, int pid)
11181 {
11182 	const size_t attr_sz = sizeof(struct perf_event_attr);
11183 	struct perf_event_attr attr;
11184 	int type, pfd, err;
11185 
11186 	err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
11187 	if (err < 0) {
11188 		pr_warn("failed to add legacy uprobe event for %s:0x%zx: %d\n",
11189 			binary_path, (size_t)offset, err);
11190 		return err;
11191 	}
11192 	type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
11193 	if (type < 0) {
11194 		err = type;
11195 		pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %d\n",
11196 			binary_path, offset, err);
11197 		goto err_clean_legacy;
11198 	}
11199 
11200 	memset(&attr, 0, attr_sz);
11201 	attr.size = attr_sz;
11202 	attr.config = type;
11203 	attr.type = PERF_TYPE_TRACEPOINT;
11204 
11205 	pfd = syscall(__NR_perf_event_open, &attr,
11206 		      pid < 0 ? -1 : pid, /* pid */
11207 		      pid == -1 ? 0 : -1, /* cpu */
11208 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
11209 	if (pfd < 0) {
11210 		err = -errno;
11211 		pr_warn("legacy uprobe perf_event_open() failed: %d\n", err);
11212 		goto err_clean_legacy;
11213 	}
11214 	return pfd;
11215 
11216 err_clean_legacy:
11217 	/* Clear the newly added legacy uprobe_event */
11218 	remove_uprobe_event_legacy(probe_name, retprobe);
11219 	return err;
11220 }
11221 
11222 /* Find offset of function name in archive specified by path. Currently
11223  * supported are .zip files that do not compress their contents, as used on
11224  * Android in the form of APKs, for example. "file_name" is the name of the ELF
11225  * file inside the archive. "func_name" matches symbol name or name@@LIB for
11226  * library functions.
11227  *
11228  * An overview of the APK format specifically provided here:
11229  * https://en.wikipedia.org/w/index.php?title=Apk_(file_format)&oldid=1139099120#Package_contents
11230  */
11231 static long elf_find_func_offset_from_archive(const char *archive_path, const char *file_name,
11232 					      const char *func_name)
11233 {
11234 	struct zip_archive *archive;
11235 	struct zip_entry entry;
11236 	long ret;
11237 	Elf *elf;
11238 
11239 	archive = zip_archive_open(archive_path);
11240 	if (IS_ERR(archive)) {
11241 		ret = PTR_ERR(archive);
11242 		pr_warn("zip: failed to open %s: %ld\n", archive_path, ret);
11243 		return ret;
11244 	}
11245 
11246 	ret = zip_archive_find_entry(archive, file_name, &entry);
11247 	if (ret) {
11248 		pr_warn("zip: could not find archive member %s in %s: %ld\n", file_name,
11249 			archive_path, ret);
11250 		goto out;
11251 	}
11252 	pr_debug("zip: found entry for %s in %s at 0x%lx\n", file_name, archive_path,
11253 		 (unsigned long)entry.data_offset);
11254 
11255 	if (entry.compression) {
11256 		pr_warn("zip: entry %s of %s is compressed and cannot be handled\n", file_name,
11257 			archive_path);
11258 		ret = -LIBBPF_ERRNO__FORMAT;
11259 		goto out;
11260 	}
11261 
11262 	elf = elf_memory((void *)entry.data, entry.data_length);
11263 	if (!elf) {
11264 		pr_warn("elf: could not read elf file %s from %s: %s\n", file_name, archive_path,
11265 			elf_errmsg(-1));
11266 		ret = -LIBBPF_ERRNO__LIBELF;
11267 		goto out;
11268 	}
11269 
11270 	ret = elf_find_func_offset(elf, file_name, func_name);
11271 	if (ret > 0) {
11272 		pr_debug("elf: symbol address match for %s of %s in %s: 0x%x + 0x%lx = 0x%lx\n",
11273 			 func_name, file_name, archive_path, entry.data_offset, ret,
11274 			 ret + entry.data_offset);
11275 		ret += entry.data_offset;
11276 	}
11277 	elf_end(elf);
11278 
11279 out:
11280 	zip_archive_close(archive);
11281 	return ret;
11282 }
11283 
11284 static const char *arch_specific_lib_paths(void)
11285 {
11286 	/*
11287 	 * Based on https://packages.debian.org/sid/libc6.
11288 	 *
11289 	 * Assume that the traced program is built for the same architecture
11290 	 * as libbpf, which should cover the vast majority of cases.
11291 	 */
11292 #if defined(__x86_64__)
11293 	return "/lib/x86_64-linux-gnu";
11294 #elif defined(__i386__)
11295 	return "/lib/i386-linux-gnu";
11296 #elif defined(__s390x__)
11297 	return "/lib/s390x-linux-gnu";
11298 #elif defined(__s390__)
11299 	return "/lib/s390-linux-gnu";
11300 #elif defined(__arm__) && defined(__SOFTFP__)
11301 	return "/lib/arm-linux-gnueabi";
11302 #elif defined(__arm__) && !defined(__SOFTFP__)
11303 	return "/lib/arm-linux-gnueabihf";
11304 #elif defined(__aarch64__)
11305 	return "/lib/aarch64-linux-gnu";
11306 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 64
11307 	return "/lib/mips64el-linux-gnuabi64";
11308 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 32
11309 	return "/lib/mipsel-linux-gnu";
11310 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
11311 	return "/lib/powerpc64le-linux-gnu";
11312 #elif defined(__sparc__) && defined(__arch64__)
11313 	return "/lib/sparc64-linux-gnu";
11314 #elif defined(__riscv) && __riscv_xlen == 64
11315 	return "/lib/riscv64-linux-gnu";
11316 #else
11317 	return NULL;
11318 #endif
11319 }
11320 
11321 /* Get full path to program/shared library. */
11322 static int resolve_full_path(const char *file, char *result, size_t result_sz)
11323 {
11324 	const char *search_paths[3] = {};
11325 	int i, perm;
11326 
11327 	if (str_has_sfx(file, ".so") || strstr(file, ".so.")) {
11328 		search_paths[0] = getenv("LD_LIBRARY_PATH");
11329 		search_paths[1] = "/usr/lib64:/usr/lib";
11330 		search_paths[2] = arch_specific_lib_paths();
11331 		perm = R_OK;
11332 	} else {
11333 		search_paths[0] = getenv("PATH");
11334 		search_paths[1] = "/usr/bin:/usr/sbin";
11335 		perm = R_OK | X_OK;
11336 	}
11337 
11338 	for (i = 0; i < ARRAY_SIZE(search_paths); i++) {
11339 		const char *s;
11340 
11341 		if (!search_paths[i])
11342 			continue;
11343 		for (s = search_paths[i]; s != NULL; s = strchr(s, ':')) {
11344 			char *next_path;
11345 			int seg_len;
11346 
11347 			if (s[0] == ':')
11348 				s++;
11349 			next_path = strchr(s, ':');
11350 			seg_len = next_path ? next_path - s : strlen(s);
11351 			if (!seg_len)
11352 				continue;
11353 			snprintf(result, result_sz, "%.*s/%s", seg_len, s, file);
11354 			/* ensure it has required permissions */
11355 			if (faccessat(AT_FDCWD, result, perm, AT_EACCESS) < 0)
11356 				continue;
11357 			pr_debug("resolved '%s' to '%s'\n", file, result);
11358 			return 0;
11359 		}
11360 	}
11361 	return -ENOENT;
11362 }
11363 
11364 struct bpf_link *
11365 bpf_program__attach_uprobe_multi(const struct bpf_program *prog,
11366 				 pid_t pid,
11367 				 const char *path,
11368 				 const char *func_pattern,
11369 				 const struct bpf_uprobe_multi_opts *opts)
11370 {
11371 	const unsigned long *ref_ctr_offsets = NULL, *offsets = NULL;
11372 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
11373 	unsigned long *resolved_offsets = NULL;
11374 	int err = 0, link_fd, prog_fd;
11375 	struct bpf_link *link = NULL;
11376 	char errmsg[STRERR_BUFSIZE];
11377 	char full_path[PATH_MAX];
11378 	const __u64 *cookies;
11379 	const char **syms;
11380 	size_t cnt;
11381 
11382 	if (!OPTS_VALID(opts, bpf_uprobe_multi_opts))
11383 		return libbpf_err_ptr(-EINVAL);
11384 
11385 	syms = OPTS_GET(opts, syms, NULL);
11386 	offsets = OPTS_GET(opts, offsets, NULL);
11387 	ref_ctr_offsets = OPTS_GET(opts, ref_ctr_offsets, NULL);
11388 	cookies = OPTS_GET(opts, cookies, NULL);
11389 	cnt = OPTS_GET(opts, cnt, 0);
11390 
11391 	/*
11392 	 * User can specify 2 mutually exclusive set of inputs:
11393 	 *
11394 	 * 1) use only path/func_pattern/pid arguments
11395 	 *
11396 	 * 2) use path/pid with allowed combinations of:
11397 	 *    syms/offsets/ref_ctr_offsets/cookies/cnt
11398 	 *
11399 	 *    - syms and offsets are mutually exclusive
11400 	 *    - ref_ctr_offsets and cookies are optional
11401 	 *
11402 	 * Any other usage results in error.
11403 	 */
11404 
11405 	if (!path)
11406 		return libbpf_err_ptr(-EINVAL);
11407 	if (!func_pattern && cnt == 0)
11408 		return libbpf_err_ptr(-EINVAL);
11409 
11410 	if (func_pattern) {
11411 		if (syms || offsets || ref_ctr_offsets || cookies || cnt)
11412 			return libbpf_err_ptr(-EINVAL);
11413 	} else {
11414 		if (!!syms == !!offsets)
11415 			return libbpf_err_ptr(-EINVAL);
11416 	}
11417 
11418 	if (func_pattern) {
11419 		if (!strchr(path, '/')) {
11420 			err = resolve_full_path(path, full_path, sizeof(full_path));
11421 			if (err) {
11422 				pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11423 					prog->name, path, err);
11424 				return libbpf_err_ptr(err);
11425 			}
11426 			path = full_path;
11427 		}
11428 
11429 		err = elf_resolve_pattern_offsets(path, func_pattern,
11430 						  &resolved_offsets, &cnt);
11431 		if (err < 0)
11432 			return libbpf_err_ptr(err);
11433 		offsets = resolved_offsets;
11434 	} else if (syms) {
11435 		err = elf_resolve_syms_offsets(path, cnt, syms, &resolved_offsets);
11436 		if (err < 0)
11437 			return libbpf_err_ptr(err);
11438 		offsets = resolved_offsets;
11439 	}
11440 
11441 	lopts.uprobe_multi.path = path;
11442 	lopts.uprobe_multi.offsets = offsets;
11443 	lopts.uprobe_multi.ref_ctr_offsets = ref_ctr_offsets;
11444 	lopts.uprobe_multi.cookies = cookies;
11445 	lopts.uprobe_multi.cnt = cnt;
11446 	lopts.uprobe_multi.flags = OPTS_GET(opts, retprobe, false) ? BPF_F_UPROBE_MULTI_RETURN : 0;
11447 
11448 	if (pid == 0)
11449 		pid = getpid();
11450 	if (pid > 0)
11451 		lopts.uprobe_multi.pid = pid;
11452 
11453 	link = calloc(1, sizeof(*link));
11454 	if (!link) {
11455 		err = -ENOMEM;
11456 		goto error;
11457 	}
11458 	link->detach = &bpf_link__detach_fd;
11459 
11460 	prog_fd = bpf_program__fd(prog);
11461 	link_fd = bpf_link_create(prog_fd, 0, BPF_TRACE_UPROBE_MULTI, &lopts);
11462 	if (link_fd < 0) {
11463 		err = -errno;
11464 		pr_warn("prog '%s': failed to attach multi-uprobe: %s\n",
11465 			prog->name, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11466 		goto error;
11467 	}
11468 	link->fd = link_fd;
11469 	free(resolved_offsets);
11470 	return link;
11471 
11472 error:
11473 	free(resolved_offsets);
11474 	free(link);
11475 	return libbpf_err_ptr(err);
11476 }
11477 
11478 LIBBPF_API struct bpf_link *
11479 bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
11480 				const char *binary_path, size_t func_offset,
11481 				const struct bpf_uprobe_opts *opts)
11482 {
11483 	const char *archive_path = NULL, *archive_sep = NULL;
11484 	char errmsg[STRERR_BUFSIZE], *legacy_probe = NULL;
11485 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11486 	enum probe_attach_mode attach_mode;
11487 	char full_path[PATH_MAX];
11488 	struct bpf_link *link;
11489 	size_t ref_ctr_off;
11490 	int pfd, err;
11491 	bool retprobe, legacy;
11492 	const char *func_name;
11493 
11494 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
11495 		return libbpf_err_ptr(-EINVAL);
11496 
11497 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
11498 	retprobe = OPTS_GET(opts, retprobe, false);
11499 	ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
11500 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11501 
11502 	if (!binary_path)
11503 		return libbpf_err_ptr(-EINVAL);
11504 
11505 	/* Check if "binary_path" refers to an archive. */
11506 	archive_sep = strstr(binary_path, "!/");
11507 	if (archive_sep) {
11508 		full_path[0] = '\0';
11509 		libbpf_strlcpy(full_path, binary_path,
11510 			       min(sizeof(full_path), (size_t)(archive_sep - binary_path + 1)));
11511 		archive_path = full_path;
11512 		binary_path = archive_sep + 2;
11513 	} else if (!strchr(binary_path, '/')) {
11514 		err = resolve_full_path(binary_path, full_path, sizeof(full_path));
11515 		if (err) {
11516 			pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11517 				prog->name, binary_path, err);
11518 			return libbpf_err_ptr(err);
11519 		}
11520 		binary_path = full_path;
11521 	}
11522 	func_name = OPTS_GET(opts, func_name, NULL);
11523 	if (func_name) {
11524 		long sym_off;
11525 
11526 		if (archive_path) {
11527 			sym_off = elf_find_func_offset_from_archive(archive_path, binary_path,
11528 								    func_name);
11529 			binary_path = archive_path;
11530 		} else {
11531 			sym_off = elf_find_func_offset_from_file(binary_path, func_name);
11532 		}
11533 		if (sym_off < 0)
11534 			return libbpf_err_ptr(sym_off);
11535 		func_offset += sym_off;
11536 	}
11537 
11538 	legacy = determine_uprobe_perf_type() < 0;
11539 	switch (attach_mode) {
11540 	case PROBE_ATTACH_MODE_LEGACY:
11541 		legacy = true;
11542 		pe_opts.force_ioctl_attach = true;
11543 		break;
11544 	case PROBE_ATTACH_MODE_PERF:
11545 		if (legacy)
11546 			return libbpf_err_ptr(-ENOTSUP);
11547 		pe_opts.force_ioctl_attach = true;
11548 		break;
11549 	case PROBE_ATTACH_MODE_LINK:
11550 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
11551 			return libbpf_err_ptr(-ENOTSUP);
11552 		break;
11553 	case PROBE_ATTACH_MODE_DEFAULT:
11554 		break;
11555 	default:
11556 		return libbpf_err_ptr(-EINVAL);
11557 	}
11558 
11559 	if (!legacy) {
11560 		pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
11561 					    func_offset, pid, ref_ctr_off);
11562 	} else {
11563 		char probe_name[PATH_MAX + 64];
11564 
11565 		if (ref_ctr_off)
11566 			return libbpf_err_ptr(-EINVAL);
11567 
11568 		gen_uprobe_legacy_event_name(probe_name, sizeof(probe_name),
11569 					     binary_path, func_offset);
11570 
11571 		legacy_probe = strdup(probe_name);
11572 		if (!legacy_probe)
11573 			return libbpf_err_ptr(-ENOMEM);
11574 
11575 		pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
11576 						    binary_path, func_offset, pid);
11577 	}
11578 	if (pfd < 0) {
11579 		err = -errno;
11580 		pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
11581 			prog->name, retprobe ? "uretprobe" : "uprobe",
11582 			binary_path, func_offset,
11583 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11584 		goto err_out;
11585 	}
11586 
11587 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11588 	err = libbpf_get_error(link);
11589 	if (err) {
11590 		close(pfd);
11591 		pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
11592 			prog->name, retprobe ? "uretprobe" : "uprobe",
11593 			binary_path, func_offset,
11594 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11595 		goto err_clean_legacy;
11596 	}
11597 	if (legacy) {
11598 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
11599 
11600 		perf_link->legacy_probe_name = legacy_probe;
11601 		perf_link->legacy_is_kprobe = false;
11602 		perf_link->legacy_is_retprobe = retprobe;
11603 	}
11604 	return link;
11605 
11606 err_clean_legacy:
11607 	if (legacy)
11608 		remove_uprobe_event_legacy(legacy_probe, retprobe);
11609 err_out:
11610 	free(legacy_probe);
11611 	return libbpf_err_ptr(err);
11612 }
11613 
11614 /* Format of u[ret]probe section definition supporting auto-attach:
11615  * u[ret]probe/binary:function[+offset]
11616  *
11617  * binary can be an absolute/relative path or a filename; the latter is resolved to a
11618  * full binary path via bpf_program__attach_uprobe_opts.
11619  *
11620  * Specifying uprobe+ ensures we carry out strict matching; either "uprobe" must be
11621  * specified (and auto-attach is not possible) or the above format is specified for
11622  * auto-attach.
11623  */
11624 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11625 {
11626 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts);
11627 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
11628 	int n, ret = -EINVAL;
11629 	long offset = 0;
11630 
11631 	*link = NULL;
11632 
11633 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[a-zA-Z0-9_.]+%li",
11634 		   &probe_type, &binary_path, &func_name, &offset);
11635 	switch (n) {
11636 	case 1:
11637 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
11638 		ret = 0;
11639 		break;
11640 	case 2:
11641 		pr_warn("prog '%s': section '%s' missing ':function[+offset]' specification\n",
11642 			prog->name, prog->sec_name);
11643 		break;
11644 	case 3:
11645 	case 4:
11646 		opts.retprobe = strcmp(probe_type, "uretprobe") == 0 ||
11647 				strcmp(probe_type, "uretprobe.s") == 0;
11648 		if (opts.retprobe && offset != 0) {
11649 			pr_warn("prog '%s': uretprobes do not support offset specification\n",
11650 				prog->name);
11651 			break;
11652 		}
11653 		opts.func_name = func_name;
11654 		*link = bpf_program__attach_uprobe_opts(prog, -1, binary_path, offset, &opts);
11655 		ret = libbpf_get_error(*link);
11656 		break;
11657 	default:
11658 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
11659 			prog->sec_name);
11660 		break;
11661 	}
11662 	free(probe_type);
11663 	free(binary_path);
11664 	free(func_name);
11665 
11666 	return ret;
11667 }
11668 
11669 struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
11670 					    bool retprobe, pid_t pid,
11671 					    const char *binary_path,
11672 					    size_t func_offset)
11673 {
11674 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
11675 
11676 	return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
11677 }
11678 
11679 struct bpf_link *bpf_program__attach_usdt(const struct bpf_program *prog,
11680 					  pid_t pid, const char *binary_path,
11681 					  const char *usdt_provider, const char *usdt_name,
11682 					  const struct bpf_usdt_opts *opts)
11683 {
11684 	char resolved_path[512];
11685 	struct bpf_object *obj = prog->obj;
11686 	struct bpf_link *link;
11687 	__u64 usdt_cookie;
11688 	int err;
11689 
11690 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
11691 		return libbpf_err_ptr(-EINVAL);
11692 
11693 	if (bpf_program__fd(prog) < 0) {
11694 		pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
11695 			prog->name);
11696 		return libbpf_err_ptr(-EINVAL);
11697 	}
11698 
11699 	if (!binary_path)
11700 		return libbpf_err_ptr(-EINVAL);
11701 
11702 	if (!strchr(binary_path, '/')) {
11703 		err = resolve_full_path(binary_path, resolved_path, sizeof(resolved_path));
11704 		if (err) {
11705 			pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11706 				prog->name, binary_path, err);
11707 			return libbpf_err_ptr(err);
11708 		}
11709 		binary_path = resolved_path;
11710 	}
11711 
11712 	/* USDT manager is instantiated lazily on first USDT attach. It will
11713 	 * be destroyed together with BPF object in bpf_object__close().
11714 	 */
11715 	if (IS_ERR(obj->usdt_man))
11716 		return libbpf_ptr(obj->usdt_man);
11717 	if (!obj->usdt_man) {
11718 		obj->usdt_man = usdt_manager_new(obj);
11719 		if (IS_ERR(obj->usdt_man))
11720 			return libbpf_ptr(obj->usdt_man);
11721 	}
11722 
11723 	usdt_cookie = OPTS_GET(opts, usdt_cookie, 0);
11724 	link = usdt_manager_attach_usdt(obj->usdt_man, prog, pid, binary_path,
11725 					usdt_provider, usdt_name, usdt_cookie);
11726 	err = libbpf_get_error(link);
11727 	if (err)
11728 		return libbpf_err_ptr(err);
11729 	return link;
11730 }
11731 
11732 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11733 {
11734 	char *path = NULL, *provider = NULL, *name = NULL;
11735 	const char *sec_name;
11736 	int n, err;
11737 
11738 	sec_name = bpf_program__section_name(prog);
11739 	if (strcmp(sec_name, "usdt") == 0) {
11740 		/* no auto-attach for just SEC("usdt") */
11741 		*link = NULL;
11742 		return 0;
11743 	}
11744 
11745 	n = sscanf(sec_name, "usdt/%m[^:]:%m[^:]:%m[^:]", &path, &provider, &name);
11746 	if (n != 3) {
11747 		pr_warn("invalid section '%s', expected SEC(\"usdt/<path>:<provider>:<name>\")\n",
11748 			sec_name);
11749 		err = -EINVAL;
11750 	} else {
11751 		*link = bpf_program__attach_usdt(prog, -1 /* any process */, path,
11752 						 provider, name, NULL);
11753 		err = libbpf_get_error(*link);
11754 	}
11755 	free(path);
11756 	free(provider);
11757 	free(name);
11758 	return err;
11759 }
11760 
11761 static int determine_tracepoint_id(const char *tp_category,
11762 				   const char *tp_name)
11763 {
11764 	char file[PATH_MAX];
11765 	int ret;
11766 
11767 	ret = snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11768 		       tracefs_path(), tp_category, tp_name);
11769 	if (ret < 0)
11770 		return -errno;
11771 	if (ret >= sizeof(file)) {
11772 		pr_debug("tracepoint %s/%s path is too long\n",
11773 			 tp_category, tp_name);
11774 		return -E2BIG;
11775 	}
11776 	return parse_uint_from_file(file, "%d\n");
11777 }
11778 
11779 static int perf_event_open_tracepoint(const char *tp_category,
11780 				      const char *tp_name)
11781 {
11782 	const size_t attr_sz = sizeof(struct perf_event_attr);
11783 	struct perf_event_attr attr;
11784 	char errmsg[STRERR_BUFSIZE];
11785 	int tp_id, pfd, err;
11786 
11787 	tp_id = determine_tracepoint_id(tp_category, tp_name);
11788 	if (tp_id < 0) {
11789 		pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
11790 			tp_category, tp_name,
11791 			libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
11792 		return tp_id;
11793 	}
11794 
11795 	memset(&attr, 0, attr_sz);
11796 	attr.type = PERF_TYPE_TRACEPOINT;
11797 	attr.size = attr_sz;
11798 	attr.config = tp_id;
11799 
11800 	pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
11801 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
11802 	if (pfd < 0) {
11803 		err = -errno;
11804 		pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
11805 			tp_category, tp_name,
11806 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11807 		return err;
11808 	}
11809 	return pfd;
11810 }
11811 
11812 struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
11813 						     const char *tp_category,
11814 						     const char *tp_name,
11815 						     const struct bpf_tracepoint_opts *opts)
11816 {
11817 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11818 	char errmsg[STRERR_BUFSIZE];
11819 	struct bpf_link *link;
11820 	int pfd, err;
11821 
11822 	if (!OPTS_VALID(opts, bpf_tracepoint_opts))
11823 		return libbpf_err_ptr(-EINVAL);
11824 
11825 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11826 
11827 	pfd = perf_event_open_tracepoint(tp_category, tp_name);
11828 	if (pfd < 0) {
11829 		pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
11830 			prog->name, tp_category, tp_name,
11831 			libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11832 		return libbpf_err_ptr(pfd);
11833 	}
11834 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11835 	err = libbpf_get_error(link);
11836 	if (err) {
11837 		close(pfd);
11838 		pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
11839 			prog->name, tp_category, tp_name,
11840 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11841 		return libbpf_err_ptr(err);
11842 	}
11843 	return link;
11844 }
11845 
11846 struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
11847 						const char *tp_category,
11848 						const char *tp_name)
11849 {
11850 	return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
11851 }
11852 
11853 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11854 {
11855 	char *sec_name, *tp_cat, *tp_name;
11856 
11857 	*link = NULL;
11858 
11859 	/* no auto-attach for SEC("tp") or SEC("tracepoint") */
11860 	if (strcmp(prog->sec_name, "tp") == 0 || strcmp(prog->sec_name, "tracepoint") == 0)
11861 		return 0;
11862 
11863 	sec_name = strdup(prog->sec_name);
11864 	if (!sec_name)
11865 		return -ENOMEM;
11866 
11867 	/* extract "tp/<category>/<name>" or "tracepoint/<category>/<name>" */
11868 	if (str_has_pfx(prog->sec_name, "tp/"))
11869 		tp_cat = sec_name + sizeof("tp/") - 1;
11870 	else
11871 		tp_cat = sec_name + sizeof("tracepoint/") - 1;
11872 	tp_name = strchr(tp_cat, '/');
11873 	if (!tp_name) {
11874 		free(sec_name);
11875 		return -EINVAL;
11876 	}
11877 	*tp_name = '\0';
11878 	tp_name++;
11879 
11880 	*link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
11881 	free(sec_name);
11882 	return libbpf_get_error(*link);
11883 }
11884 
11885 struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
11886 						    const char *tp_name)
11887 {
11888 	char errmsg[STRERR_BUFSIZE];
11889 	struct bpf_link *link;
11890 	int prog_fd, pfd;
11891 
11892 	prog_fd = bpf_program__fd(prog);
11893 	if (prog_fd < 0) {
11894 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11895 		return libbpf_err_ptr(-EINVAL);
11896 	}
11897 
11898 	link = calloc(1, sizeof(*link));
11899 	if (!link)
11900 		return libbpf_err_ptr(-ENOMEM);
11901 	link->detach = &bpf_link__detach_fd;
11902 
11903 	pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
11904 	if (pfd < 0) {
11905 		pfd = -errno;
11906 		free(link);
11907 		pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
11908 			prog->name, tp_name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11909 		return libbpf_err_ptr(pfd);
11910 	}
11911 	link->fd = pfd;
11912 	return link;
11913 }
11914 
11915 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11916 {
11917 	static const char *const prefixes[] = {
11918 		"raw_tp",
11919 		"raw_tracepoint",
11920 		"raw_tp.w",
11921 		"raw_tracepoint.w",
11922 	};
11923 	size_t i;
11924 	const char *tp_name = NULL;
11925 
11926 	*link = NULL;
11927 
11928 	for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
11929 		size_t pfx_len;
11930 
11931 		if (!str_has_pfx(prog->sec_name, prefixes[i]))
11932 			continue;
11933 
11934 		pfx_len = strlen(prefixes[i]);
11935 		/* no auto-attach case of, e.g., SEC("raw_tp") */
11936 		if (prog->sec_name[pfx_len] == '\0')
11937 			return 0;
11938 
11939 		if (prog->sec_name[pfx_len] != '/')
11940 			continue;
11941 
11942 		tp_name = prog->sec_name + pfx_len + 1;
11943 		break;
11944 	}
11945 
11946 	if (!tp_name) {
11947 		pr_warn("prog '%s': invalid section name '%s'\n",
11948 			prog->name, prog->sec_name);
11949 		return -EINVAL;
11950 	}
11951 
11952 	*link = bpf_program__attach_raw_tracepoint(prog, tp_name);
11953 	return libbpf_get_error(*link);
11954 }
11955 
11956 /* Common logic for all BPF program types that attach to a btf_id */
11957 static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog,
11958 						   const struct bpf_trace_opts *opts)
11959 {
11960 	LIBBPF_OPTS(bpf_link_create_opts, link_opts);
11961 	char errmsg[STRERR_BUFSIZE];
11962 	struct bpf_link *link;
11963 	int prog_fd, pfd;
11964 
11965 	if (!OPTS_VALID(opts, bpf_trace_opts))
11966 		return libbpf_err_ptr(-EINVAL);
11967 
11968 	prog_fd = bpf_program__fd(prog);
11969 	if (prog_fd < 0) {
11970 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11971 		return libbpf_err_ptr(-EINVAL);
11972 	}
11973 
11974 	link = calloc(1, sizeof(*link));
11975 	if (!link)
11976 		return libbpf_err_ptr(-ENOMEM);
11977 	link->detach = &bpf_link__detach_fd;
11978 
11979 	/* libbpf is smart enough to redirect to BPF_RAW_TRACEPOINT_OPEN on old kernels */
11980 	link_opts.tracing.cookie = OPTS_GET(opts, cookie, 0);
11981 	pfd = bpf_link_create(prog_fd, 0, bpf_program__expected_attach_type(prog), &link_opts);
11982 	if (pfd < 0) {
11983 		pfd = -errno;
11984 		free(link);
11985 		pr_warn("prog '%s': failed to attach: %s\n",
11986 			prog->name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11987 		return libbpf_err_ptr(pfd);
11988 	}
11989 	link->fd = pfd;
11990 	return link;
11991 }
11992 
11993 struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
11994 {
11995 	return bpf_program__attach_btf_id(prog, NULL);
11996 }
11997 
11998 struct bpf_link *bpf_program__attach_trace_opts(const struct bpf_program *prog,
11999 						const struct bpf_trace_opts *opts)
12000 {
12001 	return bpf_program__attach_btf_id(prog, opts);
12002 }
12003 
12004 struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
12005 {
12006 	return bpf_program__attach_btf_id(prog, NULL);
12007 }
12008 
12009 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12010 {
12011 	*link = bpf_program__attach_trace(prog);
12012 	return libbpf_get_error(*link);
12013 }
12014 
12015 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12016 {
12017 	*link = bpf_program__attach_lsm(prog);
12018 	return libbpf_get_error(*link);
12019 }
12020 
12021 static struct bpf_link *
12022 bpf_program_attach_fd(const struct bpf_program *prog,
12023 		      int target_fd, const char *target_name,
12024 		      const struct bpf_link_create_opts *opts)
12025 {
12026 	enum bpf_attach_type attach_type;
12027 	char errmsg[STRERR_BUFSIZE];
12028 	struct bpf_link *link;
12029 	int prog_fd, link_fd;
12030 
12031 	prog_fd = bpf_program__fd(prog);
12032 	if (prog_fd < 0) {
12033 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12034 		return libbpf_err_ptr(-EINVAL);
12035 	}
12036 
12037 	link = calloc(1, sizeof(*link));
12038 	if (!link)
12039 		return libbpf_err_ptr(-ENOMEM);
12040 	link->detach = &bpf_link__detach_fd;
12041 
12042 	attach_type = bpf_program__expected_attach_type(prog);
12043 	link_fd = bpf_link_create(prog_fd, target_fd, attach_type, opts);
12044 	if (link_fd < 0) {
12045 		link_fd = -errno;
12046 		free(link);
12047 		pr_warn("prog '%s': failed to attach to %s: %s\n",
12048 			prog->name, target_name,
12049 			libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
12050 		return libbpf_err_ptr(link_fd);
12051 	}
12052 	link->fd = link_fd;
12053 	return link;
12054 }
12055 
12056 struct bpf_link *
12057 bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
12058 {
12059 	return bpf_program_attach_fd(prog, cgroup_fd, "cgroup", NULL);
12060 }
12061 
12062 struct bpf_link *
12063 bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
12064 {
12065 	return bpf_program_attach_fd(prog, netns_fd, "netns", NULL);
12066 }
12067 
12068 struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
12069 {
12070 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
12071 	return bpf_program_attach_fd(prog, ifindex, "xdp", NULL);
12072 }
12073 
12074 struct bpf_link *
12075 bpf_program__attach_tcx(const struct bpf_program *prog, int ifindex,
12076 			const struct bpf_tcx_opts *opts)
12077 {
12078 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12079 	__u32 relative_id;
12080 	int relative_fd;
12081 
12082 	if (!OPTS_VALID(opts, bpf_tcx_opts))
12083 		return libbpf_err_ptr(-EINVAL);
12084 
12085 	relative_id = OPTS_GET(opts, relative_id, 0);
12086 	relative_fd = OPTS_GET(opts, relative_fd, 0);
12087 
12088 	/* validate we don't have unexpected combinations of non-zero fields */
12089 	if (!ifindex) {
12090 		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
12091 			prog->name);
12092 		return libbpf_err_ptr(-EINVAL);
12093 	}
12094 	if (relative_fd && relative_id) {
12095 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
12096 			prog->name);
12097 		return libbpf_err_ptr(-EINVAL);
12098 	}
12099 
12100 	link_create_opts.tcx.expected_revision = OPTS_GET(opts, expected_revision, 0);
12101 	link_create_opts.tcx.relative_fd = relative_fd;
12102 	link_create_opts.tcx.relative_id = relative_id;
12103 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
12104 
12105 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
12106 	return bpf_program_attach_fd(prog, ifindex, "tcx", &link_create_opts);
12107 }
12108 
12109 struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
12110 					      int target_fd,
12111 					      const char *attach_func_name)
12112 {
12113 	int btf_id;
12114 
12115 	if (!!target_fd != !!attach_func_name) {
12116 		pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
12117 			prog->name);
12118 		return libbpf_err_ptr(-EINVAL);
12119 	}
12120 
12121 	if (prog->type != BPF_PROG_TYPE_EXT) {
12122 		pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace",
12123 			prog->name);
12124 		return libbpf_err_ptr(-EINVAL);
12125 	}
12126 
12127 	if (target_fd) {
12128 		LIBBPF_OPTS(bpf_link_create_opts, target_opts);
12129 
12130 		btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd);
12131 		if (btf_id < 0)
12132 			return libbpf_err_ptr(btf_id);
12133 
12134 		target_opts.target_btf_id = btf_id;
12135 
12136 		return bpf_program_attach_fd(prog, target_fd, "freplace",
12137 					     &target_opts);
12138 	} else {
12139 		/* no target, so use raw_tracepoint_open for compatibility
12140 		 * with old kernels
12141 		 */
12142 		return bpf_program__attach_trace(prog);
12143 	}
12144 }
12145 
12146 struct bpf_link *
12147 bpf_program__attach_iter(const struct bpf_program *prog,
12148 			 const struct bpf_iter_attach_opts *opts)
12149 {
12150 	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12151 	char errmsg[STRERR_BUFSIZE];
12152 	struct bpf_link *link;
12153 	int prog_fd, link_fd;
12154 	__u32 target_fd = 0;
12155 
12156 	if (!OPTS_VALID(opts, bpf_iter_attach_opts))
12157 		return libbpf_err_ptr(-EINVAL);
12158 
12159 	link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
12160 	link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
12161 
12162 	prog_fd = bpf_program__fd(prog);
12163 	if (prog_fd < 0) {
12164 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12165 		return libbpf_err_ptr(-EINVAL);
12166 	}
12167 
12168 	link = calloc(1, sizeof(*link));
12169 	if (!link)
12170 		return libbpf_err_ptr(-ENOMEM);
12171 	link->detach = &bpf_link__detach_fd;
12172 
12173 	link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
12174 				  &link_create_opts);
12175 	if (link_fd < 0) {
12176 		link_fd = -errno;
12177 		free(link);
12178 		pr_warn("prog '%s': failed to attach to iterator: %s\n",
12179 			prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
12180 		return libbpf_err_ptr(link_fd);
12181 	}
12182 	link->fd = link_fd;
12183 	return link;
12184 }
12185 
12186 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12187 {
12188 	*link = bpf_program__attach_iter(prog, NULL);
12189 	return libbpf_get_error(*link);
12190 }
12191 
12192 struct bpf_link *bpf_program__attach_netfilter(const struct bpf_program *prog,
12193 					       const struct bpf_netfilter_opts *opts)
12194 {
12195 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
12196 	struct bpf_link *link;
12197 	int prog_fd, link_fd;
12198 
12199 	if (!OPTS_VALID(opts, bpf_netfilter_opts))
12200 		return libbpf_err_ptr(-EINVAL);
12201 
12202 	prog_fd = bpf_program__fd(prog);
12203 	if (prog_fd < 0) {
12204 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12205 		return libbpf_err_ptr(-EINVAL);
12206 	}
12207 
12208 	link = calloc(1, sizeof(*link));
12209 	if (!link)
12210 		return libbpf_err_ptr(-ENOMEM);
12211 
12212 	link->detach = &bpf_link__detach_fd;
12213 
12214 	lopts.netfilter.pf = OPTS_GET(opts, pf, 0);
12215 	lopts.netfilter.hooknum = OPTS_GET(opts, hooknum, 0);
12216 	lopts.netfilter.priority = OPTS_GET(opts, priority, 0);
12217 	lopts.netfilter.flags = OPTS_GET(opts, flags, 0);
12218 
12219 	link_fd = bpf_link_create(prog_fd, 0, BPF_NETFILTER, &lopts);
12220 	if (link_fd < 0) {
12221 		char errmsg[STRERR_BUFSIZE];
12222 
12223 		link_fd = -errno;
12224 		free(link);
12225 		pr_warn("prog '%s': failed to attach to netfilter: %s\n",
12226 			prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
12227 		return libbpf_err_ptr(link_fd);
12228 	}
12229 	link->fd = link_fd;
12230 
12231 	return link;
12232 }
12233 
12234 struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
12235 {
12236 	struct bpf_link *link = NULL;
12237 	int err;
12238 
12239 	if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
12240 		return libbpf_err_ptr(-EOPNOTSUPP);
12241 
12242 	err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, &link);
12243 	if (err)
12244 		return libbpf_err_ptr(err);
12245 
12246 	/* When calling bpf_program__attach() explicitly, auto-attach support
12247 	 * is expected to work, so NULL returned link is considered an error.
12248 	 * This is different for skeleton's attach, see comment in
12249 	 * bpf_object__attach_skeleton().
12250 	 */
12251 	if (!link)
12252 		return libbpf_err_ptr(-EOPNOTSUPP);
12253 
12254 	return link;
12255 }
12256 
12257 struct bpf_link_struct_ops {
12258 	struct bpf_link link;
12259 	int map_fd;
12260 };
12261 
12262 static int bpf_link__detach_struct_ops(struct bpf_link *link)
12263 {
12264 	struct bpf_link_struct_ops *st_link;
12265 	__u32 zero = 0;
12266 
12267 	st_link = container_of(link, struct bpf_link_struct_ops, link);
12268 
12269 	if (st_link->map_fd < 0)
12270 		/* w/o a real link */
12271 		return bpf_map_delete_elem(link->fd, &zero);
12272 
12273 	return close(link->fd);
12274 }
12275 
12276 struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
12277 {
12278 	struct bpf_link_struct_ops *link;
12279 	__u32 zero = 0;
12280 	int err, fd;
12281 
12282 	if (!bpf_map__is_struct_ops(map) || map->fd == -1)
12283 		return libbpf_err_ptr(-EINVAL);
12284 
12285 	link = calloc(1, sizeof(*link));
12286 	if (!link)
12287 		return libbpf_err_ptr(-EINVAL);
12288 
12289 	/* kern_vdata should be prepared during the loading phase. */
12290 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
12291 	/* It can be EBUSY if the map has been used to create or
12292 	 * update a link before.  We don't allow updating the value of
12293 	 * a struct_ops once it is set.  That ensures that the value
12294 	 * never changed.  So, it is safe to skip EBUSY.
12295 	 */
12296 	if (err && (!(map->def.map_flags & BPF_F_LINK) || err != -EBUSY)) {
12297 		free(link);
12298 		return libbpf_err_ptr(err);
12299 	}
12300 
12301 	link->link.detach = bpf_link__detach_struct_ops;
12302 
12303 	if (!(map->def.map_flags & BPF_F_LINK)) {
12304 		/* w/o a real link */
12305 		link->link.fd = map->fd;
12306 		link->map_fd = -1;
12307 		return &link->link;
12308 	}
12309 
12310 	fd = bpf_link_create(map->fd, 0, BPF_STRUCT_OPS, NULL);
12311 	if (fd < 0) {
12312 		free(link);
12313 		return libbpf_err_ptr(fd);
12314 	}
12315 
12316 	link->link.fd = fd;
12317 	link->map_fd = map->fd;
12318 
12319 	return &link->link;
12320 }
12321 
12322 /*
12323  * Swap the back struct_ops of a link with a new struct_ops map.
12324  */
12325 int bpf_link__update_map(struct bpf_link *link, const struct bpf_map *map)
12326 {
12327 	struct bpf_link_struct_ops *st_ops_link;
12328 	__u32 zero = 0;
12329 	int err;
12330 
12331 	if (!bpf_map__is_struct_ops(map) || map->fd < 0)
12332 		return -EINVAL;
12333 
12334 	st_ops_link = container_of(link, struct bpf_link_struct_ops, link);
12335 	/* Ensure the type of a link is correct */
12336 	if (st_ops_link->map_fd < 0)
12337 		return -EINVAL;
12338 
12339 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
12340 	/* It can be EBUSY if the map has been used to create or
12341 	 * update a link before.  We don't allow updating the value of
12342 	 * a struct_ops once it is set.  That ensures that the value
12343 	 * never changed.  So, it is safe to skip EBUSY.
12344 	 */
12345 	if (err && err != -EBUSY)
12346 		return err;
12347 
12348 	err = bpf_link_update(link->fd, map->fd, NULL);
12349 	if (err < 0)
12350 		return err;
12351 
12352 	st_ops_link->map_fd = map->fd;
12353 
12354 	return 0;
12355 }
12356 
12357 typedef enum bpf_perf_event_ret (*bpf_perf_event_print_t)(struct perf_event_header *hdr,
12358 							  void *private_data);
12359 
12360 static enum bpf_perf_event_ret
12361 perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
12362 		       void **copy_mem, size_t *copy_size,
12363 		       bpf_perf_event_print_t fn, void *private_data)
12364 {
12365 	struct perf_event_mmap_page *header = mmap_mem;
12366 	__u64 data_head = ring_buffer_read_head(header);
12367 	__u64 data_tail = header->data_tail;
12368 	void *base = ((__u8 *)header) + page_size;
12369 	int ret = LIBBPF_PERF_EVENT_CONT;
12370 	struct perf_event_header *ehdr;
12371 	size_t ehdr_size;
12372 
12373 	while (data_head != data_tail) {
12374 		ehdr = base + (data_tail & (mmap_size - 1));
12375 		ehdr_size = ehdr->size;
12376 
12377 		if (((void *)ehdr) + ehdr_size > base + mmap_size) {
12378 			void *copy_start = ehdr;
12379 			size_t len_first = base + mmap_size - copy_start;
12380 			size_t len_secnd = ehdr_size - len_first;
12381 
12382 			if (*copy_size < ehdr_size) {
12383 				free(*copy_mem);
12384 				*copy_mem = malloc(ehdr_size);
12385 				if (!*copy_mem) {
12386 					*copy_size = 0;
12387 					ret = LIBBPF_PERF_EVENT_ERROR;
12388 					break;
12389 				}
12390 				*copy_size = ehdr_size;
12391 			}
12392 
12393 			memcpy(*copy_mem, copy_start, len_first);
12394 			memcpy(*copy_mem + len_first, base, len_secnd);
12395 			ehdr = *copy_mem;
12396 		}
12397 
12398 		ret = fn(ehdr, private_data);
12399 		data_tail += ehdr_size;
12400 		if (ret != LIBBPF_PERF_EVENT_CONT)
12401 			break;
12402 	}
12403 
12404 	ring_buffer_write_tail(header, data_tail);
12405 	return libbpf_err(ret);
12406 }
12407 
12408 struct perf_buffer;
12409 
12410 struct perf_buffer_params {
12411 	struct perf_event_attr *attr;
12412 	/* if event_cb is specified, it takes precendence */
12413 	perf_buffer_event_fn event_cb;
12414 	/* sample_cb and lost_cb are higher-level common-case callbacks */
12415 	perf_buffer_sample_fn sample_cb;
12416 	perf_buffer_lost_fn lost_cb;
12417 	void *ctx;
12418 	int cpu_cnt;
12419 	int *cpus;
12420 	int *map_keys;
12421 };
12422 
12423 struct perf_cpu_buf {
12424 	struct perf_buffer *pb;
12425 	void *base; /* mmap()'ed memory */
12426 	void *buf; /* for reconstructing segmented data */
12427 	size_t buf_size;
12428 	int fd;
12429 	int cpu;
12430 	int map_key;
12431 };
12432 
12433 struct perf_buffer {
12434 	perf_buffer_event_fn event_cb;
12435 	perf_buffer_sample_fn sample_cb;
12436 	perf_buffer_lost_fn lost_cb;
12437 	void *ctx; /* passed into callbacks */
12438 
12439 	size_t page_size;
12440 	size_t mmap_size;
12441 	struct perf_cpu_buf **cpu_bufs;
12442 	struct epoll_event *events;
12443 	int cpu_cnt; /* number of allocated CPU buffers */
12444 	int epoll_fd; /* perf event FD */
12445 	int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
12446 };
12447 
12448 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
12449 				      struct perf_cpu_buf *cpu_buf)
12450 {
12451 	if (!cpu_buf)
12452 		return;
12453 	if (cpu_buf->base &&
12454 	    munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
12455 		pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
12456 	if (cpu_buf->fd >= 0) {
12457 		ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
12458 		close(cpu_buf->fd);
12459 	}
12460 	free(cpu_buf->buf);
12461 	free(cpu_buf);
12462 }
12463 
12464 void perf_buffer__free(struct perf_buffer *pb)
12465 {
12466 	int i;
12467 
12468 	if (IS_ERR_OR_NULL(pb))
12469 		return;
12470 	if (pb->cpu_bufs) {
12471 		for (i = 0; i < pb->cpu_cnt; i++) {
12472 			struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
12473 
12474 			if (!cpu_buf)
12475 				continue;
12476 
12477 			bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
12478 			perf_buffer__free_cpu_buf(pb, cpu_buf);
12479 		}
12480 		free(pb->cpu_bufs);
12481 	}
12482 	if (pb->epoll_fd >= 0)
12483 		close(pb->epoll_fd);
12484 	free(pb->events);
12485 	free(pb);
12486 }
12487 
12488 static struct perf_cpu_buf *
12489 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
12490 			  int cpu, int map_key)
12491 {
12492 	struct perf_cpu_buf *cpu_buf;
12493 	char msg[STRERR_BUFSIZE];
12494 	int err;
12495 
12496 	cpu_buf = calloc(1, sizeof(*cpu_buf));
12497 	if (!cpu_buf)
12498 		return ERR_PTR(-ENOMEM);
12499 
12500 	cpu_buf->pb = pb;
12501 	cpu_buf->cpu = cpu;
12502 	cpu_buf->map_key = map_key;
12503 
12504 	cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
12505 			      -1, PERF_FLAG_FD_CLOEXEC);
12506 	if (cpu_buf->fd < 0) {
12507 		err = -errno;
12508 		pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
12509 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
12510 		goto error;
12511 	}
12512 
12513 	cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
12514 			     PROT_READ | PROT_WRITE, MAP_SHARED,
12515 			     cpu_buf->fd, 0);
12516 	if (cpu_buf->base == MAP_FAILED) {
12517 		cpu_buf->base = NULL;
12518 		err = -errno;
12519 		pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
12520 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
12521 		goto error;
12522 	}
12523 
12524 	if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
12525 		err = -errno;
12526 		pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
12527 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
12528 		goto error;
12529 	}
12530 
12531 	return cpu_buf;
12532 
12533 error:
12534 	perf_buffer__free_cpu_buf(pb, cpu_buf);
12535 	return (struct perf_cpu_buf *)ERR_PTR(err);
12536 }
12537 
12538 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
12539 					      struct perf_buffer_params *p);
12540 
12541 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
12542 				     perf_buffer_sample_fn sample_cb,
12543 				     perf_buffer_lost_fn lost_cb,
12544 				     void *ctx,
12545 				     const struct perf_buffer_opts *opts)
12546 {
12547 	const size_t attr_sz = sizeof(struct perf_event_attr);
12548 	struct perf_buffer_params p = {};
12549 	struct perf_event_attr attr;
12550 	__u32 sample_period;
12551 
12552 	if (!OPTS_VALID(opts, perf_buffer_opts))
12553 		return libbpf_err_ptr(-EINVAL);
12554 
12555 	sample_period = OPTS_GET(opts, sample_period, 1);
12556 	if (!sample_period)
12557 		sample_period = 1;
12558 
12559 	memset(&attr, 0, attr_sz);
12560 	attr.size = attr_sz;
12561 	attr.config = PERF_COUNT_SW_BPF_OUTPUT;
12562 	attr.type = PERF_TYPE_SOFTWARE;
12563 	attr.sample_type = PERF_SAMPLE_RAW;
12564 	attr.sample_period = sample_period;
12565 	attr.wakeup_events = sample_period;
12566 
12567 	p.attr = &attr;
12568 	p.sample_cb = sample_cb;
12569 	p.lost_cb = lost_cb;
12570 	p.ctx = ctx;
12571 
12572 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
12573 }
12574 
12575 struct perf_buffer *perf_buffer__new_raw(int map_fd, size_t page_cnt,
12576 					 struct perf_event_attr *attr,
12577 					 perf_buffer_event_fn event_cb, void *ctx,
12578 					 const struct perf_buffer_raw_opts *opts)
12579 {
12580 	struct perf_buffer_params p = {};
12581 
12582 	if (!attr)
12583 		return libbpf_err_ptr(-EINVAL);
12584 
12585 	if (!OPTS_VALID(opts, perf_buffer_raw_opts))
12586 		return libbpf_err_ptr(-EINVAL);
12587 
12588 	p.attr = attr;
12589 	p.event_cb = event_cb;
12590 	p.ctx = ctx;
12591 	p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
12592 	p.cpus = OPTS_GET(opts, cpus, NULL);
12593 	p.map_keys = OPTS_GET(opts, map_keys, NULL);
12594 
12595 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
12596 }
12597 
12598 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
12599 					      struct perf_buffer_params *p)
12600 {
12601 	const char *online_cpus_file = "/sys/devices/system/cpu/online";
12602 	struct bpf_map_info map;
12603 	char msg[STRERR_BUFSIZE];
12604 	struct perf_buffer *pb;
12605 	bool *online = NULL;
12606 	__u32 map_info_len;
12607 	int err, i, j, n;
12608 
12609 	if (page_cnt == 0 || (page_cnt & (page_cnt - 1))) {
12610 		pr_warn("page count should be power of two, but is %zu\n",
12611 			page_cnt);
12612 		return ERR_PTR(-EINVAL);
12613 	}
12614 
12615 	/* best-effort sanity checks */
12616 	memset(&map, 0, sizeof(map));
12617 	map_info_len = sizeof(map);
12618 	err = bpf_map_get_info_by_fd(map_fd, &map, &map_info_len);
12619 	if (err) {
12620 		err = -errno;
12621 		/* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
12622 		 * -EBADFD, -EFAULT, or -E2BIG on real error
12623 		 */
12624 		if (err != -EINVAL) {
12625 			pr_warn("failed to get map info for map FD %d: %s\n",
12626 				map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
12627 			return ERR_PTR(err);
12628 		}
12629 		pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
12630 			 map_fd);
12631 	} else {
12632 		if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
12633 			pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
12634 				map.name);
12635 			return ERR_PTR(-EINVAL);
12636 		}
12637 	}
12638 
12639 	pb = calloc(1, sizeof(*pb));
12640 	if (!pb)
12641 		return ERR_PTR(-ENOMEM);
12642 
12643 	pb->event_cb = p->event_cb;
12644 	pb->sample_cb = p->sample_cb;
12645 	pb->lost_cb = p->lost_cb;
12646 	pb->ctx = p->ctx;
12647 
12648 	pb->page_size = getpagesize();
12649 	pb->mmap_size = pb->page_size * page_cnt;
12650 	pb->map_fd = map_fd;
12651 
12652 	pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
12653 	if (pb->epoll_fd < 0) {
12654 		err = -errno;
12655 		pr_warn("failed to create epoll instance: %s\n",
12656 			libbpf_strerror_r(err, msg, sizeof(msg)));
12657 		goto error;
12658 	}
12659 
12660 	if (p->cpu_cnt > 0) {
12661 		pb->cpu_cnt = p->cpu_cnt;
12662 	} else {
12663 		pb->cpu_cnt = libbpf_num_possible_cpus();
12664 		if (pb->cpu_cnt < 0) {
12665 			err = pb->cpu_cnt;
12666 			goto error;
12667 		}
12668 		if (map.max_entries && map.max_entries < pb->cpu_cnt)
12669 			pb->cpu_cnt = map.max_entries;
12670 	}
12671 
12672 	pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
12673 	if (!pb->events) {
12674 		err = -ENOMEM;
12675 		pr_warn("failed to allocate events: out of memory\n");
12676 		goto error;
12677 	}
12678 	pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
12679 	if (!pb->cpu_bufs) {
12680 		err = -ENOMEM;
12681 		pr_warn("failed to allocate buffers: out of memory\n");
12682 		goto error;
12683 	}
12684 
12685 	err = parse_cpu_mask_file(online_cpus_file, &online, &n);
12686 	if (err) {
12687 		pr_warn("failed to get online CPU mask: %d\n", err);
12688 		goto error;
12689 	}
12690 
12691 	for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
12692 		struct perf_cpu_buf *cpu_buf;
12693 		int cpu, map_key;
12694 
12695 		cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
12696 		map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
12697 
12698 		/* in case user didn't explicitly requested particular CPUs to
12699 		 * be attached to, skip offline/not present CPUs
12700 		 */
12701 		if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
12702 			continue;
12703 
12704 		cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
12705 		if (IS_ERR(cpu_buf)) {
12706 			err = PTR_ERR(cpu_buf);
12707 			goto error;
12708 		}
12709 
12710 		pb->cpu_bufs[j] = cpu_buf;
12711 
12712 		err = bpf_map_update_elem(pb->map_fd, &map_key,
12713 					  &cpu_buf->fd, 0);
12714 		if (err) {
12715 			err = -errno;
12716 			pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
12717 				cpu, map_key, cpu_buf->fd,
12718 				libbpf_strerror_r(err, msg, sizeof(msg)));
12719 			goto error;
12720 		}
12721 
12722 		pb->events[j].events = EPOLLIN;
12723 		pb->events[j].data.ptr = cpu_buf;
12724 		if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
12725 			      &pb->events[j]) < 0) {
12726 			err = -errno;
12727 			pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
12728 				cpu, cpu_buf->fd,
12729 				libbpf_strerror_r(err, msg, sizeof(msg)));
12730 			goto error;
12731 		}
12732 		j++;
12733 	}
12734 	pb->cpu_cnt = j;
12735 	free(online);
12736 
12737 	return pb;
12738 
12739 error:
12740 	free(online);
12741 	if (pb)
12742 		perf_buffer__free(pb);
12743 	return ERR_PTR(err);
12744 }
12745 
12746 struct perf_sample_raw {
12747 	struct perf_event_header header;
12748 	uint32_t size;
12749 	char data[];
12750 };
12751 
12752 struct perf_sample_lost {
12753 	struct perf_event_header header;
12754 	uint64_t id;
12755 	uint64_t lost;
12756 	uint64_t sample_id;
12757 };
12758 
12759 static enum bpf_perf_event_ret
12760 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
12761 {
12762 	struct perf_cpu_buf *cpu_buf = ctx;
12763 	struct perf_buffer *pb = cpu_buf->pb;
12764 	void *data = e;
12765 
12766 	/* user wants full control over parsing perf event */
12767 	if (pb->event_cb)
12768 		return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
12769 
12770 	switch (e->type) {
12771 	case PERF_RECORD_SAMPLE: {
12772 		struct perf_sample_raw *s = data;
12773 
12774 		if (pb->sample_cb)
12775 			pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
12776 		break;
12777 	}
12778 	case PERF_RECORD_LOST: {
12779 		struct perf_sample_lost *s = data;
12780 
12781 		if (pb->lost_cb)
12782 			pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
12783 		break;
12784 	}
12785 	default:
12786 		pr_warn("unknown perf sample type %d\n", e->type);
12787 		return LIBBPF_PERF_EVENT_ERROR;
12788 	}
12789 	return LIBBPF_PERF_EVENT_CONT;
12790 }
12791 
12792 static int perf_buffer__process_records(struct perf_buffer *pb,
12793 					struct perf_cpu_buf *cpu_buf)
12794 {
12795 	enum bpf_perf_event_ret ret;
12796 
12797 	ret = perf_event_read_simple(cpu_buf->base, pb->mmap_size,
12798 				     pb->page_size, &cpu_buf->buf,
12799 				     &cpu_buf->buf_size,
12800 				     perf_buffer__process_record, cpu_buf);
12801 	if (ret != LIBBPF_PERF_EVENT_CONT)
12802 		return ret;
12803 	return 0;
12804 }
12805 
12806 int perf_buffer__epoll_fd(const struct perf_buffer *pb)
12807 {
12808 	return pb->epoll_fd;
12809 }
12810 
12811 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
12812 {
12813 	int i, cnt, err;
12814 
12815 	cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
12816 	if (cnt < 0)
12817 		return -errno;
12818 
12819 	for (i = 0; i < cnt; i++) {
12820 		struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
12821 
12822 		err = perf_buffer__process_records(pb, cpu_buf);
12823 		if (err) {
12824 			pr_warn("error while processing records: %d\n", err);
12825 			return libbpf_err(err);
12826 		}
12827 	}
12828 	return cnt;
12829 }
12830 
12831 /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
12832  * manager.
12833  */
12834 size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
12835 {
12836 	return pb->cpu_cnt;
12837 }
12838 
12839 /*
12840  * Return perf_event FD of a ring buffer in *buf_idx* slot of
12841  * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
12842  * select()/poll()/epoll() Linux syscalls.
12843  */
12844 int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
12845 {
12846 	struct perf_cpu_buf *cpu_buf;
12847 
12848 	if (buf_idx >= pb->cpu_cnt)
12849 		return libbpf_err(-EINVAL);
12850 
12851 	cpu_buf = pb->cpu_bufs[buf_idx];
12852 	if (!cpu_buf)
12853 		return libbpf_err(-ENOENT);
12854 
12855 	return cpu_buf->fd;
12856 }
12857 
12858 int perf_buffer__buffer(struct perf_buffer *pb, int buf_idx, void **buf, size_t *buf_size)
12859 {
12860 	struct perf_cpu_buf *cpu_buf;
12861 
12862 	if (buf_idx >= pb->cpu_cnt)
12863 		return libbpf_err(-EINVAL);
12864 
12865 	cpu_buf = pb->cpu_bufs[buf_idx];
12866 	if (!cpu_buf)
12867 		return libbpf_err(-ENOENT);
12868 
12869 	*buf = cpu_buf->base;
12870 	*buf_size = pb->mmap_size;
12871 	return 0;
12872 }
12873 
12874 /*
12875  * Consume data from perf ring buffer corresponding to slot *buf_idx* in
12876  * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
12877  * consume, do nothing and return success.
12878  * Returns:
12879  *   - 0 on success;
12880  *   - <0 on failure.
12881  */
12882 int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
12883 {
12884 	struct perf_cpu_buf *cpu_buf;
12885 
12886 	if (buf_idx >= pb->cpu_cnt)
12887 		return libbpf_err(-EINVAL);
12888 
12889 	cpu_buf = pb->cpu_bufs[buf_idx];
12890 	if (!cpu_buf)
12891 		return libbpf_err(-ENOENT);
12892 
12893 	return perf_buffer__process_records(pb, cpu_buf);
12894 }
12895 
12896 int perf_buffer__consume(struct perf_buffer *pb)
12897 {
12898 	int i, err;
12899 
12900 	for (i = 0; i < pb->cpu_cnt; i++) {
12901 		struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
12902 
12903 		if (!cpu_buf)
12904 			continue;
12905 
12906 		err = perf_buffer__process_records(pb, cpu_buf);
12907 		if (err) {
12908 			pr_warn("perf_buffer: failed to process records in buffer #%d: %d\n", i, err);
12909 			return libbpf_err(err);
12910 		}
12911 	}
12912 	return 0;
12913 }
12914 
12915 int bpf_program__set_attach_target(struct bpf_program *prog,
12916 				   int attach_prog_fd,
12917 				   const char *attach_func_name)
12918 {
12919 	int btf_obj_fd = 0, btf_id = 0, err;
12920 
12921 	if (!prog || attach_prog_fd < 0)
12922 		return libbpf_err(-EINVAL);
12923 
12924 	if (prog->obj->loaded)
12925 		return libbpf_err(-EINVAL);
12926 
12927 	if (attach_prog_fd && !attach_func_name) {
12928 		/* remember attach_prog_fd and let bpf_program__load() find
12929 		 * BTF ID during the program load
12930 		 */
12931 		prog->attach_prog_fd = attach_prog_fd;
12932 		return 0;
12933 	}
12934 
12935 	if (attach_prog_fd) {
12936 		btf_id = libbpf_find_prog_btf_id(attach_func_name,
12937 						 attach_prog_fd);
12938 		if (btf_id < 0)
12939 			return libbpf_err(btf_id);
12940 	} else {
12941 		if (!attach_func_name)
12942 			return libbpf_err(-EINVAL);
12943 
12944 		/* load btf_vmlinux, if not yet */
12945 		err = bpf_object__load_vmlinux_btf(prog->obj, true);
12946 		if (err)
12947 			return libbpf_err(err);
12948 		err = find_kernel_btf_id(prog->obj, attach_func_name,
12949 					 prog->expected_attach_type,
12950 					 &btf_obj_fd, &btf_id);
12951 		if (err)
12952 			return libbpf_err(err);
12953 	}
12954 
12955 	prog->attach_btf_id = btf_id;
12956 	prog->attach_btf_obj_fd = btf_obj_fd;
12957 	prog->attach_prog_fd = attach_prog_fd;
12958 	return 0;
12959 }
12960 
12961 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
12962 {
12963 	int err = 0, n, len, start, end = -1;
12964 	bool *tmp;
12965 
12966 	*mask = NULL;
12967 	*mask_sz = 0;
12968 
12969 	/* Each sub string separated by ',' has format \d+-\d+ or \d+ */
12970 	while (*s) {
12971 		if (*s == ',' || *s == '\n') {
12972 			s++;
12973 			continue;
12974 		}
12975 		n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
12976 		if (n <= 0 || n > 2) {
12977 			pr_warn("Failed to get CPU range %s: %d\n", s, n);
12978 			err = -EINVAL;
12979 			goto cleanup;
12980 		} else if (n == 1) {
12981 			end = start;
12982 		}
12983 		if (start < 0 || start > end) {
12984 			pr_warn("Invalid CPU range [%d,%d] in %s\n",
12985 				start, end, s);
12986 			err = -EINVAL;
12987 			goto cleanup;
12988 		}
12989 		tmp = realloc(*mask, end + 1);
12990 		if (!tmp) {
12991 			err = -ENOMEM;
12992 			goto cleanup;
12993 		}
12994 		*mask = tmp;
12995 		memset(tmp + *mask_sz, 0, start - *mask_sz);
12996 		memset(tmp + start, 1, end - start + 1);
12997 		*mask_sz = end + 1;
12998 		s += len;
12999 	}
13000 	if (!*mask_sz) {
13001 		pr_warn("Empty CPU range\n");
13002 		return -EINVAL;
13003 	}
13004 	return 0;
13005 cleanup:
13006 	free(*mask);
13007 	*mask = NULL;
13008 	return err;
13009 }
13010 
13011 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
13012 {
13013 	int fd, err = 0, len;
13014 	char buf[128];
13015 
13016 	fd = open(fcpu, O_RDONLY | O_CLOEXEC);
13017 	if (fd < 0) {
13018 		err = -errno;
13019 		pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
13020 		return err;
13021 	}
13022 	len = read(fd, buf, sizeof(buf));
13023 	close(fd);
13024 	if (len <= 0) {
13025 		err = len ? -errno : -EINVAL;
13026 		pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
13027 		return err;
13028 	}
13029 	if (len >= sizeof(buf)) {
13030 		pr_warn("CPU mask is too big in file %s\n", fcpu);
13031 		return -E2BIG;
13032 	}
13033 	buf[len] = '\0';
13034 
13035 	return parse_cpu_mask_str(buf, mask, mask_sz);
13036 }
13037 
13038 int libbpf_num_possible_cpus(void)
13039 {
13040 	static const char *fcpu = "/sys/devices/system/cpu/possible";
13041 	static int cpus;
13042 	int err, n, i, tmp_cpus;
13043 	bool *mask;
13044 
13045 	tmp_cpus = READ_ONCE(cpus);
13046 	if (tmp_cpus > 0)
13047 		return tmp_cpus;
13048 
13049 	err = parse_cpu_mask_file(fcpu, &mask, &n);
13050 	if (err)
13051 		return libbpf_err(err);
13052 
13053 	tmp_cpus = 0;
13054 	for (i = 0; i < n; i++) {
13055 		if (mask[i])
13056 			tmp_cpus++;
13057 	}
13058 	free(mask);
13059 
13060 	WRITE_ONCE(cpus, tmp_cpus);
13061 	return tmp_cpus;
13062 }
13063 
13064 static int populate_skeleton_maps(const struct bpf_object *obj,
13065 				  struct bpf_map_skeleton *maps,
13066 				  size_t map_cnt)
13067 {
13068 	int i;
13069 
13070 	for (i = 0; i < map_cnt; i++) {
13071 		struct bpf_map **map = maps[i].map;
13072 		const char *name = maps[i].name;
13073 		void **mmaped = maps[i].mmaped;
13074 
13075 		*map = bpf_object__find_map_by_name(obj, name);
13076 		if (!*map) {
13077 			pr_warn("failed to find skeleton map '%s'\n", name);
13078 			return -ESRCH;
13079 		}
13080 
13081 		/* externs shouldn't be pre-setup from user code */
13082 		if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
13083 			*mmaped = (*map)->mmaped;
13084 	}
13085 	return 0;
13086 }
13087 
13088 static int populate_skeleton_progs(const struct bpf_object *obj,
13089 				   struct bpf_prog_skeleton *progs,
13090 				   size_t prog_cnt)
13091 {
13092 	int i;
13093 
13094 	for (i = 0; i < prog_cnt; i++) {
13095 		struct bpf_program **prog = progs[i].prog;
13096 		const char *name = progs[i].name;
13097 
13098 		*prog = bpf_object__find_program_by_name(obj, name);
13099 		if (!*prog) {
13100 			pr_warn("failed to find skeleton program '%s'\n", name);
13101 			return -ESRCH;
13102 		}
13103 	}
13104 	return 0;
13105 }
13106 
13107 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
13108 			      const struct bpf_object_open_opts *opts)
13109 {
13110 	DECLARE_LIBBPF_OPTS(bpf_object_open_opts, skel_opts,
13111 		.object_name = s->name,
13112 	);
13113 	struct bpf_object *obj;
13114 	int err;
13115 
13116 	/* Attempt to preserve opts->object_name, unless overriden by user
13117 	 * explicitly. Overwriting object name for skeletons is discouraged,
13118 	 * as it breaks global data maps, because they contain object name
13119 	 * prefix as their own map name prefix. When skeleton is generated,
13120 	 * bpftool is making an assumption that this name will stay the same.
13121 	 */
13122 	if (opts) {
13123 		memcpy(&skel_opts, opts, sizeof(*opts));
13124 		if (!opts->object_name)
13125 			skel_opts.object_name = s->name;
13126 	}
13127 
13128 	obj = bpf_object__open_mem(s->data, s->data_sz, &skel_opts);
13129 	err = libbpf_get_error(obj);
13130 	if (err) {
13131 		pr_warn("failed to initialize skeleton BPF object '%s': %d\n",
13132 			s->name, err);
13133 		return libbpf_err(err);
13134 	}
13135 
13136 	*s->obj = obj;
13137 	err = populate_skeleton_maps(obj, s->maps, s->map_cnt);
13138 	if (err) {
13139 		pr_warn("failed to populate skeleton maps for '%s': %d\n", s->name, err);
13140 		return libbpf_err(err);
13141 	}
13142 
13143 	err = populate_skeleton_progs(obj, s->progs, s->prog_cnt);
13144 	if (err) {
13145 		pr_warn("failed to populate skeleton progs for '%s': %d\n", s->name, err);
13146 		return libbpf_err(err);
13147 	}
13148 
13149 	return 0;
13150 }
13151 
13152 int bpf_object__open_subskeleton(struct bpf_object_subskeleton *s)
13153 {
13154 	int err, len, var_idx, i;
13155 	const char *var_name;
13156 	const struct bpf_map *map;
13157 	struct btf *btf;
13158 	__u32 map_type_id;
13159 	const struct btf_type *map_type, *var_type;
13160 	const struct bpf_var_skeleton *var_skel;
13161 	struct btf_var_secinfo *var;
13162 
13163 	if (!s->obj)
13164 		return libbpf_err(-EINVAL);
13165 
13166 	btf = bpf_object__btf(s->obj);
13167 	if (!btf) {
13168 		pr_warn("subskeletons require BTF at runtime (object %s)\n",
13169 			bpf_object__name(s->obj));
13170 		return libbpf_err(-errno);
13171 	}
13172 
13173 	err = populate_skeleton_maps(s->obj, s->maps, s->map_cnt);
13174 	if (err) {
13175 		pr_warn("failed to populate subskeleton maps: %d\n", err);
13176 		return libbpf_err(err);
13177 	}
13178 
13179 	err = populate_skeleton_progs(s->obj, s->progs, s->prog_cnt);
13180 	if (err) {
13181 		pr_warn("failed to populate subskeleton maps: %d\n", err);
13182 		return libbpf_err(err);
13183 	}
13184 
13185 	for (var_idx = 0; var_idx < s->var_cnt; var_idx++) {
13186 		var_skel = &s->vars[var_idx];
13187 		map = *var_skel->map;
13188 		map_type_id = bpf_map__btf_value_type_id(map);
13189 		map_type = btf__type_by_id(btf, map_type_id);
13190 
13191 		if (!btf_is_datasec(map_type)) {
13192 			pr_warn("type for map '%1$s' is not a datasec: %2$s",
13193 				bpf_map__name(map),
13194 				__btf_kind_str(btf_kind(map_type)));
13195 			return libbpf_err(-EINVAL);
13196 		}
13197 
13198 		len = btf_vlen(map_type);
13199 		var = btf_var_secinfos(map_type);
13200 		for (i = 0; i < len; i++, var++) {
13201 			var_type = btf__type_by_id(btf, var->type);
13202 			var_name = btf__name_by_offset(btf, var_type->name_off);
13203 			if (strcmp(var_name, var_skel->name) == 0) {
13204 				*var_skel->addr = map->mmaped + var->offset;
13205 				break;
13206 			}
13207 		}
13208 	}
13209 	return 0;
13210 }
13211 
13212 void bpf_object__destroy_subskeleton(struct bpf_object_subskeleton *s)
13213 {
13214 	if (!s)
13215 		return;
13216 	free(s->maps);
13217 	free(s->progs);
13218 	free(s->vars);
13219 	free(s);
13220 }
13221 
13222 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
13223 {
13224 	int i, err;
13225 
13226 	err = bpf_object__load(*s->obj);
13227 	if (err) {
13228 		pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
13229 		return libbpf_err(err);
13230 	}
13231 
13232 	for (i = 0; i < s->map_cnt; i++) {
13233 		struct bpf_map *map = *s->maps[i].map;
13234 		size_t mmap_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
13235 		int prot, map_fd = bpf_map__fd(map);
13236 		void **mmaped = s->maps[i].mmaped;
13237 
13238 		if (!mmaped)
13239 			continue;
13240 
13241 		if (!(map->def.map_flags & BPF_F_MMAPABLE)) {
13242 			*mmaped = NULL;
13243 			continue;
13244 		}
13245 
13246 		if (map->def.map_flags & BPF_F_RDONLY_PROG)
13247 			prot = PROT_READ;
13248 		else
13249 			prot = PROT_READ | PROT_WRITE;
13250 
13251 		/* Remap anonymous mmap()-ed "map initialization image" as
13252 		 * a BPF map-backed mmap()-ed memory, but preserving the same
13253 		 * memory address. This will cause kernel to change process'
13254 		 * page table to point to a different piece of kernel memory,
13255 		 * but from userspace point of view memory address (and its
13256 		 * contents, being identical at this point) will stay the
13257 		 * same. This mapping will be released by bpf_object__close()
13258 		 * as per normal clean up procedure, so we don't need to worry
13259 		 * about it from skeleton's clean up perspective.
13260 		 */
13261 		*mmaped = mmap(map->mmaped, mmap_sz, prot, MAP_SHARED | MAP_FIXED, map_fd, 0);
13262 		if (*mmaped == MAP_FAILED) {
13263 			err = -errno;
13264 			*mmaped = NULL;
13265 			pr_warn("failed to re-mmap() map '%s': %d\n",
13266 				 bpf_map__name(map), err);
13267 			return libbpf_err(err);
13268 		}
13269 	}
13270 
13271 	return 0;
13272 }
13273 
13274 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
13275 {
13276 	int i, err;
13277 
13278 	for (i = 0; i < s->prog_cnt; i++) {
13279 		struct bpf_program *prog = *s->progs[i].prog;
13280 		struct bpf_link **link = s->progs[i].link;
13281 
13282 		if (!prog->autoload || !prog->autoattach)
13283 			continue;
13284 
13285 		/* auto-attaching not supported for this program */
13286 		if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
13287 			continue;
13288 
13289 		/* if user already set the link manually, don't attempt auto-attach */
13290 		if (*link)
13291 			continue;
13292 
13293 		err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, link);
13294 		if (err) {
13295 			pr_warn("prog '%s': failed to auto-attach: %d\n",
13296 				bpf_program__name(prog), err);
13297 			return libbpf_err(err);
13298 		}
13299 
13300 		/* It's possible that for some SEC() definitions auto-attach
13301 		 * is supported in some cases (e.g., if definition completely
13302 		 * specifies target information), but is not in other cases.
13303 		 * SEC("uprobe") is one such case. If user specified target
13304 		 * binary and function name, such BPF program can be
13305 		 * auto-attached. But if not, it shouldn't trigger skeleton's
13306 		 * attach to fail. It should just be skipped.
13307 		 * attach_fn signals such case with returning 0 (no error) and
13308 		 * setting link to NULL.
13309 		 */
13310 	}
13311 
13312 	return 0;
13313 }
13314 
13315 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
13316 {
13317 	int i;
13318 
13319 	for (i = 0; i < s->prog_cnt; i++) {
13320 		struct bpf_link **link = s->progs[i].link;
13321 
13322 		bpf_link__destroy(*link);
13323 		*link = NULL;
13324 	}
13325 }
13326 
13327 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
13328 {
13329 	if (!s)
13330 		return;
13331 
13332 	if (s->progs)
13333 		bpf_object__detach_skeleton(s);
13334 	if (s->obj)
13335 		bpf_object__close(*s->obj);
13336 	free(s->maps);
13337 	free(s->progs);
13338 	free(s);
13339 }
13340