xref: /linux/tools/lib/bpf/libbpf.c (revision 5b9b41617bf3e1282cc60f07d3d52e62399aa4ba)
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_UNIX_CONNECT]       = "cgroup_unix_connect",
86 	[BPF_CGROUP_INET4_POST_BIND]	= "cgroup_inet4_post_bind",
87 	[BPF_CGROUP_INET6_POST_BIND]	= "cgroup_inet6_post_bind",
88 	[BPF_CGROUP_INET4_GETPEERNAME]	= "cgroup_inet4_getpeername",
89 	[BPF_CGROUP_INET6_GETPEERNAME]	= "cgroup_inet6_getpeername",
90 	[BPF_CGROUP_UNIX_GETPEERNAME]	= "cgroup_unix_getpeername",
91 	[BPF_CGROUP_INET4_GETSOCKNAME]	= "cgroup_inet4_getsockname",
92 	[BPF_CGROUP_INET6_GETSOCKNAME]	= "cgroup_inet6_getsockname",
93 	[BPF_CGROUP_UNIX_GETSOCKNAME]	= "cgroup_unix_getsockname",
94 	[BPF_CGROUP_UDP4_SENDMSG]	= "cgroup_udp4_sendmsg",
95 	[BPF_CGROUP_UDP6_SENDMSG]	= "cgroup_udp6_sendmsg",
96 	[BPF_CGROUP_UNIX_SENDMSG]	= "cgroup_unix_sendmsg",
97 	[BPF_CGROUP_SYSCTL]		= "cgroup_sysctl",
98 	[BPF_CGROUP_UDP4_RECVMSG]	= "cgroup_udp4_recvmsg",
99 	[BPF_CGROUP_UDP6_RECVMSG]	= "cgroup_udp6_recvmsg",
100 	[BPF_CGROUP_UNIX_RECVMSG]	= "cgroup_unix_recvmsg",
101 	[BPF_CGROUP_GETSOCKOPT]		= "cgroup_getsockopt",
102 	[BPF_CGROUP_SETSOCKOPT]		= "cgroup_setsockopt",
103 	[BPF_SK_SKB_STREAM_PARSER]	= "sk_skb_stream_parser",
104 	[BPF_SK_SKB_STREAM_VERDICT]	= "sk_skb_stream_verdict",
105 	[BPF_SK_SKB_VERDICT]		= "sk_skb_verdict",
106 	[BPF_SK_MSG_VERDICT]		= "sk_msg_verdict",
107 	[BPF_LIRC_MODE2]		= "lirc_mode2",
108 	[BPF_FLOW_DISSECTOR]		= "flow_dissector",
109 	[BPF_TRACE_RAW_TP]		= "trace_raw_tp",
110 	[BPF_TRACE_FENTRY]		= "trace_fentry",
111 	[BPF_TRACE_FEXIT]		= "trace_fexit",
112 	[BPF_MODIFY_RETURN]		= "modify_return",
113 	[BPF_LSM_MAC]			= "lsm_mac",
114 	[BPF_LSM_CGROUP]		= "lsm_cgroup",
115 	[BPF_SK_LOOKUP]			= "sk_lookup",
116 	[BPF_TRACE_ITER]		= "trace_iter",
117 	[BPF_XDP_DEVMAP]		= "xdp_devmap",
118 	[BPF_XDP_CPUMAP]		= "xdp_cpumap",
119 	[BPF_XDP]			= "xdp",
120 	[BPF_SK_REUSEPORT_SELECT]	= "sk_reuseport_select",
121 	[BPF_SK_REUSEPORT_SELECT_OR_MIGRATE]	= "sk_reuseport_select_or_migrate",
122 	[BPF_PERF_EVENT]		= "perf_event",
123 	[BPF_TRACE_KPROBE_MULTI]	= "trace_kprobe_multi",
124 	[BPF_STRUCT_OPS]		= "struct_ops",
125 	[BPF_NETFILTER]			= "netfilter",
126 	[BPF_TCX_INGRESS]		= "tcx_ingress",
127 	[BPF_TCX_EGRESS]		= "tcx_egress",
128 	[BPF_TRACE_UPROBE_MULTI]	= "trace_uprobe_multi",
129 	[BPF_NETKIT_PRIMARY]		= "netkit_primary",
130 	[BPF_NETKIT_PEER]		= "netkit_peer",
131 };
132 
133 static const char * const link_type_name[] = {
134 	[BPF_LINK_TYPE_UNSPEC]			= "unspec",
135 	[BPF_LINK_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
136 	[BPF_LINK_TYPE_TRACING]			= "tracing",
137 	[BPF_LINK_TYPE_CGROUP]			= "cgroup",
138 	[BPF_LINK_TYPE_ITER]			= "iter",
139 	[BPF_LINK_TYPE_NETNS]			= "netns",
140 	[BPF_LINK_TYPE_XDP]			= "xdp",
141 	[BPF_LINK_TYPE_PERF_EVENT]		= "perf_event",
142 	[BPF_LINK_TYPE_KPROBE_MULTI]		= "kprobe_multi",
143 	[BPF_LINK_TYPE_STRUCT_OPS]		= "struct_ops",
144 	[BPF_LINK_TYPE_NETFILTER]		= "netfilter",
145 	[BPF_LINK_TYPE_TCX]			= "tcx",
146 	[BPF_LINK_TYPE_UPROBE_MULTI]		= "uprobe_multi",
147 	[BPF_LINK_TYPE_NETKIT]			= "netkit",
148 };
149 
150 static const char * const map_type_name[] = {
151 	[BPF_MAP_TYPE_UNSPEC]			= "unspec",
152 	[BPF_MAP_TYPE_HASH]			= "hash",
153 	[BPF_MAP_TYPE_ARRAY]			= "array",
154 	[BPF_MAP_TYPE_PROG_ARRAY]		= "prog_array",
155 	[BPF_MAP_TYPE_PERF_EVENT_ARRAY]		= "perf_event_array",
156 	[BPF_MAP_TYPE_PERCPU_HASH]		= "percpu_hash",
157 	[BPF_MAP_TYPE_PERCPU_ARRAY]		= "percpu_array",
158 	[BPF_MAP_TYPE_STACK_TRACE]		= "stack_trace",
159 	[BPF_MAP_TYPE_CGROUP_ARRAY]		= "cgroup_array",
160 	[BPF_MAP_TYPE_LRU_HASH]			= "lru_hash",
161 	[BPF_MAP_TYPE_LRU_PERCPU_HASH]		= "lru_percpu_hash",
162 	[BPF_MAP_TYPE_LPM_TRIE]			= "lpm_trie",
163 	[BPF_MAP_TYPE_ARRAY_OF_MAPS]		= "array_of_maps",
164 	[BPF_MAP_TYPE_HASH_OF_MAPS]		= "hash_of_maps",
165 	[BPF_MAP_TYPE_DEVMAP]			= "devmap",
166 	[BPF_MAP_TYPE_DEVMAP_HASH]		= "devmap_hash",
167 	[BPF_MAP_TYPE_SOCKMAP]			= "sockmap",
168 	[BPF_MAP_TYPE_CPUMAP]			= "cpumap",
169 	[BPF_MAP_TYPE_XSKMAP]			= "xskmap",
170 	[BPF_MAP_TYPE_SOCKHASH]			= "sockhash",
171 	[BPF_MAP_TYPE_CGROUP_STORAGE]		= "cgroup_storage",
172 	[BPF_MAP_TYPE_REUSEPORT_SOCKARRAY]	= "reuseport_sockarray",
173 	[BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE]	= "percpu_cgroup_storage",
174 	[BPF_MAP_TYPE_QUEUE]			= "queue",
175 	[BPF_MAP_TYPE_STACK]			= "stack",
176 	[BPF_MAP_TYPE_SK_STORAGE]		= "sk_storage",
177 	[BPF_MAP_TYPE_STRUCT_OPS]		= "struct_ops",
178 	[BPF_MAP_TYPE_RINGBUF]			= "ringbuf",
179 	[BPF_MAP_TYPE_INODE_STORAGE]		= "inode_storage",
180 	[BPF_MAP_TYPE_TASK_STORAGE]		= "task_storage",
181 	[BPF_MAP_TYPE_BLOOM_FILTER]		= "bloom_filter",
182 	[BPF_MAP_TYPE_USER_RINGBUF]             = "user_ringbuf",
183 	[BPF_MAP_TYPE_CGRP_STORAGE]		= "cgrp_storage",
184 };
185 
186 static const char * const prog_type_name[] = {
187 	[BPF_PROG_TYPE_UNSPEC]			= "unspec",
188 	[BPF_PROG_TYPE_SOCKET_FILTER]		= "socket_filter",
189 	[BPF_PROG_TYPE_KPROBE]			= "kprobe",
190 	[BPF_PROG_TYPE_SCHED_CLS]		= "sched_cls",
191 	[BPF_PROG_TYPE_SCHED_ACT]		= "sched_act",
192 	[BPF_PROG_TYPE_TRACEPOINT]		= "tracepoint",
193 	[BPF_PROG_TYPE_XDP]			= "xdp",
194 	[BPF_PROG_TYPE_PERF_EVENT]		= "perf_event",
195 	[BPF_PROG_TYPE_CGROUP_SKB]		= "cgroup_skb",
196 	[BPF_PROG_TYPE_CGROUP_SOCK]		= "cgroup_sock",
197 	[BPF_PROG_TYPE_LWT_IN]			= "lwt_in",
198 	[BPF_PROG_TYPE_LWT_OUT]			= "lwt_out",
199 	[BPF_PROG_TYPE_LWT_XMIT]		= "lwt_xmit",
200 	[BPF_PROG_TYPE_SOCK_OPS]		= "sock_ops",
201 	[BPF_PROG_TYPE_SK_SKB]			= "sk_skb",
202 	[BPF_PROG_TYPE_CGROUP_DEVICE]		= "cgroup_device",
203 	[BPF_PROG_TYPE_SK_MSG]			= "sk_msg",
204 	[BPF_PROG_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
205 	[BPF_PROG_TYPE_CGROUP_SOCK_ADDR]	= "cgroup_sock_addr",
206 	[BPF_PROG_TYPE_LWT_SEG6LOCAL]		= "lwt_seg6local",
207 	[BPF_PROG_TYPE_LIRC_MODE2]		= "lirc_mode2",
208 	[BPF_PROG_TYPE_SK_REUSEPORT]		= "sk_reuseport",
209 	[BPF_PROG_TYPE_FLOW_DISSECTOR]		= "flow_dissector",
210 	[BPF_PROG_TYPE_CGROUP_SYSCTL]		= "cgroup_sysctl",
211 	[BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE]	= "raw_tracepoint_writable",
212 	[BPF_PROG_TYPE_CGROUP_SOCKOPT]		= "cgroup_sockopt",
213 	[BPF_PROG_TYPE_TRACING]			= "tracing",
214 	[BPF_PROG_TYPE_STRUCT_OPS]		= "struct_ops",
215 	[BPF_PROG_TYPE_EXT]			= "ext",
216 	[BPF_PROG_TYPE_LSM]			= "lsm",
217 	[BPF_PROG_TYPE_SK_LOOKUP]		= "sk_lookup",
218 	[BPF_PROG_TYPE_SYSCALL]			= "syscall",
219 	[BPF_PROG_TYPE_NETFILTER]		= "netfilter",
220 };
221 
222 static int __base_pr(enum libbpf_print_level level, const char *format,
223 		     va_list args)
224 {
225 	if (level == LIBBPF_DEBUG)
226 		return 0;
227 
228 	return vfprintf(stderr, format, args);
229 }
230 
231 static libbpf_print_fn_t __libbpf_pr = __base_pr;
232 
233 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
234 {
235 	libbpf_print_fn_t old_print_fn;
236 
237 	old_print_fn = __atomic_exchange_n(&__libbpf_pr, fn, __ATOMIC_RELAXED);
238 
239 	return old_print_fn;
240 }
241 
242 __printf(2, 3)
243 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
244 {
245 	va_list args;
246 	int old_errno;
247 	libbpf_print_fn_t print_fn;
248 
249 	print_fn = __atomic_load_n(&__libbpf_pr, __ATOMIC_RELAXED);
250 	if (!print_fn)
251 		return;
252 
253 	old_errno = errno;
254 
255 	va_start(args, format);
256 	__libbpf_pr(level, format, args);
257 	va_end(args);
258 
259 	errno = old_errno;
260 }
261 
262 static void pr_perm_msg(int err)
263 {
264 	struct rlimit limit;
265 	char buf[100];
266 
267 	if (err != -EPERM || geteuid() != 0)
268 		return;
269 
270 	err = getrlimit(RLIMIT_MEMLOCK, &limit);
271 	if (err)
272 		return;
273 
274 	if (limit.rlim_cur == RLIM_INFINITY)
275 		return;
276 
277 	if (limit.rlim_cur < 1024)
278 		snprintf(buf, sizeof(buf), "%zu bytes", (size_t)limit.rlim_cur);
279 	else if (limit.rlim_cur < 1024*1024)
280 		snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
281 	else
282 		snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
283 
284 	pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
285 		buf);
286 }
287 
288 #define STRERR_BUFSIZE  128
289 
290 /* Copied from tools/perf/util/util.h */
291 #ifndef zfree
292 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
293 #endif
294 
295 #ifndef zclose
296 # define zclose(fd) ({			\
297 	int ___err = 0;			\
298 	if ((fd) >= 0)			\
299 		___err = close((fd));	\
300 	fd = -1;			\
301 	___err; })
302 #endif
303 
304 static inline __u64 ptr_to_u64(const void *ptr)
305 {
306 	return (__u64) (unsigned long) ptr;
307 }
308 
309 int libbpf_set_strict_mode(enum libbpf_strict_mode mode)
310 {
311 	/* as of v1.0 libbpf_set_strict_mode() is a no-op */
312 	return 0;
313 }
314 
315 __u32 libbpf_major_version(void)
316 {
317 	return LIBBPF_MAJOR_VERSION;
318 }
319 
320 __u32 libbpf_minor_version(void)
321 {
322 	return LIBBPF_MINOR_VERSION;
323 }
324 
325 const char *libbpf_version_string(void)
326 {
327 #define __S(X) #X
328 #define _S(X) __S(X)
329 	return  "v" _S(LIBBPF_MAJOR_VERSION) "." _S(LIBBPF_MINOR_VERSION);
330 #undef _S
331 #undef __S
332 }
333 
334 enum reloc_type {
335 	RELO_LD64,
336 	RELO_CALL,
337 	RELO_DATA,
338 	RELO_EXTERN_LD64,
339 	RELO_EXTERN_CALL,
340 	RELO_SUBPROG_ADDR,
341 	RELO_CORE,
342 };
343 
344 struct reloc_desc {
345 	enum reloc_type type;
346 	int insn_idx;
347 	union {
348 		const struct bpf_core_relo *core_relo; /* used when type == RELO_CORE */
349 		struct {
350 			int map_idx;
351 			int sym_off;
352 			int ext_idx;
353 		};
354 	};
355 };
356 
357 /* stored as sec_def->cookie for all libbpf-supported SEC()s */
358 enum sec_def_flags {
359 	SEC_NONE = 0,
360 	/* expected_attach_type is optional, if kernel doesn't support that */
361 	SEC_EXP_ATTACH_OPT = 1,
362 	/* legacy, only used by libbpf_get_type_names() and
363 	 * libbpf_attach_type_by_name(), not used by libbpf itself at all.
364 	 * This used to be associated with cgroup (and few other) BPF programs
365 	 * that were attachable through BPF_PROG_ATTACH command. Pretty
366 	 * meaningless nowadays, though.
367 	 */
368 	SEC_ATTACHABLE = 2,
369 	SEC_ATTACHABLE_OPT = SEC_ATTACHABLE | SEC_EXP_ATTACH_OPT,
370 	/* attachment target is specified through BTF ID in either kernel or
371 	 * other BPF program's BTF object
372 	 */
373 	SEC_ATTACH_BTF = 4,
374 	/* BPF program type allows sleeping/blocking in kernel */
375 	SEC_SLEEPABLE = 8,
376 	/* BPF program support non-linear XDP buffer */
377 	SEC_XDP_FRAGS = 16,
378 	/* Setup proper attach type for usdt probes. */
379 	SEC_USDT = 32,
380 };
381 
382 struct bpf_sec_def {
383 	char *sec;
384 	enum bpf_prog_type prog_type;
385 	enum bpf_attach_type expected_attach_type;
386 	long cookie;
387 	int handler_id;
388 
389 	libbpf_prog_setup_fn_t prog_setup_fn;
390 	libbpf_prog_prepare_load_fn_t prog_prepare_load_fn;
391 	libbpf_prog_attach_fn_t prog_attach_fn;
392 };
393 
394 /*
395  * bpf_prog should be a better name but it has been used in
396  * linux/filter.h.
397  */
398 struct bpf_program {
399 	char *name;
400 	char *sec_name;
401 	size_t sec_idx;
402 	const struct bpf_sec_def *sec_def;
403 	/* this program's instruction offset (in number of instructions)
404 	 * within its containing ELF section
405 	 */
406 	size_t sec_insn_off;
407 	/* number of original instructions in ELF section belonging to this
408 	 * program, not taking into account subprogram instructions possible
409 	 * appended later during relocation
410 	 */
411 	size_t sec_insn_cnt;
412 	/* Offset (in number of instructions) of the start of instruction
413 	 * belonging to this BPF program  within its containing main BPF
414 	 * program. For the entry-point (main) BPF program, this is always
415 	 * zero. For a sub-program, this gets reset before each of main BPF
416 	 * programs are processed and relocated and is used to determined
417 	 * whether sub-program was already appended to the main program, and
418 	 * if yes, at which instruction offset.
419 	 */
420 	size_t sub_insn_off;
421 
422 	/* instructions that belong to BPF program; insns[0] is located at
423 	 * sec_insn_off instruction within its ELF section in ELF file, so
424 	 * when mapping ELF file instruction index to the local instruction,
425 	 * one needs to subtract sec_insn_off; and vice versa.
426 	 */
427 	struct bpf_insn *insns;
428 	/* actual number of instruction in this BPF program's image; for
429 	 * entry-point BPF programs this includes the size of main program
430 	 * itself plus all the used sub-programs, appended at the end
431 	 */
432 	size_t insns_cnt;
433 
434 	struct reloc_desc *reloc_desc;
435 	int nr_reloc;
436 
437 	/* BPF verifier log settings */
438 	char *log_buf;
439 	size_t log_size;
440 	__u32 log_level;
441 
442 	struct bpf_object *obj;
443 
444 	int fd;
445 	bool autoload;
446 	bool autoattach;
447 	bool sym_global;
448 	bool mark_btf_static;
449 	enum bpf_prog_type type;
450 	enum bpf_attach_type expected_attach_type;
451 	int exception_cb_idx;
452 
453 	int prog_ifindex;
454 	__u32 attach_btf_obj_fd;
455 	__u32 attach_btf_id;
456 	__u32 attach_prog_fd;
457 
458 	void *func_info;
459 	__u32 func_info_rec_size;
460 	__u32 func_info_cnt;
461 
462 	void *line_info;
463 	__u32 line_info_rec_size;
464 	__u32 line_info_cnt;
465 	__u32 prog_flags;
466 };
467 
468 struct bpf_struct_ops {
469 	const char *tname;
470 	const struct btf_type *type;
471 	struct bpf_program **progs;
472 	__u32 *kern_func_off;
473 	/* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
474 	void *data;
475 	/* e.g. struct bpf_struct_ops_tcp_congestion_ops in
476 	 *      btf_vmlinux's format.
477 	 * struct bpf_struct_ops_tcp_congestion_ops {
478 	 *	[... some other kernel fields ...]
479 	 *	struct tcp_congestion_ops data;
480 	 * }
481 	 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
482 	 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
483 	 * from "data".
484 	 */
485 	void *kern_vdata;
486 	__u32 type_id;
487 };
488 
489 #define DATA_SEC ".data"
490 #define BSS_SEC ".bss"
491 #define RODATA_SEC ".rodata"
492 #define KCONFIG_SEC ".kconfig"
493 #define KSYMS_SEC ".ksyms"
494 #define STRUCT_OPS_SEC ".struct_ops"
495 #define STRUCT_OPS_LINK_SEC ".struct_ops.link"
496 
497 enum libbpf_map_type {
498 	LIBBPF_MAP_UNSPEC,
499 	LIBBPF_MAP_DATA,
500 	LIBBPF_MAP_BSS,
501 	LIBBPF_MAP_RODATA,
502 	LIBBPF_MAP_KCONFIG,
503 };
504 
505 struct bpf_map_def {
506 	unsigned int type;
507 	unsigned int key_size;
508 	unsigned int value_size;
509 	unsigned int max_entries;
510 	unsigned int map_flags;
511 };
512 
513 struct bpf_map {
514 	struct bpf_object *obj;
515 	char *name;
516 	/* real_name is defined for special internal maps (.rodata*,
517 	 * .data*, .bss, .kconfig) and preserves their original ELF section
518 	 * name. This is important to be able to find corresponding BTF
519 	 * DATASEC information.
520 	 */
521 	char *real_name;
522 	int fd;
523 	int sec_idx;
524 	size_t sec_offset;
525 	int map_ifindex;
526 	int inner_map_fd;
527 	struct bpf_map_def def;
528 	__u32 numa_node;
529 	__u32 btf_var_idx;
530 	__u32 btf_key_type_id;
531 	__u32 btf_value_type_id;
532 	__u32 btf_vmlinux_value_type_id;
533 	enum libbpf_map_type libbpf_type;
534 	void *mmaped;
535 	struct bpf_struct_ops *st_ops;
536 	struct bpf_map *inner_map;
537 	void **init_slots;
538 	int init_slots_sz;
539 	char *pin_path;
540 	bool pinned;
541 	bool reused;
542 	bool autocreate;
543 	__u64 map_extra;
544 };
545 
546 enum extern_type {
547 	EXT_UNKNOWN,
548 	EXT_KCFG,
549 	EXT_KSYM,
550 };
551 
552 enum kcfg_type {
553 	KCFG_UNKNOWN,
554 	KCFG_CHAR,
555 	KCFG_BOOL,
556 	KCFG_INT,
557 	KCFG_TRISTATE,
558 	KCFG_CHAR_ARR,
559 };
560 
561 struct extern_desc {
562 	enum extern_type type;
563 	int sym_idx;
564 	int btf_id;
565 	int sec_btf_id;
566 	const char *name;
567 	char *essent_name;
568 	bool is_set;
569 	bool is_weak;
570 	union {
571 		struct {
572 			enum kcfg_type type;
573 			int sz;
574 			int align;
575 			int data_off;
576 			bool is_signed;
577 		} kcfg;
578 		struct {
579 			unsigned long long addr;
580 
581 			/* target btf_id of the corresponding kernel var. */
582 			int kernel_btf_obj_fd;
583 			int kernel_btf_id;
584 
585 			/* local btf_id of the ksym extern's type. */
586 			__u32 type_id;
587 			/* BTF fd index to be patched in for insn->off, this is
588 			 * 0 for vmlinux BTF, index in obj->fd_array for module
589 			 * BTF
590 			 */
591 			__s16 btf_fd_idx;
592 		} ksym;
593 	};
594 };
595 
596 struct module_btf {
597 	struct btf *btf;
598 	char *name;
599 	__u32 id;
600 	int fd;
601 	int fd_array_idx;
602 };
603 
604 enum sec_type {
605 	SEC_UNUSED = 0,
606 	SEC_RELO,
607 	SEC_BSS,
608 	SEC_DATA,
609 	SEC_RODATA,
610 };
611 
612 struct elf_sec_desc {
613 	enum sec_type sec_type;
614 	Elf64_Shdr *shdr;
615 	Elf_Data *data;
616 };
617 
618 struct elf_state {
619 	int fd;
620 	const void *obj_buf;
621 	size_t obj_buf_sz;
622 	Elf *elf;
623 	Elf64_Ehdr *ehdr;
624 	Elf_Data *symbols;
625 	Elf_Data *st_ops_data;
626 	Elf_Data *st_ops_link_data;
627 	size_t shstrndx; /* section index for section name strings */
628 	size_t strtabidx;
629 	struct elf_sec_desc *secs;
630 	size_t sec_cnt;
631 	int btf_maps_shndx;
632 	__u32 btf_maps_sec_btf_id;
633 	int text_shndx;
634 	int symbols_shndx;
635 	int st_ops_shndx;
636 	int st_ops_link_shndx;
637 };
638 
639 struct usdt_manager;
640 
641 struct bpf_object {
642 	char name[BPF_OBJ_NAME_LEN];
643 	char license[64];
644 	__u32 kern_version;
645 
646 	struct bpf_program *programs;
647 	size_t nr_programs;
648 	struct bpf_map *maps;
649 	size_t nr_maps;
650 	size_t maps_cap;
651 
652 	char *kconfig;
653 	struct extern_desc *externs;
654 	int nr_extern;
655 	int kconfig_map_idx;
656 
657 	bool loaded;
658 	bool has_subcalls;
659 	bool has_rodata;
660 
661 	struct bpf_gen *gen_loader;
662 
663 	/* Information when doing ELF related work. Only valid if efile.elf is not NULL */
664 	struct elf_state efile;
665 
666 	struct btf *btf;
667 	struct btf_ext *btf_ext;
668 
669 	/* Parse and load BTF vmlinux if any of the programs in the object need
670 	 * it at load time.
671 	 */
672 	struct btf *btf_vmlinux;
673 	/* Path to the custom BTF to be used for BPF CO-RE relocations as an
674 	 * override for vmlinux BTF.
675 	 */
676 	char *btf_custom_path;
677 	/* vmlinux BTF override for CO-RE relocations */
678 	struct btf *btf_vmlinux_override;
679 	/* Lazily initialized kernel module BTFs */
680 	struct module_btf *btf_modules;
681 	bool btf_modules_loaded;
682 	size_t btf_module_cnt;
683 	size_t btf_module_cap;
684 
685 	/* optional log settings passed to BPF_BTF_LOAD and BPF_PROG_LOAD commands */
686 	char *log_buf;
687 	size_t log_size;
688 	__u32 log_level;
689 
690 	int *fd_array;
691 	size_t fd_array_cap;
692 	size_t fd_array_cnt;
693 
694 	struct usdt_manager *usdt_man;
695 
696 	char path[];
697 };
698 
699 static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
700 static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
701 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
702 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
703 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn);
704 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
705 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
706 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx);
707 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx);
708 
709 void bpf_program__unload(struct bpf_program *prog)
710 {
711 	if (!prog)
712 		return;
713 
714 	zclose(prog->fd);
715 
716 	zfree(&prog->func_info);
717 	zfree(&prog->line_info);
718 }
719 
720 static void bpf_program__exit(struct bpf_program *prog)
721 {
722 	if (!prog)
723 		return;
724 
725 	bpf_program__unload(prog);
726 	zfree(&prog->name);
727 	zfree(&prog->sec_name);
728 	zfree(&prog->insns);
729 	zfree(&prog->reloc_desc);
730 
731 	prog->nr_reloc = 0;
732 	prog->insns_cnt = 0;
733 	prog->sec_idx = -1;
734 }
735 
736 static bool insn_is_subprog_call(const struct bpf_insn *insn)
737 {
738 	return BPF_CLASS(insn->code) == BPF_JMP &&
739 	       BPF_OP(insn->code) == BPF_CALL &&
740 	       BPF_SRC(insn->code) == BPF_K &&
741 	       insn->src_reg == BPF_PSEUDO_CALL &&
742 	       insn->dst_reg == 0 &&
743 	       insn->off == 0;
744 }
745 
746 static bool is_call_insn(const struct bpf_insn *insn)
747 {
748 	return insn->code == (BPF_JMP | BPF_CALL);
749 }
750 
751 static bool insn_is_pseudo_func(struct bpf_insn *insn)
752 {
753 	return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
754 }
755 
756 static int
757 bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
758 		      const char *name, size_t sec_idx, const char *sec_name,
759 		      size_t sec_off, void *insn_data, size_t insn_data_sz)
760 {
761 	if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
762 		pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
763 			sec_name, name, sec_off, insn_data_sz);
764 		return -EINVAL;
765 	}
766 
767 	memset(prog, 0, sizeof(*prog));
768 	prog->obj = obj;
769 
770 	prog->sec_idx = sec_idx;
771 	prog->sec_insn_off = sec_off / BPF_INSN_SZ;
772 	prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
773 	/* insns_cnt can later be increased by appending used subprograms */
774 	prog->insns_cnt = prog->sec_insn_cnt;
775 
776 	prog->type = BPF_PROG_TYPE_UNSPEC;
777 	prog->fd = -1;
778 	prog->exception_cb_idx = -1;
779 
780 	/* libbpf's convention for SEC("?abc...") is that it's just like
781 	 * SEC("abc...") but the corresponding bpf_program starts out with
782 	 * autoload set to false.
783 	 */
784 	if (sec_name[0] == '?') {
785 		prog->autoload = false;
786 		/* from now on forget there was ? in section name */
787 		sec_name++;
788 	} else {
789 		prog->autoload = true;
790 	}
791 
792 	prog->autoattach = true;
793 
794 	/* inherit object's log_level */
795 	prog->log_level = obj->log_level;
796 
797 	prog->sec_name = strdup(sec_name);
798 	if (!prog->sec_name)
799 		goto errout;
800 
801 	prog->name = strdup(name);
802 	if (!prog->name)
803 		goto errout;
804 
805 	prog->insns = malloc(insn_data_sz);
806 	if (!prog->insns)
807 		goto errout;
808 	memcpy(prog->insns, insn_data, insn_data_sz);
809 
810 	return 0;
811 errout:
812 	pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
813 	bpf_program__exit(prog);
814 	return -ENOMEM;
815 }
816 
817 static int
818 bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
819 			 const char *sec_name, int sec_idx)
820 {
821 	Elf_Data *symbols = obj->efile.symbols;
822 	struct bpf_program *prog, *progs;
823 	void *data = sec_data->d_buf;
824 	size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
825 	int nr_progs, err, i;
826 	const char *name;
827 	Elf64_Sym *sym;
828 
829 	progs = obj->programs;
830 	nr_progs = obj->nr_programs;
831 	nr_syms = symbols->d_size / sizeof(Elf64_Sym);
832 
833 	for (i = 0; i < nr_syms; i++) {
834 		sym = elf_sym_by_idx(obj, i);
835 
836 		if (sym->st_shndx != sec_idx)
837 			continue;
838 		if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC)
839 			continue;
840 
841 		prog_sz = sym->st_size;
842 		sec_off = sym->st_value;
843 
844 		name = elf_sym_str(obj, sym->st_name);
845 		if (!name) {
846 			pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
847 				sec_name, sec_off);
848 			return -LIBBPF_ERRNO__FORMAT;
849 		}
850 
851 		if (sec_off + prog_sz > sec_sz) {
852 			pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
853 				sec_name, sec_off);
854 			return -LIBBPF_ERRNO__FORMAT;
855 		}
856 
857 		if (sec_idx != obj->efile.text_shndx && ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
858 			pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
859 			return -ENOTSUP;
860 		}
861 
862 		pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
863 			 sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
864 
865 		progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
866 		if (!progs) {
867 			/*
868 			 * In this case the original obj->programs
869 			 * is still valid, so don't need special treat for
870 			 * bpf_close_object().
871 			 */
872 			pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
873 				sec_name, name);
874 			return -ENOMEM;
875 		}
876 		obj->programs = progs;
877 
878 		prog = &progs[nr_progs];
879 
880 		err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
881 					    sec_off, data + sec_off, prog_sz);
882 		if (err)
883 			return err;
884 
885 		if (ELF64_ST_BIND(sym->st_info) != STB_LOCAL)
886 			prog->sym_global = true;
887 
888 		/* if function is a global/weak symbol, but has restricted
889 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
890 		 * as static to enable more permissive BPF verification mode
891 		 * with more outside context available to BPF verifier
892 		 */
893 		if (prog->sym_global && (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
894 		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL))
895 			prog->mark_btf_static = true;
896 
897 		nr_progs++;
898 		obj->nr_programs = nr_progs;
899 	}
900 
901 	return 0;
902 }
903 
904 static const struct btf_member *
905 find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
906 {
907 	struct btf_member *m;
908 	int i;
909 
910 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
911 		if (btf_member_bit_offset(t, i) == bit_offset)
912 			return m;
913 	}
914 
915 	return NULL;
916 }
917 
918 static const struct btf_member *
919 find_member_by_name(const struct btf *btf, const struct btf_type *t,
920 		    const char *name)
921 {
922 	struct btf_member *m;
923 	int i;
924 
925 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
926 		if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
927 			return m;
928 	}
929 
930 	return NULL;
931 }
932 
933 #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
934 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
935 				   const char *name, __u32 kind);
936 
937 static int
938 find_struct_ops_kern_types(const struct btf *btf, const char *tname,
939 			   const struct btf_type **type, __u32 *type_id,
940 			   const struct btf_type **vtype, __u32 *vtype_id,
941 			   const struct btf_member **data_member)
942 {
943 	const struct btf_type *kern_type, *kern_vtype;
944 	const struct btf_member *kern_data_member;
945 	__s32 kern_vtype_id, kern_type_id;
946 	__u32 i;
947 
948 	kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
949 	if (kern_type_id < 0) {
950 		pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n",
951 			tname);
952 		return kern_type_id;
953 	}
954 	kern_type = btf__type_by_id(btf, kern_type_id);
955 
956 	/* Find the corresponding "map_value" type that will be used
957 	 * in map_update(BPF_MAP_TYPE_STRUCT_OPS).  For example,
958 	 * find "struct bpf_struct_ops_tcp_congestion_ops" from the
959 	 * btf_vmlinux.
960 	 */
961 	kern_vtype_id = find_btf_by_prefix_kind(btf, STRUCT_OPS_VALUE_PREFIX,
962 						tname, BTF_KIND_STRUCT);
963 	if (kern_vtype_id < 0) {
964 		pr_warn("struct_ops init_kern: struct %s%s is not found in kernel BTF\n",
965 			STRUCT_OPS_VALUE_PREFIX, tname);
966 		return kern_vtype_id;
967 	}
968 	kern_vtype = btf__type_by_id(btf, kern_vtype_id);
969 
970 	/* Find "struct tcp_congestion_ops" from
971 	 * struct bpf_struct_ops_tcp_congestion_ops {
972 	 *	[ ... ]
973 	 *	struct tcp_congestion_ops data;
974 	 * }
975 	 */
976 	kern_data_member = btf_members(kern_vtype);
977 	for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
978 		if (kern_data_member->type == kern_type_id)
979 			break;
980 	}
981 	if (i == btf_vlen(kern_vtype)) {
982 		pr_warn("struct_ops init_kern: struct %s data is not found in struct %s%s\n",
983 			tname, STRUCT_OPS_VALUE_PREFIX, tname);
984 		return -EINVAL;
985 	}
986 
987 	*type = kern_type;
988 	*type_id = kern_type_id;
989 	*vtype = kern_vtype;
990 	*vtype_id = kern_vtype_id;
991 	*data_member = kern_data_member;
992 
993 	return 0;
994 }
995 
996 static bool bpf_map__is_struct_ops(const struct bpf_map *map)
997 {
998 	return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
999 }
1000 
1001 /* Init the map's fields that depend on kern_btf */
1002 static int bpf_map__init_kern_struct_ops(struct bpf_map *map,
1003 					 const struct btf *btf,
1004 					 const struct btf *kern_btf)
1005 {
1006 	const struct btf_member *member, *kern_member, *kern_data_member;
1007 	const struct btf_type *type, *kern_type, *kern_vtype;
1008 	__u32 i, kern_type_id, kern_vtype_id, kern_data_off;
1009 	struct bpf_struct_ops *st_ops;
1010 	void *data, *kern_data;
1011 	const char *tname;
1012 	int err;
1013 
1014 	st_ops = map->st_ops;
1015 	type = st_ops->type;
1016 	tname = st_ops->tname;
1017 	err = find_struct_ops_kern_types(kern_btf, tname,
1018 					 &kern_type, &kern_type_id,
1019 					 &kern_vtype, &kern_vtype_id,
1020 					 &kern_data_member);
1021 	if (err)
1022 		return err;
1023 
1024 	pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
1025 		 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
1026 
1027 	map->def.value_size = kern_vtype->size;
1028 	map->btf_vmlinux_value_type_id = kern_vtype_id;
1029 
1030 	st_ops->kern_vdata = calloc(1, kern_vtype->size);
1031 	if (!st_ops->kern_vdata)
1032 		return -ENOMEM;
1033 
1034 	data = st_ops->data;
1035 	kern_data_off = kern_data_member->offset / 8;
1036 	kern_data = st_ops->kern_vdata + kern_data_off;
1037 
1038 	member = btf_members(type);
1039 	for (i = 0; i < btf_vlen(type); i++, member++) {
1040 		const struct btf_type *mtype, *kern_mtype;
1041 		__u32 mtype_id, kern_mtype_id;
1042 		void *mdata, *kern_mdata;
1043 		__s64 msize, kern_msize;
1044 		__u32 moff, kern_moff;
1045 		__u32 kern_member_idx;
1046 		const char *mname;
1047 
1048 		mname = btf__name_by_offset(btf, member->name_off);
1049 		kern_member = find_member_by_name(kern_btf, kern_type, mname);
1050 		if (!kern_member) {
1051 			pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
1052 				map->name, mname);
1053 			return -ENOTSUP;
1054 		}
1055 
1056 		kern_member_idx = kern_member - btf_members(kern_type);
1057 		if (btf_member_bitfield_size(type, i) ||
1058 		    btf_member_bitfield_size(kern_type, kern_member_idx)) {
1059 			pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
1060 				map->name, mname);
1061 			return -ENOTSUP;
1062 		}
1063 
1064 		moff = member->offset / 8;
1065 		kern_moff = kern_member->offset / 8;
1066 
1067 		mdata = data + moff;
1068 		kern_mdata = kern_data + kern_moff;
1069 
1070 		mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
1071 		kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
1072 						    &kern_mtype_id);
1073 		if (BTF_INFO_KIND(mtype->info) !=
1074 		    BTF_INFO_KIND(kern_mtype->info)) {
1075 			pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
1076 				map->name, mname, BTF_INFO_KIND(mtype->info),
1077 				BTF_INFO_KIND(kern_mtype->info));
1078 			return -ENOTSUP;
1079 		}
1080 
1081 		if (btf_is_ptr(mtype)) {
1082 			struct bpf_program *prog;
1083 
1084 			prog = st_ops->progs[i];
1085 			if (!prog)
1086 				continue;
1087 
1088 			kern_mtype = skip_mods_and_typedefs(kern_btf,
1089 							    kern_mtype->type,
1090 							    &kern_mtype_id);
1091 
1092 			/* mtype->type must be a func_proto which was
1093 			 * guaranteed in bpf_object__collect_st_ops_relos(),
1094 			 * so only check kern_mtype for func_proto here.
1095 			 */
1096 			if (!btf_is_func_proto(kern_mtype)) {
1097 				pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
1098 					map->name, mname);
1099 				return -ENOTSUP;
1100 			}
1101 
1102 			prog->attach_btf_id = kern_type_id;
1103 			prog->expected_attach_type = kern_member_idx;
1104 
1105 			st_ops->kern_func_off[i] = kern_data_off + kern_moff;
1106 
1107 			pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
1108 				 map->name, mname, prog->name, moff,
1109 				 kern_moff);
1110 
1111 			continue;
1112 		}
1113 
1114 		msize = btf__resolve_size(btf, mtype_id);
1115 		kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
1116 		if (msize < 0 || kern_msize < 0 || msize != kern_msize) {
1117 			pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
1118 				map->name, mname, (ssize_t)msize,
1119 				(ssize_t)kern_msize);
1120 			return -ENOTSUP;
1121 		}
1122 
1123 		pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
1124 			 map->name, mname, (unsigned int)msize,
1125 			 moff, kern_moff);
1126 		memcpy(kern_mdata, mdata, msize);
1127 	}
1128 
1129 	return 0;
1130 }
1131 
1132 static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
1133 {
1134 	struct bpf_map *map;
1135 	size_t i;
1136 	int err;
1137 
1138 	for (i = 0; i < obj->nr_maps; i++) {
1139 		map = &obj->maps[i];
1140 
1141 		if (!bpf_map__is_struct_ops(map))
1142 			continue;
1143 
1144 		err = bpf_map__init_kern_struct_ops(map, obj->btf,
1145 						    obj->btf_vmlinux);
1146 		if (err)
1147 			return err;
1148 	}
1149 
1150 	return 0;
1151 }
1152 
1153 static int init_struct_ops_maps(struct bpf_object *obj, const char *sec_name,
1154 				int shndx, Elf_Data *data, __u32 map_flags)
1155 {
1156 	const struct btf_type *type, *datasec;
1157 	const struct btf_var_secinfo *vsi;
1158 	struct bpf_struct_ops *st_ops;
1159 	const char *tname, *var_name;
1160 	__s32 type_id, datasec_id;
1161 	const struct btf *btf;
1162 	struct bpf_map *map;
1163 	__u32 i;
1164 
1165 	if (shndx == -1)
1166 		return 0;
1167 
1168 	btf = obj->btf;
1169 	datasec_id = btf__find_by_name_kind(btf, sec_name,
1170 					    BTF_KIND_DATASEC);
1171 	if (datasec_id < 0) {
1172 		pr_warn("struct_ops init: DATASEC %s not found\n",
1173 			sec_name);
1174 		return -EINVAL;
1175 	}
1176 
1177 	datasec = btf__type_by_id(btf, datasec_id);
1178 	vsi = btf_var_secinfos(datasec);
1179 	for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
1180 		type = btf__type_by_id(obj->btf, vsi->type);
1181 		var_name = btf__name_by_offset(obj->btf, type->name_off);
1182 
1183 		type_id = btf__resolve_type(obj->btf, vsi->type);
1184 		if (type_id < 0) {
1185 			pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
1186 				vsi->type, sec_name);
1187 			return -EINVAL;
1188 		}
1189 
1190 		type = btf__type_by_id(obj->btf, type_id);
1191 		tname = btf__name_by_offset(obj->btf, type->name_off);
1192 		if (!tname[0]) {
1193 			pr_warn("struct_ops init: anonymous type is not supported\n");
1194 			return -ENOTSUP;
1195 		}
1196 		if (!btf_is_struct(type)) {
1197 			pr_warn("struct_ops init: %s is not a struct\n", tname);
1198 			return -EINVAL;
1199 		}
1200 
1201 		map = bpf_object__add_map(obj);
1202 		if (IS_ERR(map))
1203 			return PTR_ERR(map);
1204 
1205 		map->sec_idx = shndx;
1206 		map->sec_offset = vsi->offset;
1207 		map->name = strdup(var_name);
1208 		if (!map->name)
1209 			return -ENOMEM;
1210 
1211 		map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
1212 		map->def.key_size = sizeof(int);
1213 		map->def.value_size = type->size;
1214 		map->def.max_entries = 1;
1215 		map->def.map_flags = map_flags;
1216 
1217 		map->st_ops = calloc(1, sizeof(*map->st_ops));
1218 		if (!map->st_ops)
1219 			return -ENOMEM;
1220 		st_ops = map->st_ops;
1221 		st_ops->data = malloc(type->size);
1222 		st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1223 		st_ops->kern_func_off = malloc(btf_vlen(type) *
1224 					       sizeof(*st_ops->kern_func_off));
1225 		if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1226 			return -ENOMEM;
1227 
1228 		if (vsi->offset + type->size > data->d_size) {
1229 			pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1230 				var_name, sec_name);
1231 			return -EINVAL;
1232 		}
1233 
1234 		memcpy(st_ops->data,
1235 		       data->d_buf + vsi->offset,
1236 		       type->size);
1237 		st_ops->tname = tname;
1238 		st_ops->type = type;
1239 		st_ops->type_id = type_id;
1240 
1241 		pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
1242 			 tname, type_id, var_name, vsi->offset);
1243 	}
1244 
1245 	return 0;
1246 }
1247 
1248 static int bpf_object_init_struct_ops(struct bpf_object *obj)
1249 {
1250 	int err;
1251 
1252 	err = init_struct_ops_maps(obj, STRUCT_OPS_SEC, obj->efile.st_ops_shndx,
1253 				   obj->efile.st_ops_data, 0);
1254 	err = err ?: init_struct_ops_maps(obj, STRUCT_OPS_LINK_SEC,
1255 					  obj->efile.st_ops_link_shndx,
1256 					  obj->efile.st_ops_link_data,
1257 					  BPF_F_LINK);
1258 	return err;
1259 }
1260 
1261 static struct bpf_object *bpf_object__new(const char *path,
1262 					  const void *obj_buf,
1263 					  size_t obj_buf_sz,
1264 					  const char *obj_name)
1265 {
1266 	struct bpf_object *obj;
1267 	char *end;
1268 
1269 	obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1270 	if (!obj) {
1271 		pr_warn("alloc memory failed for %s\n", path);
1272 		return ERR_PTR(-ENOMEM);
1273 	}
1274 
1275 	strcpy(obj->path, path);
1276 	if (obj_name) {
1277 		libbpf_strlcpy(obj->name, obj_name, sizeof(obj->name));
1278 	} else {
1279 		/* Using basename() GNU version which doesn't modify arg. */
1280 		libbpf_strlcpy(obj->name, basename((void *)path), sizeof(obj->name));
1281 		end = strchr(obj->name, '.');
1282 		if (end)
1283 			*end = 0;
1284 	}
1285 
1286 	obj->efile.fd = -1;
1287 	/*
1288 	 * Caller of this function should also call
1289 	 * bpf_object__elf_finish() after data collection to return
1290 	 * obj_buf to user. If not, we should duplicate the buffer to
1291 	 * avoid user freeing them before elf finish.
1292 	 */
1293 	obj->efile.obj_buf = obj_buf;
1294 	obj->efile.obj_buf_sz = obj_buf_sz;
1295 	obj->efile.btf_maps_shndx = -1;
1296 	obj->efile.st_ops_shndx = -1;
1297 	obj->efile.st_ops_link_shndx = -1;
1298 	obj->kconfig_map_idx = -1;
1299 
1300 	obj->kern_version = get_kernel_version();
1301 	obj->loaded = false;
1302 
1303 	return obj;
1304 }
1305 
1306 static void bpf_object__elf_finish(struct bpf_object *obj)
1307 {
1308 	if (!obj->efile.elf)
1309 		return;
1310 
1311 	elf_end(obj->efile.elf);
1312 	obj->efile.elf = NULL;
1313 	obj->efile.symbols = NULL;
1314 	obj->efile.st_ops_data = NULL;
1315 	obj->efile.st_ops_link_data = NULL;
1316 
1317 	zfree(&obj->efile.secs);
1318 	obj->efile.sec_cnt = 0;
1319 	zclose(obj->efile.fd);
1320 	obj->efile.obj_buf = NULL;
1321 	obj->efile.obj_buf_sz = 0;
1322 }
1323 
1324 static int bpf_object__elf_init(struct bpf_object *obj)
1325 {
1326 	Elf64_Ehdr *ehdr;
1327 	int err = 0;
1328 	Elf *elf;
1329 
1330 	if (obj->efile.elf) {
1331 		pr_warn("elf: init internal error\n");
1332 		return -LIBBPF_ERRNO__LIBELF;
1333 	}
1334 
1335 	if (obj->efile.obj_buf_sz > 0) {
1336 		/* obj_buf should have been validated by bpf_object__open_mem(). */
1337 		elf = elf_memory((char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
1338 	} else {
1339 		obj->efile.fd = open(obj->path, O_RDONLY | O_CLOEXEC);
1340 		if (obj->efile.fd < 0) {
1341 			char errmsg[STRERR_BUFSIZE], *cp;
1342 
1343 			err = -errno;
1344 			cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
1345 			pr_warn("elf: failed to open %s: %s\n", obj->path, cp);
1346 			return err;
1347 		}
1348 
1349 		elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1350 	}
1351 
1352 	if (!elf) {
1353 		pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
1354 		err = -LIBBPF_ERRNO__LIBELF;
1355 		goto errout;
1356 	}
1357 
1358 	obj->efile.elf = elf;
1359 
1360 	if (elf_kind(elf) != ELF_K_ELF) {
1361 		err = -LIBBPF_ERRNO__FORMAT;
1362 		pr_warn("elf: '%s' is not a proper ELF object\n", obj->path);
1363 		goto errout;
1364 	}
1365 
1366 	if (gelf_getclass(elf) != ELFCLASS64) {
1367 		err = -LIBBPF_ERRNO__FORMAT;
1368 		pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path);
1369 		goto errout;
1370 	}
1371 
1372 	obj->efile.ehdr = ehdr = elf64_getehdr(elf);
1373 	if (!obj->efile.ehdr) {
1374 		pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
1375 		err = -LIBBPF_ERRNO__FORMAT;
1376 		goto errout;
1377 	}
1378 
1379 	if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
1380 		pr_warn("elf: failed to get section names section index for %s: %s\n",
1381 			obj->path, elf_errmsg(-1));
1382 		err = -LIBBPF_ERRNO__FORMAT;
1383 		goto errout;
1384 	}
1385 
1386 	/* ELF is corrupted/truncated, avoid calling elf_strptr. */
1387 	if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
1388 		pr_warn("elf: failed to get section names strings from %s: %s\n",
1389 			obj->path, elf_errmsg(-1));
1390 		err = -LIBBPF_ERRNO__FORMAT;
1391 		goto errout;
1392 	}
1393 
1394 	/* Old LLVM set e_machine to EM_NONE */
1395 	if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
1396 		pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
1397 		err = -LIBBPF_ERRNO__FORMAT;
1398 		goto errout;
1399 	}
1400 
1401 	return 0;
1402 errout:
1403 	bpf_object__elf_finish(obj);
1404 	return err;
1405 }
1406 
1407 static int bpf_object__check_endianness(struct bpf_object *obj)
1408 {
1409 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1410 	if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2LSB)
1411 		return 0;
1412 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1413 	if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2MSB)
1414 		return 0;
1415 #else
1416 # error "Unrecognized __BYTE_ORDER__"
1417 #endif
1418 	pr_warn("elf: endianness mismatch in %s.\n", obj->path);
1419 	return -LIBBPF_ERRNO__ENDIAN;
1420 }
1421 
1422 static int
1423 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1424 {
1425 	if (!data) {
1426 		pr_warn("invalid license section in %s\n", obj->path);
1427 		return -LIBBPF_ERRNO__FORMAT;
1428 	}
1429 	/* libbpf_strlcpy() only copies first N - 1 bytes, so size + 1 won't
1430 	 * go over allowed ELF data section buffer
1431 	 */
1432 	libbpf_strlcpy(obj->license, data, min(size + 1, sizeof(obj->license)));
1433 	pr_debug("license of %s is %s\n", obj->path, obj->license);
1434 	return 0;
1435 }
1436 
1437 static int
1438 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1439 {
1440 	__u32 kver;
1441 
1442 	if (!data || size != sizeof(kver)) {
1443 		pr_warn("invalid kver section in %s\n", obj->path);
1444 		return -LIBBPF_ERRNO__FORMAT;
1445 	}
1446 	memcpy(&kver, data, sizeof(kver));
1447 	obj->kern_version = kver;
1448 	pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1449 	return 0;
1450 }
1451 
1452 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1453 {
1454 	if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1455 	    type == BPF_MAP_TYPE_HASH_OF_MAPS)
1456 		return true;
1457 	return false;
1458 }
1459 
1460 static int find_elf_sec_sz(const struct bpf_object *obj, const char *name, __u32 *size)
1461 {
1462 	Elf_Data *data;
1463 	Elf_Scn *scn;
1464 
1465 	if (!name)
1466 		return -EINVAL;
1467 
1468 	scn = elf_sec_by_name(obj, name);
1469 	data = elf_sec_data(obj, scn);
1470 	if (data) {
1471 		*size = data->d_size;
1472 		return 0; /* found it */
1473 	}
1474 
1475 	return -ENOENT;
1476 }
1477 
1478 static Elf64_Sym *find_elf_var_sym(const struct bpf_object *obj, const char *name)
1479 {
1480 	Elf_Data *symbols = obj->efile.symbols;
1481 	const char *sname;
1482 	size_t si;
1483 
1484 	for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
1485 		Elf64_Sym *sym = elf_sym_by_idx(obj, si);
1486 
1487 		if (ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)
1488 			continue;
1489 
1490 		if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL &&
1491 		    ELF64_ST_BIND(sym->st_info) != STB_WEAK)
1492 			continue;
1493 
1494 		sname = elf_sym_str(obj, sym->st_name);
1495 		if (!sname) {
1496 			pr_warn("failed to get sym name string for var %s\n", name);
1497 			return ERR_PTR(-EIO);
1498 		}
1499 		if (strcmp(name, sname) == 0)
1500 			return sym;
1501 	}
1502 
1503 	return ERR_PTR(-ENOENT);
1504 }
1505 
1506 static int create_placeholder_fd(void)
1507 {
1508 	int fd;
1509 
1510 	fd = ensure_good_fd(memfd_create("libbpf-placeholder-fd", MFD_CLOEXEC));
1511 	if (fd < 0)
1512 		return -errno;
1513 	return fd;
1514 }
1515 
1516 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1517 {
1518 	struct bpf_map *map;
1519 	int err;
1520 
1521 	err = libbpf_ensure_mem((void **)&obj->maps, &obj->maps_cap,
1522 				sizeof(*obj->maps), obj->nr_maps + 1);
1523 	if (err)
1524 		return ERR_PTR(err);
1525 
1526 	map = &obj->maps[obj->nr_maps++];
1527 	map->obj = obj;
1528 	/* Preallocate map FD without actually creating BPF map just yet.
1529 	 * These map FD "placeholders" will be reused later without changing
1530 	 * FD value when map is actually created in the kernel.
1531 	 *
1532 	 * This is useful to be able to perform BPF program relocations
1533 	 * without having to create BPF maps before that step. This allows us
1534 	 * to finalize and load BTF very late in BPF object's loading phase,
1535 	 * right before BPF maps have to be created and BPF programs have to
1536 	 * be loaded. By having these map FD placeholders we can perform all
1537 	 * the sanitizations, relocations, and any other adjustments before we
1538 	 * start creating actual BPF kernel objects (BTF, maps, progs).
1539 	 */
1540 	map->fd = create_placeholder_fd();
1541 	if (map->fd < 0)
1542 		return ERR_PTR(map->fd);
1543 	map->inner_map_fd = -1;
1544 	map->autocreate = true;
1545 
1546 	return map;
1547 }
1548 
1549 static size_t bpf_map_mmap_sz(unsigned int value_sz, unsigned int max_entries)
1550 {
1551 	const long page_sz = sysconf(_SC_PAGE_SIZE);
1552 	size_t map_sz;
1553 
1554 	map_sz = (size_t)roundup(value_sz, 8) * max_entries;
1555 	map_sz = roundup(map_sz, page_sz);
1556 	return map_sz;
1557 }
1558 
1559 static int bpf_map_mmap_resize(struct bpf_map *map, size_t old_sz, size_t new_sz)
1560 {
1561 	void *mmaped;
1562 
1563 	if (!map->mmaped)
1564 		return -EINVAL;
1565 
1566 	if (old_sz == new_sz)
1567 		return 0;
1568 
1569 	mmaped = mmap(NULL, new_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1570 	if (mmaped == MAP_FAILED)
1571 		return -errno;
1572 
1573 	memcpy(mmaped, map->mmaped, min(old_sz, new_sz));
1574 	munmap(map->mmaped, old_sz);
1575 	map->mmaped = mmaped;
1576 	return 0;
1577 }
1578 
1579 static char *internal_map_name(struct bpf_object *obj, const char *real_name)
1580 {
1581 	char map_name[BPF_OBJ_NAME_LEN], *p;
1582 	int pfx_len, sfx_len = max((size_t)7, strlen(real_name));
1583 
1584 	/* This is one of the more confusing parts of libbpf for various
1585 	 * reasons, some of which are historical. The original idea for naming
1586 	 * internal names was to include as much of BPF object name prefix as
1587 	 * possible, so that it can be distinguished from similar internal
1588 	 * maps of a different BPF object.
1589 	 * As an example, let's say we have bpf_object named 'my_object_name'
1590 	 * and internal map corresponding to '.rodata' ELF section. The final
1591 	 * map name advertised to user and to the kernel will be
1592 	 * 'my_objec.rodata', taking first 8 characters of object name and
1593 	 * entire 7 characters of '.rodata'.
1594 	 * Somewhat confusingly, if internal map ELF section name is shorter
1595 	 * than 7 characters, e.g., '.bss', we still reserve 7 characters
1596 	 * for the suffix, even though we only have 4 actual characters, and
1597 	 * resulting map will be called 'my_objec.bss', not even using all 15
1598 	 * characters allowed by the kernel. Oh well, at least the truncated
1599 	 * object name is somewhat consistent in this case. But if the map
1600 	 * name is '.kconfig', we'll still have entirety of '.kconfig' added
1601 	 * (8 chars) and thus will be left with only first 7 characters of the
1602 	 * object name ('my_obje'). Happy guessing, user, that the final map
1603 	 * name will be "my_obje.kconfig".
1604 	 * Now, with libbpf starting to support arbitrarily named .rodata.*
1605 	 * and .data.* data sections, it's possible that ELF section name is
1606 	 * longer than allowed 15 chars, so we now need to be careful to take
1607 	 * only up to 15 first characters of ELF name, taking no BPF object
1608 	 * name characters at all. So '.rodata.abracadabra' will result in
1609 	 * '.rodata.abracad' kernel and user-visible name.
1610 	 * We need to keep this convoluted logic intact for .data, .bss and
1611 	 * .rodata maps, but for new custom .data.custom and .rodata.custom
1612 	 * maps we use their ELF names as is, not prepending bpf_object name
1613 	 * in front. We still need to truncate them to 15 characters for the
1614 	 * kernel. Full name can be recovered for such maps by using DATASEC
1615 	 * BTF type associated with such map's value type, though.
1616 	 */
1617 	if (sfx_len >= BPF_OBJ_NAME_LEN)
1618 		sfx_len = BPF_OBJ_NAME_LEN - 1;
1619 
1620 	/* if there are two or more dots in map name, it's a custom dot map */
1621 	if (strchr(real_name + 1, '.') != NULL)
1622 		pfx_len = 0;
1623 	else
1624 		pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
1625 
1626 	snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1627 		 sfx_len, real_name);
1628 
1629 	/* sanitise map name to characters allowed by kernel */
1630 	for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1631 		if (!isalnum(*p) && *p != '_' && *p != '.')
1632 			*p = '_';
1633 
1634 	return strdup(map_name);
1635 }
1636 
1637 static int
1638 map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map);
1639 
1640 /* Internal BPF map is mmap()'able only if at least one of corresponding
1641  * DATASEC's VARs are to be exposed through BPF skeleton. I.e., it's a GLOBAL
1642  * variable and it's not marked as __hidden (which turns it into, effectively,
1643  * a STATIC variable).
1644  */
1645 static bool map_is_mmapable(struct bpf_object *obj, struct bpf_map *map)
1646 {
1647 	const struct btf_type *t, *vt;
1648 	struct btf_var_secinfo *vsi;
1649 	int i, n;
1650 
1651 	if (!map->btf_value_type_id)
1652 		return false;
1653 
1654 	t = btf__type_by_id(obj->btf, map->btf_value_type_id);
1655 	if (!btf_is_datasec(t))
1656 		return false;
1657 
1658 	vsi = btf_var_secinfos(t);
1659 	for (i = 0, n = btf_vlen(t); i < n; i++, vsi++) {
1660 		vt = btf__type_by_id(obj->btf, vsi->type);
1661 		if (!btf_is_var(vt))
1662 			continue;
1663 
1664 		if (btf_var(vt)->linkage != BTF_VAR_STATIC)
1665 			return true;
1666 	}
1667 
1668 	return false;
1669 }
1670 
1671 static int
1672 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
1673 			      const char *real_name, int sec_idx, void *data, size_t data_sz)
1674 {
1675 	struct bpf_map_def *def;
1676 	struct bpf_map *map;
1677 	size_t mmap_sz;
1678 	int err;
1679 
1680 	map = bpf_object__add_map(obj);
1681 	if (IS_ERR(map))
1682 		return PTR_ERR(map);
1683 
1684 	map->libbpf_type = type;
1685 	map->sec_idx = sec_idx;
1686 	map->sec_offset = 0;
1687 	map->real_name = strdup(real_name);
1688 	map->name = internal_map_name(obj, real_name);
1689 	if (!map->real_name || !map->name) {
1690 		zfree(&map->real_name);
1691 		zfree(&map->name);
1692 		return -ENOMEM;
1693 	}
1694 
1695 	def = &map->def;
1696 	def->type = BPF_MAP_TYPE_ARRAY;
1697 	def->key_size = sizeof(int);
1698 	def->value_size = data_sz;
1699 	def->max_entries = 1;
1700 	def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
1701 			 ? BPF_F_RDONLY_PROG : 0;
1702 
1703 	/* failures are fine because of maps like .rodata.str1.1 */
1704 	(void) map_fill_btf_type_info(obj, map);
1705 
1706 	if (map_is_mmapable(obj, map))
1707 		def->map_flags |= BPF_F_MMAPABLE;
1708 
1709 	pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
1710 		 map->name, map->sec_idx, map->sec_offset, def->map_flags);
1711 
1712 	mmap_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
1713 	map->mmaped = mmap(NULL, mmap_sz, PROT_READ | PROT_WRITE,
1714 			   MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1715 	if (map->mmaped == MAP_FAILED) {
1716 		err = -errno;
1717 		map->mmaped = NULL;
1718 		pr_warn("failed to alloc map '%s' content buffer: %d\n",
1719 			map->name, err);
1720 		zfree(&map->real_name);
1721 		zfree(&map->name);
1722 		return err;
1723 	}
1724 
1725 	if (data)
1726 		memcpy(map->mmaped, data, data_sz);
1727 
1728 	pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
1729 	return 0;
1730 }
1731 
1732 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
1733 {
1734 	struct elf_sec_desc *sec_desc;
1735 	const char *sec_name;
1736 	int err = 0, sec_idx;
1737 
1738 	/*
1739 	 * Populate obj->maps with libbpf internal maps.
1740 	 */
1741 	for (sec_idx = 1; sec_idx < obj->efile.sec_cnt; sec_idx++) {
1742 		sec_desc = &obj->efile.secs[sec_idx];
1743 
1744 		/* Skip recognized sections with size 0. */
1745 		if (!sec_desc->data || sec_desc->data->d_size == 0)
1746 			continue;
1747 
1748 		switch (sec_desc->sec_type) {
1749 		case SEC_DATA:
1750 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1751 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
1752 							    sec_name, sec_idx,
1753 							    sec_desc->data->d_buf,
1754 							    sec_desc->data->d_size);
1755 			break;
1756 		case SEC_RODATA:
1757 			obj->has_rodata = true;
1758 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1759 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
1760 							    sec_name, sec_idx,
1761 							    sec_desc->data->d_buf,
1762 							    sec_desc->data->d_size);
1763 			break;
1764 		case SEC_BSS:
1765 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1766 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
1767 							    sec_name, sec_idx,
1768 							    NULL,
1769 							    sec_desc->data->d_size);
1770 			break;
1771 		default:
1772 			/* skip */
1773 			break;
1774 		}
1775 		if (err)
1776 			return err;
1777 	}
1778 	return 0;
1779 }
1780 
1781 
1782 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
1783 					       const void *name)
1784 {
1785 	int i;
1786 
1787 	for (i = 0; i < obj->nr_extern; i++) {
1788 		if (strcmp(obj->externs[i].name, name) == 0)
1789 			return &obj->externs[i];
1790 	}
1791 	return NULL;
1792 }
1793 
1794 static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
1795 			      char value)
1796 {
1797 	switch (ext->kcfg.type) {
1798 	case KCFG_BOOL:
1799 		if (value == 'm') {
1800 			pr_warn("extern (kcfg) '%s': value '%c' implies tristate or char type\n",
1801 				ext->name, value);
1802 			return -EINVAL;
1803 		}
1804 		*(bool *)ext_val = value == 'y' ? true : false;
1805 		break;
1806 	case KCFG_TRISTATE:
1807 		if (value == 'y')
1808 			*(enum libbpf_tristate *)ext_val = TRI_YES;
1809 		else if (value == 'm')
1810 			*(enum libbpf_tristate *)ext_val = TRI_MODULE;
1811 		else /* value == 'n' */
1812 			*(enum libbpf_tristate *)ext_val = TRI_NO;
1813 		break;
1814 	case KCFG_CHAR:
1815 		*(char *)ext_val = value;
1816 		break;
1817 	case KCFG_UNKNOWN:
1818 	case KCFG_INT:
1819 	case KCFG_CHAR_ARR:
1820 	default:
1821 		pr_warn("extern (kcfg) '%s': value '%c' implies bool, tristate, or char type\n",
1822 			ext->name, value);
1823 		return -EINVAL;
1824 	}
1825 	ext->is_set = true;
1826 	return 0;
1827 }
1828 
1829 static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
1830 			      const char *value)
1831 {
1832 	size_t len;
1833 
1834 	if (ext->kcfg.type != KCFG_CHAR_ARR) {
1835 		pr_warn("extern (kcfg) '%s': value '%s' implies char array type\n",
1836 			ext->name, value);
1837 		return -EINVAL;
1838 	}
1839 
1840 	len = strlen(value);
1841 	if (value[len - 1] != '"') {
1842 		pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
1843 			ext->name, value);
1844 		return -EINVAL;
1845 	}
1846 
1847 	/* strip quotes */
1848 	len -= 2;
1849 	if (len >= ext->kcfg.sz) {
1850 		pr_warn("extern (kcfg) '%s': long string '%s' of (%zu bytes) truncated to %d bytes\n",
1851 			ext->name, value, len, ext->kcfg.sz - 1);
1852 		len = ext->kcfg.sz - 1;
1853 	}
1854 	memcpy(ext_val, value + 1, len);
1855 	ext_val[len] = '\0';
1856 	ext->is_set = true;
1857 	return 0;
1858 }
1859 
1860 static int parse_u64(const char *value, __u64 *res)
1861 {
1862 	char *value_end;
1863 	int err;
1864 
1865 	errno = 0;
1866 	*res = strtoull(value, &value_end, 0);
1867 	if (errno) {
1868 		err = -errno;
1869 		pr_warn("failed to parse '%s' as integer: %d\n", value, err);
1870 		return err;
1871 	}
1872 	if (*value_end) {
1873 		pr_warn("failed to parse '%s' as integer completely\n", value);
1874 		return -EINVAL;
1875 	}
1876 	return 0;
1877 }
1878 
1879 static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
1880 {
1881 	int bit_sz = ext->kcfg.sz * 8;
1882 
1883 	if (ext->kcfg.sz == 8)
1884 		return true;
1885 
1886 	/* Validate that value stored in u64 fits in integer of `ext->sz`
1887 	 * bytes size without any loss of information. If the target integer
1888 	 * is signed, we rely on the following limits of integer type of
1889 	 * Y bits and subsequent transformation:
1890 	 *
1891 	 *     -2^(Y-1) <= X           <= 2^(Y-1) - 1
1892 	 *            0 <= X + 2^(Y-1) <= 2^Y - 1
1893 	 *            0 <= X + 2^(Y-1) <  2^Y
1894 	 *
1895 	 *  For unsigned target integer, check that all the (64 - Y) bits are
1896 	 *  zero.
1897 	 */
1898 	if (ext->kcfg.is_signed)
1899 		return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
1900 	else
1901 		return (v >> bit_sz) == 0;
1902 }
1903 
1904 static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
1905 			      __u64 value)
1906 {
1907 	if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR &&
1908 	    ext->kcfg.type != KCFG_BOOL) {
1909 		pr_warn("extern (kcfg) '%s': value '%llu' implies integer, char, or boolean type\n",
1910 			ext->name, (unsigned long long)value);
1911 		return -EINVAL;
1912 	}
1913 	if (ext->kcfg.type == KCFG_BOOL && value > 1) {
1914 		pr_warn("extern (kcfg) '%s': value '%llu' isn't boolean compatible\n",
1915 			ext->name, (unsigned long long)value);
1916 		return -EINVAL;
1917 
1918 	}
1919 	if (!is_kcfg_value_in_range(ext, value)) {
1920 		pr_warn("extern (kcfg) '%s': value '%llu' doesn't fit in %d bytes\n",
1921 			ext->name, (unsigned long long)value, ext->kcfg.sz);
1922 		return -ERANGE;
1923 	}
1924 	switch (ext->kcfg.sz) {
1925 	case 1:
1926 		*(__u8 *)ext_val = value;
1927 		break;
1928 	case 2:
1929 		*(__u16 *)ext_val = value;
1930 		break;
1931 	case 4:
1932 		*(__u32 *)ext_val = value;
1933 		break;
1934 	case 8:
1935 		*(__u64 *)ext_val = value;
1936 		break;
1937 	default:
1938 		return -EINVAL;
1939 	}
1940 	ext->is_set = true;
1941 	return 0;
1942 }
1943 
1944 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
1945 					    char *buf, void *data)
1946 {
1947 	struct extern_desc *ext;
1948 	char *sep, *value;
1949 	int len, err = 0;
1950 	void *ext_val;
1951 	__u64 num;
1952 
1953 	if (!str_has_pfx(buf, "CONFIG_"))
1954 		return 0;
1955 
1956 	sep = strchr(buf, '=');
1957 	if (!sep) {
1958 		pr_warn("failed to parse '%s': no separator\n", buf);
1959 		return -EINVAL;
1960 	}
1961 
1962 	/* Trim ending '\n' */
1963 	len = strlen(buf);
1964 	if (buf[len - 1] == '\n')
1965 		buf[len - 1] = '\0';
1966 	/* Split on '=' and ensure that a value is present. */
1967 	*sep = '\0';
1968 	if (!sep[1]) {
1969 		*sep = '=';
1970 		pr_warn("failed to parse '%s': no value\n", buf);
1971 		return -EINVAL;
1972 	}
1973 
1974 	ext = find_extern_by_name(obj, buf);
1975 	if (!ext || ext->is_set)
1976 		return 0;
1977 
1978 	ext_val = data + ext->kcfg.data_off;
1979 	value = sep + 1;
1980 
1981 	switch (*value) {
1982 	case 'y': case 'n': case 'm':
1983 		err = set_kcfg_value_tri(ext, ext_val, *value);
1984 		break;
1985 	case '"':
1986 		err = set_kcfg_value_str(ext, ext_val, value);
1987 		break;
1988 	default:
1989 		/* assume integer */
1990 		err = parse_u64(value, &num);
1991 		if (err) {
1992 			pr_warn("extern (kcfg) '%s': value '%s' isn't a valid integer\n", ext->name, value);
1993 			return err;
1994 		}
1995 		if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
1996 			pr_warn("extern (kcfg) '%s': value '%s' implies integer type\n", ext->name, value);
1997 			return -EINVAL;
1998 		}
1999 		err = set_kcfg_value_num(ext, ext_val, num);
2000 		break;
2001 	}
2002 	if (err)
2003 		return err;
2004 	pr_debug("extern (kcfg) '%s': set to %s\n", ext->name, value);
2005 	return 0;
2006 }
2007 
2008 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
2009 {
2010 	char buf[PATH_MAX];
2011 	struct utsname uts;
2012 	int len, err = 0;
2013 	gzFile file;
2014 
2015 	uname(&uts);
2016 	len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
2017 	if (len < 0)
2018 		return -EINVAL;
2019 	else if (len >= PATH_MAX)
2020 		return -ENAMETOOLONG;
2021 
2022 	/* gzopen also accepts uncompressed files. */
2023 	file = gzopen(buf, "re");
2024 	if (!file)
2025 		file = gzopen("/proc/config.gz", "re");
2026 
2027 	if (!file) {
2028 		pr_warn("failed to open system Kconfig\n");
2029 		return -ENOENT;
2030 	}
2031 
2032 	while (gzgets(file, buf, sizeof(buf))) {
2033 		err = bpf_object__process_kconfig_line(obj, buf, data);
2034 		if (err) {
2035 			pr_warn("error parsing system Kconfig line '%s': %d\n",
2036 				buf, err);
2037 			goto out;
2038 		}
2039 	}
2040 
2041 out:
2042 	gzclose(file);
2043 	return err;
2044 }
2045 
2046 static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
2047 					const char *config, void *data)
2048 {
2049 	char buf[PATH_MAX];
2050 	int err = 0;
2051 	FILE *file;
2052 
2053 	file = fmemopen((void *)config, strlen(config), "r");
2054 	if (!file) {
2055 		err = -errno;
2056 		pr_warn("failed to open in-memory Kconfig: %d\n", err);
2057 		return err;
2058 	}
2059 
2060 	while (fgets(buf, sizeof(buf), file)) {
2061 		err = bpf_object__process_kconfig_line(obj, buf, data);
2062 		if (err) {
2063 			pr_warn("error parsing in-memory Kconfig line '%s': %d\n",
2064 				buf, err);
2065 			break;
2066 		}
2067 	}
2068 
2069 	fclose(file);
2070 	return err;
2071 }
2072 
2073 static int bpf_object__init_kconfig_map(struct bpf_object *obj)
2074 {
2075 	struct extern_desc *last_ext = NULL, *ext;
2076 	size_t map_sz;
2077 	int i, err;
2078 
2079 	for (i = 0; i < obj->nr_extern; i++) {
2080 		ext = &obj->externs[i];
2081 		if (ext->type == EXT_KCFG)
2082 			last_ext = ext;
2083 	}
2084 
2085 	if (!last_ext)
2086 		return 0;
2087 
2088 	map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
2089 	err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
2090 					    ".kconfig", obj->efile.symbols_shndx,
2091 					    NULL, map_sz);
2092 	if (err)
2093 		return err;
2094 
2095 	obj->kconfig_map_idx = obj->nr_maps - 1;
2096 
2097 	return 0;
2098 }
2099 
2100 const struct btf_type *
2101 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
2102 {
2103 	const struct btf_type *t = btf__type_by_id(btf, id);
2104 
2105 	if (res_id)
2106 		*res_id = id;
2107 
2108 	while (btf_is_mod(t) || btf_is_typedef(t)) {
2109 		if (res_id)
2110 			*res_id = t->type;
2111 		t = btf__type_by_id(btf, t->type);
2112 	}
2113 
2114 	return t;
2115 }
2116 
2117 static const struct btf_type *
2118 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
2119 {
2120 	const struct btf_type *t;
2121 
2122 	t = skip_mods_and_typedefs(btf, id, NULL);
2123 	if (!btf_is_ptr(t))
2124 		return NULL;
2125 
2126 	t = skip_mods_and_typedefs(btf, t->type, res_id);
2127 
2128 	return btf_is_func_proto(t) ? t : NULL;
2129 }
2130 
2131 static const char *__btf_kind_str(__u16 kind)
2132 {
2133 	switch (kind) {
2134 	case BTF_KIND_UNKN: return "void";
2135 	case BTF_KIND_INT: return "int";
2136 	case BTF_KIND_PTR: return "ptr";
2137 	case BTF_KIND_ARRAY: return "array";
2138 	case BTF_KIND_STRUCT: return "struct";
2139 	case BTF_KIND_UNION: return "union";
2140 	case BTF_KIND_ENUM: return "enum";
2141 	case BTF_KIND_FWD: return "fwd";
2142 	case BTF_KIND_TYPEDEF: return "typedef";
2143 	case BTF_KIND_VOLATILE: return "volatile";
2144 	case BTF_KIND_CONST: return "const";
2145 	case BTF_KIND_RESTRICT: return "restrict";
2146 	case BTF_KIND_FUNC: return "func";
2147 	case BTF_KIND_FUNC_PROTO: return "func_proto";
2148 	case BTF_KIND_VAR: return "var";
2149 	case BTF_KIND_DATASEC: return "datasec";
2150 	case BTF_KIND_FLOAT: return "float";
2151 	case BTF_KIND_DECL_TAG: return "decl_tag";
2152 	case BTF_KIND_TYPE_TAG: return "type_tag";
2153 	case BTF_KIND_ENUM64: return "enum64";
2154 	default: return "unknown";
2155 	}
2156 }
2157 
2158 const char *btf_kind_str(const struct btf_type *t)
2159 {
2160 	return __btf_kind_str(btf_kind(t));
2161 }
2162 
2163 /*
2164  * Fetch integer attribute of BTF map definition. Such attributes are
2165  * represented using a pointer to an array, in which dimensionality of array
2166  * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2167  * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2168  * type definition, while using only sizeof(void *) space in ELF data section.
2169  */
2170 static bool get_map_field_int(const char *map_name, const struct btf *btf,
2171 			      const struct btf_member *m, __u32 *res)
2172 {
2173 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2174 	const char *name = btf__name_by_offset(btf, m->name_off);
2175 	const struct btf_array *arr_info;
2176 	const struct btf_type *arr_t;
2177 
2178 	if (!btf_is_ptr(t)) {
2179 		pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2180 			map_name, name, btf_kind_str(t));
2181 		return false;
2182 	}
2183 
2184 	arr_t = btf__type_by_id(btf, t->type);
2185 	if (!arr_t) {
2186 		pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2187 			map_name, name, t->type);
2188 		return false;
2189 	}
2190 	if (!btf_is_array(arr_t)) {
2191 		pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2192 			map_name, name, btf_kind_str(arr_t));
2193 		return false;
2194 	}
2195 	arr_info = btf_array(arr_t);
2196 	*res = arr_info->nelems;
2197 	return true;
2198 }
2199 
2200 static int pathname_concat(char *buf, size_t buf_sz, const char *path, const char *name)
2201 {
2202 	int len;
2203 
2204 	len = snprintf(buf, buf_sz, "%s/%s", path, name);
2205 	if (len < 0)
2206 		return -EINVAL;
2207 	if (len >= buf_sz)
2208 		return -ENAMETOOLONG;
2209 
2210 	return 0;
2211 }
2212 
2213 static int build_map_pin_path(struct bpf_map *map, const char *path)
2214 {
2215 	char buf[PATH_MAX];
2216 	int err;
2217 
2218 	if (!path)
2219 		path = "/sys/fs/bpf";
2220 
2221 	err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
2222 	if (err)
2223 		return err;
2224 
2225 	return bpf_map__set_pin_path(map, buf);
2226 }
2227 
2228 /* should match definition in bpf_helpers.h */
2229 enum libbpf_pin_type {
2230 	LIBBPF_PIN_NONE,
2231 	/* PIN_BY_NAME: pin maps by name (in /sys/fs/bpf by default) */
2232 	LIBBPF_PIN_BY_NAME,
2233 };
2234 
2235 int parse_btf_map_def(const char *map_name, struct btf *btf,
2236 		      const struct btf_type *def_t, bool strict,
2237 		      struct btf_map_def *map_def, struct btf_map_def *inner_def)
2238 {
2239 	const struct btf_type *t;
2240 	const struct btf_member *m;
2241 	bool is_inner = inner_def == NULL;
2242 	int vlen, i;
2243 
2244 	vlen = btf_vlen(def_t);
2245 	m = btf_members(def_t);
2246 	for (i = 0; i < vlen; i++, m++) {
2247 		const char *name = btf__name_by_offset(btf, m->name_off);
2248 
2249 		if (!name) {
2250 			pr_warn("map '%s': invalid field #%d.\n", map_name, i);
2251 			return -EINVAL;
2252 		}
2253 		if (strcmp(name, "type") == 0) {
2254 			if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
2255 				return -EINVAL;
2256 			map_def->parts |= MAP_DEF_MAP_TYPE;
2257 		} else if (strcmp(name, "max_entries") == 0) {
2258 			if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
2259 				return -EINVAL;
2260 			map_def->parts |= MAP_DEF_MAX_ENTRIES;
2261 		} else if (strcmp(name, "map_flags") == 0) {
2262 			if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
2263 				return -EINVAL;
2264 			map_def->parts |= MAP_DEF_MAP_FLAGS;
2265 		} else if (strcmp(name, "numa_node") == 0) {
2266 			if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
2267 				return -EINVAL;
2268 			map_def->parts |= MAP_DEF_NUMA_NODE;
2269 		} else if (strcmp(name, "key_size") == 0) {
2270 			__u32 sz;
2271 
2272 			if (!get_map_field_int(map_name, btf, m, &sz))
2273 				return -EINVAL;
2274 			if (map_def->key_size && map_def->key_size != sz) {
2275 				pr_warn("map '%s': conflicting key size %u != %u.\n",
2276 					map_name, map_def->key_size, sz);
2277 				return -EINVAL;
2278 			}
2279 			map_def->key_size = sz;
2280 			map_def->parts |= MAP_DEF_KEY_SIZE;
2281 		} else if (strcmp(name, "key") == 0) {
2282 			__s64 sz;
2283 
2284 			t = btf__type_by_id(btf, m->type);
2285 			if (!t) {
2286 				pr_warn("map '%s': key type [%d] not found.\n",
2287 					map_name, m->type);
2288 				return -EINVAL;
2289 			}
2290 			if (!btf_is_ptr(t)) {
2291 				pr_warn("map '%s': key spec is not PTR: %s.\n",
2292 					map_name, btf_kind_str(t));
2293 				return -EINVAL;
2294 			}
2295 			sz = btf__resolve_size(btf, t->type);
2296 			if (sz < 0) {
2297 				pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2298 					map_name, t->type, (ssize_t)sz);
2299 				return sz;
2300 			}
2301 			if (map_def->key_size && map_def->key_size != sz) {
2302 				pr_warn("map '%s': conflicting key size %u != %zd.\n",
2303 					map_name, map_def->key_size, (ssize_t)sz);
2304 				return -EINVAL;
2305 			}
2306 			map_def->key_size = sz;
2307 			map_def->key_type_id = t->type;
2308 			map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
2309 		} else if (strcmp(name, "value_size") == 0) {
2310 			__u32 sz;
2311 
2312 			if (!get_map_field_int(map_name, btf, m, &sz))
2313 				return -EINVAL;
2314 			if (map_def->value_size && map_def->value_size != sz) {
2315 				pr_warn("map '%s': conflicting value size %u != %u.\n",
2316 					map_name, map_def->value_size, sz);
2317 				return -EINVAL;
2318 			}
2319 			map_def->value_size = sz;
2320 			map_def->parts |= MAP_DEF_VALUE_SIZE;
2321 		} else if (strcmp(name, "value") == 0) {
2322 			__s64 sz;
2323 
2324 			t = btf__type_by_id(btf, m->type);
2325 			if (!t) {
2326 				pr_warn("map '%s': value type [%d] not found.\n",
2327 					map_name, m->type);
2328 				return -EINVAL;
2329 			}
2330 			if (!btf_is_ptr(t)) {
2331 				pr_warn("map '%s': value spec is not PTR: %s.\n",
2332 					map_name, btf_kind_str(t));
2333 				return -EINVAL;
2334 			}
2335 			sz = btf__resolve_size(btf, t->type);
2336 			if (sz < 0) {
2337 				pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2338 					map_name, t->type, (ssize_t)sz);
2339 				return sz;
2340 			}
2341 			if (map_def->value_size && map_def->value_size != sz) {
2342 				pr_warn("map '%s': conflicting value size %u != %zd.\n",
2343 					map_name, map_def->value_size, (ssize_t)sz);
2344 				return -EINVAL;
2345 			}
2346 			map_def->value_size = sz;
2347 			map_def->value_type_id = t->type;
2348 			map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
2349 		}
2350 		else if (strcmp(name, "values") == 0) {
2351 			bool is_map_in_map = bpf_map_type__is_map_in_map(map_def->map_type);
2352 			bool is_prog_array = map_def->map_type == BPF_MAP_TYPE_PROG_ARRAY;
2353 			const char *desc = is_map_in_map ? "map-in-map inner" : "prog-array value";
2354 			char inner_map_name[128];
2355 			int err;
2356 
2357 			if (is_inner) {
2358 				pr_warn("map '%s': multi-level inner maps not supported.\n",
2359 					map_name);
2360 				return -ENOTSUP;
2361 			}
2362 			if (i != vlen - 1) {
2363 				pr_warn("map '%s': '%s' member should be last.\n",
2364 					map_name, name);
2365 				return -EINVAL;
2366 			}
2367 			if (!is_map_in_map && !is_prog_array) {
2368 				pr_warn("map '%s': should be map-in-map or prog-array.\n",
2369 					map_name);
2370 				return -ENOTSUP;
2371 			}
2372 			if (map_def->value_size && map_def->value_size != 4) {
2373 				pr_warn("map '%s': conflicting value size %u != 4.\n",
2374 					map_name, map_def->value_size);
2375 				return -EINVAL;
2376 			}
2377 			map_def->value_size = 4;
2378 			t = btf__type_by_id(btf, m->type);
2379 			if (!t) {
2380 				pr_warn("map '%s': %s type [%d] not found.\n",
2381 					map_name, desc, m->type);
2382 				return -EINVAL;
2383 			}
2384 			if (!btf_is_array(t) || btf_array(t)->nelems) {
2385 				pr_warn("map '%s': %s spec is not a zero-sized array.\n",
2386 					map_name, desc);
2387 				return -EINVAL;
2388 			}
2389 			t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
2390 			if (!btf_is_ptr(t)) {
2391 				pr_warn("map '%s': %s def is of unexpected kind %s.\n",
2392 					map_name, desc, btf_kind_str(t));
2393 				return -EINVAL;
2394 			}
2395 			t = skip_mods_and_typedefs(btf, t->type, NULL);
2396 			if (is_prog_array) {
2397 				if (!btf_is_func_proto(t)) {
2398 					pr_warn("map '%s': prog-array value def is of unexpected kind %s.\n",
2399 						map_name, btf_kind_str(t));
2400 					return -EINVAL;
2401 				}
2402 				continue;
2403 			}
2404 			if (!btf_is_struct(t)) {
2405 				pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2406 					map_name, btf_kind_str(t));
2407 				return -EINVAL;
2408 			}
2409 
2410 			snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2411 			err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
2412 			if (err)
2413 				return err;
2414 
2415 			map_def->parts |= MAP_DEF_INNER_MAP;
2416 		} else if (strcmp(name, "pinning") == 0) {
2417 			__u32 val;
2418 
2419 			if (is_inner) {
2420 				pr_warn("map '%s': inner def can't be pinned.\n", map_name);
2421 				return -EINVAL;
2422 			}
2423 			if (!get_map_field_int(map_name, btf, m, &val))
2424 				return -EINVAL;
2425 			if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
2426 				pr_warn("map '%s': invalid pinning value %u.\n",
2427 					map_name, val);
2428 				return -EINVAL;
2429 			}
2430 			map_def->pinning = val;
2431 			map_def->parts |= MAP_DEF_PINNING;
2432 		} else if (strcmp(name, "map_extra") == 0) {
2433 			__u32 map_extra;
2434 
2435 			if (!get_map_field_int(map_name, btf, m, &map_extra))
2436 				return -EINVAL;
2437 			map_def->map_extra = map_extra;
2438 			map_def->parts |= MAP_DEF_MAP_EXTRA;
2439 		} else {
2440 			if (strict) {
2441 				pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
2442 				return -ENOTSUP;
2443 			}
2444 			pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
2445 		}
2446 	}
2447 
2448 	if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2449 		pr_warn("map '%s': map type isn't specified.\n", map_name);
2450 		return -EINVAL;
2451 	}
2452 
2453 	return 0;
2454 }
2455 
2456 static size_t adjust_ringbuf_sz(size_t sz)
2457 {
2458 	__u32 page_sz = sysconf(_SC_PAGE_SIZE);
2459 	__u32 mul;
2460 
2461 	/* if user forgot to set any size, make sure they see error */
2462 	if (sz == 0)
2463 		return 0;
2464 	/* Kernel expects BPF_MAP_TYPE_RINGBUF's max_entries to be
2465 	 * a power-of-2 multiple of kernel's page size. If user diligently
2466 	 * satisified these conditions, pass the size through.
2467 	 */
2468 	if ((sz % page_sz) == 0 && is_pow_of_2(sz / page_sz))
2469 		return sz;
2470 
2471 	/* Otherwise find closest (page_sz * power_of_2) product bigger than
2472 	 * user-set size to satisfy both user size request and kernel
2473 	 * requirements and substitute correct max_entries for map creation.
2474 	 */
2475 	for (mul = 1; mul <= UINT_MAX / page_sz; mul <<= 1) {
2476 		if (mul * page_sz > sz)
2477 			return mul * page_sz;
2478 	}
2479 
2480 	/* if it's impossible to satisfy the conditions (i.e., user size is
2481 	 * very close to UINT_MAX but is not a power-of-2 multiple of
2482 	 * page_size) then just return original size and let kernel reject it
2483 	 */
2484 	return sz;
2485 }
2486 
2487 static bool map_is_ringbuf(const struct bpf_map *map)
2488 {
2489 	return map->def.type == BPF_MAP_TYPE_RINGBUF ||
2490 	       map->def.type == BPF_MAP_TYPE_USER_RINGBUF;
2491 }
2492 
2493 static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2494 {
2495 	map->def.type = def->map_type;
2496 	map->def.key_size = def->key_size;
2497 	map->def.value_size = def->value_size;
2498 	map->def.max_entries = def->max_entries;
2499 	map->def.map_flags = def->map_flags;
2500 	map->map_extra = def->map_extra;
2501 
2502 	map->numa_node = def->numa_node;
2503 	map->btf_key_type_id = def->key_type_id;
2504 	map->btf_value_type_id = def->value_type_id;
2505 
2506 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
2507 	if (map_is_ringbuf(map))
2508 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
2509 
2510 	if (def->parts & MAP_DEF_MAP_TYPE)
2511 		pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2512 
2513 	if (def->parts & MAP_DEF_KEY_TYPE)
2514 		pr_debug("map '%s': found key [%u], sz = %u.\n",
2515 			 map->name, def->key_type_id, def->key_size);
2516 	else if (def->parts & MAP_DEF_KEY_SIZE)
2517 		pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2518 
2519 	if (def->parts & MAP_DEF_VALUE_TYPE)
2520 		pr_debug("map '%s': found value [%u], sz = %u.\n",
2521 			 map->name, def->value_type_id, def->value_size);
2522 	else if (def->parts & MAP_DEF_VALUE_SIZE)
2523 		pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2524 
2525 	if (def->parts & MAP_DEF_MAX_ENTRIES)
2526 		pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2527 	if (def->parts & MAP_DEF_MAP_FLAGS)
2528 		pr_debug("map '%s': found map_flags = 0x%x.\n", map->name, def->map_flags);
2529 	if (def->parts & MAP_DEF_MAP_EXTRA)
2530 		pr_debug("map '%s': found map_extra = 0x%llx.\n", map->name,
2531 			 (unsigned long long)def->map_extra);
2532 	if (def->parts & MAP_DEF_PINNING)
2533 		pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2534 	if (def->parts & MAP_DEF_NUMA_NODE)
2535 		pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2536 
2537 	if (def->parts & MAP_DEF_INNER_MAP)
2538 		pr_debug("map '%s': found inner map definition.\n", map->name);
2539 }
2540 
2541 static const char *btf_var_linkage_str(__u32 linkage)
2542 {
2543 	switch (linkage) {
2544 	case BTF_VAR_STATIC: return "static";
2545 	case BTF_VAR_GLOBAL_ALLOCATED: return "global";
2546 	case BTF_VAR_GLOBAL_EXTERN: return "extern";
2547 	default: return "unknown";
2548 	}
2549 }
2550 
2551 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2552 					 const struct btf_type *sec,
2553 					 int var_idx, int sec_idx,
2554 					 const Elf_Data *data, bool strict,
2555 					 const char *pin_root_path)
2556 {
2557 	struct btf_map_def map_def = {}, inner_def = {};
2558 	const struct btf_type *var, *def;
2559 	const struct btf_var_secinfo *vi;
2560 	const struct btf_var *var_extra;
2561 	const char *map_name;
2562 	struct bpf_map *map;
2563 	int err;
2564 
2565 	vi = btf_var_secinfos(sec) + var_idx;
2566 	var = btf__type_by_id(obj->btf, vi->type);
2567 	var_extra = btf_var(var);
2568 	map_name = btf__name_by_offset(obj->btf, var->name_off);
2569 
2570 	if (map_name == NULL || map_name[0] == '\0') {
2571 		pr_warn("map #%d: empty name.\n", var_idx);
2572 		return -EINVAL;
2573 	}
2574 	if ((__u64)vi->offset + vi->size > data->d_size) {
2575 		pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2576 		return -EINVAL;
2577 	}
2578 	if (!btf_is_var(var)) {
2579 		pr_warn("map '%s': unexpected var kind %s.\n",
2580 			map_name, btf_kind_str(var));
2581 		return -EINVAL;
2582 	}
2583 	if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
2584 		pr_warn("map '%s': unsupported map linkage %s.\n",
2585 			map_name, btf_var_linkage_str(var_extra->linkage));
2586 		return -EOPNOTSUPP;
2587 	}
2588 
2589 	def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2590 	if (!btf_is_struct(def)) {
2591 		pr_warn("map '%s': unexpected def kind %s.\n",
2592 			map_name, btf_kind_str(var));
2593 		return -EINVAL;
2594 	}
2595 	if (def->size > vi->size) {
2596 		pr_warn("map '%s': invalid def size.\n", map_name);
2597 		return -EINVAL;
2598 	}
2599 
2600 	map = bpf_object__add_map(obj);
2601 	if (IS_ERR(map))
2602 		return PTR_ERR(map);
2603 	map->name = strdup(map_name);
2604 	if (!map->name) {
2605 		pr_warn("map '%s': failed to alloc map name.\n", map_name);
2606 		return -ENOMEM;
2607 	}
2608 	map->libbpf_type = LIBBPF_MAP_UNSPEC;
2609 	map->def.type = BPF_MAP_TYPE_UNSPEC;
2610 	map->sec_idx = sec_idx;
2611 	map->sec_offset = vi->offset;
2612 	map->btf_var_idx = var_idx;
2613 	pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2614 		 map_name, map->sec_idx, map->sec_offset);
2615 
2616 	err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
2617 	if (err)
2618 		return err;
2619 
2620 	fill_map_from_def(map, &map_def);
2621 
2622 	if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
2623 		err = build_map_pin_path(map, pin_root_path);
2624 		if (err) {
2625 			pr_warn("map '%s': couldn't build pin path.\n", map->name);
2626 			return err;
2627 		}
2628 	}
2629 
2630 	if (map_def.parts & MAP_DEF_INNER_MAP) {
2631 		map->inner_map = calloc(1, sizeof(*map->inner_map));
2632 		if (!map->inner_map)
2633 			return -ENOMEM;
2634 		map->inner_map->fd = create_placeholder_fd();
2635 		if (map->inner_map->fd < 0)
2636 			return map->inner_map->fd;
2637 		map->inner_map->sec_idx = sec_idx;
2638 		map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
2639 		if (!map->inner_map->name)
2640 			return -ENOMEM;
2641 		sprintf(map->inner_map->name, "%s.inner", map_name);
2642 
2643 		fill_map_from_def(map->inner_map, &inner_def);
2644 	}
2645 
2646 	err = map_fill_btf_type_info(obj, map);
2647 	if (err)
2648 		return err;
2649 
2650 	return 0;
2651 }
2652 
2653 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
2654 					  const char *pin_root_path)
2655 {
2656 	const struct btf_type *sec = NULL;
2657 	int nr_types, i, vlen, err;
2658 	const struct btf_type *t;
2659 	const char *name;
2660 	Elf_Data *data;
2661 	Elf_Scn *scn;
2662 
2663 	if (obj->efile.btf_maps_shndx < 0)
2664 		return 0;
2665 
2666 	scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
2667 	data = elf_sec_data(obj, scn);
2668 	if (!scn || !data) {
2669 		pr_warn("elf: failed to get %s map definitions for %s\n",
2670 			MAPS_ELF_SEC, obj->path);
2671 		return -EINVAL;
2672 	}
2673 
2674 	nr_types = btf__type_cnt(obj->btf);
2675 	for (i = 1; i < nr_types; i++) {
2676 		t = btf__type_by_id(obj->btf, i);
2677 		if (!btf_is_datasec(t))
2678 			continue;
2679 		name = btf__name_by_offset(obj->btf, t->name_off);
2680 		if (strcmp(name, MAPS_ELF_SEC) == 0) {
2681 			sec = t;
2682 			obj->efile.btf_maps_sec_btf_id = i;
2683 			break;
2684 		}
2685 	}
2686 
2687 	if (!sec) {
2688 		pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
2689 		return -ENOENT;
2690 	}
2691 
2692 	vlen = btf_vlen(sec);
2693 	for (i = 0; i < vlen; i++) {
2694 		err = bpf_object__init_user_btf_map(obj, sec, i,
2695 						    obj->efile.btf_maps_shndx,
2696 						    data, strict,
2697 						    pin_root_path);
2698 		if (err)
2699 			return err;
2700 	}
2701 
2702 	return 0;
2703 }
2704 
2705 static int bpf_object__init_maps(struct bpf_object *obj,
2706 				 const struct bpf_object_open_opts *opts)
2707 {
2708 	const char *pin_root_path;
2709 	bool strict;
2710 	int err = 0;
2711 
2712 	strict = !OPTS_GET(opts, relaxed_maps, false);
2713 	pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
2714 
2715 	err = bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
2716 	err = err ?: bpf_object__init_global_data_maps(obj);
2717 	err = err ?: bpf_object__init_kconfig_map(obj);
2718 	err = err ?: bpf_object_init_struct_ops(obj);
2719 
2720 	return err;
2721 }
2722 
2723 static bool section_have_execinstr(struct bpf_object *obj, int idx)
2724 {
2725 	Elf64_Shdr *sh;
2726 
2727 	sh = elf_sec_hdr(obj, elf_sec_by_idx(obj, idx));
2728 	if (!sh)
2729 		return false;
2730 
2731 	return sh->sh_flags & SHF_EXECINSTR;
2732 }
2733 
2734 static bool btf_needs_sanitization(struct bpf_object *obj)
2735 {
2736 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2737 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2738 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2739 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2740 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2741 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2742 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
2743 
2744 	return !has_func || !has_datasec || !has_func_global || !has_float ||
2745 	       !has_decl_tag || !has_type_tag || !has_enum64;
2746 }
2747 
2748 static int bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *btf)
2749 {
2750 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2751 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2752 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2753 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2754 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2755 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2756 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
2757 	int enum64_placeholder_id = 0;
2758 	struct btf_type *t;
2759 	int i, j, vlen;
2760 
2761 	for (i = 1; i < btf__type_cnt(btf); i++) {
2762 		t = (struct btf_type *)btf__type_by_id(btf, i);
2763 
2764 		if ((!has_datasec && btf_is_var(t)) || (!has_decl_tag && btf_is_decl_tag(t))) {
2765 			/* replace VAR/DECL_TAG with INT */
2766 			t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
2767 			/*
2768 			 * using size = 1 is the safest choice, 4 will be too
2769 			 * big and cause kernel BTF validation failure if
2770 			 * original variable took less than 4 bytes
2771 			 */
2772 			t->size = 1;
2773 			*(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
2774 		} else if (!has_datasec && btf_is_datasec(t)) {
2775 			/* replace DATASEC with STRUCT */
2776 			const struct btf_var_secinfo *v = btf_var_secinfos(t);
2777 			struct btf_member *m = btf_members(t);
2778 			struct btf_type *vt;
2779 			char *name;
2780 
2781 			name = (char *)btf__name_by_offset(btf, t->name_off);
2782 			while (*name) {
2783 				if (*name == '.')
2784 					*name = '_';
2785 				name++;
2786 			}
2787 
2788 			vlen = btf_vlen(t);
2789 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
2790 			for (j = 0; j < vlen; j++, v++, m++) {
2791 				/* order of field assignments is important */
2792 				m->offset = v->offset * 8;
2793 				m->type = v->type;
2794 				/* preserve variable name as member name */
2795 				vt = (void *)btf__type_by_id(btf, v->type);
2796 				m->name_off = vt->name_off;
2797 			}
2798 		} else if (!has_func && btf_is_func_proto(t)) {
2799 			/* replace FUNC_PROTO with ENUM */
2800 			vlen = btf_vlen(t);
2801 			t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
2802 			t->size = sizeof(__u32); /* kernel enforced */
2803 		} else if (!has_func && btf_is_func(t)) {
2804 			/* replace FUNC with TYPEDEF */
2805 			t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
2806 		} else if (!has_func_global && btf_is_func(t)) {
2807 			/* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
2808 			t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
2809 		} else if (!has_float && btf_is_float(t)) {
2810 			/* replace FLOAT with an equally-sized empty STRUCT;
2811 			 * since C compilers do not accept e.g. "float" as a
2812 			 * valid struct name, make it anonymous
2813 			 */
2814 			t->name_off = 0;
2815 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
2816 		} else if (!has_type_tag && btf_is_type_tag(t)) {
2817 			/* replace TYPE_TAG with a CONST */
2818 			t->name_off = 0;
2819 			t->info = BTF_INFO_ENC(BTF_KIND_CONST, 0, 0);
2820 		} else if (!has_enum64 && btf_is_enum(t)) {
2821 			/* clear the kflag */
2822 			t->info = btf_type_info(btf_kind(t), btf_vlen(t), false);
2823 		} else if (!has_enum64 && btf_is_enum64(t)) {
2824 			/* replace ENUM64 with a union */
2825 			struct btf_member *m;
2826 
2827 			if (enum64_placeholder_id == 0) {
2828 				enum64_placeholder_id = btf__add_int(btf, "enum64_placeholder", 1, 0);
2829 				if (enum64_placeholder_id < 0)
2830 					return enum64_placeholder_id;
2831 
2832 				t = (struct btf_type *)btf__type_by_id(btf, i);
2833 			}
2834 
2835 			m = btf_members(t);
2836 			vlen = btf_vlen(t);
2837 			t->info = BTF_INFO_ENC(BTF_KIND_UNION, 0, vlen);
2838 			for (j = 0; j < vlen; j++, m++) {
2839 				m->type = enum64_placeholder_id;
2840 				m->offset = 0;
2841 			}
2842 		}
2843 	}
2844 
2845 	return 0;
2846 }
2847 
2848 static bool libbpf_needs_btf(const struct bpf_object *obj)
2849 {
2850 	return obj->efile.btf_maps_shndx >= 0 ||
2851 	       obj->efile.st_ops_shndx >= 0 ||
2852 	       obj->efile.st_ops_link_shndx >= 0 ||
2853 	       obj->nr_extern > 0;
2854 }
2855 
2856 static bool kernel_needs_btf(const struct bpf_object *obj)
2857 {
2858 	return obj->efile.st_ops_shndx >= 0 || obj->efile.st_ops_link_shndx >= 0;
2859 }
2860 
2861 static int bpf_object__init_btf(struct bpf_object *obj,
2862 				Elf_Data *btf_data,
2863 				Elf_Data *btf_ext_data)
2864 {
2865 	int err = -ENOENT;
2866 
2867 	if (btf_data) {
2868 		obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
2869 		err = libbpf_get_error(obj->btf);
2870 		if (err) {
2871 			obj->btf = NULL;
2872 			pr_warn("Error loading ELF section %s: %d.\n", BTF_ELF_SEC, err);
2873 			goto out;
2874 		}
2875 		/* enforce 8-byte pointers for BPF-targeted BTFs */
2876 		btf__set_pointer_size(obj->btf, 8);
2877 	}
2878 	if (btf_ext_data) {
2879 		struct btf_ext_info *ext_segs[3];
2880 		int seg_num, sec_num;
2881 
2882 		if (!obj->btf) {
2883 			pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
2884 				 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
2885 			goto out;
2886 		}
2887 		obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
2888 		err = libbpf_get_error(obj->btf_ext);
2889 		if (err) {
2890 			pr_warn("Error loading ELF section %s: %d. Ignored and continue.\n",
2891 				BTF_EXT_ELF_SEC, err);
2892 			obj->btf_ext = NULL;
2893 			goto out;
2894 		}
2895 
2896 		/* setup .BTF.ext to ELF section mapping */
2897 		ext_segs[0] = &obj->btf_ext->func_info;
2898 		ext_segs[1] = &obj->btf_ext->line_info;
2899 		ext_segs[2] = &obj->btf_ext->core_relo_info;
2900 		for (seg_num = 0; seg_num < ARRAY_SIZE(ext_segs); seg_num++) {
2901 			struct btf_ext_info *seg = ext_segs[seg_num];
2902 			const struct btf_ext_info_sec *sec;
2903 			const char *sec_name;
2904 			Elf_Scn *scn;
2905 
2906 			if (seg->sec_cnt == 0)
2907 				continue;
2908 
2909 			seg->sec_idxs = calloc(seg->sec_cnt, sizeof(*seg->sec_idxs));
2910 			if (!seg->sec_idxs) {
2911 				err = -ENOMEM;
2912 				goto out;
2913 			}
2914 
2915 			sec_num = 0;
2916 			for_each_btf_ext_sec(seg, sec) {
2917 				/* preventively increment index to avoid doing
2918 				 * this before every continue below
2919 				 */
2920 				sec_num++;
2921 
2922 				sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
2923 				if (str_is_empty(sec_name))
2924 					continue;
2925 				scn = elf_sec_by_name(obj, sec_name);
2926 				if (!scn)
2927 					continue;
2928 
2929 				seg->sec_idxs[sec_num - 1] = elf_ndxscn(scn);
2930 			}
2931 		}
2932 	}
2933 out:
2934 	if (err && libbpf_needs_btf(obj)) {
2935 		pr_warn("BTF is required, but is missing or corrupted.\n");
2936 		return err;
2937 	}
2938 	return 0;
2939 }
2940 
2941 static int compare_vsi_off(const void *_a, const void *_b)
2942 {
2943 	const struct btf_var_secinfo *a = _a;
2944 	const struct btf_var_secinfo *b = _b;
2945 
2946 	return a->offset - b->offset;
2947 }
2948 
2949 static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
2950 			     struct btf_type *t)
2951 {
2952 	__u32 size = 0, i, vars = btf_vlen(t);
2953 	const char *sec_name = btf__name_by_offset(btf, t->name_off);
2954 	struct btf_var_secinfo *vsi;
2955 	bool fixup_offsets = false;
2956 	int err;
2957 
2958 	if (!sec_name) {
2959 		pr_debug("No name found in string section for DATASEC kind.\n");
2960 		return -ENOENT;
2961 	}
2962 
2963 	/* Extern-backing datasecs (.ksyms, .kconfig) have their size and
2964 	 * variable offsets set at the previous step. Further, not every
2965 	 * extern BTF VAR has corresponding ELF symbol preserved, so we skip
2966 	 * all fixups altogether for such sections and go straight to sorting
2967 	 * VARs within their DATASEC.
2968 	 */
2969 	if (strcmp(sec_name, KCONFIG_SEC) == 0 || strcmp(sec_name, KSYMS_SEC) == 0)
2970 		goto sort_vars;
2971 
2972 	/* Clang leaves DATASEC size and VAR offsets as zeroes, so we need to
2973 	 * fix this up. But BPF static linker already fixes this up and fills
2974 	 * all the sizes and offsets during static linking. So this step has
2975 	 * to be optional. But the STV_HIDDEN handling is non-optional for any
2976 	 * non-extern DATASEC, so the variable fixup loop below handles both
2977 	 * functions at the same time, paying the cost of BTF VAR <-> ELF
2978 	 * symbol matching just once.
2979 	 */
2980 	if (t->size == 0) {
2981 		err = find_elf_sec_sz(obj, sec_name, &size);
2982 		if (err || !size) {
2983 			pr_debug("sec '%s': failed to determine size from ELF: size %u, err %d\n",
2984 				 sec_name, size, err);
2985 			return -ENOENT;
2986 		}
2987 
2988 		t->size = size;
2989 		fixup_offsets = true;
2990 	}
2991 
2992 	for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
2993 		const struct btf_type *t_var;
2994 		struct btf_var *var;
2995 		const char *var_name;
2996 		Elf64_Sym *sym;
2997 
2998 		t_var = btf__type_by_id(btf, vsi->type);
2999 		if (!t_var || !btf_is_var(t_var)) {
3000 			pr_debug("sec '%s': unexpected non-VAR type found\n", sec_name);
3001 			return -EINVAL;
3002 		}
3003 
3004 		var = btf_var(t_var);
3005 		if (var->linkage == BTF_VAR_STATIC || var->linkage == BTF_VAR_GLOBAL_EXTERN)
3006 			continue;
3007 
3008 		var_name = btf__name_by_offset(btf, t_var->name_off);
3009 		if (!var_name) {
3010 			pr_debug("sec '%s': failed to find name of DATASEC's member #%d\n",
3011 				 sec_name, i);
3012 			return -ENOENT;
3013 		}
3014 
3015 		sym = find_elf_var_sym(obj, var_name);
3016 		if (IS_ERR(sym)) {
3017 			pr_debug("sec '%s': failed to find ELF symbol for VAR '%s'\n",
3018 				 sec_name, var_name);
3019 			return -ENOENT;
3020 		}
3021 
3022 		if (fixup_offsets)
3023 			vsi->offset = sym->st_value;
3024 
3025 		/* if variable is a global/weak symbol, but has restricted
3026 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF VAR
3027 		 * as static. This follows similar logic for functions (BPF
3028 		 * subprogs) and influences libbpf's further decisions about
3029 		 * whether to make global data BPF array maps as
3030 		 * BPF_F_MMAPABLE.
3031 		 */
3032 		if (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
3033 		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL)
3034 			var->linkage = BTF_VAR_STATIC;
3035 	}
3036 
3037 sort_vars:
3038 	qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
3039 	return 0;
3040 }
3041 
3042 static int bpf_object_fixup_btf(struct bpf_object *obj)
3043 {
3044 	int i, n, err = 0;
3045 
3046 	if (!obj->btf)
3047 		return 0;
3048 
3049 	n = btf__type_cnt(obj->btf);
3050 	for (i = 1; i < n; i++) {
3051 		struct btf_type *t = btf_type_by_id(obj->btf, i);
3052 
3053 		/* Loader needs to fix up some of the things compiler
3054 		 * couldn't get its hands on while emitting BTF. This
3055 		 * is section size and global variable offset. We use
3056 		 * the info from the ELF itself for this purpose.
3057 		 */
3058 		if (btf_is_datasec(t)) {
3059 			err = btf_fixup_datasec(obj, obj->btf, t);
3060 			if (err)
3061 				return err;
3062 		}
3063 	}
3064 
3065 	return 0;
3066 }
3067 
3068 static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
3069 {
3070 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
3071 	    prog->type == BPF_PROG_TYPE_LSM)
3072 		return true;
3073 
3074 	/* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
3075 	 * also need vmlinux BTF
3076 	 */
3077 	if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
3078 		return true;
3079 
3080 	return false;
3081 }
3082 
3083 static bool map_needs_vmlinux_btf(struct bpf_map *map)
3084 {
3085 	return bpf_map__is_struct_ops(map);
3086 }
3087 
3088 static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
3089 {
3090 	struct bpf_program *prog;
3091 	struct bpf_map *map;
3092 	int i;
3093 
3094 	/* CO-RE relocations need kernel BTF, only when btf_custom_path
3095 	 * is not specified
3096 	 */
3097 	if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
3098 		return true;
3099 
3100 	/* Support for typed ksyms needs kernel BTF */
3101 	for (i = 0; i < obj->nr_extern; i++) {
3102 		const struct extern_desc *ext;
3103 
3104 		ext = &obj->externs[i];
3105 		if (ext->type == EXT_KSYM && ext->ksym.type_id)
3106 			return true;
3107 	}
3108 
3109 	bpf_object__for_each_program(prog, obj) {
3110 		if (!prog->autoload)
3111 			continue;
3112 		if (prog_needs_vmlinux_btf(prog))
3113 			return true;
3114 	}
3115 
3116 	bpf_object__for_each_map(map, obj) {
3117 		if (map_needs_vmlinux_btf(map))
3118 			return true;
3119 	}
3120 
3121 	return false;
3122 }
3123 
3124 static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
3125 {
3126 	int err;
3127 
3128 	/* btf_vmlinux could be loaded earlier */
3129 	if (obj->btf_vmlinux || obj->gen_loader)
3130 		return 0;
3131 
3132 	if (!force && !obj_needs_vmlinux_btf(obj))
3133 		return 0;
3134 
3135 	obj->btf_vmlinux = btf__load_vmlinux_btf();
3136 	err = libbpf_get_error(obj->btf_vmlinux);
3137 	if (err) {
3138 		pr_warn("Error loading vmlinux BTF: %d\n", err);
3139 		obj->btf_vmlinux = NULL;
3140 		return err;
3141 	}
3142 	return 0;
3143 }
3144 
3145 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
3146 {
3147 	struct btf *kern_btf = obj->btf;
3148 	bool btf_mandatory, sanitize;
3149 	int i, err = 0;
3150 
3151 	if (!obj->btf)
3152 		return 0;
3153 
3154 	if (!kernel_supports(obj, FEAT_BTF)) {
3155 		if (kernel_needs_btf(obj)) {
3156 			err = -EOPNOTSUPP;
3157 			goto report;
3158 		}
3159 		pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
3160 		return 0;
3161 	}
3162 
3163 	/* Even though some subprogs are global/weak, user might prefer more
3164 	 * permissive BPF verification process that BPF verifier performs for
3165 	 * static functions, taking into account more context from the caller
3166 	 * functions. In such case, they need to mark such subprogs with
3167 	 * __attribute__((visibility("hidden"))) and libbpf will adjust
3168 	 * corresponding FUNC BTF type to be marked as static and trigger more
3169 	 * involved BPF verification process.
3170 	 */
3171 	for (i = 0; i < obj->nr_programs; i++) {
3172 		struct bpf_program *prog = &obj->programs[i];
3173 		struct btf_type *t;
3174 		const char *name;
3175 		int j, n;
3176 
3177 		if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
3178 			continue;
3179 
3180 		n = btf__type_cnt(obj->btf);
3181 		for (j = 1; j < n; j++) {
3182 			t = btf_type_by_id(obj->btf, j);
3183 			if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
3184 				continue;
3185 
3186 			name = btf__str_by_offset(obj->btf, t->name_off);
3187 			if (strcmp(name, prog->name) != 0)
3188 				continue;
3189 
3190 			t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
3191 			break;
3192 		}
3193 	}
3194 
3195 	sanitize = btf_needs_sanitization(obj);
3196 	if (sanitize) {
3197 		const void *raw_data;
3198 		__u32 sz;
3199 
3200 		/* clone BTF to sanitize a copy and leave the original intact */
3201 		raw_data = btf__raw_data(obj->btf, &sz);
3202 		kern_btf = btf__new(raw_data, sz);
3203 		err = libbpf_get_error(kern_btf);
3204 		if (err)
3205 			return err;
3206 
3207 		/* enforce 8-byte pointers for BPF-targeted BTFs */
3208 		btf__set_pointer_size(obj->btf, 8);
3209 		err = bpf_object__sanitize_btf(obj, kern_btf);
3210 		if (err)
3211 			return err;
3212 	}
3213 
3214 	if (obj->gen_loader) {
3215 		__u32 raw_size = 0;
3216 		const void *raw_data = btf__raw_data(kern_btf, &raw_size);
3217 
3218 		if (!raw_data)
3219 			return -ENOMEM;
3220 		bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
3221 		/* Pretend to have valid FD to pass various fd >= 0 checks.
3222 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
3223 		 */
3224 		btf__set_fd(kern_btf, 0);
3225 	} else {
3226 		/* currently BPF_BTF_LOAD only supports log_level 1 */
3227 		err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
3228 					   obj->log_level ? 1 : 0);
3229 	}
3230 	if (sanitize) {
3231 		if (!err) {
3232 			/* move fd to libbpf's BTF */
3233 			btf__set_fd(obj->btf, btf__fd(kern_btf));
3234 			btf__set_fd(kern_btf, -1);
3235 		}
3236 		btf__free(kern_btf);
3237 	}
3238 report:
3239 	if (err) {
3240 		btf_mandatory = kernel_needs_btf(obj);
3241 		pr_warn("Error loading .BTF into kernel: %d. %s\n", err,
3242 			btf_mandatory ? "BTF is mandatory, can't proceed."
3243 				      : "BTF is optional, ignoring.");
3244 		if (!btf_mandatory)
3245 			err = 0;
3246 	}
3247 	return err;
3248 }
3249 
3250 static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
3251 {
3252 	const char *name;
3253 
3254 	name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
3255 	if (!name) {
3256 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3257 			off, obj->path, elf_errmsg(-1));
3258 		return NULL;
3259 	}
3260 
3261 	return name;
3262 }
3263 
3264 static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
3265 {
3266 	const char *name;
3267 
3268 	name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
3269 	if (!name) {
3270 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3271 			off, obj->path, elf_errmsg(-1));
3272 		return NULL;
3273 	}
3274 
3275 	return name;
3276 }
3277 
3278 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
3279 {
3280 	Elf_Scn *scn;
3281 
3282 	scn = elf_getscn(obj->efile.elf, idx);
3283 	if (!scn) {
3284 		pr_warn("elf: failed to get section(%zu) from %s: %s\n",
3285 			idx, obj->path, elf_errmsg(-1));
3286 		return NULL;
3287 	}
3288 	return scn;
3289 }
3290 
3291 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
3292 {
3293 	Elf_Scn *scn = NULL;
3294 	Elf *elf = obj->efile.elf;
3295 	const char *sec_name;
3296 
3297 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3298 		sec_name = elf_sec_name(obj, scn);
3299 		if (!sec_name)
3300 			return NULL;
3301 
3302 		if (strcmp(sec_name, name) != 0)
3303 			continue;
3304 
3305 		return scn;
3306 	}
3307 	return NULL;
3308 }
3309 
3310 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn)
3311 {
3312 	Elf64_Shdr *shdr;
3313 
3314 	if (!scn)
3315 		return NULL;
3316 
3317 	shdr = elf64_getshdr(scn);
3318 	if (!shdr) {
3319 		pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
3320 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3321 		return NULL;
3322 	}
3323 
3324 	return shdr;
3325 }
3326 
3327 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
3328 {
3329 	const char *name;
3330 	Elf64_Shdr *sh;
3331 
3332 	if (!scn)
3333 		return NULL;
3334 
3335 	sh = elf_sec_hdr(obj, scn);
3336 	if (!sh)
3337 		return NULL;
3338 
3339 	name = elf_sec_str(obj, sh->sh_name);
3340 	if (!name) {
3341 		pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
3342 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3343 		return NULL;
3344 	}
3345 
3346 	return name;
3347 }
3348 
3349 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
3350 {
3351 	Elf_Data *data;
3352 
3353 	if (!scn)
3354 		return NULL;
3355 
3356 	data = elf_getdata(scn, 0);
3357 	if (!data) {
3358 		pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
3359 			elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
3360 			obj->path, elf_errmsg(-1));
3361 		return NULL;
3362 	}
3363 
3364 	return data;
3365 }
3366 
3367 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx)
3368 {
3369 	if (idx >= obj->efile.symbols->d_size / sizeof(Elf64_Sym))
3370 		return NULL;
3371 
3372 	return (Elf64_Sym *)obj->efile.symbols->d_buf + idx;
3373 }
3374 
3375 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx)
3376 {
3377 	if (idx >= data->d_size / sizeof(Elf64_Rel))
3378 		return NULL;
3379 
3380 	return (Elf64_Rel *)data->d_buf + idx;
3381 }
3382 
3383 static bool is_sec_name_dwarf(const char *name)
3384 {
3385 	/* approximation, but the actual list is too long */
3386 	return str_has_pfx(name, ".debug_");
3387 }
3388 
3389 static bool ignore_elf_section(Elf64_Shdr *hdr, const char *name)
3390 {
3391 	/* no special handling of .strtab */
3392 	if (hdr->sh_type == SHT_STRTAB)
3393 		return true;
3394 
3395 	/* ignore .llvm_addrsig section as well */
3396 	if (hdr->sh_type == SHT_LLVM_ADDRSIG)
3397 		return true;
3398 
3399 	/* no subprograms will lead to an empty .text section, ignore it */
3400 	if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
3401 	    strcmp(name, ".text") == 0)
3402 		return true;
3403 
3404 	/* DWARF sections */
3405 	if (is_sec_name_dwarf(name))
3406 		return true;
3407 
3408 	if (str_has_pfx(name, ".rel")) {
3409 		name += sizeof(".rel") - 1;
3410 		/* DWARF section relocations */
3411 		if (is_sec_name_dwarf(name))
3412 			return true;
3413 
3414 		/* .BTF and .BTF.ext don't need relocations */
3415 		if (strcmp(name, BTF_ELF_SEC) == 0 ||
3416 		    strcmp(name, BTF_EXT_ELF_SEC) == 0)
3417 			return true;
3418 	}
3419 
3420 	return false;
3421 }
3422 
3423 static int cmp_progs(const void *_a, const void *_b)
3424 {
3425 	const struct bpf_program *a = _a;
3426 	const struct bpf_program *b = _b;
3427 
3428 	if (a->sec_idx != b->sec_idx)
3429 		return a->sec_idx < b->sec_idx ? -1 : 1;
3430 
3431 	/* sec_insn_off can't be the same within the section */
3432 	return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
3433 }
3434 
3435 static int bpf_object__elf_collect(struct bpf_object *obj)
3436 {
3437 	struct elf_sec_desc *sec_desc;
3438 	Elf *elf = obj->efile.elf;
3439 	Elf_Data *btf_ext_data = NULL;
3440 	Elf_Data *btf_data = NULL;
3441 	int idx = 0, err = 0;
3442 	const char *name;
3443 	Elf_Data *data;
3444 	Elf_Scn *scn;
3445 	Elf64_Shdr *sh;
3446 
3447 	/* ELF section indices are 0-based, but sec #0 is special "invalid"
3448 	 * section. Since section count retrieved by elf_getshdrnum() does
3449 	 * include sec #0, it is already the necessary size of an array to keep
3450 	 * all the sections.
3451 	 */
3452 	if (elf_getshdrnum(obj->efile.elf, &obj->efile.sec_cnt)) {
3453 		pr_warn("elf: failed to get the number of sections for %s: %s\n",
3454 			obj->path, elf_errmsg(-1));
3455 		return -LIBBPF_ERRNO__FORMAT;
3456 	}
3457 	obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs));
3458 	if (!obj->efile.secs)
3459 		return -ENOMEM;
3460 
3461 	/* a bunch of ELF parsing functionality depends on processing symbols,
3462 	 * so do the first pass and find the symbol table
3463 	 */
3464 	scn = NULL;
3465 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3466 		sh = elf_sec_hdr(obj, scn);
3467 		if (!sh)
3468 			return -LIBBPF_ERRNO__FORMAT;
3469 
3470 		if (sh->sh_type == SHT_SYMTAB) {
3471 			if (obj->efile.symbols) {
3472 				pr_warn("elf: multiple symbol tables in %s\n", obj->path);
3473 				return -LIBBPF_ERRNO__FORMAT;
3474 			}
3475 
3476 			data = elf_sec_data(obj, scn);
3477 			if (!data)
3478 				return -LIBBPF_ERRNO__FORMAT;
3479 
3480 			idx = elf_ndxscn(scn);
3481 
3482 			obj->efile.symbols = data;
3483 			obj->efile.symbols_shndx = idx;
3484 			obj->efile.strtabidx = sh->sh_link;
3485 		}
3486 	}
3487 
3488 	if (!obj->efile.symbols) {
3489 		pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
3490 			obj->path);
3491 		return -ENOENT;
3492 	}
3493 
3494 	scn = NULL;
3495 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3496 		idx = elf_ndxscn(scn);
3497 		sec_desc = &obj->efile.secs[idx];
3498 
3499 		sh = elf_sec_hdr(obj, scn);
3500 		if (!sh)
3501 			return -LIBBPF_ERRNO__FORMAT;
3502 
3503 		name = elf_sec_str(obj, sh->sh_name);
3504 		if (!name)
3505 			return -LIBBPF_ERRNO__FORMAT;
3506 
3507 		if (ignore_elf_section(sh, name))
3508 			continue;
3509 
3510 		data = elf_sec_data(obj, scn);
3511 		if (!data)
3512 			return -LIBBPF_ERRNO__FORMAT;
3513 
3514 		pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
3515 			 idx, name, (unsigned long)data->d_size,
3516 			 (int)sh->sh_link, (unsigned long)sh->sh_flags,
3517 			 (int)sh->sh_type);
3518 
3519 		if (strcmp(name, "license") == 0) {
3520 			err = bpf_object__init_license(obj, data->d_buf, data->d_size);
3521 			if (err)
3522 				return err;
3523 		} else if (strcmp(name, "version") == 0) {
3524 			err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
3525 			if (err)
3526 				return err;
3527 		} else if (strcmp(name, "maps") == 0) {
3528 			pr_warn("elf: legacy map definitions in 'maps' section are not supported by libbpf v1.0+\n");
3529 			return -ENOTSUP;
3530 		} else if (strcmp(name, MAPS_ELF_SEC) == 0) {
3531 			obj->efile.btf_maps_shndx = idx;
3532 		} else if (strcmp(name, BTF_ELF_SEC) == 0) {
3533 			if (sh->sh_type != SHT_PROGBITS)
3534 				return -LIBBPF_ERRNO__FORMAT;
3535 			btf_data = data;
3536 		} else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
3537 			if (sh->sh_type != SHT_PROGBITS)
3538 				return -LIBBPF_ERRNO__FORMAT;
3539 			btf_ext_data = data;
3540 		} else if (sh->sh_type == SHT_SYMTAB) {
3541 			/* already processed during the first pass above */
3542 		} else if (sh->sh_type == SHT_PROGBITS && data->d_size > 0) {
3543 			if (sh->sh_flags & SHF_EXECINSTR) {
3544 				if (strcmp(name, ".text") == 0)
3545 					obj->efile.text_shndx = idx;
3546 				err = bpf_object__add_programs(obj, data, name, idx);
3547 				if (err)
3548 					return err;
3549 			} else if (strcmp(name, DATA_SEC) == 0 ||
3550 				   str_has_pfx(name, DATA_SEC ".")) {
3551 				sec_desc->sec_type = SEC_DATA;
3552 				sec_desc->shdr = sh;
3553 				sec_desc->data = data;
3554 			} else if (strcmp(name, RODATA_SEC) == 0 ||
3555 				   str_has_pfx(name, RODATA_SEC ".")) {
3556 				sec_desc->sec_type = SEC_RODATA;
3557 				sec_desc->shdr = sh;
3558 				sec_desc->data = data;
3559 			} else if (strcmp(name, STRUCT_OPS_SEC) == 0) {
3560 				obj->efile.st_ops_data = data;
3561 				obj->efile.st_ops_shndx = idx;
3562 			} else if (strcmp(name, STRUCT_OPS_LINK_SEC) == 0) {
3563 				obj->efile.st_ops_link_data = data;
3564 				obj->efile.st_ops_link_shndx = idx;
3565 			} else {
3566 				pr_info("elf: skipping unrecognized data section(%d) %s\n",
3567 					idx, name);
3568 			}
3569 		} else if (sh->sh_type == SHT_REL) {
3570 			int targ_sec_idx = sh->sh_info; /* points to other section */
3571 
3572 			if (sh->sh_entsize != sizeof(Elf64_Rel) ||
3573 			    targ_sec_idx >= obj->efile.sec_cnt)
3574 				return -LIBBPF_ERRNO__FORMAT;
3575 
3576 			/* Only do relo for section with exec instructions */
3577 			if (!section_have_execinstr(obj, targ_sec_idx) &&
3578 			    strcmp(name, ".rel" STRUCT_OPS_SEC) &&
3579 			    strcmp(name, ".rel" STRUCT_OPS_LINK_SEC) &&
3580 			    strcmp(name, ".rel" MAPS_ELF_SEC)) {
3581 				pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
3582 					idx, name, targ_sec_idx,
3583 					elf_sec_name(obj, elf_sec_by_idx(obj, targ_sec_idx)) ?: "<?>");
3584 				continue;
3585 			}
3586 
3587 			sec_desc->sec_type = SEC_RELO;
3588 			sec_desc->shdr = sh;
3589 			sec_desc->data = data;
3590 		} else if (sh->sh_type == SHT_NOBITS && (strcmp(name, BSS_SEC) == 0 ||
3591 							 str_has_pfx(name, BSS_SEC "."))) {
3592 			sec_desc->sec_type = SEC_BSS;
3593 			sec_desc->shdr = sh;
3594 			sec_desc->data = data;
3595 		} else {
3596 			pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
3597 				(size_t)sh->sh_size);
3598 		}
3599 	}
3600 
3601 	if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
3602 		pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
3603 		return -LIBBPF_ERRNO__FORMAT;
3604 	}
3605 
3606 	/* sort BPF programs by section name and in-section instruction offset
3607 	 * for faster search
3608 	 */
3609 	if (obj->nr_programs)
3610 		qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
3611 
3612 	return bpf_object__init_btf(obj, btf_data, btf_ext_data);
3613 }
3614 
3615 static bool sym_is_extern(const Elf64_Sym *sym)
3616 {
3617 	int bind = ELF64_ST_BIND(sym->st_info);
3618 	/* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
3619 	return sym->st_shndx == SHN_UNDEF &&
3620 	       (bind == STB_GLOBAL || bind == STB_WEAK) &&
3621 	       ELF64_ST_TYPE(sym->st_info) == STT_NOTYPE;
3622 }
3623 
3624 static bool sym_is_subprog(const Elf64_Sym *sym, int text_shndx)
3625 {
3626 	int bind = ELF64_ST_BIND(sym->st_info);
3627 	int type = ELF64_ST_TYPE(sym->st_info);
3628 
3629 	/* in .text section */
3630 	if (sym->st_shndx != text_shndx)
3631 		return false;
3632 
3633 	/* local function */
3634 	if (bind == STB_LOCAL && type == STT_SECTION)
3635 		return true;
3636 
3637 	/* global function */
3638 	return bind == STB_GLOBAL && type == STT_FUNC;
3639 }
3640 
3641 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
3642 {
3643 	const struct btf_type *t;
3644 	const char *tname;
3645 	int i, n;
3646 
3647 	if (!btf)
3648 		return -ESRCH;
3649 
3650 	n = btf__type_cnt(btf);
3651 	for (i = 1; i < n; i++) {
3652 		t = btf__type_by_id(btf, i);
3653 
3654 		if (!btf_is_var(t) && !btf_is_func(t))
3655 			continue;
3656 
3657 		tname = btf__name_by_offset(btf, t->name_off);
3658 		if (strcmp(tname, ext_name))
3659 			continue;
3660 
3661 		if (btf_is_var(t) &&
3662 		    btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
3663 			return -EINVAL;
3664 
3665 		if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
3666 			return -EINVAL;
3667 
3668 		return i;
3669 	}
3670 
3671 	return -ENOENT;
3672 }
3673 
3674 static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
3675 	const struct btf_var_secinfo *vs;
3676 	const struct btf_type *t;
3677 	int i, j, n;
3678 
3679 	if (!btf)
3680 		return -ESRCH;
3681 
3682 	n = btf__type_cnt(btf);
3683 	for (i = 1; i < n; i++) {
3684 		t = btf__type_by_id(btf, i);
3685 
3686 		if (!btf_is_datasec(t))
3687 			continue;
3688 
3689 		vs = btf_var_secinfos(t);
3690 		for (j = 0; j < btf_vlen(t); j++, vs++) {
3691 			if (vs->type == ext_btf_id)
3692 				return i;
3693 		}
3694 	}
3695 
3696 	return -ENOENT;
3697 }
3698 
3699 static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
3700 				     bool *is_signed)
3701 {
3702 	const struct btf_type *t;
3703 	const char *name;
3704 
3705 	t = skip_mods_and_typedefs(btf, id, NULL);
3706 	name = btf__name_by_offset(btf, t->name_off);
3707 
3708 	if (is_signed)
3709 		*is_signed = false;
3710 	switch (btf_kind(t)) {
3711 	case BTF_KIND_INT: {
3712 		int enc = btf_int_encoding(t);
3713 
3714 		if (enc & BTF_INT_BOOL)
3715 			return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
3716 		if (is_signed)
3717 			*is_signed = enc & BTF_INT_SIGNED;
3718 		if (t->size == 1)
3719 			return KCFG_CHAR;
3720 		if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
3721 			return KCFG_UNKNOWN;
3722 		return KCFG_INT;
3723 	}
3724 	case BTF_KIND_ENUM:
3725 		if (t->size != 4)
3726 			return KCFG_UNKNOWN;
3727 		if (strcmp(name, "libbpf_tristate"))
3728 			return KCFG_UNKNOWN;
3729 		return KCFG_TRISTATE;
3730 	case BTF_KIND_ENUM64:
3731 		if (strcmp(name, "libbpf_tristate"))
3732 			return KCFG_UNKNOWN;
3733 		return KCFG_TRISTATE;
3734 	case BTF_KIND_ARRAY:
3735 		if (btf_array(t)->nelems == 0)
3736 			return KCFG_UNKNOWN;
3737 		if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
3738 			return KCFG_UNKNOWN;
3739 		return KCFG_CHAR_ARR;
3740 	default:
3741 		return KCFG_UNKNOWN;
3742 	}
3743 }
3744 
3745 static int cmp_externs(const void *_a, const void *_b)
3746 {
3747 	const struct extern_desc *a = _a;
3748 	const struct extern_desc *b = _b;
3749 
3750 	if (a->type != b->type)
3751 		return a->type < b->type ? -1 : 1;
3752 
3753 	if (a->type == EXT_KCFG) {
3754 		/* descending order by alignment requirements */
3755 		if (a->kcfg.align != b->kcfg.align)
3756 			return a->kcfg.align > b->kcfg.align ? -1 : 1;
3757 		/* ascending order by size, within same alignment class */
3758 		if (a->kcfg.sz != b->kcfg.sz)
3759 			return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
3760 	}
3761 
3762 	/* resolve ties by name */
3763 	return strcmp(a->name, b->name);
3764 }
3765 
3766 static int find_int_btf_id(const struct btf *btf)
3767 {
3768 	const struct btf_type *t;
3769 	int i, n;
3770 
3771 	n = btf__type_cnt(btf);
3772 	for (i = 1; i < n; i++) {
3773 		t = btf__type_by_id(btf, i);
3774 
3775 		if (btf_is_int(t) && btf_int_bits(t) == 32)
3776 			return i;
3777 	}
3778 
3779 	return 0;
3780 }
3781 
3782 static int add_dummy_ksym_var(struct btf *btf)
3783 {
3784 	int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
3785 	const struct btf_var_secinfo *vs;
3786 	const struct btf_type *sec;
3787 
3788 	if (!btf)
3789 		return 0;
3790 
3791 	sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
3792 					    BTF_KIND_DATASEC);
3793 	if (sec_btf_id < 0)
3794 		return 0;
3795 
3796 	sec = btf__type_by_id(btf, sec_btf_id);
3797 	vs = btf_var_secinfos(sec);
3798 	for (i = 0; i < btf_vlen(sec); i++, vs++) {
3799 		const struct btf_type *vt;
3800 
3801 		vt = btf__type_by_id(btf, vs->type);
3802 		if (btf_is_func(vt))
3803 			break;
3804 	}
3805 
3806 	/* No func in ksyms sec.  No need to add dummy var. */
3807 	if (i == btf_vlen(sec))
3808 		return 0;
3809 
3810 	int_btf_id = find_int_btf_id(btf);
3811 	dummy_var_btf_id = btf__add_var(btf,
3812 					"dummy_ksym",
3813 					BTF_VAR_GLOBAL_ALLOCATED,
3814 					int_btf_id);
3815 	if (dummy_var_btf_id < 0)
3816 		pr_warn("cannot create a dummy_ksym var\n");
3817 
3818 	return dummy_var_btf_id;
3819 }
3820 
3821 static int bpf_object__collect_externs(struct bpf_object *obj)
3822 {
3823 	struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
3824 	const struct btf_type *t;
3825 	struct extern_desc *ext;
3826 	int i, n, off, dummy_var_btf_id;
3827 	const char *ext_name, *sec_name;
3828 	size_t ext_essent_len;
3829 	Elf_Scn *scn;
3830 	Elf64_Shdr *sh;
3831 
3832 	if (!obj->efile.symbols)
3833 		return 0;
3834 
3835 	scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
3836 	sh = elf_sec_hdr(obj, scn);
3837 	if (!sh || sh->sh_entsize != sizeof(Elf64_Sym))
3838 		return -LIBBPF_ERRNO__FORMAT;
3839 
3840 	dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
3841 	if (dummy_var_btf_id < 0)
3842 		return dummy_var_btf_id;
3843 
3844 	n = sh->sh_size / sh->sh_entsize;
3845 	pr_debug("looking for externs among %d symbols...\n", n);
3846 
3847 	for (i = 0; i < n; i++) {
3848 		Elf64_Sym *sym = elf_sym_by_idx(obj, i);
3849 
3850 		if (!sym)
3851 			return -LIBBPF_ERRNO__FORMAT;
3852 		if (!sym_is_extern(sym))
3853 			continue;
3854 		ext_name = elf_sym_str(obj, sym->st_name);
3855 		if (!ext_name || !ext_name[0])
3856 			continue;
3857 
3858 		ext = obj->externs;
3859 		ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
3860 		if (!ext)
3861 			return -ENOMEM;
3862 		obj->externs = ext;
3863 		ext = &ext[obj->nr_extern];
3864 		memset(ext, 0, sizeof(*ext));
3865 		obj->nr_extern++;
3866 
3867 		ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
3868 		if (ext->btf_id <= 0) {
3869 			pr_warn("failed to find BTF for extern '%s': %d\n",
3870 				ext_name, ext->btf_id);
3871 			return ext->btf_id;
3872 		}
3873 		t = btf__type_by_id(obj->btf, ext->btf_id);
3874 		ext->name = btf__name_by_offset(obj->btf, t->name_off);
3875 		ext->sym_idx = i;
3876 		ext->is_weak = ELF64_ST_BIND(sym->st_info) == STB_WEAK;
3877 
3878 		ext_essent_len = bpf_core_essential_name_len(ext->name);
3879 		ext->essent_name = NULL;
3880 		if (ext_essent_len != strlen(ext->name)) {
3881 			ext->essent_name = strndup(ext->name, ext_essent_len);
3882 			if (!ext->essent_name)
3883 				return -ENOMEM;
3884 		}
3885 
3886 		ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
3887 		if (ext->sec_btf_id <= 0) {
3888 			pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
3889 				ext_name, ext->btf_id, ext->sec_btf_id);
3890 			return ext->sec_btf_id;
3891 		}
3892 		sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
3893 		sec_name = btf__name_by_offset(obj->btf, sec->name_off);
3894 
3895 		if (strcmp(sec_name, KCONFIG_SEC) == 0) {
3896 			if (btf_is_func(t)) {
3897 				pr_warn("extern function %s is unsupported under %s section\n",
3898 					ext->name, KCONFIG_SEC);
3899 				return -ENOTSUP;
3900 			}
3901 			kcfg_sec = sec;
3902 			ext->type = EXT_KCFG;
3903 			ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
3904 			if (ext->kcfg.sz <= 0) {
3905 				pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
3906 					ext_name, ext->kcfg.sz);
3907 				return ext->kcfg.sz;
3908 			}
3909 			ext->kcfg.align = btf__align_of(obj->btf, t->type);
3910 			if (ext->kcfg.align <= 0) {
3911 				pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
3912 					ext_name, ext->kcfg.align);
3913 				return -EINVAL;
3914 			}
3915 			ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
3916 							&ext->kcfg.is_signed);
3917 			if (ext->kcfg.type == KCFG_UNKNOWN) {
3918 				pr_warn("extern (kcfg) '%s': type is unsupported\n", ext_name);
3919 				return -ENOTSUP;
3920 			}
3921 		} else if (strcmp(sec_name, KSYMS_SEC) == 0) {
3922 			ksym_sec = sec;
3923 			ext->type = EXT_KSYM;
3924 			skip_mods_and_typedefs(obj->btf, t->type,
3925 					       &ext->ksym.type_id);
3926 		} else {
3927 			pr_warn("unrecognized extern section '%s'\n", sec_name);
3928 			return -ENOTSUP;
3929 		}
3930 	}
3931 	pr_debug("collected %d externs total\n", obj->nr_extern);
3932 
3933 	if (!obj->nr_extern)
3934 		return 0;
3935 
3936 	/* sort externs by type, for kcfg ones also by (align, size, name) */
3937 	qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
3938 
3939 	/* for .ksyms section, we need to turn all externs into allocated
3940 	 * variables in BTF to pass kernel verification; we do this by
3941 	 * pretending that each extern is a 8-byte variable
3942 	 */
3943 	if (ksym_sec) {
3944 		/* find existing 4-byte integer type in BTF to use for fake
3945 		 * extern variables in DATASEC
3946 		 */
3947 		int int_btf_id = find_int_btf_id(obj->btf);
3948 		/* For extern function, a dummy_var added earlier
3949 		 * will be used to replace the vs->type and
3950 		 * its name string will be used to refill
3951 		 * the missing param's name.
3952 		 */
3953 		const struct btf_type *dummy_var;
3954 
3955 		dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
3956 		for (i = 0; i < obj->nr_extern; i++) {
3957 			ext = &obj->externs[i];
3958 			if (ext->type != EXT_KSYM)
3959 				continue;
3960 			pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
3961 				 i, ext->sym_idx, ext->name);
3962 		}
3963 
3964 		sec = ksym_sec;
3965 		n = btf_vlen(sec);
3966 		for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
3967 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3968 			struct btf_type *vt;
3969 
3970 			vt = (void *)btf__type_by_id(obj->btf, vs->type);
3971 			ext_name = btf__name_by_offset(obj->btf, vt->name_off);
3972 			ext = find_extern_by_name(obj, ext_name);
3973 			if (!ext) {
3974 				pr_warn("failed to find extern definition for BTF %s '%s'\n",
3975 					btf_kind_str(vt), ext_name);
3976 				return -ESRCH;
3977 			}
3978 			if (btf_is_func(vt)) {
3979 				const struct btf_type *func_proto;
3980 				struct btf_param *param;
3981 				int j;
3982 
3983 				func_proto = btf__type_by_id(obj->btf,
3984 							     vt->type);
3985 				param = btf_params(func_proto);
3986 				/* Reuse the dummy_var string if the
3987 				 * func proto does not have param name.
3988 				 */
3989 				for (j = 0; j < btf_vlen(func_proto); j++)
3990 					if (param[j].type && !param[j].name_off)
3991 						param[j].name_off =
3992 							dummy_var->name_off;
3993 				vs->type = dummy_var_btf_id;
3994 				vt->info &= ~0xffff;
3995 				vt->info |= BTF_FUNC_GLOBAL;
3996 			} else {
3997 				btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3998 				vt->type = int_btf_id;
3999 			}
4000 			vs->offset = off;
4001 			vs->size = sizeof(int);
4002 		}
4003 		sec->size = off;
4004 	}
4005 
4006 	if (kcfg_sec) {
4007 		sec = kcfg_sec;
4008 		/* for kcfg externs calculate their offsets within a .kconfig map */
4009 		off = 0;
4010 		for (i = 0; i < obj->nr_extern; i++) {
4011 			ext = &obj->externs[i];
4012 			if (ext->type != EXT_KCFG)
4013 				continue;
4014 
4015 			ext->kcfg.data_off = roundup(off, ext->kcfg.align);
4016 			off = ext->kcfg.data_off + ext->kcfg.sz;
4017 			pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
4018 				 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
4019 		}
4020 		sec->size = off;
4021 		n = btf_vlen(sec);
4022 		for (i = 0; i < n; i++) {
4023 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4024 
4025 			t = btf__type_by_id(obj->btf, vs->type);
4026 			ext_name = btf__name_by_offset(obj->btf, t->name_off);
4027 			ext = find_extern_by_name(obj, ext_name);
4028 			if (!ext) {
4029 				pr_warn("failed to find extern definition for BTF var '%s'\n",
4030 					ext_name);
4031 				return -ESRCH;
4032 			}
4033 			btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4034 			vs->offset = ext->kcfg.data_off;
4035 		}
4036 	}
4037 	return 0;
4038 }
4039 
4040 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog)
4041 {
4042 	return prog->sec_idx == obj->efile.text_shndx && obj->nr_programs > 1;
4043 }
4044 
4045 struct bpf_program *
4046 bpf_object__find_program_by_name(const struct bpf_object *obj,
4047 				 const char *name)
4048 {
4049 	struct bpf_program *prog;
4050 
4051 	bpf_object__for_each_program(prog, obj) {
4052 		if (prog_is_subprog(obj, prog))
4053 			continue;
4054 		if (!strcmp(prog->name, name))
4055 			return prog;
4056 	}
4057 	return errno = ENOENT, NULL;
4058 }
4059 
4060 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
4061 				      int shndx)
4062 {
4063 	switch (obj->efile.secs[shndx].sec_type) {
4064 	case SEC_BSS:
4065 	case SEC_DATA:
4066 	case SEC_RODATA:
4067 		return true;
4068 	default:
4069 		return false;
4070 	}
4071 }
4072 
4073 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
4074 				      int shndx)
4075 {
4076 	return shndx == obj->efile.btf_maps_shndx;
4077 }
4078 
4079 static enum libbpf_map_type
4080 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
4081 {
4082 	if (shndx == obj->efile.symbols_shndx)
4083 		return LIBBPF_MAP_KCONFIG;
4084 
4085 	switch (obj->efile.secs[shndx].sec_type) {
4086 	case SEC_BSS:
4087 		return LIBBPF_MAP_BSS;
4088 	case SEC_DATA:
4089 		return LIBBPF_MAP_DATA;
4090 	case SEC_RODATA:
4091 		return LIBBPF_MAP_RODATA;
4092 	default:
4093 		return LIBBPF_MAP_UNSPEC;
4094 	}
4095 }
4096 
4097 static int bpf_program__record_reloc(struct bpf_program *prog,
4098 				     struct reloc_desc *reloc_desc,
4099 				     __u32 insn_idx, const char *sym_name,
4100 				     const Elf64_Sym *sym, const Elf64_Rel *rel)
4101 {
4102 	struct bpf_insn *insn = &prog->insns[insn_idx];
4103 	size_t map_idx, nr_maps = prog->obj->nr_maps;
4104 	struct bpf_object *obj = prog->obj;
4105 	__u32 shdr_idx = sym->st_shndx;
4106 	enum libbpf_map_type type;
4107 	const char *sym_sec_name;
4108 	struct bpf_map *map;
4109 
4110 	if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
4111 		pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n",
4112 			prog->name, sym_name, insn_idx, insn->code);
4113 		return -LIBBPF_ERRNO__RELOC;
4114 	}
4115 
4116 	if (sym_is_extern(sym)) {
4117 		int sym_idx = ELF64_R_SYM(rel->r_info);
4118 		int i, n = obj->nr_extern;
4119 		struct extern_desc *ext;
4120 
4121 		for (i = 0; i < n; i++) {
4122 			ext = &obj->externs[i];
4123 			if (ext->sym_idx == sym_idx)
4124 				break;
4125 		}
4126 		if (i >= n) {
4127 			pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
4128 				prog->name, sym_name, sym_idx);
4129 			return -LIBBPF_ERRNO__RELOC;
4130 		}
4131 		pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
4132 			 prog->name, i, ext->name, ext->sym_idx, insn_idx);
4133 		if (insn->code == (BPF_JMP | BPF_CALL))
4134 			reloc_desc->type = RELO_EXTERN_CALL;
4135 		else
4136 			reloc_desc->type = RELO_EXTERN_LD64;
4137 		reloc_desc->insn_idx = insn_idx;
4138 		reloc_desc->ext_idx = i;
4139 		return 0;
4140 	}
4141 
4142 	/* sub-program call relocation */
4143 	if (is_call_insn(insn)) {
4144 		if (insn->src_reg != BPF_PSEUDO_CALL) {
4145 			pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
4146 			return -LIBBPF_ERRNO__RELOC;
4147 		}
4148 		/* text_shndx can be 0, if no default "main" program exists */
4149 		if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
4150 			sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4151 			pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
4152 				prog->name, sym_name, sym_sec_name);
4153 			return -LIBBPF_ERRNO__RELOC;
4154 		}
4155 		if (sym->st_value % BPF_INSN_SZ) {
4156 			pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
4157 				prog->name, sym_name, (size_t)sym->st_value);
4158 			return -LIBBPF_ERRNO__RELOC;
4159 		}
4160 		reloc_desc->type = RELO_CALL;
4161 		reloc_desc->insn_idx = insn_idx;
4162 		reloc_desc->sym_off = sym->st_value;
4163 		return 0;
4164 	}
4165 
4166 	if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
4167 		pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
4168 			prog->name, sym_name, shdr_idx);
4169 		return -LIBBPF_ERRNO__RELOC;
4170 	}
4171 
4172 	/* loading subprog addresses */
4173 	if (sym_is_subprog(sym, obj->efile.text_shndx)) {
4174 		/* global_func: sym->st_value = offset in the section, insn->imm = 0.
4175 		 * local_func: sym->st_value = 0, insn->imm = offset in the section.
4176 		 */
4177 		if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
4178 			pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
4179 				prog->name, sym_name, (size_t)sym->st_value, insn->imm);
4180 			return -LIBBPF_ERRNO__RELOC;
4181 		}
4182 
4183 		reloc_desc->type = RELO_SUBPROG_ADDR;
4184 		reloc_desc->insn_idx = insn_idx;
4185 		reloc_desc->sym_off = sym->st_value;
4186 		return 0;
4187 	}
4188 
4189 	type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
4190 	sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4191 
4192 	/* generic map reference relocation */
4193 	if (type == LIBBPF_MAP_UNSPEC) {
4194 		if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
4195 			pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
4196 				prog->name, sym_name, sym_sec_name);
4197 			return -LIBBPF_ERRNO__RELOC;
4198 		}
4199 		for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4200 			map = &obj->maps[map_idx];
4201 			if (map->libbpf_type != type ||
4202 			    map->sec_idx != sym->st_shndx ||
4203 			    map->sec_offset != sym->st_value)
4204 				continue;
4205 			pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n",
4206 				 prog->name, map_idx, map->name, map->sec_idx,
4207 				 map->sec_offset, insn_idx);
4208 			break;
4209 		}
4210 		if (map_idx >= nr_maps) {
4211 			pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
4212 				prog->name, sym_sec_name, (size_t)sym->st_value);
4213 			return -LIBBPF_ERRNO__RELOC;
4214 		}
4215 		reloc_desc->type = RELO_LD64;
4216 		reloc_desc->insn_idx = insn_idx;
4217 		reloc_desc->map_idx = map_idx;
4218 		reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
4219 		return 0;
4220 	}
4221 
4222 	/* global data map relocation */
4223 	if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
4224 		pr_warn("prog '%s': bad data relo against section '%s'\n",
4225 			prog->name, sym_sec_name);
4226 		return -LIBBPF_ERRNO__RELOC;
4227 	}
4228 	for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4229 		map = &obj->maps[map_idx];
4230 		if (map->libbpf_type != type || map->sec_idx != sym->st_shndx)
4231 			continue;
4232 		pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n",
4233 			 prog->name, map_idx, map->name, map->sec_idx,
4234 			 map->sec_offset, insn_idx);
4235 		break;
4236 	}
4237 	if (map_idx >= nr_maps) {
4238 		pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
4239 			prog->name, sym_sec_name);
4240 		return -LIBBPF_ERRNO__RELOC;
4241 	}
4242 
4243 	reloc_desc->type = RELO_DATA;
4244 	reloc_desc->insn_idx = insn_idx;
4245 	reloc_desc->map_idx = map_idx;
4246 	reloc_desc->sym_off = sym->st_value;
4247 	return 0;
4248 }
4249 
4250 static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
4251 {
4252 	return insn_idx >= prog->sec_insn_off &&
4253 	       insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
4254 }
4255 
4256 static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
4257 						 size_t sec_idx, size_t insn_idx)
4258 {
4259 	int l = 0, r = obj->nr_programs - 1, m;
4260 	struct bpf_program *prog;
4261 
4262 	if (!obj->nr_programs)
4263 		return NULL;
4264 
4265 	while (l < r) {
4266 		m = l + (r - l + 1) / 2;
4267 		prog = &obj->programs[m];
4268 
4269 		if (prog->sec_idx < sec_idx ||
4270 		    (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
4271 			l = m;
4272 		else
4273 			r = m - 1;
4274 	}
4275 	/* matching program could be at index l, but it still might be the
4276 	 * wrong one, so we need to double check conditions for the last time
4277 	 */
4278 	prog = &obj->programs[l];
4279 	if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
4280 		return prog;
4281 	return NULL;
4282 }
4283 
4284 static int
4285 bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
4286 {
4287 	const char *relo_sec_name, *sec_name;
4288 	size_t sec_idx = shdr->sh_info, sym_idx;
4289 	struct bpf_program *prog;
4290 	struct reloc_desc *relos;
4291 	int err, i, nrels;
4292 	const char *sym_name;
4293 	__u32 insn_idx;
4294 	Elf_Scn *scn;
4295 	Elf_Data *scn_data;
4296 	Elf64_Sym *sym;
4297 	Elf64_Rel *rel;
4298 
4299 	if (sec_idx >= obj->efile.sec_cnt)
4300 		return -EINVAL;
4301 
4302 	scn = elf_sec_by_idx(obj, sec_idx);
4303 	scn_data = elf_sec_data(obj, scn);
4304 	if (!scn_data)
4305 		return -LIBBPF_ERRNO__FORMAT;
4306 
4307 	relo_sec_name = elf_sec_str(obj, shdr->sh_name);
4308 	sec_name = elf_sec_name(obj, scn);
4309 	if (!relo_sec_name || !sec_name)
4310 		return -EINVAL;
4311 
4312 	pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
4313 		 relo_sec_name, sec_idx, sec_name);
4314 	nrels = shdr->sh_size / shdr->sh_entsize;
4315 
4316 	for (i = 0; i < nrels; i++) {
4317 		rel = elf_rel_by_idx(data, i);
4318 		if (!rel) {
4319 			pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
4320 			return -LIBBPF_ERRNO__FORMAT;
4321 		}
4322 
4323 		sym_idx = ELF64_R_SYM(rel->r_info);
4324 		sym = elf_sym_by_idx(obj, sym_idx);
4325 		if (!sym) {
4326 			pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
4327 				relo_sec_name, sym_idx, i);
4328 			return -LIBBPF_ERRNO__FORMAT;
4329 		}
4330 
4331 		if (sym->st_shndx >= obj->efile.sec_cnt) {
4332 			pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
4333 				relo_sec_name, sym_idx, (size_t)sym->st_shndx, i);
4334 			return -LIBBPF_ERRNO__FORMAT;
4335 		}
4336 
4337 		if (rel->r_offset % BPF_INSN_SZ || rel->r_offset >= scn_data->d_size) {
4338 			pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
4339 				relo_sec_name, (size_t)rel->r_offset, i);
4340 			return -LIBBPF_ERRNO__FORMAT;
4341 		}
4342 
4343 		insn_idx = rel->r_offset / BPF_INSN_SZ;
4344 		/* relocations against static functions are recorded as
4345 		 * relocations against the section that contains a function;
4346 		 * in such case, symbol will be STT_SECTION and sym.st_name
4347 		 * will point to empty string (0), so fetch section name
4348 		 * instead
4349 		 */
4350 		if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
4351 			sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx));
4352 		else
4353 			sym_name = elf_sym_str(obj, sym->st_name);
4354 		sym_name = sym_name ?: "<?";
4355 
4356 		pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
4357 			 relo_sec_name, i, insn_idx, sym_name);
4358 
4359 		prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
4360 		if (!prog) {
4361 			pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
4362 				relo_sec_name, i, sec_name, insn_idx);
4363 			continue;
4364 		}
4365 
4366 		relos = libbpf_reallocarray(prog->reloc_desc,
4367 					    prog->nr_reloc + 1, sizeof(*relos));
4368 		if (!relos)
4369 			return -ENOMEM;
4370 		prog->reloc_desc = relos;
4371 
4372 		/* adjust insn_idx to local BPF program frame of reference */
4373 		insn_idx -= prog->sec_insn_off;
4374 		err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
4375 						insn_idx, sym_name, sym, rel);
4376 		if (err)
4377 			return err;
4378 
4379 		prog->nr_reloc++;
4380 	}
4381 	return 0;
4382 }
4383 
4384 static int map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map)
4385 {
4386 	int id;
4387 
4388 	if (!obj->btf)
4389 		return -ENOENT;
4390 
4391 	/* if it's BTF-defined map, we don't need to search for type IDs.
4392 	 * For struct_ops map, it does not need btf_key_type_id and
4393 	 * btf_value_type_id.
4394 	 */
4395 	if (map->sec_idx == obj->efile.btf_maps_shndx || bpf_map__is_struct_ops(map))
4396 		return 0;
4397 
4398 	/*
4399 	 * LLVM annotates global data differently in BTF, that is,
4400 	 * only as '.data', '.bss' or '.rodata'.
4401 	 */
4402 	if (!bpf_map__is_internal(map))
4403 		return -ENOENT;
4404 
4405 	id = btf__find_by_name(obj->btf, map->real_name);
4406 	if (id < 0)
4407 		return id;
4408 
4409 	map->btf_key_type_id = 0;
4410 	map->btf_value_type_id = id;
4411 	return 0;
4412 }
4413 
4414 static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
4415 {
4416 	char file[PATH_MAX], buff[4096];
4417 	FILE *fp;
4418 	__u32 val;
4419 	int err;
4420 
4421 	snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
4422 	memset(info, 0, sizeof(*info));
4423 
4424 	fp = fopen(file, "re");
4425 	if (!fp) {
4426 		err = -errno;
4427 		pr_warn("failed to open %s: %d. No procfs support?\n", file,
4428 			err);
4429 		return err;
4430 	}
4431 
4432 	while (fgets(buff, sizeof(buff), fp)) {
4433 		if (sscanf(buff, "map_type:\t%u", &val) == 1)
4434 			info->type = val;
4435 		else if (sscanf(buff, "key_size:\t%u", &val) == 1)
4436 			info->key_size = val;
4437 		else if (sscanf(buff, "value_size:\t%u", &val) == 1)
4438 			info->value_size = val;
4439 		else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
4440 			info->max_entries = val;
4441 		else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
4442 			info->map_flags = val;
4443 	}
4444 
4445 	fclose(fp);
4446 
4447 	return 0;
4448 }
4449 
4450 bool bpf_map__autocreate(const struct bpf_map *map)
4451 {
4452 	return map->autocreate;
4453 }
4454 
4455 int bpf_map__set_autocreate(struct bpf_map *map, bool autocreate)
4456 {
4457 	if (map->obj->loaded)
4458 		return libbpf_err(-EBUSY);
4459 
4460 	map->autocreate = autocreate;
4461 	return 0;
4462 }
4463 
4464 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
4465 {
4466 	struct bpf_map_info info;
4467 	__u32 len = sizeof(info), name_len;
4468 	int new_fd, err;
4469 	char *new_name;
4470 
4471 	memset(&info, 0, len);
4472 	err = bpf_map_get_info_by_fd(fd, &info, &len);
4473 	if (err && errno == EINVAL)
4474 		err = bpf_get_map_info_from_fdinfo(fd, &info);
4475 	if (err)
4476 		return libbpf_err(err);
4477 
4478 	name_len = strlen(info.name);
4479 	if (name_len == BPF_OBJ_NAME_LEN - 1 && strncmp(map->name, info.name, name_len) == 0)
4480 		new_name = strdup(map->name);
4481 	else
4482 		new_name = strdup(info.name);
4483 
4484 	if (!new_name)
4485 		return libbpf_err(-errno);
4486 
4487 	/*
4488 	 * Like dup(), but make sure new FD is >= 3 and has O_CLOEXEC set.
4489 	 * This is similar to what we do in ensure_good_fd(), but without
4490 	 * closing original FD.
4491 	 */
4492 	new_fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
4493 	if (new_fd < 0) {
4494 		err = -errno;
4495 		goto err_free_new_name;
4496 	}
4497 
4498 	err = reuse_fd(map->fd, new_fd);
4499 	if (err)
4500 		goto err_free_new_name;
4501 
4502 	free(map->name);
4503 
4504 	map->name = new_name;
4505 	map->def.type = info.type;
4506 	map->def.key_size = info.key_size;
4507 	map->def.value_size = info.value_size;
4508 	map->def.max_entries = info.max_entries;
4509 	map->def.map_flags = info.map_flags;
4510 	map->btf_key_type_id = info.btf_key_type_id;
4511 	map->btf_value_type_id = info.btf_value_type_id;
4512 	map->reused = true;
4513 	map->map_extra = info.map_extra;
4514 
4515 	return 0;
4516 
4517 err_free_new_name:
4518 	free(new_name);
4519 	return libbpf_err(err);
4520 }
4521 
4522 __u32 bpf_map__max_entries(const struct bpf_map *map)
4523 {
4524 	return map->def.max_entries;
4525 }
4526 
4527 struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
4528 {
4529 	if (!bpf_map_type__is_map_in_map(map->def.type))
4530 		return errno = EINVAL, NULL;
4531 
4532 	return map->inner_map;
4533 }
4534 
4535 int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
4536 {
4537 	if (map->obj->loaded)
4538 		return libbpf_err(-EBUSY);
4539 
4540 	map->def.max_entries = max_entries;
4541 
4542 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
4543 	if (map_is_ringbuf(map))
4544 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
4545 
4546 	return 0;
4547 }
4548 
4549 static int
4550 bpf_object__probe_loading(struct bpf_object *obj)
4551 {
4552 	char *cp, errmsg[STRERR_BUFSIZE];
4553 	struct bpf_insn insns[] = {
4554 		BPF_MOV64_IMM(BPF_REG_0, 0),
4555 		BPF_EXIT_INSN(),
4556 	};
4557 	int ret, insn_cnt = ARRAY_SIZE(insns);
4558 
4559 	if (obj->gen_loader)
4560 		return 0;
4561 
4562 	ret = bump_rlimit_memlock();
4563 	if (ret)
4564 		pr_warn("Failed to bump RLIMIT_MEMLOCK (err = %d), you might need to do it explicitly!\n", ret);
4565 
4566 	/* make sure basic loading works */
4567 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4568 	if (ret < 0)
4569 		ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
4570 	if (ret < 0) {
4571 		ret = errno;
4572 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4573 		pr_warn("Error in %s():%s(%d). Couldn't load trivial BPF "
4574 			"program. Make sure your kernel supports BPF "
4575 			"(CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is "
4576 			"set to big enough value.\n", __func__, cp, ret);
4577 		return -ret;
4578 	}
4579 	close(ret);
4580 
4581 	return 0;
4582 }
4583 
4584 static int probe_fd(int fd)
4585 {
4586 	if (fd >= 0)
4587 		close(fd);
4588 	return fd >= 0;
4589 }
4590 
4591 static int probe_kern_prog_name(void)
4592 {
4593 	const size_t attr_sz = offsetofend(union bpf_attr, prog_name);
4594 	struct bpf_insn insns[] = {
4595 		BPF_MOV64_IMM(BPF_REG_0, 0),
4596 		BPF_EXIT_INSN(),
4597 	};
4598 	union bpf_attr attr;
4599 	int ret;
4600 
4601 	memset(&attr, 0, attr_sz);
4602 	attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
4603 	attr.license = ptr_to_u64("GPL");
4604 	attr.insns = ptr_to_u64(insns);
4605 	attr.insn_cnt = (__u32)ARRAY_SIZE(insns);
4606 	libbpf_strlcpy(attr.prog_name, "libbpf_nametest", sizeof(attr.prog_name));
4607 
4608 	/* make sure loading with name works */
4609 	ret = sys_bpf_prog_load(&attr, attr_sz, PROG_LOAD_ATTEMPTS);
4610 	return probe_fd(ret);
4611 }
4612 
4613 static int probe_kern_global_data(void)
4614 {
4615 	char *cp, errmsg[STRERR_BUFSIZE];
4616 	struct bpf_insn insns[] = {
4617 		BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
4618 		BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
4619 		BPF_MOV64_IMM(BPF_REG_0, 0),
4620 		BPF_EXIT_INSN(),
4621 	};
4622 	int ret, map, insn_cnt = ARRAY_SIZE(insns);
4623 
4624 	map = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_global", sizeof(int), 32, 1, NULL);
4625 	if (map < 0) {
4626 		ret = -errno;
4627 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4628 		pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4629 			__func__, cp, -ret);
4630 		return ret;
4631 	}
4632 
4633 	insns[0].imm = map;
4634 
4635 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4636 	close(map);
4637 	return probe_fd(ret);
4638 }
4639 
4640 static int probe_kern_btf(void)
4641 {
4642 	static const char strs[] = "\0int";
4643 	__u32 types[] = {
4644 		/* int */
4645 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4646 	};
4647 
4648 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4649 					     strs, sizeof(strs)));
4650 }
4651 
4652 static int probe_kern_btf_func(void)
4653 {
4654 	static const char strs[] = "\0int\0x\0a";
4655 	/* void x(int a) {} */
4656 	__u32 types[] = {
4657 		/* int */
4658 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4659 		/* FUNC_PROTO */                                /* [2] */
4660 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4661 		BTF_PARAM_ENC(7, 1),
4662 		/* FUNC x */                                    /* [3] */
4663 		BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
4664 	};
4665 
4666 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4667 					     strs, sizeof(strs)));
4668 }
4669 
4670 static int probe_kern_btf_func_global(void)
4671 {
4672 	static const char strs[] = "\0int\0x\0a";
4673 	/* static void x(int a) {} */
4674 	__u32 types[] = {
4675 		/* int */
4676 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4677 		/* FUNC_PROTO */                                /* [2] */
4678 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4679 		BTF_PARAM_ENC(7, 1),
4680 		/* FUNC x BTF_FUNC_GLOBAL */                    /* [3] */
4681 		BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, BTF_FUNC_GLOBAL), 2),
4682 	};
4683 
4684 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4685 					     strs, sizeof(strs)));
4686 }
4687 
4688 static int probe_kern_btf_datasec(void)
4689 {
4690 	static const char strs[] = "\0x\0.data";
4691 	/* static int a; */
4692 	__u32 types[] = {
4693 		/* int */
4694 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4695 		/* VAR x */                                     /* [2] */
4696 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4697 		BTF_VAR_STATIC,
4698 		/* DATASEC val */                               /* [3] */
4699 		BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
4700 		BTF_VAR_SECINFO_ENC(2, 0, 4),
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_float(void)
4708 {
4709 	static const char strs[] = "\0float";
4710 	__u32 types[] = {
4711 		/* float */
4712 		BTF_TYPE_FLOAT_ENC(1, 4),
4713 	};
4714 
4715 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4716 					     strs, sizeof(strs)));
4717 }
4718 
4719 static int probe_kern_btf_decl_tag(void)
4720 {
4721 	static const char strs[] = "\0tag";
4722 	__u32 types[] = {
4723 		/* int */
4724 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4725 		/* VAR x */                                     /* [2] */
4726 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4727 		BTF_VAR_STATIC,
4728 		/* attr */
4729 		BTF_TYPE_DECL_TAG_ENC(1, 2, -1),
4730 	};
4731 
4732 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4733 					     strs, sizeof(strs)));
4734 }
4735 
4736 static int probe_kern_btf_type_tag(void)
4737 {
4738 	static const char strs[] = "\0tag";
4739 	__u32 types[] = {
4740 		/* int */
4741 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),		/* [1] */
4742 		/* attr */
4743 		BTF_TYPE_TYPE_TAG_ENC(1, 1),				/* [2] */
4744 		/* ptr */
4745 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_PTR, 0, 0), 2),	/* [3] */
4746 	};
4747 
4748 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4749 					     strs, sizeof(strs)));
4750 }
4751 
4752 static int probe_kern_array_mmap(void)
4753 {
4754 	LIBBPF_OPTS(bpf_map_create_opts, opts, .map_flags = BPF_F_MMAPABLE);
4755 	int fd;
4756 
4757 	fd = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_mmap", sizeof(int), sizeof(int), 1, &opts);
4758 	return probe_fd(fd);
4759 }
4760 
4761 static int probe_kern_exp_attach_type(void)
4762 {
4763 	LIBBPF_OPTS(bpf_prog_load_opts, opts, .expected_attach_type = BPF_CGROUP_INET_SOCK_CREATE);
4764 	struct bpf_insn insns[] = {
4765 		BPF_MOV64_IMM(BPF_REG_0, 0),
4766 		BPF_EXIT_INSN(),
4767 	};
4768 	int fd, insn_cnt = ARRAY_SIZE(insns);
4769 
4770 	/* use any valid combination of program type and (optional)
4771 	 * non-zero expected attach type (i.e., not a BPF_CGROUP_INET_INGRESS)
4772 	 * to see if kernel supports expected_attach_type field for
4773 	 * BPF_PROG_LOAD command
4774 	 */
4775 	fd = bpf_prog_load(BPF_PROG_TYPE_CGROUP_SOCK, NULL, "GPL", insns, insn_cnt, &opts);
4776 	return probe_fd(fd);
4777 }
4778 
4779 static int probe_kern_probe_read_kernel(void)
4780 {
4781 	struct bpf_insn insns[] = {
4782 		BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),	/* r1 = r10 (fp) */
4783 		BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -8),	/* r1 += -8 */
4784 		BPF_MOV64_IMM(BPF_REG_2, 8),		/* r2 = 8 */
4785 		BPF_MOV64_IMM(BPF_REG_3, 0),		/* r3 = 0 */
4786 		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_probe_read_kernel),
4787 		BPF_EXIT_INSN(),
4788 	};
4789 	int fd, insn_cnt = ARRAY_SIZE(insns);
4790 
4791 	fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
4792 	return probe_fd(fd);
4793 }
4794 
4795 static int probe_prog_bind_map(void)
4796 {
4797 	char *cp, errmsg[STRERR_BUFSIZE];
4798 	struct bpf_insn insns[] = {
4799 		BPF_MOV64_IMM(BPF_REG_0, 0),
4800 		BPF_EXIT_INSN(),
4801 	};
4802 	int ret, map, prog, insn_cnt = ARRAY_SIZE(insns);
4803 
4804 	map = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_det_bind", sizeof(int), 32, 1, NULL);
4805 	if (map < 0) {
4806 		ret = -errno;
4807 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4808 		pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4809 			__func__, cp, -ret);
4810 		return ret;
4811 	}
4812 
4813 	prog = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4814 	if (prog < 0) {
4815 		close(map);
4816 		return 0;
4817 	}
4818 
4819 	ret = bpf_prog_bind_map(prog, map, NULL);
4820 
4821 	close(map);
4822 	close(prog);
4823 
4824 	return ret >= 0;
4825 }
4826 
4827 static int probe_module_btf(void)
4828 {
4829 	static const char strs[] = "\0int";
4830 	__u32 types[] = {
4831 		/* int */
4832 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4833 	};
4834 	struct bpf_btf_info info;
4835 	__u32 len = sizeof(info);
4836 	char name[16];
4837 	int fd, err;
4838 
4839 	fd = libbpf__load_raw_btf((char *)types, sizeof(types), strs, sizeof(strs));
4840 	if (fd < 0)
4841 		return 0; /* BTF not supported at all */
4842 
4843 	memset(&info, 0, sizeof(info));
4844 	info.name = ptr_to_u64(name);
4845 	info.name_len = sizeof(name);
4846 
4847 	/* check that BPF_OBJ_GET_INFO_BY_FD supports specifying name pointer;
4848 	 * kernel's module BTF support coincides with support for
4849 	 * name/name_len fields in struct bpf_btf_info.
4850 	 */
4851 	err = bpf_btf_get_info_by_fd(fd, &info, &len);
4852 	close(fd);
4853 	return !err;
4854 }
4855 
4856 static int probe_perf_link(void)
4857 {
4858 	struct bpf_insn insns[] = {
4859 		BPF_MOV64_IMM(BPF_REG_0, 0),
4860 		BPF_EXIT_INSN(),
4861 	};
4862 	int prog_fd, link_fd, err;
4863 
4864 	prog_fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL",
4865 				insns, ARRAY_SIZE(insns), NULL);
4866 	if (prog_fd < 0)
4867 		return -errno;
4868 
4869 	/* use invalid perf_event FD to get EBADF, if link is supported;
4870 	 * otherwise EINVAL should be returned
4871 	 */
4872 	link_fd = bpf_link_create(prog_fd, -1, BPF_PERF_EVENT, NULL);
4873 	err = -errno; /* close() can clobber errno */
4874 
4875 	if (link_fd >= 0)
4876 		close(link_fd);
4877 	close(prog_fd);
4878 
4879 	return link_fd < 0 && err == -EBADF;
4880 }
4881 
4882 static int probe_uprobe_multi_link(void)
4883 {
4884 	LIBBPF_OPTS(bpf_prog_load_opts, load_opts,
4885 		.expected_attach_type = BPF_TRACE_UPROBE_MULTI,
4886 	);
4887 	LIBBPF_OPTS(bpf_link_create_opts, link_opts);
4888 	struct bpf_insn insns[] = {
4889 		BPF_MOV64_IMM(BPF_REG_0, 0),
4890 		BPF_EXIT_INSN(),
4891 	};
4892 	int prog_fd, link_fd, err;
4893 	unsigned long offset = 0;
4894 
4895 	prog_fd = bpf_prog_load(BPF_PROG_TYPE_KPROBE, NULL, "GPL",
4896 				insns, ARRAY_SIZE(insns), &load_opts);
4897 	if (prog_fd < 0)
4898 		return -errno;
4899 
4900 	/* Creating uprobe in '/' binary should fail with -EBADF. */
4901 	link_opts.uprobe_multi.path = "/";
4902 	link_opts.uprobe_multi.offsets = &offset;
4903 	link_opts.uprobe_multi.cnt = 1;
4904 
4905 	link_fd = bpf_link_create(prog_fd, -1, BPF_TRACE_UPROBE_MULTI, &link_opts);
4906 	err = -errno; /* close() can clobber errno */
4907 
4908 	if (link_fd >= 0)
4909 		close(link_fd);
4910 	close(prog_fd);
4911 
4912 	return link_fd < 0 && err == -EBADF;
4913 }
4914 
4915 static int probe_kern_bpf_cookie(void)
4916 {
4917 	struct bpf_insn insns[] = {
4918 		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_get_attach_cookie),
4919 		BPF_EXIT_INSN(),
4920 	};
4921 	int ret, insn_cnt = ARRAY_SIZE(insns);
4922 
4923 	ret = bpf_prog_load(BPF_PROG_TYPE_KPROBE, NULL, "GPL", insns, insn_cnt, NULL);
4924 	return probe_fd(ret);
4925 }
4926 
4927 static int probe_kern_btf_enum64(void)
4928 {
4929 	static const char strs[] = "\0enum64";
4930 	__u32 types[] = {
4931 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_ENUM64, 0, 0), 8),
4932 	};
4933 
4934 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4935 					     strs, sizeof(strs)));
4936 }
4937 
4938 static int probe_kern_syscall_wrapper(void);
4939 
4940 enum kern_feature_result {
4941 	FEAT_UNKNOWN = 0,
4942 	FEAT_SUPPORTED = 1,
4943 	FEAT_MISSING = 2,
4944 };
4945 
4946 typedef int (*feature_probe_fn)(void);
4947 
4948 static struct kern_feature_desc {
4949 	const char *desc;
4950 	feature_probe_fn probe;
4951 	enum kern_feature_result res;
4952 } feature_probes[__FEAT_CNT] = {
4953 	[FEAT_PROG_NAME] = {
4954 		"BPF program name", probe_kern_prog_name,
4955 	},
4956 	[FEAT_GLOBAL_DATA] = {
4957 		"global variables", probe_kern_global_data,
4958 	},
4959 	[FEAT_BTF] = {
4960 		"minimal BTF", probe_kern_btf,
4961 	},
4962 	[FEAT_BTF_FUNC] = {
4963 		"BTF functions", probe_kern_btf_func,
4964 	},
4965 	[FEAT_BTF_GLOBAL_FUNC] = {
4966 		"BTF global function", probe_kern_btf_func_global,
4967 	},
4968 	[FEAT_BTF_DATASEC] = {
4969 		"BTF data section and variable", probe_kern_btf_datasec,
4970 	},
4971 	[FEAT_ARRAY_MMAP] = {
4972 		"ARRAY map mmap()", probe_kern_array_mmap,
4973 	},
4974 	[FEAT_EXP_ATTACH_TYPE] = {
4975 		"BPF_PROG_LOAD expected_attach_type attribute",
4976 		probe_kern_exp_attach_type,
4977 	},
4978 	[FEAT_PROBE_READ_KERN] = {
4979 		"bpf_probe_read_kernel() helper", probe_kern_probe_read_kernel,
4980 	},
4981 	[FEAT_PROG_BIND_MAP] = {
4982 		"BPF_PROG_BIND_MAP support", probe_prog_bind_map,
4983 	},
4984 	[FEAT_MODULE_BTF] = {
4985 		"module BTF support", probe_module_btf,
4986 	},
4987 	[FEAT_BTF_FLOAT] = {
4988 		"BTF_KIND_FLOAT support", probe_kern_btf_float,
4989 	},
4990 	[FEAT_PERF_LINK] = {
4991 		"BPF perf link support", probe_perf_link,
4992 	},
4993 	[FEAT_BTF_DECL_TAG] = {
4994 		"BTF_KIND_DECL_TAG support", probe_kern_btf_decl_tag,
4995 	},
4996 	[FEAT_BTF_TYPE_TAG] = {
4997 		"BTF_KIND_TYPE_TAG support", probe_kern_btf_type_tag,
4998 	},
4999 	[FEAT_MEMCG_ACCOUNT] = {
5000 		"memcg-based memory accounting", probe_memcg_account,
5001 	},
5002 	[FEAT_BPF_COOKIE] = {
5003 		"BPF cookie support", probe_kern_bpf_cookie,
5004 	},
5005 	[FEAT_BTF_ENUM64] = {
5006 		"BTF_KIND_ENUM64 support", probe_kern_btf_enum64,
5007 	},
5008 	[FEAT_SYSCALL_WRAPPER] = {
5009 		"Kernel using syscall wrapper", probe_kern_syscall_wrapper,
5010 	},
5011 	[FEAT_UPROBE_MULTI_LINK] = {
5012 		"BPF multi-uprobe link support", probe_uprobe_multi_link,
5013 	},
5014 };
5015 
5016 bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
5017 {
5018 	struct kern_feature_desc *feat = &feature_probes[feat_id];
5019 	int ret;
5020 
5021 	if (obj && obj->gen_loader)
5022 		/* To generate loader program assume the latest kernel
5023 		 * to avoid doing extra prog_load, map_create syscalls.
5024 		 */
5025 		return true;
5026 
5027 	if (READ_ONCE(feat->res) == FEAT_UNKNOWN) {
5028 		ret = feat->probe();
5029 		if (ret > 0) {
5030 			WRITE_ONCE(feat->res, FEAT_SUPPORTED);
5031 		} else if (ret == 0) {
5032 			WRITE_ONCE(feat->res, FEAT_MISSING);
5033 		} else {
5034 			pr_warn("Detection of kernel %s support failed: %d\n", feat->desc, ret);
5035 			WRITE_ONCE(feat->res, FEAT_MISSING);
5036 		}
5037 	}
5038 
5039 	return READ_ONCE(feat->res) == FEAT_SUPPORTED;
5040 }
5041 
5042 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
5043 {
5044 	struct bpf_map_info map_info;
5045 	char msg[STRERR_BUFSIZE];
5046 	__u32 map_info_len = sizeof(map_info);
5047 	int err;
5048 
5049 	memset(&map_info, 0, map_info_len);
5050 	err = bpf_map_get_info_by_fd(map_fd, &map_info, &map_info_len);
5051 	if (err && errno == EINVAL)
5052 		err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
5053 	if (err) {
5054 		pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
5055 			libbpf_strerror_r(errno, msg, sizeof(msg)));
5056 		return false;
5057 	}
5058 
5059 	return (map_info.type == map->def.type &&
5060 		map_info.key_size == map->def.key_size &&
5061 		map_info.value_size == map->def.value_size &&
5062 		map_info.max_entries == map->def.max_entries &&
5063 		map_info.map_flags == map->def.map_flags &&
5064 		map_info.map_extra == map->map_extra);
5065 }
5066 
5067 static int
5068 bpf_object__reuse_map(struct bpf_map *map)
5069 {
5070 	char *cp, errmsg[STRERR_BUFSIZE];
5071 	int err, pin_fd;
5072 
5073 	pin_fd = bpf_obj_get(map->pin_path);
5074 	if (pin_fd < 0) {
5075 		err = -errno;
5076 		if (err == -ENOENT) {
5077 			pr_debug("found no pinned map to reuse at '%s'\n",
5078 				 map->pin_path);
5079 			return 0;
5080 		}
5081 
5082 		cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
5083 		pr_warn("couldn't retrieve pinned map '%s': %s\n",
5084 			map->pin_path, cp);
5085 		return err;
5086 	}
5087 
5088 	if (!map_is_reuse_compat(map, pin_fd)) {
5089 		pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
5090 			map->pin_path);
5091 		close(pin_fd);
5092 		return -EINVAL;
5093 	}
5094 
5095 	err = bpf_map__reuse_fd(map, pin_fd);
5096 	close(pin_fd);
5097 	if (err)
5098 		return err;
5099 
5100 	map->pinned = true;
5101 	pr_debug("reused pinned map at '%s'\n", map->pin_path);
5102 
5103 	return 0;
5104 }
5105 
5106 static int
5107 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
5108 {
5109 	enum libbpf_map_type map_type = map->libbpf_type;
5110 	char *cp, errmsg[STRERR_BUFSIZE];
5111 	int err, zero = 0;
5112 
5113 	if (obj->gen_loader) {
5114 		bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
5115 					 map->mmaped, map->def.value_size);
5116 		if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
5117 			bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
5118 		return 0;
5119 	}
5120 	err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
5121 	if (err) {
5122 		err = -errno;
5123 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5124 		pr_warn("Error setting initial map(%s) contents: %s\n",
5125 			map->name, cp);
5126 		return err;
5127 	}
5128 
5129 	/* Freeze .rodata and .kconfig map as read-only from syscall side. */
5130 	if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
5131 		err = bpf_map_freeze(map->fd);
5132 		if (err) {
5133 			err = -errno;
5134 			cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5135 			pr_warn("Error freezing map(%s) as read-only: %s\n",
5136 				map->name, cp);
5137 			return err;
5138 		}
5139 	}
5140 	return 0;
5141 }
5142 
5143 static void bpf_map__destroy(struct bpf_map *map);
5144 
5145 static bool map_is_created(const struct bpf_map *map)
5146 {
5147 	return map->obj->loaded || map->reused;
5148 }
5149 
5150 static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
5151 {
5152 	LIBBPF_OPTS(bpf_map_create_opts, create_attr);
5153 	struct bpf_map_def *def = &map->def;
5154 	const char *map_name = NULL;
5155 	int err = 0, map_fd;
5156 
5157 	if (kernel_supports(obj, FEAT_PROG_NAME))
5158 		map_name = map->name;
5159 	create_attr.map_ifindex = map->map_ifindex;
5160 	create_attr.map_flags = def->map_flags;
5161 	create_attr.numa_node = map->numa_node;
5162 	create_attr.map_extra = map->map_extra;
5163 
5164 	if (bpf_map__is_struct_ops(map))
5165 		create_attr.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
5166 
5167 	if (obj->btf && btf__fd(obj->btf) >= 0) {
5168 		create_attr.btf_fd = btf__fd(obj->btf);
5169 		create_attr.btf_key_type_id = map->btf_key_type_id;
5170 		create_attr.btf_value_type_id = map->btf_value_type_id;
5171 	}
5172 
5173 	if (bpf_map_type__is_map_in_map(def->type)) {
5174 		if (map->inner_map) {
5175 			err = bpf_object__create_map(obj, map->inner_map, true);
5176 			if (err) {
5177 				pr_warn("map '%s': failed to create inner map: %d\n",
5178 					map->name, err);
5179 				return err;
5180 			}
5181 			map->inner_map_fd = map->inner_map->fd;
5182 		}
5183 		if (map->inner_map_fd >= 0)
5184 			create_attr.inner_map_fd = map->inner_map_fd;
5185 	}
5186 
5187 	switch (def->type) {
5188 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5189 	case BPF_MAP_TYPE_CGROUP_ARRAY:
5190 	case BPF_MAP_TYPE_STACK_TRACE:
5191 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5192 	case BPF_MAP_TYPE_HASH_OF_MAPS:
5193 	case BPF_MAP_TYPE_DEVMAP:
5194 	case BPF_MAP_TYPE_DEVMAP_HASH:
5195 	case BPF_MAP_TYPE_CPUMAP:
5196 	case BPF_MAP_TYPE_XSKMAP:
5197 	case BPF_MAP_TYPE_SOCKMAP:
5198 	case BPF_MAP_TYPE_SOCKHASH:
5199 	case BPF_MAP_TYPE_QUEUE:
5200 	case BPF_MAP_TYPE_STACK:
5201 		create_attr.btf_fd = 0;
5202 		create_attr.btf_key_type_id = 0;
5203 		create_attr.btf_value_type_id = 0;
5204 		map->btf_key_type_id = 0;
5205 		map->btf_value_type_id = 0;
5206 	default:
5207 		break;
5208 	}
5209 
5210 	if (obj->gen_loader) {
5211 		bpf_gen__map_create(obj->gen_loader, def->type, map_name,
5212 				    def->key_size, def->value_size, def->max_entries,
5213 				    &create_attr, is_inner ? -1 : map - obj->maps);
5214 		/* We keep pretenting we have valid FD to pass various fd >= 0
5215 		 * checks by just keeping original placeholder FDs in place.
5216 		 * See bpf_object__add_map() comment.
5217 		 * This placeholder fd will not be used with any syscall and
5218 		 * will be reset to -1 eventually.
5219 		 */
5220 		map_fd = map->fd;
5221 	} else {
5222 		map_fd = bpf_map_create(def->type, map_name,
5223 					def->key_size, def->value_size,
5224 					def->max_entries, &create_attr);
5225 	}
5226 	if (map_fd < 0 && (create_attr.btf_key_type_id || create_attr.btf_value_type_id)) {
5227 		char *cp, errmsg[STRERR_BUFSIZE];
5228 
5229 		err = -errno;
5230 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5231 		pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
5232 			map->name, cp, err);
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 		map_fd = bpf_map_create(def->type, map_name,
5239 					def->key_size, def->value_size,
5240 					def->max_entries, &create_attr);
5241 	}
5242 
5243 	if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
5244 		if (obj->gen_loader)
5245 			map->inner_map->fd = -1;
5246 		bpf_map__destroy(map->inner_map);
5247 		zfree(&map->inner_map);
5248 	}
5249 
5250 	if (map_fd < 0)
5251 		return map_fd;
5252 
5253 	/* obj->gen_loader case, prevent reuse_fd() from closing map_fd */
5254 	if (map->fd == map_fd)
5255 		return 0;
5256 
5257 	/* Keep placeholder FD value but now point it to the BPF map object.
5258 	 * This way everything that relied on this map's FD (e.g., relocated
5259 	 * ldimm64 instructions) will stay valid and won't need adjustments.
5260 	 * map->fd stays valid but now point to what map_fd points to.
5261 	 */
5262 	return reuse_fd(map->fd, map_fd);
5263 }
5264 
5265 static int init_map_in_map_slots(struct bpf_object *obj, struct bpf_map *map)
5266 {
5267 	const struct bpf_map *targ_map;
5268 	unsigned int i;
5269 	int fd, err = 0;
5270 
5271 	for (i = 0; i < map->init_slots_sz; i++) {
5272 		if (!map->init_slots[i])
5273 			continue;
5274 
5275 		targ_map = map->init_slots[i];
5276 		fd = targ_map->fd;
5277 
5278 		if (obj->gen_loader) {
5279 			bpf_gen__populate_outer_map(obj->gen_loader,
5280 						    map - obj->maps, i,
5281 						    targ_map - obj->maps);
5282 		} else {
5283 			err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5284 		}
5285 		if (err) {
5286 			err = -errno;
5287 			pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %d\n",
5288 				map->name, i, targ_map->name, fd, err);
5289 			return err;
5290 		}
5291 		pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
5292 			 map->name, i, targ_map->name, fd);
5293 	}
5294 
5295 	zfree(&map->init_slots);
5296 	map->init_slots_sz = 0;
5297 
5298 	return 0;
5299 }
5300 
5301 static int init_prog_array_slots(struct bpf_object *obj, struct bpf_map *map)
5302 {
5303 	const struct bpf_program *targ_prog;
5304 	unsigned int i;
5305 	int fd, err;
5306 
5307 	if (obj->gen_loader)
5308 		return -ENOTSUP;
5309 
5310 	for (i = 0; i < map->init_slots_sz; i++) {
5311 		if (!map->init_slots[i])
5312 			continue;
5313 
5314 		targ_prog = map->init_slots[i];
5315 		fd = bpf_program__fd(targ_prog);
5316 
5317 		err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5318 		if (err) {
5319 			err = -errno;
5320 			pr_warn("map '%s': failed to initialize slot [%d] to prog '%s' fd=%d: %d\n",
5321 				map->name, i, targ_prog->name, fd, err);
5322 			return err;
5323 		}
5324 		pr_debug("map '%s': slot [%d] set to prog '%s' fd=%d\n",
5325 			 map->name, i, targ_prog->name, fd);
5326 	}
5327 
5328 	zfree(&map->init_slots);
5329 	map->init_slots_sz = 0;
5330 
5331 	return 0;
5332 }
5333 
5334 static int bpf_object_init_prog_arrays(struct bpf_object *obj)
5335 {
5336 	struct bpf_map *map;
5337 	int i, err;
5338 
5339 	for (i = 0; i < obj->nr_maps; i++) {
5340 		map = &obj->maps[i];
5341 
5342 		if (!map->init_slots_sz || map->def.type != BPF_MAP_TYPE_PROG_ARRAY)
5343 			continue;
5344 
5345 		err = init_prog_array_slots(obj, map);
5346 		if (err < 0)
5347 			return err;
5348 	}
5349 	return 0;
5350 }
5351 
5352 static int map_set_def_max_entries(struct bpf_map *map)
5353 {
5354 	if (map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !map->def.max_entries) {
5355 		int nr_cpus;
5356 
5357 		nr_cpus = libbpf_num_possible_cpus();
5358 		if (nr_cpus < 0) {
5359 			pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
5360 				map->name, nr_cpus);
5361 			return nr_cpus;
5362 		}
5363 		pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
5364 		map->def.max_entries = nr_cpus;
5365 	}
5366 
5367 	return 0;
5368 }
5369 
5370 static int
5371 bpf_object__create_maps(struct bpf_object *obj)
5372 {
5373 	struct bpf_map *map;
5374 	char *cp, errmsg[STRERR_BUFSIZE];
5375 	unsigned int i, j;
5376 	int err;
5377 	bool retried;
5378 
5379 	for (i = 0; i < obj->nr_maps; i++) {
5380 		map = &obj->maps[i];
5381 
5382 		/* To support old kernels, we skip creating global data maps
5383 		 * (.rodata, .data, .kconfig, etc); later on, during program
5384 		 * loading, if we detect that at least one of the to-be-loaded
5385 		 * programs is referencing any global data map, we'll error
5386 		 * out with program name and relocation index logged.
5387 		 * This approach allows to accommodate Clang emitting
5388 		 * unnecessary .rodata.str1.1 sections for string literals,
5389 		 * but also it allows to have CO-RE applications that use
5390 		 * global variables in some of BPF programs, but not others.
5391 		 * If those global variable-using programs are not loaded at
5392 		 * runtime due to bpf_program__set_autoload(prog, false),
5393 		 * bpf_object loading will succeed just fine even on old
5394 		 * kernels.
5395 		 */
5396 		if (bpf_map__is_internal(map) && !kernel_supports(obj, FEAT_GLOBAL_DATA))
5397 			map->autocreate = false;
5398 
5399 		if (!map->autocreate) {
5400 			pr_debug("map '%s': skipped auto-creating...\n", map->name);
5401 			continue;
5402 		}
5403 
5404 		err = map_set_def_max_entries(map);
5405 		if (err)
5406 			goto err_out;
5407 
5408 		retried = false;
5409 retry:
5410 		if (map->pin_path) {
5411 			err = bpf_object__reuse_map(map);
5412 			if (err) {
5413 				pr_warn("map '%s': error reusing pinned map\n",
5414 					map->name);
5415 				goto err_out;
5416 			}
5417 			if (retried && map->fd < 0) {
5418 				pr_warn("map '%s': cannot find pinned map\n",
5419 					map->name);
5420 				err = -ENOENT;
5421 				goto err_out;
5422 			}
5423 		}
5424 
5425 		if (map->reused) {
5426 			pr_debug("map '%s': skipping creation (preset fd=%d)\n",
5427 				 map->name, map->fd);
5428 		} else {
5429 			err = bpf_object__create_map(obj, map, false);
5430 			if (err)
5431 				goto err_out;
5432 
5433 			pr_debug("map '%s': created successfully, fd=%d\n",
5434 				 map->name, map->fd);
5435 
5436 			if (bpf_map__is_internal(map)) {
5437 				err = bpf_object__populate_internal_map(obj, map);
5438 				if (err < 0)
5439 					goto err_out;
5440 			}
5441 
5442 			if (map->init_slots_sz && map->def.type != BPF_MAP_TYPE_PROG_ARRAY) {
5443 				err = init_map_in_map_slots(obj, map);
5444 				if (err < 0)
5445 					goto err_out;
5446 			}
5447 		}
5448 
5449 		if (map->pin_path && !map->pinned) {
5450 			err = bpf_map__pin(map, NULL);
5451 			if (err) {
5452 				if (!retried && err == -EEXIST) {
5453 					retried = true;
5454 					goto retry;
5455 				}
5456 				pr_warn("map '%s': failed to auto-pin at '%s': %d\n",
5457 					map->name, map->pin_path, err);
5458 				goto err_out;
5459 			}
5460 		}
5461 	}
5462 
5463 	return 0;
5464 
5465 err_out:
5466 	cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5467 	pr_warn("map '%s': failed to create: %s(%d)\n", map->name, cp, err);
5468 	pr_perm_msg(err);
5469 	for (j = 0; j < i; j++)
5470 		zclose(obj->maps[j].fd);
5471 	return err;
5472 }
5473 
5474 static bool bpf_core_is_flavor_sep(const char *s)
5475 {
5476 	/* check X___Y name pattern, where X and Y are not underscores */
5477 	return s[0] != '_' &&				      /* X */
5478 	       s[1] == '_' && s[2] == '_' && s[3] == '_' &&   /* ___ */
5479 	       s[4] != '_';				      /* Y */
5480 }
5481 
5482 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
5483  * before last triple underscore. Struct name part after last triple
5484  * underscore is ignored by BPF CO-RE relocation during relocation matching.
5485  */
5486 size_t bpf_core_essential_name_len(const char *name)
5487 {
5488 	size_t n = strlen(name);
5489 	int i;
5490 
5491 	for (i = n - 5; i >= 0; i--) {
5492 		if (bpf_core_is_flavor_sep(name + i))
5493 			return i + 1;
5494 	}
5495 	return n;
5496 }
5497 
5498 void bpf_core_free_cands(struct bpf_core_cand_list *cands)
5499 {
5500 	if (!cands)
5501 		return;
5502 
5503 	free(cands->cands);
5504 	free(cands);
5505 }
5506 
5507 int bpf_core_add_cands(struct bpf_core_cand *local_cand,
5508 		       size_t local_essent_len,
5509 		       const struct btf *targ_btf,
5510 		       const char *targ_btf_name,
5511 		       int targ_start_id,
5512 		       struct bpf_core_cand_list *cands)
5513 {
5514 	struct bpf_core_cand *new_cands, *cand;
5515 	const struct btf_type *t, *local_t;
5516 	const char *targ_name, *local_name;
5517 	size_t targ_essent_len;
5518 	int n, i;
5519 
5520 	local_t = btf__type_by_id(local_cand->btf, local_cand->id);
5521 	local_name = btf__str_by_offset(local_cand->btf, local_t->name_off);
5522 
5523 	n = btf__type_cnt(targ_btf);
5524 	for (i = targ_start_id; i < n; i++) {
5525 		t = btf__type_by_id(targ_btf, i);
5526 		if (!btf_kind_core_compat(t, local_t))
5527 			continue;
5528 
5529 		targ_name = btf__name_by_offset(targ_btf, t->name_off);
5530 		if (str_is_empty(targ_name))
5531 			continue;
5532 
5533 		targ_essent_len = bpf_core_essential_name_len(targ_name);
5534 		if (targ_essent_len != local_essent_len)
5535 			continue;
5536 
5537 		if (strncmp(local_name, targ_name, local_essent_len) != 0)
5538 			continue;
5539 
5540 		pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s in [%s]\n",
5541 			 local_cand->id, btf_kind_str(local_t),
5542 			 local_name, i, btf_kind_str(t), targ_name,
5543 			 targ_btf_name);
5544 		new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
5545 					      sizeof(*cands->cands));
5546 		if (!new_cands)
5547 			return -ENOMEM;
5548 
5549 		cand = &new_cands[cands->len];
5550 		cand->btf = targ_btf;
5551 		cand->id = i;
5552 
5553 		cands->cands = new_cands;
5554 		cands->len++;
5555 	}
5556 	return 0;
5557 }
5558 
5559 static int load_module_btfs(struct bpf_object *obj)
5560 {
5561 	struct bpf_btf_info info;
5562 	struct module_btf *mod_btf;
5563 	struct btf *btf;
5564 	char name[64];
5565 	__u32 id = 0, len;
5566 	int err, fd;
5567 
5568 	if (obj->btf_modules_loaded)
5569 		return 0;
5570 
5571 	if (obj->gen_loader)
5572 		return 0;
5573 
5574 	/* don't do this again, even if we find no module BTFs */
5575 	obj->btf_modules_loaded = true;
5576 
5577 	/* kernel too old to support module BTFs */
5578 	if (!kernel_supports(obj, FEAT_MODULE_BTF))
5579 		return 0;
5580 
5581 	while (true) {
5582 		err = bpf_btf_get_next_id(id, &id);
5583 		if (err && errno == ENOENT)
5584 			return 0;
5585 		if (err && errno == EPERM) {
5586 			pr_debug("skipping module BTFs loading, missing privileges\n");
5587 			return 0;
5588 		}
5589 		if (err) {
5590 			err = -errno;
5591 			pr_warn("failed to iterate BTF objects: %d\n", err);
5592 			return err;
5593 		}
5594 
5595 		fd = bpf_btf_get_fd_by_id(id);
5596 		if (fd < 0) {
5597 			if (errno == ENOENT)
5598 				continue; /* expected race: BTF was unloaded */
5599 			err = -errno;
5600 			pr_warn("failed to get BTF object #%d FD: %d\n", id, err);
5601 			return err;
5602 		}
5603 
5604 		len = sizeof(info);
5605 		memset(&info, 0, sizeof(info));
5606 		info.name = ptr_to_u64(name);
5607 		info.name_len = sizeof(name);
5608 
5609 		err = bpf_btf_get_info_by_fd(fd, &info, &len);
5610 		if (err) {
5611 			err = -errno;
5612 			pr_warn("failed to get BTF object #%d info: %d\n", id, err);
5613 			goto err_out;
5614 		}
5615 
5616 		/* ignore non-module BTFs */
5617 		if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
5618 			close(fd);
5619 			continue;
5620 		}
5621 
5622 		btf = btf_get_from_fd(fd, obj->btf_vmlinux);
5623 		err = libbpf_get_error(btf);
5624 		if (err) {
5625 			pr_warn("failed to load module [%s]'s BTF object #%d: %d\n",
5626 				name, id, err);
5627 			goto err_out;
5628 		}
5629 
5630 		err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
5631 					sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
5632 		if (err)
5633 			goto err_out;
5634 
5635 		mod_btf = &obj->btf_modules[obj->btf_module_cnt++];
5636 
5637 		mod_btf->btf = btf;
5638 		mod_btf->id = id;
5639 		mod_btf->fd = fd;
5640 		mod_btf->name = strdup(name);
5641 		if (!mod_btf->name) {
5642 			err = -ENOMEM;
5643 			goto err_out;
5644 		}
5645 		continue;
5646 
5647 err_out:
5648 		close(fd);
5649 		return err;
5650 	}
5651 
5652 	return 0;
5653 }
5654 
5655 static struct bpf_core_cand_list *
5656 bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
5657 {
5658 	struct bpf_core_cand local_cand = {};
5659 	struct bpf_core_cand_list *cands;
5660 	const struct btf *main_btf;
5661 	const struct btf_type *local_t;
5662 	const char *local_name;
5663 	size_t local_essent_len;
5664 	int err, i;
5665 
5666 	local_cand.btf = local_btf;
5667 	local_cand.id = local_type_id;
5668 	local_t = btf__type_by_id(local_btf, local_type_id);
5669 	if (!local_t)
5670 		return ERR_PTR(-EINVAL);
5671 
5672 	local_name = btf__name_by_offset(local_btf, local_t->name_off);
5673 	if (str_is_empty(local_name))
5674 		return ERR_PTR(-EINVAL);
5675 	local_essent_len = bpf_core_essential_name_len(local_name);
5676 
5677 	cands = calloc(1, sizeof(*cands));
5678 	if (!cands)
5679 		return ERR_PTR(-ENOMEM);
5680 
5681 	/* Attempt to find target candidates in vmlinux BTF first */
5682 	main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
5683 	err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
5684 	if (err)
5685 		goto err_out;
5686 
5687 	/* if vmlinux BTF has any candidate, don't got for module BTFs */
5688 	if (cands->len)
5689 		return cands;
5690 
5691 	/* if vmlinux BTF was overridden, don't attempt to load module BTFs */
5692 	if (obj->btf_vmlinux_override)
5693 		return cands;
5694 
5695 	/* now look through module BTFs, trying to still find candidates */
5696 	err = load_module_btfs(obj);
5697 	if (err)
5698 		goto err_out;
5699 
5700 	for (i = 0; i < obj->btf_module_cnt; i++) {
5701 		err = bpf_core_add_cands(&local_cand, local_essent_len,
5702 					 obj->btf_modules[i].btf,
5703 					 obj->btf_modules[i].name,
5704 					 btf__type_cnt(obj->btf_vmlinux),
5705 					 cands);
5706 		if (err)
5707 			goto err_out;
5708 	}
5709 
5710 	return cands;
5711 err_out:
5712 	bpf_core_free_cands(cands);
5713 	return ERR_PTR(err);
5714 }
5715 
5716 /* Check local and target types for compatibility. This check is used for
5717  * type-based CO-RE relocations and follow slightly different rules than
5718  * field-based relocations. This function assumes that root types were already
5719  * checked for name match. Beyond that initial root-level name check, names
5720  * are completely ignored. Compatibility rules are as follows:
5721  *   - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
5722  *     kind should match for local and target types (i.e., STRUCT is not
5723  *     compatible with UNION);
5724  *   - for ENUMs, the size is ignored;
5725  *   - for INT, size and signedness are ignored;
5726  *   - for ARRAY, dimensionality is ignored, element types are checked for
5727  *     compatibility recursively;
5728  *   - CONST/VOLATILE/RESTRICT modifiers are ignored;
5729  *   - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
5730  *   - FUNC_PROTOs are compatible if they have compatible signature: same
5731  *     number of input args and compatible return and argument types.
5732  * These rules are not set in stone and probably will be adjusted as we get
5733  * more experience with using BPF CO-RE relocations.
5734  */
5735 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
5736 			      const struct btf *targ_btf, __u32 targ_id)
5737 {
5738 	return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id, 32);
5739 }
5740 
5741 int bpf_core_types_match(const struct btf *local_btf, __u32 local_id,
5742 			 const struct btf *targ_btf, __u32 targ_id)
5743 {
5744 	return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false, 32);
5745 }
5746 
5747 static size_t bpf_core_hash_fn(const long key, void *ctx)
5748 {
5749 	return key;
5750 }
5751 
5752 static bool bpf_core_equal_fn(const long k1, const long k2, void *ctx)
5753 {
5754 	return k1 == k2;
5755 }
5756 
5757 static int record_relo_core(struct bpf_program *prog,
5758 			    const struct bpf_core_relo *core_relo, int insn_idx)
5759 {
5760 	struct reloc_desc *relos, *relo;
5761 
5762 	relos = libbpf_reallocarray(prog->reloc_desc,
5763 				    prog->nr_reloc + 1, sizeof(*relos));
5764 	if (!relos)
5765 		return -ENOMEM;
5766 	relo = &relos[prog->nr_reloc];
5767 	relo->type = RELO_CORE;
5768 	relo->insn_idx = insn_idx;
5769 	relo->core_relo = core_relo;
5770 	prog->reloc_desc = relos;
5771 	prog->nr_reloc++;
5772 	return 0;
5773 }
5774 
5775 static const struct bpf_core_relo *find_relo_core(struct bpf_program *prog, int insn_idx)
5776 {
5777 	struct reloc_desc *relo;
5778 	int i;
5779 
5780 	for (i = 0; i < prog->nr_reloc; i++) {
5781 		relo = &prog->reloc_desc[i];
5782 		if (relo->type != RELO_CORE || relo->insn_idx != insn_idx)
5783 			continue;
5784 
5785 		return relo->core_relo;
5786 	}
5787 
5788 	return NULL;
5789 }
5790 
5791 static int bpf_core_resolve_relo(struct bpf_program *prog,
5792 				 const struct bpf_core_relo *relo,
5793 				 int relo_idx,
5794 				 const struct btf *local_btf,
5795 				 struct hashmap *cand_cache,
5796 				 struct bpf_core_relo_res *targ_res)
5797 {
5798 	struct bpf_core_spec specs_scratch[3] = {};
5799 	struct bpf_core_cand_list *cands = NULL;
5800 	const char *prog_name = prog->name;
5801 	const struct btf_type *local_type;
5802 	const char *local_name;
5803 	__u32 local_id = relo->type_id;
5804 	int err;
5805 
5806 	local_type = btf__type_by_id(local_btf, local_id);
5807 	if (!local_type)
5808 		return -EINVAL;
5809 
5810 	local_name = btf__name_by_offset(local_btf, local_type->name_off);
5811 	if (!local_name)
5812 		return -EINVAL;
5813 
5814 	if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
5815 	    !hashmap__find(cand_cache, local_id, &cands)) {
5816 		cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
5817 		if (IS_ERR(cands)) {
5818 			pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n",
5819 				prog_name, relo_idx, local_id, btf_kind_str(local_type),
5820 				local_name, PTR_ERR(cands));
5821 			return PTR_ERR(cands);
5822 		}
5823 		err = hashmap__set(cand_cache, local_id, cands, NULL, NULL);
5824 		if (err) {
5825 			bpf_core_free_cands(cands);
5826 			return err;
5827 		}
5828 	}
5829 
5830 	return bpf_core_calc_relo_insn(prog_name, relo, relo_idx, local_btf, cands, specs_scratch,
5831 				       targ_res);
5832 }
5833 
5834 static int
5835 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
5836 {
5837 	const struct btf_ext_info_sec *sec;
5838 	struct bpf_core_relo_res targ_res;
5839 	const struct bpf_core_relo *rec;
5840 	const struct btf_ext_info *seg;
5841 	struct hashmap_entry *entry;
5842 	struct hashmap *cand_cache = NULL;
5843 	struct bpf_program *prog;
5844 	struct bpf_insn *insn;
5845 	const char *sec_name;
5846 	int i, err = 0, insn_idx, sec_idx, sec_num;
5847 
5848 	if (obj->btf_ext->core_relo_info.len == 0)
5849 		return 0;
5850 
5851 	if (targ_btf_path) {
5852 		obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
5853 		err = libbpf_get_error(obj->btf_vmlinux_override);
5854 		if (err) {
5855 			pr_warn("failed to parse target BTF: %d\n", err);
5856 			return err;
5857 		}
5858 	}
5859 
5860 	cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
5861 	if (IS_ERR(cand_cache)) {
5862 		err = PTR_ERR(cand_cache);
5863 		goto out;
5864 	}
5865 
5866 	seg = &obj->btf_ext->core_relo_info;
5867 	sec_num = 0;
5868 	for_each_btf_ext_sec(seg, sec) {
5869 		sec_idx = seg->sec_idxs[sec_num];
5870 		sec_num++;
5871 
5872 		sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
5873 		if (str_is_empty(sec_name)) {
5874 			err = -EINVAL;
5875 			goto out;
5876 		}
5877 
5878 		pr_debug("sec '%s': found %d CO-RE relocations\n", sec_name, sec->num_info);
5879 
5880 		for_each_btf_ext_rec(seg, sec, i, rec) {
5881 			if (rec->insn_off % BPF_INSN_SZ)
5882 				return -EINVAL;
5883 			insn_idx = rec->insn_off / BPF_INSN_SZ;
5884 			prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
5885 			if (!prog) {
5886 				/* When __weak subprog is "overridden" by another instance
5887 				 * of the subprog from a different object file, linker still
5888 				 * appends all the .BTF.ext info that used to belong to that
5889 				 * eliminated subprogram.
5890 				 * This is similar to what x86-64 linker does for relocations.
5891 				 * So just ignore such relocations just like we ignore
5892 				 * subprog instructions when discovering subprograms.
5893 				 */
5894 				pr_debug("sec '%s': skipping CO-RE relocation #%d for insn #%d belonging to eliminated weak subprogram\n",
5895 					 sec_name, i, insn_idx);
5896 				continue;
5897 			}
5898 			/* no need to apply CO-RE relocation if the program is
5899 			 * not going to be loaded
5900 			 */
5901 			if (!prog->autoload)
5902 				continue;
5903 
5904 			/* adjust insn_idx from section frame of reference to the local
5905 			 * program's frame of reference; (sub-)program code is not yet
5906 			 * relocated, so it's enough to just subtract in-section offset
5907 			 */
5908 			insn_idx = insn_idx - prog->sec_insn_off;
5909 			if (insn_idx >= prog->insns_cnt)
5910 				return -EINVAL;
5911 			insn = &prog->insns[insn_idx];
5912 
5913 			err = record_relo_core(prog, rec, insn_idx);
5914 			if (err) {
5915 				pr_warn("prog '%s': relo #%d: failed to record relocation: %d\n",
5916 					prog->name, i, err);
5917 				goto out;
5918 			}
5919 
5920 			if (prog->obj->gen_loader)
5921 				continue;
5922 
5923 			err = bpf_core_resolve_relo(prog, rec, i, obj->btf, cand_cache, &targ_res);
5924 			if (err) {
5925 				pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
5926 					prog->name, i, err);
5927 				goto out;
5928 			}
5929 
5930 			err = bpf_core_patch_insn(prog->name, insn, insn_idx, rec, i, &targ_res);
5931 			if (err) {
5932 				pr_warn("prog '%s': relo #%d: failed to patch insn #%u: %d\n",
5933 					prog->name, i, insn_idx, err);
5934 				goto out;
5935 			}
5936 		}
5937 	}
5938 
5939 out:
5940 	/* obj->btf_vmlinux and module BTFs are freed after object load */
5941 	btf__free(obj->btf_vmlinux_override);
5942 	obj->btf_vmlinux_override = NULL;
5943 
5944 	if (!IS_ERR_OR_NULL(cand_cache)) {
5945 		hashmap__for_each_entry(cand_cache, entry, i) {
5946 			bpf_core_free_cands(entry->pvalue);
5947 		}
5948 		hashmap__free(cand_cache);
5949 	}
5950 	return err;
5951 }
5952 
5953 /* base map load ldimm64 special constant, used also for log fixup logic */
5954 #define POISON_LDIMM64_MAP_BASE 2001000000
5955 #define POISON_LDIMM64_MAP_PFX "200100"
5956 
5957 static void poison_map_ldimm64(struct bpf_program *prog, int relo_idx,
5958 			       int insn_idx, struct bpf_insn *insn,
5959 			       int map_idx, const struct bpf_map *map)
5960 {
5961 	int i;
5962 
5963 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that loads map #%d '%s'\n",
5964 		 prog->name, relo_idx, insn_idx, map_idx, map->name);
5965 
5966 	/* we turn single ldimm64 into two identical invalid calls */
5967 	for (i = 0; i < 2; i++) {
5968 		insn->code = BPF_JMP | BPF_CALL;
5969 		insn->dst_reg = 0;
5970 		insn->src_reg = 0;
5971 		insn->off = 0;
5972 		/* if this instruction is reachable (not a dead code),
5973 		 * verifier will complain with something like:
5974 		 * invalid func unknown#2001000123
5975 		 * where lower 123 is map index into obj->maps[] array
5976 		 */
5977 		insn->imm = POISON_LDIMM64_MAP_BASE + map_idx;
5978 
5979 		insn++;
5980 	}
5981 }
5982 
5983 /* unresolved kfunc call special constant, used also for log fixup logic */
5984 #define POISON_CALL_KFUNC_BASE 2002000000
5985 #define POISON_CALL_KFUNC_PFX "2002"
5986 
5987 static void poison_kfunc_call(struct bpf_program *prog, int relo_idx,
5988 			      int insn_idx, struct bpf_insn *insn,
5989 			      int ext_idx, const struct extern_desc *ext)
5990 {
5991 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that calls kfunc '%s'\n",
5992 		 prog->name, relo_idx, insn_idx, ext->name);
5993 
5994 	/* we turn kfunc call into invalid helper call with identifiable constant */
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 extern index into obj->externs[] array
6003 	 */
6004 	insn->imm = POISON_CALL_KFUNC_BASE + ext_idx;
6005 }
6006 
6007 /* Relocate data references within program code:
6008  *  - map references;
6009  *  - global variable references;
6010  *  - extern references.
6011  */
6012 static int
6013 bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
6014 {
6015 	int i;
6016 
6017 	for (i = 0; i < prog->nr_reloc; i++) {
6018 		struct reloc_desc *relo = &prog->reloc_desc[i];
6019 		struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6020 		const struct bpf_map *map;
6021 		struct extern_desc *ext;
6022 
6023 		switch (relo->type) {
6024 		case RELO_LD64:
6025 			map = &obj->maps[relo->map_idx];
6026 			if (obj->gen_loader) {
6027 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
6028 				insn[0].imm = relo->map_idx;
6029 			} else if (map->autocreate) {
6030 				insn[0].src_reg = BPF_PSEUDO_MAP_FD;
6031 				insn[0].imm = map->fd;
6032 			} else {
6033 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6034 						   relo->map_idx, map);
6035 			}
6036 			break;
6037 		case RELO_DATA:
6038 			map = &obj->maps[relo->map_idx];
6039 			insn[1].imm = insn[0].imm + relo->sym_off;
6040 			if (obj->gen_loader) {
6041 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6042 				insn[0].imm = relo->map_idx;
6043 			} else if (map->autocreate) {
6044 				insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6045 				insn[0].imm = map->fd;
6046 			} else {
6047 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6048 						   relo->map_idx, map);
6049 			}
6050 			break;
6051 		case RELO_EXTERN_LD64:
6052 			ext = &obj->externs[relo->ext_idx];
6053 			if (ext->type == EXT_KCFG) {
6054 				if (obj->gen_loader) {
6055 					insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6056 					insn[0].imm = obj->kconfig_map_idx;
6057 				} else {
6058 					insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6059 					insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
6060 				}
6061 				insn[1].imm = ext->kcfg.data_off;
6062 			} else /* EXT_KSYM */ {
6063 				if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
6064 					insn[0].src_reg = BPF_PSEUDO_BTF_ID;
6065 					insn[0].imm = ext->ksym.kernel_btf_id;
6066 					insn[1].imm = ext->ksym.kernel_btf_obj_fd;
6067 				} else { /* typeless ksyms or unresolved typed ksyms */
6068 					insn[0].imm = (__u32)ext->ksym.addr;
6069 					insn[1].imm = ext->ksym.addr >> 32;
6070 				}
6071 			}
6072 			break;
6073 		case RELO_EXTERN_CALL:
6074 			ext = &obj->externs[relo->ext_idx];
6075 			insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
6076 			if (ext->is_set) {
6077 				insn[0].imm = ext->ksym.kernel_btf_id;
6078 				insn[0].off = ext->ksym.btf_fd_idx;
6079 			} else { /* unresolved weak kfunc call */
6080 				poison_kfunc_call(prog, i, relo->insn_idx, insn,
6081 						  relo->ext_idx, ext);
6082 			}
6083 			break;
6084 		case RELO_SUBPROG_ADDR:
6085 			if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
6086 				pr_warn("prog '%s': relo #%d: bad insn\n",
6087 					prog->name, i);
6088 				return -EINVAL;
6089 			}
6090 			/* handled already */
6091 			break;
6092 		case RELO_CALL:
6093 			/* handled already */
6094 			break;
6095 		case RELO_CORE:
6096 			/* will be handled by bpf_program_record_relos() */
6097 			break;
6098 		default:
6099 			pr_warn("prog '%s': relo #%d: bad relo type %d\n",
6100 				prog->name, i, relo->type);
6101 			return -EINVAL;
6102 		}
6103 	}
6104 
6105 	return 0;
6106 }
6107 
6108 static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
6109 				    const struct bpf_program *prog,
6110 				    const struct btf_ext_info *ext_info,
6111 				    void **prog_info, __u32 *prog_rec_cnt,
6112 				    __u32 *prog_rec_sz)
6113 {
6114 	void *copy_start = NULL, *copy_end = NULL;
6115 	void *rec, *rec_end, *new_prog_info;
6116 	const struct btf_ext_info_sec *sec;
6117 	size_t old_sz, new_sz;
6118 	int i, sec_num, sec_idx, off_adj;
6119 
6120 	sec_num = 0;
6121 	for_each_btf_ext_sec(ext_info, sec) {
6122 		sec_idx = ext_info->sec_idxs[sec_num];
6123 		sec_num++;
6124 		if (prog->sec_idx != sec_idx)
6125 			continue;
6126 
6127 		for_each_btf_ext_rec(ext_info, sec, i, rec) {
6128 			__u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
6129 
6130 			if (insn_off < prog->sec_insn_off)
6131 				continue;
6132 			if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
6133 				break;
6134 
6135 			if (!copy_start)
6136 				copy_start = rec;
6137 			copy_end = rec + ext_info->rec_size;
6138 		}
6139 
6140 		if (!copy_start)
6141 			return -ENOENT;
6142 
6143 		/* append func/line info of a given (sub-)program to the main
6144 		 * program func/line info
6145 		 */
6146 		old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
6147 		new_sz = old_sz + (copy_end - copy_start);
6148 		new_prog_info = realloc(*prog_info, new_sz);
6149 		if (!new_prog_info)
6150 			return -ENOMEM;
6151 		*prog_info = new_prog_info;
6152 		*prog_rec_cnt = new_sz / ext_info->rec_size;
6153 		memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
6154 
6155 		/* Kernel instruction offsets are in units of 8-byte
6156 		 * instructions, while .BTF.ext instruction offsets generated
6157 		 * by Clang are in units of bytes. So convert Clang offsets
6158 		 * into kernel offsets and adjust offset according to program
6159 		 * relocated position.
6160 		 */
6161 		off_adj = prog->sub_insn_off - prog->sec_insn_off;
6162 		rec = new_prog_info + old_sz;
6163 		rec_end = new_prog_info + new_sz;
6164 		for (; rec < rec_end; rec += ext_info->rec_size) {
6165 			__u32 *insn_off = rec;
6166 
6167 			*insn_off = *insn_off / BPF_INSN_SZ + off_adj;
6168 		}
6169 		*prog_rec_sz = ext_info->rec_size;
6170 		return 0;
6171 	}
6172 
6173 	return -ENOENT;
6174 }
6175 
6176 static int
6177 reloc_prog_func_and_line_info(const struct bpf_object *obj,
6178 			      struct bpf_program *main_prog,
6179 			      const struct bpf_program *prog)
6180 {
6181 	int err;
6182 
6183 	/* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
6184 	 * support func/line info
6185 	 */
6186 	if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
6187 		return 0;
6188 
6189 	/* only attempt func info relocation if main program's func_info
6190 	 * relocation was successful
6191 	 */
6192 	if (main_prog != prog && !main_prog->func_info)
6193 		goto line_info;
6194 
6195 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
6196 				       &main_prog->func_info,
6197 				       &main_prog->func_info_cnt,
6198 				       &main_prog->func_info_rec_size);
6199 	if (err) {
6200 		if (err != -ENOENT) {
6201 			pr_warn("prog '%s': error relocating .BTF.ext function info: %d\n",
6202 				prog->name, err);
6203 			return err;
6204 		}
6205 		if (main_prog->func_info) {
6206 			/*
6207 			 * Some info has already been found but has problem
6208 			 * in the last btf_ext reloc. Must have to error out.
6209 			 */
6210 			pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
6211 			return err;
6212 		}
6213 		/* Have problem loading the very first info. Ignore the rest. */
6214 		pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
6215 			prog->name);
6216 	}
6217 
6218 line_info:
6219 	/* don't relocate line info if main program's relocation failed */
6220 	if (main_prog != prog && !main_prog->line_info)
6221 		return 0;
6222 
6223 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
6224 				       &main_prog->line_info,
6225 				       &main_prog->line_info_cnt,
6226 				       &main_prog->line_info_rec_size);
6227 	if (err) {
6228 		if (err != -ENOENT) {
6229 			pr_warn("prog '%s': error relocating .BTF.ext line info: %d\n",
6230 				prog->name, err);
6231 			return err;
6232 		}
6233 		if (main_prog->line_info) {
6234 			/*
6235 			 * Some info has already been found but has problem
6236 			 * in the last btf_ext reloc. Must have to error out.
6237 			 */
6238 			pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
6239 			return err;
6240 		}
6241 		/* Have problem loading the very first info. Ignore the rest. */
6242 		pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
6243 			prog->name);
6244 	}
6245 	return 0;
6246 }
6247 
6248 static int cmp_relo_by_insn_idx(const void *key, const void *elem)
6249 {
6250 	size_t insn_idx = *(const size_t *)key;
6251 	const struct reloc_desc *relo = elem;
6252 
6253 	if (insn_idx == relo->insn_idx)
6254 		return 0;
6255 	return insn_idx < relo->insn_idx ? -1 : 1;
6256 }
6257 
6258 static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
6259 {
6260 	if (!prog->nr_reloc)
6261 		return NULL;
6262 	return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
6263 		       sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
6264 }
6265 
6266 static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
6267 {
6268 	int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
6269 	struct reloc_desc *relos;
6270 	int i;
6271 
6272 	if (main_prog == subprog)
6273 		return 0;
6274 	relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
6275 	/* if new count is zero, reallocarray can return a valid NULL result;
6276 	 * in this case the previous pointer will be freed, so we *have to*
6277 	 * reassign old pointer to the new value (even if it's NULL)
6278 	 */
6279 	if (!relos && new_cnt)
6280 		return -ENOMEM;
6281 	if (subprog->nr_reloc)
6282 		memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
6283 		       sizeof(*relos) * subprog->nr_reloc);
6284 
6285 	for (i = main_prog->nr_reloc; i < new_cnt; i++)
6286 		relos[i].insn_idx += subprog->sub_insn_off;
6287 	/* After insn_idx adjustment the 'relos' array is still sorted
6288 	 * by insn_idx and doesn't break bsearch.
6289 	 */
6290 	main_prog->reloc_desc = relos;
6291 	main_prog->nr_reloc = new_cnt;
6292 	return 0;
6293 }
6294 
6295 static int
6296 bpf_object__append_subprog_code(struct bpf_object *obj, struct bpf_program *main_prog,
6297 				struct bpf_program *subprog)
6298 {
6299        struct bpf_insn *insns;
6300        size_t new_cnt;
6301        int err;
6302 
6303        subprog->sub_insn_off = main_prog->insns_cnt;
6304 
6305        new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
6306        insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
6307        if (!insns) {
6308                pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
6309                return -ENOMEM;
6310        }
6311        main_prog->insns = insns;
6312        main_prog->insns_cnt = new_cnt;
6313 
6314        memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
6315               subprog->insns_cnt * sizeof(*insns));
6316 
6317        pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
6318                 main_prog->name, subprog->insns_cnt, subprog->name);
6319 
6320        /* The subprog insns are now appended. Append its relos too. */
6321        err = append_subprog_relos(main_prog, subprog);
6322        if (err)
6323                return err;
6324        return 0;
6325 }
6326 
6327 static int
6328 bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
6329 		       struct bpf_program *prog)
6330 {
6331 	size_t sub_insn_idx, insn_idx;
6332 	struct bpf_program *subprog;
6333 	struct reloc_desc *relo;
6334 	struct bpf_insn *insn;
6335 	int err;
6336 
6337 	err = reloc_prog_func_and_line_info(obj, main_prog, prog);
6338 	if (err)
6339 		return err;
6340 
6341 	for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
6342 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6343 		if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
6344 			continue;
6345 
6346 		relo = find_prog_insn_relo(prog, insn_idx);
6347 		if (relo && relo->type == RELO_EXTERN_CALL)
6348 			/* kfunc relocations will be handled later
6349 			 * in bpf_object__relocate_data()
6350 			 */
6351 			continue;
6352 		if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
6353 			pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
6354 				prog->name, insn_idx, relo->type);
6355 			return -LIBBPF_ERRNO__RELOC;
6356 		}
6357 		if (relo) {
6358 			/* sub-program instruction index is a combination of
6359 			 * an offset of a symbol pointed to by relocation and
6360 			 * call instruction's imm field; for global functions,
6361 			 * call always has imm = -1, but for static functions
6362 			 * relocation is against STT_SECTION and insn->imm
6363 			 * points to a start of a static function
6364 			 *
6365 			 * for subprog addr relocation, the relo->sym_off + insn->imm is
6366 			 * the byte offset in the corresponding section.
6367 			 */
6368 			if (relo->type == RELO_CALL)
6369 				sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
6370 			else
6371 				sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
6372 		} else if (insn_is_pseudo_func(insn)) {
6373 			/*
6374 			 * RELO_SUBPROG_ADDR relo is always emitted even if both
6375 			 * functions are in the same section, so it shouldn't reach here.
6376 			 */
6377 			pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
6378 				prog->name, insn_idx);
6379 			return -LIBBPF_ERRNO__RELOC;
6380 		} else {
6381 			/* if subprogram call is to a static function within
6382 			 * the same ELF section, there won't be any relocation
6383 			 * emitted, but it also means there is no additional
6384 			 * offset necessary, insns->imm is relative to
6385 			 * instruction's original position within the section
6386 			 */
6387 			sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
6388 		}
6389 
6390 		/* we enforce that sub-programs should be in .text section */
6391 		subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
6392 		if (!subprog) {
6393 			pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
6394 				prog->name);
6395 			return -LIBBPF_ERRNO__RELOC;
6396 		}
6397 
6398 		/* if it's the first call instruction calling into this
6399 		 * subprogram (meaning this subprog hasn't been processed
6400 		 * yet) within the context of current main program:
6401 		 *   - append it at the end of main program's instructions blog;
6402 		 *   - process is recursively, while current program is put on hold;
6403 		 *   - if that subprogram calls some other not yet processes
6404 		 *   subprogram, same thing will happen recursively until
6405 		 *   there are no more unprocesses subprograms left to append
6406 		 *   and relocate.
6407 		 */
6408 		if (subprog->sub_insn_off == 0) {
6409 			err = bpf_object__append_subprog_code(obj, main_prog, subprog);
6410 			if (err)
6411 				return err;
6412 			err = bpf_object__reloc_code(obj, main_prog, subprog);
6413 			if (err)
6414 				return err;
6415 		}
6416 
6417 		/* main_prog->insns memory could have been re-allocated, so
6418 		 * calculate pointer again
6419 		 */
6420 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6421 		/* calculate correct instruction position within current main
6422 		 * prog; each main prog can have a different set of
6423 		 * subprograms appended (potentially in different order as
6424 		 * well), so position of any subprog can be different for
6425 		 * different main programs
6426 		 */
6427 		insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
6428 
6429 		pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
6430 			 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
6431 	}
6432 
6433 	return 0;
6434 }
6435 
6436 /*
6437  * Relocate sub-program calls.
6438  *
6439  * Algorithm operates as follows. Each entry-point BPF program (referred to as
6440  * main prog) is processed separately. For each subprog (non-entry functions,
6441  * that can be called from either entry progs or other subprogs) gets their
6442  * sub_insn_off reset to zero. This serves as indicator that this subprogram
6443  * hasn't been yet appended and relocated within current main prog. Once its
6444  * relocated, sub_insn_off will point at the position within current main prog
6445  * where given subprog was appended. This will further be used to relocate all
6446  * the call instructions jumping into this subprog.
6447  *
6448  * We start with main program and process all call instructions. If the call
6449  * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
6450  * is zero), subprog instructions are appended at the end of main program's
6451  * instruction array. Then main program is "put on hold" while we recursively
6452  * process newly appended subprogram. If that subprogram calls into another
6453  * subprogram that hasn't been appended, new subprogram is appended again to
6454  * the *main* prog's instructions (subprog's instructions are always left
6455  * untouched, as they need to be in unmodified state for subsequent main progs
6456  * and subprog instructions are always sent only as part of a main prog) and
6457  * the process continues recursively. Once all the subprogs called from a main
6458  * prog or any of its subprogs are appended (and relocated), all their
6459  * positions within finalized instructions array are known, so it's easy to
6460  * rewrite call instructions with correct relative offsets, corresponding to
6461  * desired target subprog.
6462  *
6463  * Its important to realize that some subprogs might not be called from some
6464  * main prog and any of its called/used subprogs. Those will keep their
6465  * subprog->sub_insn_off as zero at all times and won't be appended to current
6466  * main prog and won't be relocated within the context of current main prog.
6467  * They might still be used from other main progs later.
6468  *
6469  * Visually this process can be shown as below. Suppose we have two main
6470  * programs mainA and mainB and BPF object contains three subprogs: subA,
6471  * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
6472  * subC both call subB:
6473  *
6474  *        +--------+ +-------+
6475  *        |        v v       |
6476  *     +--+---+ +--+-+-+ +---+--+
6477  *     | subA | | subB | | subC |
6478  *     +--+---+ +------+ +---+--+
6479  *        ^                  ^
6480  *        |                  |
6481  *    +---+-------+   +------+----+
6482  *    |   mainA   |   |   mainB   |
6483  *    +-----------+   +-----------+
6484  *
6485  * We'll start relocating mainA, will find subA, append it and start
6486  * processing sub A recursively:
6487  *
6488  *    +-----------+------+
6489  *    |   mainA   | subA |
6490  *    +-----------+------+
6491  *
6492  * At this point we notice that subB is used from subA, so we append it and
6493  * relocate (there are no further subcalls from subB):
6494  *
6495  *    +-----------+------+------+
6496  *    |   mainA   | subA | subB |
6497  *    +-----------+------+------+
6498  *
6499  * At this point, we relocate subA calls, then go one level up and finish with
6500  * relocatin mainA calls. mainA is done.
6501  *
6502  * For mainB process is similar but results in different order. We start with
6503  * mainB and skip subA and subB, as mainB never calls them (at least
6504  * directly), but we see subC is needed, so we append and start processing it:
6505  *
6506  *    +-----------+------+
6507  *    |   mainB   | subC |
6508  *    +-----------+------+
6509  * Now we see subC needs subB, so we go back to it, append and relocate it:
6510  *
6511  *    +-----------+------+------+
6512  *    |   mainB   | subC | subB |
6513  *    +-----------+------+------+
6514  *
6515  * At this point we unwind recursion, relocate calls in subC, then in mainB.
6516  */
6517 static int
6518 bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
6519 {
6520 	struct bpf_program *subprog;
6521 	int i, err;
6522 
6523 	/* mark all subprogs as not relocated (yet) within the context of
6524 	 * current main program
6525 	 */
6526 	for (i = 0; i < obj->nr_programs; i++) {
6527 		subprog = &obj->programs[i];
6528 		if (!prog_is_subprog(obj, subprog))
6529 			continue;
6530 
6531 		subprog->sub_insn_off = 0;
6532 	}
6533 
6534 	err = bpf_object__reloc_code(obj, prog, prog);
6535 	if (err)
6536 		return err;
6537 
6538 	return 0;
6539 }
6540 
6541 static void
6542 bpf_object__free_relocs(struct bpf_object *obj)
6543 {
6544 	struct bpf_program *prog;
6545 	int i;
6546 
6547 	/* free up relocation descriptors */
6548 	for (i = 0; i < obj->nr_programs; i++) {
6549 		prog = &obj->programs[i];
6550 		zfree(&prog->reloc_desc);
6551 		prog->nr_reloc = 0;
6552 	}
6553 }
6554 
6555 static int cmp_relocs(const void *_a, const void *_b)
6556 {
6557 	const struct reloc_desc *a = _a;
6558 	const struct reloc_desc *b = _b;
6559 
6560 	if (a->insn_idx != b->insn_idx)
6561 		return a->insn_idx < b->insn_idx ? -1 : 1;
6562 
6563 	/* no two relocations should have the same insn_idx, but ... */
6564 	if (a->type != b->type)
6565 		return a->type < b->type ? -1 : 1;
6566 
6567 	return 0;
6568 }
6569 
6570 static void bpf_object__sort_relos(struct bpf_object *obj)
6571 {
6572 	int i;
6573 
6574 	for (i = 0; i < obj->nr_programs; i++) {
6575 		struct bpf_program *p = &obj->programs[i];
6576 
6577 		if (!p->nr_reloc)
6578 			continue;
6579 
6580 		qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
6581 	}
6582 }
6583 
6584 static int bpf_prog_assign_exc_cb(struct bpf_object *obj, struct bpf_program *prog)
6585 {
6586 	const char *str = "exception_callback:";
6587 	size_t pfx_len = strlen(str);
6588 	int i, j, n;
6589 
6590 	if (!obj->btf || !kernel_supports(obj, FEAT_BTF_DECL_TAG))
6591 		return 0;
6592 
6593 	n = btf__type_cnt(obj->btf);
6594 	for (i = 1; i < n; i++) {
6595 		const char *name;
6596 		struct btf_type *t;
6597 
6598 		t = btf_type_by_id(obj->btf, i);
6599 		if (!btf_is_decl_tag(t) || btf_decl_tag(t)->component_idx != -1)
6600 			continue;
6601 
6602 		name = btf__str_by_offset(obj->btf, t->name_off);
6603 		if (strncmp(name, str, pfx_len) != 0)
6604 			continue;
6605 
6606 		t = btf_type_by_id(obj->btf, t->type);
6607 		if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
6608 			pr_warn("prog '%s': exception_callback:<value> decl tag not applied to the main program\n",
6609 				prog->name);
6610 			return -EINVAL;
6611 		}
6612 		if (strcmp(prog->name, btf__str_by_offset(obj->btf, t->name_off)) != 0)
6613 			continue;
6614 		/* Multiple callbacks are specified for the same prog,
6615 		 * the verifier will eventually return an error for this
6616 		 * case, hence simply skip appending a subprog.
6617 		 */
6618 		if (prog->exception_cb_idx >= 0) {
6619 			prog->exception_cb_idx = -1;
6620 			break;
6621 		}
6622 
6623 		name += pfx_len;
6624 		if (str_is_empty(name)) {
6625 			pr_warn("prog '%s': exception_callback:<value> decl tag contains empty value\n",
6626 				prog->name);
6627 			return -EINVAL;
6628 		}
6629 
6630 		for (j = 0; j < obj->nr_programs; j++) {
6631 			struct bpf_program *subprog = &obj->programs[j];
6632 
6633 			if (!prog_is_subprog(obj, subprog))
6634 				continue;
6635 			if (strcmp(name, subprog->name) != 0)
6636 				continue;
6637 			/* Enforce non-hidden, as from verifier point of
6638 			 * view it expects global functions, whereas the
6639 			 * mark_btf_static fixes up linkage as static.
6640 			 */
6641 			if (!subprog->sym_global || subprog->mark_btf_static) {
6642 				pr_warn("prog '%s': exception callback %s must be a global non-hidden function\n",
6643 					prog->name, subprog->name);
6644 				return -EINVAL;
6645 			}
6646 			/* Let's see if we already saw a static exception callback with the same name */
6647 			if (prog->exception_cb_idx >= 0) {
6648 				pr_warn("prog '%s': multiple subprogs with same name as exception callback '%s'\n",
6649 					prog->name, subprog->name);
6650 				return -EINVAL;
6651 			}
6652 			prog->exception_cb_idx = j;
6653 			break;
6654 		}
6655 
6656 		if (prog->exception_cb_idx >= 0)
6657 			continue;
6658 
6659 		pr_warn("prog '%s': cannot find exception callback '%s'\n", prog->name, name);
6660 		return -ENOENT;
6661 	}
6662 
6663 	return 0;
6664 }
6665 
6666 static struct {
6667 	enum bpf_prog_type prog_type;
6668 	const char *ctx_name;
6669 } global_ctx_map[] = {
6670 	{ BPF_PROG_TYPE_CGROUP_DEVICE,           "bpf_cgroup_dev_ctx" },
6671 	{ BPF_PROG_TYPE_CGROUP_SKB,              "__sk_buff" },
6672 	{ BPF_PROG_TYPE_CGROUP_SOCK,             "bpf_sock" },
6673 	{ BPF_PROG_TYPE_CGROUP_SOCK_ADDR,        "bpf_sock_addr" },
6674 	{ BPF_PROG_TYPE_CGROUP_SOCKOPT,          "bpf_sockopt" },
6675 	{ BPF_PROG_TYPE_CGROUP_SYSCTL,           "bpf_sysctl" },
6676 	{ BPF_PROG_TYPE_FLOW_DISSECTOR,          "__sk_buff" },
6677 	{ BPF_PROG_TYPE_KPROBE,                  "bpf_user_pt_regs_t" },
6678 	{ BPF_PROG_TYPE_LWT_IN,                  "__sk_buff" },
6679 	{ BPF_PROG_TYPE_LWT_OUT,                 "__sk_buff" },
6680 	{ BPF_PROG_TYPE_LWT_SEG6LOCAL,           "__sk_buff" },
6681 	{ BPF_PROG_TYPE_LWT_XMIT,                "__sk_buff" },
6682 	{ BPF_PROG_TYPE_NETFILTER,               "bpf_nf_ctx" },
6683 	{ BPF_PROG_TYPE_PERF_EVENT,              "bpf_perf_event_data" },
6684 	{ BPF_PROG_TYPE_RAW_TRACEPOINT,          "bpf_raw_tracepoint_args" },
6685 	{ BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE, "bpf_raw_tracepoint_args" },
6686 	{ BPF_PROG_TYPE_SCHED_ACT,               "__sk_buff" },
6687 	{ BPF_PROG_TYPE_SCHED_CLS,               "__sk_buff" },
6688 	{ BPF_PROG_TYPE_SK_LOOKUP,               "bpf_sk_lookup" },
6689 	{ BPF_PROG_TYPE_SK_MSG,                  "sk_msg_md" },
6690 	{ BPF_PROG_TYPE_SK_REUSEPORT,            "sk_reuseport_md" },
6691 	{ BPF_PROG_TYPE_SK_SKB,                  "__sk_buff" },
6692 	{ BPF_PROG_TYPE_SOCK_OPS,                "bpf_sock_ops" },
6693 	{ BPF_PROG_TYPE_SOCKET_FILTER,           "__sk_buff" },
6694 	{ BPF_PROG_TYPE_XDP,                     "xdp_md" },
6695 	/* all other program types don't have "named" context structs */
6696 };
6697 
6698 static int clone_func_btf_info(struct btf *btf, int orig_fn_id, struct bpf_program *prog)
6699 {
6700 	int fn_id, fn_proto_id, ret_type_id, orig_proto_id;
6701 	int i, err, arg_cnt, fn_name_off, linkage;
6702 	struct btf_type *fn_t, *fn_proto_t, *t;
6703 	struct btf_param *p;
6704 
6705 	/* caller already validated FUNC -> FUNC_PROTO validity */
6706 	fn_t = btf_type_by_id(btf, orig_fn_id);
6707 	fn_proto_t = btf_type_by_id(btf, fn_t->type);
6708 
6709 	/* Note that each btf__add_xxx() operation invalidates
6710 	 * all btf_type and string pointers, so we need to be
6711 	 * very careful when cloning BTF types. BTF type
6712 	 * pointers have to be always refetched. And to avoid
6713 	 * problems with invalidated string pointers, we
6714 	 * add empty strings initially, then just fix up
6715 	 * name_off offsets in place. Offsets are stable for
6716 	 * existing strings, so that works out.
6717 	 */
6718 	fn_name_off = fn_t->name_off; /* we are about to invalidate fn_t */
6719 	linkage = btf_func_linkage(fn_t);
6720 	orig_proto_id = fn_t->type; /* original FUNC_PROTO ID */
6721 	ret_type_id = fn_proto_t->type; /* fn_proto_t will be invalidated */
6722 	arg_cnt = btf_vlen(fn_proto_t);
6723 
6724 	/* clone FUNC_PROTO and its params */
6725 	fn_proto_id = btf__add_func_proto(btf, ret_type_id);
6726 	if (fn_proto_id < 0)
6727 		return -EINVAL;
6728 
6729 	for (i = 0; i < arg_cnt; i++) {
6730 		int name_off;
6731 
6732 		/* copy original parameter data */
6733 		t = btf_type_by_id(btf, orig_proto_id);
6734 		p = &btf_params(t)[i];
6735 		name_off = p->name_off;
6736 
6737 		err = btf__add_func_param(btf, "", p->type);
6738 		if (err)
6739 			return err;
6740 
6741 		fn_proto_t = btf_type_by_id(btf, fn_proto_id);
6742 		p = &btf_params(fn_proto_t)[i];
6743 		p->name_off = name_off; /* use remembered str offset */
6744 	}
6745 
6746 	/* clone FUNC now, btf__add_func() enforces non-empty name, so use
6747 	 * entry program's name as a placeholder, which we replace immediately
6748 	 * with original name_off
6749 	 */
6750 	fn_id = btf__add_func(btf, prog->name, linkage, fn_proto_id);
6751 	if (fn_id < 0)
6752 		return -EINVAL;
6753 
6754 	fn_t = btf_type_by_id(btf, fn_id);
6755 	fn_t->name_off = fn_name_off; /* reuse original string */
6756 
6757 	return fn_id;
6758 }
6759 
6760 /* Check if main program or global subprog's function prototype has `arg:ctx`
6761  * argument tags, and, if necessary, substitute correct type to match what BPF
6762  * verifier would expect, taking into account specific program type. This
6763  * allows to support __arg_ctx tag transparently on old kernels that don't yet
6764  * have a native support for it in the verifier, making user's life much
6765  * easier.
6766  */
6767 static int bpf_program_fixup_func_info(struct bpf_object *obj, struct bpf_program *prog)
6768 {
6769 	const char *ctx_name = NULL, *ctx_tag = "arg:ctx";
6770 	struct bpf_func_info_min *func_rec;
6771 	struct btf_type *fn_t, *fn_proto_t;
6772 	struct btf *btf = obj->btf;
6773 	const struct btf_type *t;
6774 	struct btf_param *p;
6775 	int ptr_id = 0, struct_id, tag_id, orig_fn_id;
6776 	int i, n, arg_idx, arg_cnt, err, rec_idx;
6777 	int *orig_ids;
6778 
6779 	/* no .BTF.ext, no problem */
6780 	if (!obj->btf_ext || !prog->func_info)
6781 		return 0;
6782 
6783 	/* some BPF program types just don't have named context structs, so
6784 	 * this fallback mechanism doesn't work for them
6785 	 */
6786 	for (i = 0; i < ARRAY_SIZE(global_ctx_map); i++) {
6787 		if (global_ctx_map[i].prog_type != prog->type)
6788 			continue;
6789 		ctx_name = global_ctx_map[i].ctx_name;
6790 		break;
6791 	}
6792 	if (!ctx_name)
6793 		return 0;
6794 
6795 	/* remember original func BTF IDs to detect if we already cloned them */
6796 	orig_ids = calloc(prog->func_info_cnt, sizeof(*orig_ids));
6797 	if (!orig_ids)
6798 		return -ENOMEM;
6799 	for (i = 0; i < prog->func_info_cnt; i++) {
6800 		func_rec = prog->func_info + prog->func_info_rec_size * i;
6801 		orig_ids[i] = func_rec->type_id;
6802 	}
6803 
6804 	/* go through each DECL_TAG with "arg:ctx" and see if it points to one
6805 	 * of our subprogs; if yes and subprog is global and needs adjustment,
6806 	 * clone and adjust FUNC -> FUNC_PROTO combo
6807 	 */
6808 	for (i = 1, n = btf__type_cnt(btf); i < n; i++) {
6809 		/* only DECL_TAG with "arg:ctx" value are interesting */
6810 		t = btf__type_by_id(btf, i);
6811 		if (!btf_is_decl_tag(t))
6812 			continue;
6813 		if (strcmp(btf__str_by_offset(btf, t->name_off), ctx_tag) != 0)
6814 			continue;
6815 
6816 		/* only global funcs need adjustment, if at all */
6817 		orig_fn_id = t->type;
6818 		fn_t = btf_type_by_id(btf, orig_fn_id);
6819 		if (!btf_is_func(fn_t) || btf_func_linkage(fn_t) != BTF_FUNC_GLOBAL)
6820 			continue;
6821 
6822 		/* sanity check FUNC -> FUNC_PROTO chain, just in case */
6823 		fn_proto_t = btf_type_by_id(btf, fn_t->type);
6824 		if (!fn_proto_t || !btf_is_func_proto(fn_proto_t))
6825 			continue;
6826 
6827 		/* find corresponding func_info record */
6828 		func_rec = NULL;
6829 		for (rec_idx = 0; rec_idx < prog->func_info_cnt; rec_idx++) {
6830 			if (orig_ids[rec_idx] == t->type) {
6831 				func_rec = prog->func_info + prog->func_info_rec_size * rec_idx;
6832 				break;
6833 			}
6834 		}
6835 		/* current main program doesn't call into this subprog */
6836 		if (!func_rec)
6837 			continue;
6838 
6839 		/* some more sanity checking of DECL_TAG */
6840 		arg_cnt = btf_vlen(fn_proto_t);
6841 		arg_idx = btf_decl_tag(t)->component_idx;
6842 		if (arg_idx < 0 || arg_idx >= arg_cnt)
6843 			continue;
6844 
6845 		/* check if existing parameter already matches verifier expectations */
6846 		p = &btf_params(fn_proto_t)[arg_idx];
6847 		t = skip_mods_and_typedefs(btf, p->type, NULL);
6848 		if (btf_is_ptr(t) &&
6849 		    (t = skip_mods_and_typedefs(btf, t->type, NULL)) &&
6850 		    btf_is_struct(t) &&
6851 		    strcmp(btf__str_by_offset(btf, t->name_off), ctx_name) == 0) {
6852 			continue; /* no need for fix up */
6853 		}
6854 
6855 		/* clone fn/fn_proto, unless we already did it for another arg */
6856 		if (func_rec->type_id == orig_fn_id) {
6857 			int fn_id;
6858 
6859 			fn_id = clone_func_btf_info(btf, orig_fn_id, prog);
6860 			if (fn_id < 0) {
6861 				err = fn_id;
6862 				goto err_out;
6863 			}
6864 
6865 			/* point func_info record to a cloned FUNC type */
6866 			func_rec->type_id = fn_id;
6867 		}
6868 
6869 		/* create PTR -> STRUCT type chain to mark PTR_TO_CTX argument;
6870 		 * we do it just once per main BPF program, as all global
6871 		 * funcs share the same program type, so need only PTR ->
6872 		 * STRUCT type chain
6873 		 */
6874 		if (ptr_id == 0) {
6875 			struct_id = btf__add_struct(btf, ctx_name, 0);
6876 			ptr_id = btf__add_ptr(btf, struct_id);
6877 			if (ptr_id < 0 || struct_id < 0) {
6878 				err = -EINVAL;
6879 				goto err_out;
6880 			}
6881 		}
6882 
6883 		/* for completeness, clone DECL_TAG and point it to cloned param */
6884 		tag_id = btf__add_decl_tag(btf, ctx_tag, func_rec->type_id, arg_idx);
6885 		if (tag_id < 0) {
6886 			err = -EINVAL;
6887 			goto err_out;
6888 		}
6889 
6890 		/* all the BTF manipulations invalidated pointers, refetch them */
6891 		fn_t = btf_type_by_id(btf, func_rec->type_id);
6892 		fn_proto_t = btf_type_by_id(btf, fn_t->type);
6893 
6894 		/* fix up type ID pointed to by param */
6895 		p = &btf_params(fn_proto_t)[arg_idx];
6896 		p->type = ptr_id;
6897 	}
6898 
6899 	free(orig_ids);
6900 	return 0;
6901 err_out:
6902 	free(orig_ids);
6903 	return err;
6904 }
6905 
6906 static int bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
6907 {
6908 	struct bpf_program *prog;
6909 	size_t i, j;
6910 	int err;
6911 
6912 	if (obj->btf_ext) {
6913 		err = bpf_object__relocate_core(obj, targ_btf_path);
6914 		if (err) {
6915 			pr_warn("failed to perform CO-RE relocations: %d\n",
6916 				err);
6917 			return err;
6918 		}
6919 		bpf_object__sort_relos(obj);
6920 	}
6921 
6922 	/* Before relocating calls pre-process relocations and mark
6923 	 * few ld_imm64 instructions that points to subprogs.
6924 	 * Otherwise bpf_object__reloc_code() later would have to consider
6925 	 * all ld_imm64 insns as relocation candidates. That would
6926 	 * reduce relocation speed, since amount of find_prog_insn_relo()
6927 	 * would increase and most of them will fail to find a relo.
6928 	 */
6929 	for (i = 0; i < obj->nr_programs; i++) {
6930 		prog = &obj->programs[i];
6931 		for (j = 0; j < prog->nr_reloc; j++) {
6932 			struct reloc_desc *relo = &prog->reloc_desc[j];
6933 			struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6934 
6935 			/* mark the insn, so it's recognized by insn_is_pseudo_func() */
6936 			if (relo->type == RELO_SUBPROG_ADDR)
6937 				insn[0].src_reg = BPF_PSEUDO_FUNC;
6938 		}
6939 	}
6940 
6941 	/* relocate subprogram calls and append used subprograms to main
6942 	 * programs; each copy of subprogram code needs to be relocated
6943 	 * differently for each main program, because its code location might
6944 	 * have changed.
6945 	 * Append subprog relos to main programs to allow data relos to be
6946 	 * processed after text is completely relocated.
6947 	 */
6948 	for (i = 0; i < obj->nr_programs; i++) {
6949 		prog = &obj->programs[i];
6950 		/* sub-program's sub-calls are relocated within the context of
6951 		 * its main program only
6952 		 */
6953 		if (prog_is_subprog(obj, prog))
6954 			continue;
6955 		if (!prog->autoload)
6956 			continue;
6957 
6958 		err = bpf_object__relocate_calls(obj, prog);
6959 		if (err) {
6960 			pr_warn("prog '%s': failed to relocate calls: %d\n",
6961 				prog->name, err);
6962 			return err;
6963 		}
6964 
6965 		err = bpf_prog_assign_exc_cb(obj, prog);
6966 		if (err)
6967 			return err;
6968 		/* Now, also append exception callback if it has not been done already. */
6969 		if (prog->exception_cb_idx >= 0) {
6970 			struct bpf_program *subprog = &obj->programs[prog->exception_cb_idx];
6971 
6972 			/* Calling exception callback directly is disallowed, which the
6973 			 * verifier will reject later. In case it was processed already,
6974 			 * we can skip this step, otherwise for all other valid cases we
6975 			 * have to append exception callback now.
6976 			 */
6977 			if (subprog->sub_insn_off == 0) {
6978 				err = bpf_object__append_subprog_code(obj, prog, subprog);
6979 				if (err)
6980 					return err;
6981 				err = bpf_object__reloc_code(obj, prog, subprog);
6982 				if (err)
6983 					return err;
6984 			}
6985 		}
6986 	}
6987 	for (i = 0; i < obj->nr_programs; i++) {
6988 		prog = &obj->programs[i];
6989 		if (prog_is_subprog(obj, prog))
6990 			continue;
6991 		if (!prog->autoload)
6992 			continue;
6993 
6994 		/* Process data relos for main programs */
6995 		err = bpf_object__relocate_data(obj, prog);
6996 		if (err) {
6997 			pr_warn("prog '%s': failed to relocate data references: %d\n",
6998 				prog->name, err);
6999 			return err;
7000 		}
7001 
7002 		/* Fix up .BTF.ext information, if necessary */
7003 		err = bpf_program_fixup_func_info(obj, prog);
7004 		if (err) {
7005 			pr_warn("prog '%s': failed to perform .BTF.ext fix ups: %d\n",
7006 				prog->name, err);
7007 			return err;
7008 		}
7009 	}
7010 
7011 	return 0;
7012 }
7013 
7014 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
7015 					    Elf64_Shdr *shdr, Elf_Data *data);
7016 
7017 static int bpf_object__collect_map_relos(struct bpf_object *obj,
7018 					 Elf64_Shdr *shdr, Elf_Data *data)
7019 {
7020 	const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
7021 	int i, j, nrels, new_sz;
7022 	const struct btf_var_secinfo *vi = NULL;
7023 	const struct btf_type *sec, *var, *def;
7024 	struct bpf_map *map = NULL, *targ_map = NULL;
7025 	struct bpf_program *targ_prog = NULL;
7026 	bool is_prog_array, is_map_in_map;
7027 	const struct btf_member *member;
7028 	const char *name, *mname, *type;
7029 	unsigned int moff;
7030 	Elf64_Sym *sym;
7031 	Elf64_Rel *rel;
7032 	void *tmp;
7033 
7034 	if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
7035 		return -EINVAL;
7036 	sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
7037 	if (!sec)
7038 		return -EINVAL;
7039 
7040 	nrels = shdr->sh_size / shdr->sh_entsize;
7041 	for (i = 0; i < nrels; i++) {
7042 		rel = elf_rel_by_idx(data, i);
7043 		if (!rel) {
7044 			pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
7045 			return -LIBBPF_ERRNO__FORMAT;
7046 		}
7047 
7048 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
7049 		if (!sym) {
7050 			pr_warn(".maps relo #%d: symbol %zx not found\n",
7051 				i, (size_t)ELF64_R_SYM(rel->r_info));
7052 			return -LIBBPF_ERRNO__FORMAT;
7053 		}
7054 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
7055 
7056 		pr_debug(".maps relo #%d: for %zd value %zd rel->r_offset %zu name %d ('%s')\n",
7057 			 i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
7058 			 (size_t)rel->r_offset, sym->st_name, name);
7059 
7060 		for (j = 0; j < obj->nr_maps; j++) {
7061 			map = &obj->maps[j];
7062 			if (map->sec_idx != obj->efile.btf_maps_shndx)
7063 				continue;
7064 
7065 			vi = btf_var_secinfos(sec) + map->btf_var_idx;
7066 			if (vi->offset <= rel->r_offset &&
7067 			    rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size)
7068 				break;
7069 		}
7070 		if (j == obj->nr_maps) {
7071 			pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
7072 				i, name, (size_t)rel->r_offset);
7073 			return -EINVAL;
7074 		}
7075 
7076 		is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
7077 		is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
7078 		type = is_map_in_map ? "map" : "prog";
7079 		if (is_map_in_map) {
7080 			if (sym->st_shndx != obj->efile.btf_maps_shndx) {
7081 				pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
7082 					i, name);
7083 				return -LIBBPF_ERRNO__RELOC;
7084 			}
7085 			if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
7086 			    map->def.key_size != sizeof(int)) {
7087 				pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
7088 					i, map->name, sizeof(int));
7089 				return -EINVAL;
7090 			}
7091 			targ_map = bpf_object__find_map_by_name(obj, name);
7092 			if (!targ_map) {
7093 				pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
7094 					i, name);
7095 				return -ESRCH;
7096 			}
7097 		} else if (is_prog_array) {
7098 			targ_prog = bpf_object__find_program_by_name(obj, name);
7099 			if (!targ_prog) {
7100 				pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
7101 					i, name);
7102 				return -ESRCH;
7103 			}
7104 			if (targ_prog->sec_idx != sym->st_shndx ||
7105 			    targ_prog->sec_insn_off * 8 != sym->st_value ||
7106 			    prog_is_subprog(obj, targ_prog)) {
7107 				pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
7108 					i, name);
7109 				return -LIBBPF_ERRNO__RELOC;
7110 			}
7111 		} else {
7112 			return -EINVAL;
7113 		}
7114 
7115 		var = btf__type_by_id(obj->btf, vi->type);
7116 		def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
7117 		if (btf_vlen(def) == 0)
7118 			return -EINVAL;
7119 		member = btf_members(def) + btf_vlen(def) - 1;
7120 		mname = btf__name_by_offset(obj->btf, member->name_off);
7121 		if (strcmp(mname, "values"))
7122 			return -EINVAL;
7123 
7124 		moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
7125 		if (rel->r_offset - vi->offset < moff)
7126 			return -EINVAL;
7127 
7128 		moff = rel->r_offset - vi->offset - moff;
7129 		/* here we use BPF pointer size, which is always 64 bit, as we
7130 		 * are parsing ELF that was built for BPF target
7131 		 */
7132 		if (moff % bpf_ptr_sz)
7133 			return -EINVAL;
7134 		moff /= bpf_ptr_sz;
7135 		if (moff >= map->init_slots_sz) {
7136 			new_sz = moff + 1;
7137 			tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
7138 			if (!tmp)
7139 				return -ENOMEM;
7140 			map->init_slots = tmp;
7141 			memset(map->init_slots + map->init_slots_sz, 0,
7142 			       (new_sz - map->init_slots_sz) * host_ptr_sz);
7143 			map->init_slots_sz = new_sz;
7144 		}
7145 		map->init_slots[moff] = is_map_in_map ? (void *)targ_map : (void *)targ_prog;
7146 
7147 		pr_debug(".maps relo #%d: map '%s' slot [%d] points to %s '%s'\n",
7148 			 i, map->name, moff, type, name);
7149 	}
7150 
7151 	return 0;
7152 }
7153 
7154 static int bpf_object__collect_relos(struct bpf_object *obj)
7155 {
7156 	int i, err;
7157 
7158 	for (i = 0; i < obj->efile.sec_cnt; i++) {
7159 		struct elf_sec_desc *sec_desc = &obj->efile.secs[i];
7160 		Elf64_Shdr *shdr;
7161 		Elf_Data *data;
7162 		int idx;
7163 
7164 		if (sec_desc->sec_type != SEC_RELO)
7165 			continue;
7166 
7167 		shdr = sec_desc->shdr;
7168 		data = sec_desc->data;
7169 		idx = shdr->sh_info;
7170 
7171 		if (shdr->sh_type != SHT_REL) {
7172 			pr_warn("internal error at %d\n", __LINE__);
7173 			return -LIBBPF_ERRNO__INTERNAL;
7174 		}
7175 
7176 		if (idx == obj->efile.st_ops_shndx || idx == obj->efile.st_ops_link_shndx)
7177 			err = bpf_object__collect_st_ops_relos(obj, shdr, data);
7178 		else if (idx == obj->efile.btf_maps_shndx)
7179 			err = bpf_object__collect_map_relos(obj, shdr, data);
7180 		else
7181 			err = bpf_object__collect_prog_relos(obj, shdr, data);
7182 		if (err)
7183 			return err;
7184 	}
7185 
7186 	bpf_object__sort_relos(obj);
7187 	return 0;
7188 }
7189 
7190 static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
7191 {
7192 	if (BPF_CLASS(insn->code) == BPF_JMP &&
7193 	    BPF_OP(insn->code) == BPF_CALL &&
7194 	    BPF_SRC(insn->code) == BPF_K &&
7195 	    insn->src_reg == 0 &&
7196 	    insn->dst_reg == 0) {
7197 		    *func_id = insn->imm;
7198 		    return true;
7199 	}
7200 	return false;
7201 }
7202 
7203 static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
7204 {
7205 	struct bpf_insn *insn = prog->insns;
7206 	enum bpf_func_id func_id;
7207 	int i;
7208 
7209 	if (obj->gen_loader)
7210 		return 0;
7211 
7212 	for (i = 0; i < prog->insns_cnt; i++, insn++) {
7213 		if (!insn_is_helper_call(insn, &func_id))
7214 			continue;
7215 
7216 		/* on kernels that don't yet support
7217 		 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
7218 		 * to bpf_probe_read() which works well for old kernels
7219 		 */
7220 		switch (func_id) {
7221 		case BPF_FUNC_probe_read_kernel:
7222 		case BPF_FUNC_probe_read_user:
7223 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
7224 				insn->imm = BPF_FUNC_probe_read;
7225 			break;
7226 		case BPF_FUNC_probe_read_kernel_str:
7227 		case BPF_FUNC_probe_read_user_str:
7228 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
7229 				insn->imm = BPF_FUNC_probe_read_str;
7230 			break;
7231 		default:
7232 			break;
7233 		}
7234 	}
7235 	return 0;
7236 }
7237 
7238 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
7239 				     int *btf_obj_fd, int *btf_type_id);
7240 
7241 /* this is called as prog->sec_def->prog_prepare_load_fn for libbpf-supported sec_defs */
7242 static int libbpf_prepare_prog_load(struct bpf_program *prog,
7243 				    struct bpf_prog_load_opts *opts, long cookie)
7244 {
7245 	enum sec_def_flags def = cookie;
7246 
7247 	/* old kernels might not support specifying expected_attach_type */
7248 	if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
7249 		opts->expected_attach_type = 0;
7250 
7251 	if (def & SEC_SLEEPABLE)
7252 		opts->prog_flags |= BPF_F_SLEEPABLE;
7253 
7254 	if (prog->type == BPF_PROG_TYPE_XDP && (def & SEC_XDP_FRAGS))
7255 		opts->prog_flags |= BPF_F_XDP_HAS_FRAGS;
7256 
7257 	/* special check for usdt to use uprobe_multi link */
7258 	if ((def & SEC_USDT) && kernel_supports(prog->obj, FEAT_UPROBE_MULTI_LINK))
7259 		prog->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
7260 
7261 	if ((def & SEC_ATTACH_BTF) && !prog->attach_btf_id) {
7262 		int btf_obj_fd = 0, btf_type_id = 0, err;
7263 		const char *attach_name;
7264 
7265 		attach_name = strchr(prog->sec_name, '/');
7266 		if (!attach_name) {
7267 			/* if BPF program is annotated with just SEC("fentry")
7268 			 * (or similar) without declaratively specifying
7269 			 * target, then it is expected that target will be
7270 			 * specified with bpf_program__set_attach_target() at
7271 			 * runtime before BPF object load step. If not, then
7272 			 * there is nothing to load into the kernel as BPF
7273 			 * verifier won't be able to validate BPF program
7274 			 * correctness anyways.
7275 			 */
7276 			pr_warn("prog '%s': no BTF-based attach target is specified, use bpf_program__set_attach_target()\n",
7277 				prog->name);
7278 			return -EINVAL;
7279 		}
7280 		attach_name++; /* skip over / */
7281 
7282 		err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
7283 		if (err)
7284 			return err;
7285 
7286 		/* cache resolved BTF FD and BTF type ID in the prog */
7287 		prog->attach_btf_obj_fd = btf_obj_fd;
7288 		prog->attach_btf_id = btf_type_id;
7289 
7290 		/* but by now libbpf common logic is not utilizing
7291 		 * prog->atach_btf_obj_fd/prog->attach_btf_id anymore because
7292 		 * this callback is called after opts were populated by
7293 		 * libbpf, so this callback has to update opts explicitly here
7294 		 */
7295 		opts->attach_btf_obj_fd = btf_obj_fd;
7296 		opts->attach_btf_id = btf_type_id;
7297 	}
7298 	return 0;
7299 }
7300 
7301 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz);
7302 
7303 static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
7304 				struct bpf_insn *insns, int insns_cnt,
7305 				const char *license, __u32 kern_version, int *prog_fd)
7306 {
7307 	LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
7308 	const char *prog_name = NULL;
7309 	char *cp, errmsg[STRERR_BUFSIZE];
7310 	size_t log_buf_size = 0;
7311 	char *log_buf = NULL, *tmp;
7312 	int btf_fd, ret, err;
7313 	bool own_log_buf = true;
7314 	__u32 log_level = prog->log_level;
7315 
7316 	if (prog->type == BPF_PROG_TYPE_UNSPEC) {
7317 		/*
7318 		 * The program type must be set.  Most likely we couldn't find a proper
7319 		 * section definition at load time, and thus we didn't infer the type.
7320 		 */
7321 		pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
7322 			prog->name, prog->sec_name);
7323 		return -EINVAL;
7324 	}
7325 
7326 	if (!insns || !insns_cnt)
7327 		return -EINVAL;
7328 
7329 	if (kernel_supports(obj, FEAT_PROG_NAME))
7330 		prog_name = prog->name;
7331 	load_attr.attach_prog_fd = prog->attach_prog_fd;
7332 	load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
7333 	load_attr.attach_btf_id = prog->attach_btf_id;
7334 	load_attr.kern_version = kern_version;
7335 	load_attr.prog_ifindex = prog->prog_ifindex;
7336 
7337 	/* specify func_info/line_info only if kernel supports them */
7338 	btf_fd = btf__fd(obj->btf);
7339 	if (btf_fd >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
7340 		load_attr.prog_btf_fd = btf_fd;
7341 		load_attr.func_info = prog->func_info;
7342 		load_attr.func_info_rec_size = prog->func_info_rec_size;
7343 		load_attr.func_info_cnt = prog->func_info_cnt;
7344 		load_attr.line_info = prog->line_info;
7345 		load_attr.line_info_rec_size = prog->line_info_rec_size;
7346 		load_attr.line_info_cnt = prog->line_info_cnt;
7347 	}
7348 	load_attr.log_level = log_level;
7349 	load_attr.prog_flags = prog->prog_flags;
7350 	load_attr.fd_array = obj->fd_array;
7351 
7352 	/* adjust load_attr if sec_def provides custom preload callback */
7353 	if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
7354 		err = prog->sec_def->prog_prepare_load_fn(prog, &load_attr, prog->sec_def->cookie);
7355 		if (err < 0) {
7356 			pr_warn("prog '%s': failed to prepare load attributes: %d\n",
7357 				prog->name, err);
7358 			return err;
7359 		}
7360 		insns = prog->insns;
7361 		insns_cnt = prog->insns_cnt;
7362 	}
7363 
7364 	/* allow prog_prepare_load_fn to change expected_attach_type */
7365 	load_attr.expected_attach_type = prog->expected_attach_type;
7366 
7367 	if (obj->gen_loader) {
7368 		bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
7369 				   license, insns, insns_cnt, &load_attr,
7370 				   prog - obj->programs);
7371 		*prog_fd = -1;
7372 		return 0;
7373 	}
7374 
7375 retry_load:
7376 	/* if log_level is zero, we don't request logs initially even if
7377 	 * custom log_buf is specified; if the program load fails, then we'll
7378 	 * bump log_level to 1 and use either custom log_buf or we'll allocate
7379 	 * our own and retry the load to get details on what failed
7380 	 */
7381 	if (log_level) {
7382 		if (prog->log_buf) {
7383 			log_buf = prog->log_buf;
7384 			log_buf_size = prog->log_size;
7385 			own_log_buf = false;
7386 		} else if (obj->log_buf) {
7387 			log_buf = obj->log_buf;
7388 			log_buf_size = obj->log_size;
7389 			own_log_buf = false;
7390 		} else {
7391 			log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
7392 			tmp = realloc(log_buf, log_buf_size);
7393 			if (!tmp) {
7394 				ret = -ENOMEM;
7395 				goto out;
7396 			}
7397 			log_buf = tmp;
7398 			log_buf[0] = '\0';
7399 			own_log_buf = true;
7400 		}
7401 	}
7402 
7403 	load_attr.log_buf = log_buf;
7404 	load_attr.log_size = log_buf_size;
7405 	load_attr.log_level = log_level;
7406 
7407 	ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
7408 	if (ret >= 0) {
7409 		if (log_level && own_log_buf) {
7410 			pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
7411 				 prog->name, log_buf);
7412 		}
7413 
7414 		if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
7415 			struct bpf_map *map;
7416 			int i;
7417 
7418 			for (i = 0; i < obj->nr_maps; i++) {
7419 				map = &prog->obj->maps[i];
7420 				if (map->libbpf_type != LIBBPF_MAP_RODATA)
7421 					continue;
7422 
7423 				if (bpf_prog_bind_map(ret, map->fd, NULL)) {
7424 					cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
7425 					pr_warn("prog '%s': failed to bind map '%s': %s\n",
7426 						prog->name, map->real_name, cp);
7427 					/* Don't fail hard if can't bind rodata. */
7428 				}
7429 			}
7430 		}
7431 
7432 		*prog_fd = ret;
7433 		ret = 0;
7434 		goto out;
7435 	}
7436 
7437 	if (log_level == 0) {
7438 		log_level = 1;
7439 		goto retry_load;
7440 	}
7441 	/* On ENOSPC, increase log buffer size and retry, unless custom
7442 	 * log_buf is specified.
7443 	 * Be careful to not overflow u32, though. Kernel's log buf size limit
7444 	 * isn't part of UAPI so it can always be bumped to full 4GB. So don't
7445 	 * multiply by 2 unless we are sure we'll fit within 32 bits.
7446 	 * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
7447 	 */
7448 	if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
7449 		goto retry_load;
7450 
7451 	ret = -errno;
7452 
7453 	/* post-process verifier log to improve error descriptions */
7454 	fixup_verifier_log(prog, log_buf, log_buf_size);
7455 
7456 	cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
7457 	pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, cp);
7458 	pr_perm_msg(ret);
7459 
7460 	if (own_log_buf && log_buf && log_buf[0] != '\0') {
7461 		pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
7462 			prog->name, log_buf);
7463 	}
7464 
7465 out:
7466 	if (own_log_buf)
7467 		free(log_buf);
7468 	return ret;
7469 }
7470 
7471 static char *find_prev_line(char *buf, char *cur)
7472 {
7473 	char *p;
7474 
7475 	if (cur == buf) /* end of a log buf */
7476 		return NULL;
7477 
7478 	p = cur - 1;
7479 	while (p - 1 >= buf && *(p - 1) != '\n')
7480 		p--;
7481 
7482 	return p;
7483 }
7484 
7485 static void patch_log(char *buf, size_t buf_sz, size_t log_sz,
7486 		      char *orig, size_t orig_sz, const char *patch)
7487 {
7488 	/* size of the remaining log content to the right from the to-be-replaced part */
7489 	size_t rem_sz = (buf + log_sz) - (orig + orig_sz);
7490 	size_t patch_sz = strlen(patch);
7491 
7492 	if (patch_sz != orig_sz) {
7493 		/* If patch line(s) are longer than original piece of verifier log,
7494 		 * shift log contents by (patch_sz - orig_sz) bytes to the right
7495 		 * starting from after to-be-replaced part of the log.
7496 		 *
7497 		 * If patch line(s) are shorter than original piece of verifier log,
7498 		 * shift log contents by (orig_sz - patch_sz) bytes to the left
7499 		 * starting from after to-be-replaced part of the log
7500 		 *
7501 		 * We need to be careful about not overflowing available
7502 		 * buf_sz capacity. If that's the case, we'll truncate the end
7503 		 * of the original log, as necessary.
7504 		 */
7505 		if (patch_sz > orig_sz) {
7506 			if (orig + patch_sz >= buf + buf_sz) {
7507 				/* patch is big enough to cover remaining space completely */
7508 				patch_sz -= (orig + patch_sz) - (buf + buf_sz) + 1;
7509 				rem_sz = 0;
7510 			} else if (patch_sz - orig_sz > buf_sz - log_sz) {
7511 				/* patch causes part of remaining log to be truncated */
7512 				rem_sz -= (patch_sz - orig_sz) - (buf_sz - log_sz);
7513 			}
7514 		}
7515 		/* shift remaining log to the right by calculated amount */
7516 		memmove(orig + patch_sz, orig + orig_sz, rem_sz);
7517 	}
7518 
7519 	memcpy(orig, patch, patch_sz);
7520 }
7521 
7522 static void fixup_log_failed_core_relo(struct bpf_program *prog,
7523 				       char *buf, size_t buf_sz, size_t log_sz,
7524 				       char *line1, char *line2, char *line3)
7525 {
7526 	/* Expected log for failed and not properly guarded CO-RE relocation:
7527 	 * line1 -> 123: (85) call unknown#195896080
7528 	 * line2 -> invalid func unknown#195896080
7529 	 * line3 -> <anything else or end of buffer>
7530 	 *
7531 	 * "123" is the index of the instruction that was poisoned. We extract
7532 	 * instruction index to find corresponding CO-RE relocation and
7533 	 * replace this part of the log with more relevant information about
7534 	 * failed CO-RE relocation.
7535 	 */
7536 	const struct bpf_core_relo *relo;
7537 	struct bpf_core_spec spec;
7538 	char patch[512], spec_buf[256];
7539 	int insn_idx, err, spec_len;
7540 
7541 	if (sscanf(line1, "%d: (%*d) call unknown#195896080\n", &insn_idx) != 1)
7542 		return;
7543 
7544 	relo = find_relo_core(prog, insn_idx);
7545 	if (!relo)
7546 		return;
7547 
7548 	err = bpf_core_parse_spec(prog->name, prog->obj->btf, relo, &spec);
7549 	if (err)
7550 		return;
7551 
7552 	spec_len = bpf_core_format_spec(spec_buf, sizeof(spec_buf), &spec);
7553 	snprintf(patch, sizeof(patch),
7554 		 "%d: <invalid CO-RE relocation>\n"
7555 		 "failed to resolve CO-RE relocation %s%s\n",
7556 		 insn_idx, spec_buf, spec_len >= sizeof(spec_buf) ? "..." : "");
7557 
7558 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7559 }
7560 
7561 static void fixup_log_missing_map_load(struct bpf_program *prog,
7562 				       char *buf, size_t buf_sz, size_t log_sz,
7563 				       char *line1, char *line2, char *line3)
7564 {
7565 	/* Expected log for failed and not properly guarded map reference:
7566 	 * line1 -> 123: (85) call unknown#2001000345
7567 	 * line2 -> invalid func unknown#2001000345
7568 	 * line3 -> <anything else or end of buffer>
7569 	 *
7570 	 * "123" is the index of the instruction that was poisoned.
7571 	 * "345" in "2001000345" is a map index in obj->maps to fetch map name.
7572 	 */
7573 	struct bpf_object *obj = prog->obj;
7574 	const struct bpf_map *map;
7575 	int insn_idx, map_idx;
7576 	char patch[128];
7577 
7578 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &map_idx) != 2)
7579 		return;
7580 
7581 	map_idx -= POISON_LDIMM64_MAP_BASE;
7582 	if (map_idx < 0 || map_idx >= obj->nr_maps)
7583 		return;
7584 	map = &obj->maps[map_idx];
7585 
7586 	snprintf(patch, sizeof(patch),
7587 		 "%d: <invalid BPF map reference>\n"
7588 		 "BPF map '%s' is referenced but wasn't created\n",
7589 		 insn_idx, map->name);
7590 
7591 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7592 }
7593 
7594 static void fixup_log_missing_kfunc_call(struct bpf_program *prog,
7595 					 char *buf, size_t buf_sz, size_t log_sz,
7596 					 char *line1, char *line2, char *line3)
7597 {
7598 	/* Expected log for failed and not properly guarded kfunc call:
7599 	 * line1 -> 123: (85) call unknown#2002000345
7600 	 * line2 -> invalid func unknown#2002000345
7601 	 * line3 -> <anything else or end of buffer>
7602 	 *
7603 	 * "123" is the index of the instruction that was poisoned.
7604 	 * "345" in "2002000345" is an extern index in obj->externs to fetch kfunc name.
7605 	 */
7606 	struct bpf_object *obj = prog->obj;
7607 	const struct extern_desc *ext;
7608 	int insn_idx, ext_idx;
7609 	char patch[128];
7610 
7611 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &ext_idx) != 2)
7612 		return;
7613 
7614 	ext_idx -= POISON_CALL_KFUNC_BASE;
7615 	if (ext_idx < 0 || ext_idx >= obj->nr_extern)
7616 		return;
7617 	ext = &obj->externs[ext_idx];
7618 
7619 	snprintf(patch, sizeof(patch),
7620 		 "%d: <invalid kfunc call>\n"
7621 		 "kfunc '%s' is referenced but wasn't resolved\n",
7622 		 insn_idx, ext->name);
7623 
7624 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7625 }
7626 
7627 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz)
7628 {
7629 	/* look for familiar error patterns in last N lines of the log */
7630 	const size_t max_last_line_cnt = 10;
7631 	char *prev_line, *cur_line, *next_line;
7632 	size_t log_sz;
7633 	int i;
7634 
7635 	if (!buf)
7636 		return;
7637 
7638 	log_sz = strlen(buf) + 1;
7639 	next_line = buf + log_sz - 1;
7640 
7641 	for (i = 0; i < max_last_line_cnt; i++, next_line = cur_line) {
7642 		cur_line = find_prev_line(buf, next_line);
7643 		if (!cur_line)
7644 			return;
7645 
7646 		if (str_has_pfx(cur_line, "invalid func unknown#195896080\n")) {
7647 			prev_line = find_prev_line(buf, cur_line);
7648 			if (!prev_line)
7649 				continue;
7650 
7651 			/* failed CO-RE relocation case */
7652 			fixup_log_failed_core_relo(prog, buf, buf_sz, log_sz,
7653 						   prev_line, cur_line, next_line);
7654 			return;
7655 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_LDIMM64_MAP_PFX)) {
7656 			prev_line = find_prev_line(buf, cur_line);
7657 			if (!prev_line)
7658 				continue;
7659 
7660 			/* reference to uncreated BPF map */
7661 			fixup_log_missing_map_load(prog, buf, buf_sz, log_sz,
7662 						   prev_line, cur_line, next_line);
7663 			return;
7664 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_CALL_KFUNC_PFX)) {
7665 			prev_line = find_prev_line(buf, cur_line);
7666 			if (!prev_line)
7667 				continue;
7668 
7669 			/* reference to unresolved kfunc */
7670 			fixup_log_missing_kfunc_call(prog, buf, buf_sz, log_sz,
7671 						     prev_line, cur_line, next_line);
7672 			return;
7673 		}
7674 	}
7675 }
7676 
7677 static int bpf_program_record_relos(struct bpf_program *prog)
7678 {
7679 	struct bpf_object *obj = prog->obj;
7680 	int i;
7681 
7682 	for (i = 0; i < prog->nr_reloc; i++) {
7683 		struct reloc_desc *relo = &prog->reloc_desc[i];
7684 		struct extern_desc *ext = &obj->externs[relo->ext_idx];
7685 		int kind;
7686 
7687 		switch (relo->type) {
7688 		case RELO_EXTERN_LD64:
7689 			if (ext->type != EXT_KSYM)
7690 				continue;
7691 			kind = btf_is_var(btf__type_by_id(obj->btf, ext->btf_id)) ?
7692 				BTF_KIND_VAR : BTF_KIND_FUNC;
7693 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7694 					       ext->is_weak, !ext->ksym.type_id,
7695 					       true, kind, relo->insn_idx);
7696 			break;
7697 		case RELO_EXTERN_CALL:
7698 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7699 					       ext->is_weak, false, false, BTF_KIND_FUNC,
7700 					       relo->insn_idx);
7701 			break;
7702 		case RELO_CORE: {
7703 			struct bpf_core_relo cr = {
7704 				.insn_off = relo->insn_idx * 8,
7705 				.type_id = relo->core_relo->type_id,
7706 				.access_str_off = relo->core_relo->access_str_off,
7707 				.kind = relo->core_relo->kind,
7708 			};
7709 
7710 			bpf_gen__record_relo_core(obj->gen_loader, &cr);
7711 			break;
7712 		}
7713 		default:
7714 			continue;
7715 		}
7716 	}
7717 	return 0;
7718 }
7719 
7720 static int
7721 bpf_object__load_progs(struct bpf_object *obj, int log_level)
7722 {
7723 	struct bpf_program *prog;
7724 	size_t i;
7725 	int err;
7726 
7727 	for (i = 0; i < obj->nr_programs; i++) {
7728 		prog = &obj->programs[i];
7729 		err = bpf_object__sanitize_prog(obj, prog);
7730 		if (err)
7731 			return err;
7732 	}
7733 
7734 	for (i = 0; i < obj->nr_programs; i++) {
7735 		prog = &obj->programs[i];
7736 		if (prog_is_subprog(obj, prog))
7737 			continue;
7738 		if (!prog->autoload) {
7739 			pr_debug("prog '%s': skipped loading\n", prog->name);
7740 			continue;
7741 		}
7742 		prog->log_level |= log_level;
7743 
7744 		if (obj->gen_loader)
7745 			bpf_program_record_relos(prog);
7746 
7747 		err = bpf_object_load_prog(obj, prog, prog->insns, prog->insns_cnt,
7748 					   obj->license, obj->kern_version, &prog->fd);
7749 		if (err) {
7750 			pr_warn("prog '%s': failed to load: %d\n", prog->name, err);
7751 			return err;
7752 		}
7753 	}
7754 
7755 	bpf_object__free_relocs(obj);
7756 	return 0;
7757 }
7758 
7759 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
7760 
7761 static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
7762 {
7763 	struct bpf_program *prog;
7764 	int err;
7765 
7766 	bpf_object__for_each_program(prog, obj) {
7767 		prog->sec_def = find_sec_def(prog->sec_name);
7768 		if (!prog->sec_def) {
7769 			/* couldn't guess, but user might manually specify */
7770 			pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
7771 				prog->name, prog->sec_name);
7772 			continue;
7773 		}
7774 
7775 		prog->type = prog->sec_def->prog_type;
7776 		prog->expected_attach_type = prog->sec_def->expected_attach_type;
7777 
7778 		/* sec_def can have custom callback which should be called
7779 		 * after bpf_program is initialized to adjust its properties
7780 		 */
7781 		if (prog->sec_def->prog_setup_fn) {
7782 			err = prog->sec_def->prog_setup_fn(prog, prog->sec_def->cookie);
7783 			if (err < 0) {
7784 				pr_warn("prog '%s': failed to initialize: %d\n",
7785 					prog->name, err);
7786 				return err;
7787 			}
7788 		}
7789 	}
7790 
7791 	return 0;
7792 }
7793 
7794 static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
7795 					  const struct bpf_object_open_opts *opts)
7796 {
7797 	const char *obj_name, *kconfig, *btf_tmp_path;
7798 	struct bpf_object *obj;
7799 	char tmp_name[64];
7800 	int err;
7801 	char *log_buf;
7802 	size_t log_size;
7803 	__u32 log_level;
7804 
7805 	if (elf_version(EV_CURRENT) == EV_NONE) {
7806 		pr_warn("failed to init libelf for %s\n",
7807 			path ? : "(mem buf)");
7808 		return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
7809 	}
7810 
7811 	if (!OPTS_VALID(opts, bpf_object_open_opts))
7812 		return ERR_PTR(-EINVAL);
7813 
7814 	obj_name = OPTS_GET(opts, object_name, NULL);
7815 	if (obj_buf) {
7816 		if (!obj_name) {
7817 			snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
7818 				 (unsigned long)obj_buf,
7819 				 (unsigned long)obj_buf_sz);
7820 			obj_name = tmp_name;
7821 		}
7822 		path = obj_name;
7823 		pr_debug("loading object '%s' from buffer\n", obj_name);
7824 	}
7825 
7826 	log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
7827 	log_size = OPTS_GET(opts, kernel_log_size, 0);
7828 	log_level = OPTS_GET(opts, kernel_log_level, 0);
7829 	if (log_size > UINT_MAX)
7830 		return ERR_PTR(-EINVAL);
7831 	if (log_size && !log_buf)
7832 		return ERR_PTR(-EINVAL);
7833 
7834 	obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
7835 	if (IS_ERR(obj))
7836 		return obj;
7837 
7838 	obj->log_buf = log_buf;
7839 	obj->log_size = log_size;
7840 	obj->log_level = log_level;
7841 
7842 	btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
7843 	if (btf_tmp_path) {
7844 		if (strlen(btf_tmp_path) >= PATH_MAX) {
7845 			err = -ENAMETOOLONG;
7846 			goto out;
7847 		}
7848 		obj->btf_custom_path = strdup(btf_tmp_path);
7849 		if (!obj->btf_custom_path) {
7850 			err = -ENOMEM;
7851 			goto out;
7852 		}
7853 	}
7854 
7855 	kconfig = OPTS_GET(opts, kconfig, NULL);
7856 	if (kconfig) {
7857 		obj->kconfig = strdup(kconfig);
7858 		if (!obj->kconfig) {
7859 			err = -ENOMEM;
7860 			goto out;
7861 		}
7862 	}
7863 
7864 	err = bpf_object__elf_init(obj);
7865 	err = err ? : bpf_object__check_endianness(obj);
7866 	err = err ? : bpf_object__elf_collect(obj);
7867 	err = err ? : bpf_object__collect_externs(obj);
7868 	err = err ? : bpf_object_fixup_btf(obj);
7869 	err = err ? : bpf_object__init_maps(obj, opts);
7870 	err = err ? : bpf_object_init_progs(obj, opts);
7871 	err = err ? : bpf_object__collect_relos(obj);
7872 	if (err)
7873 		goto out;
7874 
7875 	bpf_object__elf_finish(obj);
7876 
7877 	return obj;
7878 out:
7879 	bpf_object__close(obj);
7880 	return ERR_PTR(err);
7881 }
7882 
7883 struct bpf_object *
7884 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
7885 {
7886 	if (!path)
7887 		return libbpf_err_ptr(-EINVAL);
7888 
7889 	pr_debug("loading %s\n", path);
7890 
7891 	return libbpf_ptr(bpf_object_open(path, NULL, 0, opts));
7892 }
7893 
7894 struct bpf_object *bpf_object__open(const char *path)
7895 {
7896 	return bpf_object__open_file(path, NULL);
7897 }
7898 
7899 struct bpf_object *
7900 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
7901 		     const struct bpf_object_open_opts *opts)
7902 {
7903 	if (!obj_buf || obj_buf_sz == 0)
7904 		return libbpf_err_ptr(-EINVAL);
7905 
7906 	return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, opts));
7907 }
7908 
7909 static int bpf_object_unload(struct bpf_object *obj)
7910 {
7911 	size_t i;
7912 
7913 	if (!obj)
7914 		return libbpf_err(-EINVAL);
7915 
7916 	for (i = 0; i < obj->nr_maps; i++) {
7917 		zclose(obj->maps[i].fd);
7918 		if (obj->maps[i].st_ops)
7919 			zfree(&obj->maps[i].st_ops->kern_vdata);
7920 	}
7921 
7922 	for (i = 0; i < obj->nr_programs; i++)
7923 		bpf_program__unload(&obj->programs[i]);
7924 
7925 	return 0;
7926 }
7927 
7928 static int bpf_object__sanitize_maps(struct bpf_object *obj)
7929 {
7930 	struct bpf_map *m;
7931 
7932 	bpf_object__for_each_map(m, obj) {
7933 		if (!bpf_map__is_internal(m))
7934 			continue;
7935 		if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
7936 			m->def.map_flags &= ~BPF_F_MMAPABLE;
7937 	}
7938 
7939 	return 0;
7940 }
7941 
7942 int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
7943 {
7944 	char sym_type, sym_name[500];
7945 	unsigned long long sym_addr;
7946 	int ret, err = 0;
7947 	FILE *f;
7948 
7949 	f = fopen("/proc/kallsyms", "re");
7950 	if (!f) {
7951 		err = -errno;
7952 		pr_warn("failed to open /proc/kallsyms: %d\n", err);
7953 		return err;
7954 	}
7955 
7956 	while (true) {
7957 		ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
7958 			     &sym_addr, &sym_type, sym_name);
7959 		if (ret == EOF && feof(f))
7960 			break;
7961 		if (ret != 3) {
7962 			pr_warn("failed to read kallsyms entry: %d\n", ret);
7963 			err = -EINVAL;
7964 			break;
7965 		}
7966 
7967 		err = cb(sym_addr, sym_type, sym_name, ctx);
7968 		if (err)
7969 			break;
7970 	}
7971 
7972 	fclose(f);
7973 	return err;
7974 }
7975 
7976 static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
7977 		       const char *sym_name, void *ctx)
7978 {
7979 	struct bpf_object *obj = ctx;
7980 	const struct btf_type *t;
7981 	struct extern_desc *ext;
7982 
7983 	ext = find_extern_by_name(obj, sym_name);
7984 	if (!ext || ext->type != EXT_KSYM)
7985 		return 0;
7986 
7987 	t = btf__type_by_id(obj->btf, ext->btf_id);
7988 	if (!btf_is_var(t))
7989 		return 0;
7990 
7991 	if (ext->is_set && ext->ksym.addr != sym_addr) {
7992 		pr_warn("extern (ksym) '%s': resolution is ambiguous: 0x%llx or 0x%llx\n",
7993 			sym_name, ext->ksym.addr, sym_addr);
7994 		return -EINVAL;
7995 	}
7996 	if (!ext->is_set) {
7997 		ext->is_set = true;
7998 		ext->ksym.addr = sym_addr;
7999 		pr_debug("extern (ksym) '%s': set to 0x%llx\n", sym_name, sym_addr);
8000 	}
8001 	return 0;
8002 }
8003 
8004 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
8005 {
8006 	return libbpf_kallsyms_parse(kallsyms_cb, obj);
8007 }
8008 
8009 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
8010 			    __u16 kind, struct btf **res_btf,
8011 			    struct module_btf **res_mod_btf)
8012 {
8013 	struct module_btf *mod_btf;
8014 	struct btf *btf;
8015 	int i, id, err;
8016 
8017 	btf = obj->btf_vmlinux;
8018 	mod_btf = NULL;
8019 	id = btf__find_by_name_kind(btf, ksym_name, kind);
8020 
8021 	if (id == -ENOENT) {
8022 		err = load_module_btfs(obj);
8023 		if (err)
8024 			return err;
8025 
8026 		for (i = 0; i < obj->btf_module_cnt; i++) {
8027 			/* we assume module_btf's BTF FD is always >0 */
8028 			mod_btf = &obj->btf_modules[i];
8029 			btf = mod_btf->btf;
8030 			id = btf__find_by_name_kind_own(btf, ksym_name, kind);
8031 			if (id != -ENOENT)
8032 				break;
8033 		}
8034 	}
8035 	if (id <= 0)
8036 		return -ESRCH;
8037 
8038 	*res_btf = btf;
8039 	*res_mod_btf = mod_btf;
8040 	return id;
8041 }
8042 
8043 static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
8044 					       struct extern_desc *ext)
8045 {
8046 	const struct btf_type *targ_var, *targ_type;
8047 	__u32 targ_type_id, local_type_id;
8048 	struct module_btf *mod_btf = NULL;
8049 	const char *targ_var_name;
8050 	struct btf *btf = NULL;
8051 	int id, err;
8052 
8053 	id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
8054 	if (id < 0) {
8055 		if (id == -ESRCH && ext->is_weak)
8056 			return 0;
8057 		pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
8058 			ext->name);
8059 		return id;
8060 	}
8061 
8062 	/* find local type_id */
8063 	local_type_id = ext->ksym.type_id;
8064 
8065 	/* find target type_id */
8066 	targ_var = btf__type_by_id(btf, id);
8067 	targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
8068 	targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
8069 
8070 	err = bpf_core_types_are_compat(obj->btf, local_type_id,
8071 					btf, targ_type_id);
8072 	if (err <= 0) {
8073 		const struct btf_type *local_type;
8074 		const char *targ_name, *local_name;
8075 
8076 		local_type = btf__type_by_id(obj->btf, local_type_id);
8077 		local_name = btf__name_by_offset(obj->btf, local_type->name_off);
8078 		targ_name = btf__name_by_offset(btf, targ_type->name_off);
8079 
8080 		pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
8081 			ext->name, local_type_id,
8082 			btf_kind_str(local_type), local_name, targ_type_id,
8083 			btf_kind_str(targ_type), targ_name);
8084 		return -EINVAL;
8085 	}
8086 
8087 	ext->is_set = true;
8088 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
8089 	ext->ksym.kernel_btf_id = id;
8090 	pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
8091 		 ext->name, id, btf_kind_str(targ_var), targ_var_name);
8092 
8093 	return 0;
8094 }
8095 
8096 static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
8097 						struct extern_desc *ext)
8098 {
8099 	int local_func_proto_id, kfunc_proto_id, kfunc_id;
8100 	struct module_btf *mod_btf = NULL;
8101 	const struct btf_type *kern_func;
8102 	struct btf *kern_btf = NULL;
8103 	int ret;
8104 
8105 	local_func_proto_id = ext->ksym.type_id;
8106 
8107 	kfunc_id = find_ksym_btf_id(obj, ext->essent_name ?: ext->name, BTF_KIND_FUNC, &kern_btf,
8108 				    &mod_btf);
8109 	if (kfunc_id < 0) {
8110 		if (kfunc_id == -ESRCH && ext->is_weak)
8111 			return 0;
8112 		pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
8113 			ext->name);
8114 		return kfunc_id;
8115 	}
8116 
8117 	kern_func = btf__type_by_id(kern_btf, kfunc_id);
8118 	kfunc_proto_id = kern_func->type;
8119 
8120 	ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
8121 					kern_btf, kfunc_proto_id);
8122 	if (ret <= 0) {
8123 		if (ext->is_weak)
8124 			return 0;
8125 
8126 		pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with %s [%d]\n",
8127 			ext->name, local_func_proto_id,
8128 			mod_btf ? mod_btf->name : "vmlinux", kfunc_proto_id);
8129 		return -EINVAL;
8130 	}
8131 
8132 	/* set index for module BTF fd in fd_array, if unset */
8133 	if (mod_btf && !mod_btf->fd_array_idx) {
8134 		/* insn->off is s16 */
8135 		if (obj->fd_array_cnt == INT16_MAX) {
8136 			pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
8137 				ext->name, mod_btf->fd_array_idx);
8138 			return -E2BIG;
8139 		}
8140 		/* Cannot use index 0 for module BTF fd */
8141 		if (!obj->fd_array_cnt)
8142 			obj->fd_array_cnt = 1;
8143 
8144 		ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
8145 					obj->fd_array_cnt + 1);
8146 		if (ret)
8147 			return ret;
8148 		mod_btf->fd_array_idx = obj->fd_array_cnt;
8149 		/* we assume module BTF FD is always >0 */
8150 		obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
8151 	}
8152 
8153 	ext->is_set = true;
8154 	ext->ksym.kernel_btf_id = kfunc_id;
8155 	ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
8156 	/* Also set kernel_btf_obj_fd to make sure that bpf_object__relocate_data()
8157 	 * populates FD into ld_imm64 insn when it's used to point to kfunc.
8158 	 * {kernel_btf_id, btf_fd_idx} -> fixup bpf_call.
8159 	 * {kernel_btf_id, kernel_btf_obj_fd} -> fixup ld_imm64.
8160 	 */
8161 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
8162 	pr_debug("extern (func ksym) '%s': resolved to %s [%d]\n",
8163 		 ext->name, mod_btf ? mod_btf->name : "vmlinux", kfunc_id);
8164 
8165 	return 0;
8166 }
8167 
8168 static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
8169 {
8170 	const struct btf_type *t;
8171 	struct extern_desc *ext;
8172 	int i, err;
8173 
8174 	for (i = 0; i < obj->nr_extern; i++) {
8175 		ext = &obj->externs[i];
8176 		if (ext->type != EXT_KSYM || !ext->ksym.type_id)
8177 			continue;
8178 
8179 		if (obj->gen_loader) {
8180 			ext->is_set = true;
8181 			ext->ksym.kernel_btf_obj_fd = 0;
8182 			ext->ksym.kernel_btf_id = 0;
8183 			continue;
8184 		}
8185 		t = btf__type_by_id(obj->btf, ext->btf_id);
8186 		if (btf_is_var(t))
8187 			err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
8188 		else
8189 			err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
8190 		if (err)
8191 			return err;
8192 	}
8193 	return 0;
8194 }
8195 
8196 static int bpf_object__resolve_externs(struct bpf_object *obj,
8197 				       const char *extra_kconfig)
8198 {
8199 	bool need_config = false, need_kallsyms = false;
8200 	bool need_vmlinux_btf = false;
8201 	struct extern_desc *ext;
8202 	void *kcfg_data = NULL;
8203 	int err, i;
8204 
8205 	if (obj->nr_extern == 0)
8206 		return 0;
8207 
8208 	if (obj->kconfig_map_idx >= 0)
8209 		kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
8210 
8211 	for (i = 0; i < obj->nr_extern; i++) {
8212 		ext = &obj->externs[i];
8213 
8214 		if (ext->type == EXT_KSYM) {
8215 			if (ext->ksym.type_id)
8216 				need_vmlinux_btf = true;
8217 			else
8218 				need_kallsyms = true;
8219 			continue;
8220 		} else if (ext->type == EXT_KCFG) {
8221 			void *ext_ptr = kcfg_data + ext->kcfg.data_off;
8222 			__u64 value = 0;
8223 
8224 			/* Kconfig externs need actual /proc/config.gz */
8225 			if (str_has_pfx(ext->name, "CONFIG_")) {
8226 				need_config = true;
8227 				continue;
8228 			}
8229 
8230 			/* Virtual kcfg externs are customly handled by libbpf */
8231 			if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
8232 				value = get_kernel_version();
8233 				if (!value) {
8234 					pr_warn("extern (kcfg) '%s': failed to get kernel version\n", ext->name);
8235 					return -EINVAL;
8236 				}
8237 			} else if (strcmp(ext->name, "LINUX_HAS_BPF_COOKIE") == 0) {
8238 				value = kernel_supports(obj, FEAT_BPF_COOKIE);
8239 			} else if (strcmp(ext->name, "LINUX_HAS_SYSCALL_WRAPPER") == 0) {
8240 				value = kernel_supports(obj, FEAT_SYSCALL_WRAPPER);
8241 			} else if (!str_has_pfx(ext->name, "LINUX_") || !ext->is_weak) {
8242 				/* Currently libbpf supports only CONFIG_ and LINUX_ prefixed
8243 				 * __kconfig externs, where LINUX_ ones are virtual and filled out
8244 				 * customly by libbpf (their values don't come from Kconfig).
8245 				 * If LINUX_xxx variable is not recognized by libbpf, but is marked
8246 				 * __weak, it defaults to zero value, just like for CONFIG_xxx
8247 				 * externs.
8248 				 */
8249 				pr_warn("extern (kcfg) '%s': unrecognized virtual extern\n", ext->name);
8250 				return -EINVAL;
8251 			}
8252 
8253 			err = set_kcfg_value_num(ext, ext_ptr, value);
8254 			if (err)
8255 				return err;
8256 			pr_debug("extern (kcfg) '%s': set to 0x%llx\n",
8257 				 ext->name, (long long)value);
8258 		} else {
8259 			pr_warn("extern '%s': unrecognized extern kind\n", ext->name);
8260 			return -EINVAL;
8261 		}
8262 	}
8263 	if (need_config && extra_kconfig) {
8264 		err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
8265 		if (err)
8266 			return -EINVAL;
8267 		need_config = false;
8268 		for (i = 0; i < obj->nr_extern; i++) {
8269 			ext = &obj->externs[i];
8270 			if (ext->type == EXT_KCFG && !ext->is_set) {
8271 				need_config = true;
8272 				break;
8273 			}
8274 		}
8275 	}
8276 	if (need_config) {
8277 		err = bpf_object__read_kconfig_file(obj, kcfg_data);
8278 		if (err)
8279 			return -EINVAL;
8280 	}
8281 	if (need_kallsyms) {
8282 		err = bpf_object__read_kallsyms_file(obj);
8283 		if (err)
8284 			return -EINVAL;
8285 	}
8286 	if (need_vmlinux_btf) {
8287 		err = bpf_object__resolve_ksyms_btf_id(obj);
8288 		if (err)
8289 			return -EINVAL;
8290 	}
8291 	for (i = 0; i < obj->nr_extern; i++) {
8292 		ext = &obj->externs[i];
8293 
8294 		if (!ext->is_set && !ext->is_weak) {
8295 			pr_warn("extern '%s' (strong): not resolved\n", ext->name);
8296 			return -ESRCH;
8297 		} else if (!ext->is_set) {
8298 			pr_debug("extern '%s' (weak): not resolved, defaulting to zero\n",
8299 				 ext->name);
8300 		}
8301 	}
8302 
8303 	return 0;
8304 }
8305 
8306 static void bpf_map_prepare_vdata(const struct bpf_map *map)
8307 {
8308 	struct bpf_struct_ops *st_ops;
8309 	__u32 i;
8310 
8311 	st_ops = map->st_ops;
8312 	for (i = 0; i < btf_vlen(st_ops->type); i++) {
8313 		struct bpf_program *prog = st_ops->progs[i];
8314 		void *kern_data;
8315 		int prog_fd;
8316 
8317 		if (!prog)
8318 			continue;
8319 
8320 		prog_fd = bpf_program__fd(prog);
8321 		kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
8322 		*(unsigned long *)kern_data = prog_fd;
8323 	}
8324 }
8325 
8326 static int bpf_object_prepare_struct_ops(struct bpf_object *obj)
8327 {
8328 	int i;
8329 
8330 	for (i = 0; i < obj->nr_maps; i++)
8331 		if (bpf_map__is_struct_ops(&obj->maps[i]))
8332 			bpf_map_prepare_vdata(&obj->maps[i]);
8333 
8334 	return 0;
8335 }
8336 
8337 static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
8338 {
8339 	int err, i;
8340 
8341 	if (!obj)
8342 		return libbpf_err(-EINVAL);
8343 
8344 	if (obj->loaded) {
8345 		pr_warn("object '%s': load can't be attempted twice\n", obj->name);
8346 		return libbpf_err(-EINVAL);
8347 	}
8348 
8349 	if (obj->gen_loader)
8350 		bpf_gen__init(obj->gen_loader, extra_log_level, obj->nr_programs, obj->nr_maps);
8351 
8352 	err = bpf_object__probe_loading(obj);
8353 	err = err ? : bpf_object__load_vmlinux_btf(obj, false);
8354 	err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
8355 	err = err ? : bpf_object__sanitize_maps(obj);
8356 	err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
8357 	err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
8358 	err = err ? : bpf_object__sanitize_and_load_btf(obj);
8359 	err = err ? : bpf_object__create_maps(obj);
8360 	err = err ? : bpf_object__load_progs(obj, extra_log_level);
8361 	err = err ? : bpf_object_init_prog_arrays(obj);
8362 	err = err ? : bpf_object_prepare_struct_ops(obj);
8363 
8364 	if (obj->gen_loader) {
8365 		/* reset FDs */
8366 		if (obj->btf)
8367 			btf__set_fd(obj->btf, -1);
8368 		if (!err)
8369 			err = bpf_gen__finish(obj->gen_loader, obj->nr_programs, obj->nr_maps);
8370 	}
8371 
8372 	/* clean up fd_array */
8373 	zfree(&obj->fd_array);
8374 
8375 	/* clean up module BTFs */
8376 	for (i = 0; i < obj->btf_module_cnt; i++) {
8377 		close(obj->btf_modules[i].fd);
8378 		btf__free(obj->btf_modules[i].btf);
8379 		free(obj->btf_modules[i].name);
8380 	}
8381 	free(obj->btf_modules);
8382 
8383 	/* clean up vmlinux BTF */
8384 	btf__free(obj->btf_vmlinux);
8385 	obj->btf_vmlinux = NULL;
8386 
8387 	obj->loaded = true; /* doesn't matter if successfully or not */
8388 
8389 	if (err)
8390 		goto out;
8391 
8392 	return 0;
8393 out:
8394 	/* unpin any maps that were auto-pinned during load */
8395 	for (i = 0; i < obj->nr_maps; i++)
8396 		if (obj->maps[i].pinned && !obj->maps[i].reused)
8397 			bpf_map__unpin(&obj->maps[i], NULL);
8398 
8399 	bpf_object_unload(obj);
8400 	pr_warn("failed to load object '%s'\n", obj->path);
8401 	return libbpf_err(err);
8402 }
8403 
8404 int bpf_object__load(struct bpf_object *obj)
8405 {
8406 	return bpf_object_load(obj, 0, NULL);
8407 }
8408 
8409 static int make_parent_dir(const char *path)
8410 {
8411 	char *cp, errmsg[STRERR_BUFSIZE];
8412 	char *dname, *dir;
8413 	int err = 0;
8414 
8415 	dname = strdup(path);
8416 	if (dname == NULL)
8417 		return -ENOMEM;
8418 
8419 	dir = dirname(dname);
8420 	if (mkdir(dir, 0700) && errno != EEXIST)
8421 		err = -errno;
8422 
8423 	free(dname);
8424 	if (err) {
8425 		cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
8426 		pr_warn("failed to mkdir %s: %s\n", path, cp);
8427 	}
8428 	return err;
8429 }
8430 
8431 static int check_path(const char *path)
8432 {
8433 	char *cp, errmsg[STRERR_BUFSIZE];
8434 	struct statfs st_fs;
8435 	char *dname, *dir;
8436 	int err = 0;
8437 
8438 	if (path == NULL)
8439 		return -EINVAL;
8440 
8441 	dname = strdup(path);
8442 	if (dname == NULL)
8443 		return -ENOMEM;
8444 
8445 	dir = dirname(dname);
8446 	if (statfs(dir, &st_fs)) {
8447 		cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
8448 		pr_warn("failed to statfs %s: %s\n", dir, cp);
8449 		err = -errno;
8450 	}
8451 	free(dname);
8452 
8453 	if (!err && st_fs.f_type != BPF_FS_MAGIC) {
8454 		pr_warn("specified path %s is not on BPF FS\n", path);
8455 		err = -EINVAL;
8456 	}
8457 
8458 	return err;
8459 }
8460 
8461 int bpf_program__pin(struct bpf_program *prog, const char *path)
8462 {
8463 	char *cp, errmsg[STRERR_BUFSIZE];
8464 	int err;
8465 
8466 	if (prog->fd < 0) {
8467 		pr_warn("prog '%s': can't pin program that wasn't loaded\n", prog->name);
8468 		return libbpf_err(-EINVAL);
8469 	}
8470 
8471 	err = make_parent_dir(path);
8472 	if (err)
8473 		return libbpf_err(err);
8474 
8475 	err = check_path(path);
8476 	if (err)
8477 		return libbpf_err(err);
8478 
8479 	if (bpf_obj_pin(prog->fd, path)) {
8480 		err = -errno;
8481 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
8482 		pr_warn("prog '%s': failed to pin at '%s': %s\n", prog->name, path, cp);
8483 		return libbpf_err(err);
8484 	}
8485 
8486 	pr_debug("prog '%s': pinned at '%s'\n", prog->name, path);
8487 	return 0;
8488 }
8489 
8490 int bpf_program__unpin(struct bpf_program *prog, const char *path)
8491 {
8492 	int err;
8493 
8494 	if (prog->fd < 0) {
8495 		pr_warn("prog '%s': can't unpin program that wasn't loaded\n", prog->name);
8496 		return libbpf_err(-EINVAL);
8497 	}
8498 
8499 	err = check_path(path);
8500 	if (err)
8501 		return libbpf_err(err);
8502 
8503 	err = unlink(path);
8504 	if (err)
8505 		return libbpf_err(-errno);
8506 
8507 	pr_debug("prog '%s': unpinned from '%s'\n", prog->name, path);
8508 	return 0;
8509 }
8510 
8511 int bpf_map__pin(struct bpf_map *map, const char *path)
8512 {
8513 	char *cp, errmsg[STRERR_BUFSIZE];
8514 	int err;
8515 
8516 	if (map == NULL) {
8517 		pr_warn("invalid map pointer\n");
8518 		return libbpf_err(-EINVAL);
8519 	}
8520 
8521 	if (map->pin_path) {
8522 		if (path && strcmp(path, map->pin_path)) {
8523 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8524 				bpf_map__name(map), map->pin_path, path);
8525 			return libbpf_err(-EINVAL);
8526 		} else if (map->pinned) {
8527 			pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
8528 				 bpf_map__name(map), map->pin_path);
8529 			return 0;
8530 		}
8531 	} else {
8532 		if (!path) {
8533 			pr_warn("missing a path to pin map '%s' at\n",
8534 				bpf_map__name(map));
8535 			return libbpf_err(-EINVAL);
8536 		} else if (map->pinned) {
8537 			pr_warn("map '%s' already pinned\n", bpf_map__name(map));
8538 			return libbpf_err(-EEXIST);
8539 		}
8540 
8541 		map->pin_path = strdup(path);
8542 		if (!map->pin_path) {
8543 			err = -errno;
8544 			goto out_err;
8545 		}
8546 	}
8547 
8548 	err = make_parent_dir(map->pin_path);
8549 	if (err)
8550 		return libbpf_err(err);
8551 
8552 	err = check_path(map->pin_path);
8553 	if (err)
8554 		return libbpf_err(err);
8555 
8556 	if (bpf_obj_pin(map->fd, map->pin_path)) {
8557 		err = -errno;
8558 		goto out_err;
8559 	}
8560 
8561 	map->pinned = true;
8562 	pr_debug("pinned map '%s'\n", map->pin_path);
8563 
8564 	return 0;
8565 
8566 out_err:
8567 	cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
8568 	pr_warn("failed to pin map: %s\n", cp);
8569 	return libbpf_err(err);
8570 }
8571 
8572 int bpf_map__unpin(struct bpf_map *map, const char *path)
8573 {
8574 	int err;
8575 
8576 	if (map == NULL) {
8577 		pr_warn("invalid map pointer\n");
8578 		return libbpf_err(-EINVAL);
8579 	}
8580 
8581 	if (map->pin_path) {
8582 		if (path && strcmp(path, map->pin_path)) {
8583 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8584 				bpf_map__name(map), map->pin_path, path);
8585 			return libbpf_err(-EINVAL);
8586 		}
8587 		path = map->pin_path;
8588 	} else if (!path) {
8589 		pr_warn("no path to unpin map '%s' from\n",
8590 			bpf_map__name(map));
8591 		return libbpf_err(-EINVAL);
8592 	}
8593 
8594 	err = check_path(path);
8595 	if (err)
8596 		return libbpf_err(err);
8597 
8598 	err = unlink(path);
8599 	if (err != 0)
8600 		return libbpf_err(-errno);
8601 
8602 	map->pinned = false;
8603 	pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
8604 
8605 	return 0;
8606 }
8607 
8608 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
8609 {
8610 	char *new = NULL;
8611 
8612 	if (path) {
8613 		new = strdup(path);
8614 		if (!new)
8615 			return libbpf_err(-errno);
8616 	}
8617 
8618 	free(map->pin_path);
8619 	map->pin_path = new;
8620 	return 0;
8621 }
8622 
8623 __alias(bpf_map__pin_path)
8624 const char *bpf_map__get_pin_path(const struct bpf_map *map);
8625 
8626 const char *bpf_map__pin_path(const struct bpf_map *map)
8627 {
8628 	return map->pin_path;
8629 }
8630 
8631 bool bpf_map__is_pinned(const struct bpf_map *map)
8632 {
8633 	return map->pinned;
8634 }
8635 
8636 static void sanitize_pin_path(char *s)
8637 {
8638 	/* bpffs disallows periods in path names */
8639 	while (*s) {
8640 		if (*s == '.')
8641 			*s = '_';
8642 		s++;
8643 	}
8644 }
8645 
8646 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
8647 {
8648 	struct bpf_map *map;
8649 	int err;
8650 
8651 	if (!obj)
8652 		return libbpf_err(-ENOENT);
8653 
8654 	if (!obj->loaded) {
8655 		pr_warn("object not yet loaded; load it first\n");
8656 		return libbpf_err(-ENOENT);
8657 	}
8658 
8659 	bpf_object__for_each_map(map, obj) {
8660 		char *pin_path = NULL;
8661 		char buf[PATH_MAX];
8662 
8663 		if (!map->autocreate)
8664 			continue;
8665 
8666 		if (path) {
8667 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8668 			if (err)
8669 				goto err_unpin_maps;
8670 			sanitize_pin_path(buf);
8671 			pin_path = buf;
8672 		} else if (!map->pin_path) {
8673 			continue;
8674 		}
8675 
8676 		err = bpf_map__pin(map, pin_path);
8677 		if (err)
8678 			goto err_unpin_maps;
8679 	}
8680 
8681 	return 0;
8682 
8683 err_unpin_maps:
8684 	while ((map = bpf_object__prev_map(obj, map))) {
8685 		if (!map->pin_path)
8686 			continue;
8687 
8688 		bpf_map__unpin(map, NULL);
8689 	}
8690 
8691 	return libbpf_err(err);
8692 }
8693 
8694 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
8695 {
8696 	struct bpf_map *map;
8697 	int err;
8698 
8699 	if (!obj)
8700 		return libbpf_err(-ENOENT);
8701 
8702 	bpf_object__for_each_map(map, obj) {
8703 		char *pin_path = NULL;
8704 		char buf[PATH_MAX];
8705 
8706 		if (path) {
8707 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8708 			if (err)
8709 				return libbpf_err(err);
8710 			sanitize_pin_path(buf);
8711 			pin_path = buf;
8712 		} else if (!map->pin_path) {
8713 			continue;
8714 		}
8715 
8716 		err = bpf_map__unpin(map, pin_path);
8717 		if (err)
8718 			return libbpf_err(err);
8719 	}
8720 
8721 	return 0;
8722 }
8723 
8724 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
8725 {
8726 	struct bpf_program *prog;
8727 	char buf[PATH_MAX];
8728 	int err;
8729 
8730 	if (!obj)
8731 		return libbpf_err(-ENOENT);
8732 
8733 	if (!obj->loaded) {
8734 		pr_warn("object not yet loaded; load it first\n");
8735 		return libbpf_err(-ENOENT);
8736 	}
8737 
8738 	bpf_object__for_each_program(prog, obj) {
8739 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
8740 		if (err)
8741 			goto err_unpin_programs;
8742 
8743 		err = bpf_program__pin(prog, buf);
8744 		if (err)
8745 			goto err_unpin_programs;
8746 	}
8747 
8748 	return 0;
8749 
8750 err_unpin_programs:
8751 	while ((prog = bpf_object__prev_program(obj, prog))) {
8752 		if (pathname_concat(buf, sizeof(buf), path, prog->name))
8753 			continue;
8754 
8755 		bpf_program__unpin(prog, buf);
8756 	}
8757 
8758 	return libbpf_err(err);
8759 }
8760 
8761 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
8762 {
8763 	struct bpf_program *prog;
8764 	int err;
8765 
8766 	if (!obj)
8767 		return libbpf_err(-ENOENT);
8768 
8769 	bpf_object__for_each_program(prog, obj) {
8770 		char buf[PATH_MAX];
8771 
8772 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
8773 		if (err)
8774 			return libbpf_err(err);
8775 
8776 		err = bpf_program__unpin(prog, buf);
8777 		if (err)
8778 			return libbpf_err(err);
8779 	}
8780 
8781 	return 0;
8782 }
8783 
8784 int bpf_object__pin(struct bpf_object *obj, const char *path)
8785 {
8786 	int err;
8787 
8788 	err = bpf_object__pin_maps(obj, path);
8789 	if (err)
8790 		return libbpf_err(err);
8791 
8792 	err = bpf_object__pin_programs(obj, path);
8793 	if (err) {
8794 		bpf_object__unpin_maps(obj, path);
8795 		return libbpf_err(err);
8796 	}
8797 
8798 	return 0;
8799 }
8800 
8801 int bpf_object__unpin(struct bpf_object *obj, const char *path)
8802 {
8803 	int err;
8804 
8805 	err = bpf_object__unpin_programs(obj, path);
8806 	if (err)
8807 		return libbpf_err(err);
8808 
8809 	err = bpf_object__unpin_maps(obj, path);
8810 	if (err)
8811 		return libbpf_err(err);
8812 
8813 	return 0;
8814 }
8815 
8816 static void bpf_map__destroy(struct bpf_map *map)
8817 {
8818 	if (map->inner_map) {
8819 		bpf_map__destroy(map->inner_map);
8820 		zfree(&map->inner_map);
8821 	}
8822 
8823 	zfree(&map->init_slots);
8824 	map->init_slots_sz = 0;
8825 
8826 	if (map->mmaped) {
8827 		size_t mmap_sz;
8828 
8829 		mmap_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
8830 		munmap(map->mmaped, mmap_sz);
8831 		map->mmaped = NULL;
8832 	}
8833 
8834 	if (map->st_ops) {
8835 		zfree(&map->st_ops->data);
8836 		zfree(&map->st_ops->progs);
8837 		zfree(&map->st_ops->kern_func_off);
8838 		zfree(&map->st_ops);
8839 	}
8840 
8841 	zfree(&map->name);
8842 	zfree(&map->real_name);
8843 	zfree(&map->pin_path);
8844 
8845 	if (map->fd >= 0)
8846 		zclose(map->fd);
8847 }
8848 
8849 void bpf_object__close(struct bpf_object *obj)
8850 {
8851 	size_t i;
8852 
8853 	if (IS_ERR_OR_NULL(obj))
8854 		return;
8855 
8856 	usdt_manager_free(obj->usdt_man);
8857 	obj->usdt_man = NULL;
8858 
8859 	bpf_gen__free(obj->gen_loader);
8860 	bpf_object__elf_finish(obj);
8861 	bpf_object_unload(obj);
8862 	btf__free(obj->btf);
8863 	btf__free(obj->btf_vmlinux);
8864 	btf_ext__free(obj->btf_ext);
8865 
8866 	for (i = 0; i < obj->nr_maps; i++)
8867 		bpf_map__destroy(&obj->maps[i]);
8868 
8869 	zfree(&obj->btf_custom_path);
8870 	zfree(&obj->kconfig);
8871 
8872 	for (i = 0; i < obj->nr_extern; i++)
8873 		zfree(&obj->externs[i].essent_name);
8874 
8875 	zfree(&obj->externs);
8876 	obj->nr_extern = 0;
8877 
8878 	zfree(&obj->maps);
8879 	obj->nr_maps = 0;
8880 
8881 	if (obj->programs && obj->nr_programs) {
8882 		for (i = 0; i < obj->nr_programs; i++)
8883 			bpf_program__exit(&obj->programs[i]);
8884 	}
8885 	zfree(&obj->programs);
8886 
8887 	free(obj);
8888 }
8889 
8890 const char *bpf_object__name(const struct bpf_object *obj)
8891 {
8892 	return obj ? obj->name : libbpf_err_ptr(-EINVAL);
8893 }
8894 
8895 unsigned int bpf_object__kversion(const struct bpf_object *obj)
8896 {
8897 	return obj ? obj->kern_version : 0;
8898 }
8899 
8900 struct btf *bpf_object__btf(const struct bpf_object *obj)
8901 {
8902 	return obj ? obj->btf : NULL;
8903 }
8904 
8905 int bpf_object__btf_fd(const struct bpf_object *obj)
8906 {
8907 	return obj->btf ? btf__fd(obj->btf) : -1;
8908 }
8909 
8910 int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
8911 {
8912 	if (obj->loaded)
8913 		return libbpf_err(-EINVAL);
8914 
8915 	obj->kern_version = kern_version;
8916 
8917 	return 0;
8918 }
8919 
8920 int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
8921 {
8922 	struct bpf_gen *gen;
8923 
8924 	if (!opts)
8925 		return -EFAULT;
8926 	if (!OPTS_VALID(opts, gen_loader_opts))
8927 		return -EINVAL;
8928 	gen = calloc(sizeof(*gen), 1);
8929 	if (!gen)
8930 		return -ENOMEM;
8931 	gen->opts = opts;
8932 	obj->gen_loader = gen;
8933 	return 0;
8934 }
8935 
8936 static struct bpf_program *
8937 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
8938 		    bool forward)
8939 {
8940 	size_t nr_programs = obj->nr_programs;
8941 	ssize_t idx;
8942 
8943 	if (!nr_programs)
8944 		return NULL;
8945 
8946 	if (!p)
8947 		/* Iter from the beginning */
8948 		return forward ? &obj->programs[0] :
8949 			&obj->programs[nr_programs - 1];
8950 
8951 	if (p->obj != obj) {
8952 		pr_warn("error: program handler doesn't match object\n");
8953 		return errno = EINVAL, NULL;
8954 	}
8955 
8956 	idx = (p - obj->programs) + (forward ? 1 : -1);
8957 	if (idx >= obj->nr_programs || idx < 0)
8958 		return NULL;
8959 	return &obj->programs[idx];
8960 }
8961 
8962 struct bpf_program *
8963 bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
8964 {
8965 	struct bpf_program *prog = prev;
8966 
8967 	do {
8968 		prog = __bpf_program__iter(prog, obj, true);
8969 	} while (prog && prog_is_subprog(obj, prog));
8970 
8971 	return prog;
8972 }
8973 
8974 struct bpf_program *
8975 bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
8976 {
8977 	struct bpf_program *prog = next;
8978 
8979 	do {
8980 		prog = __bpf_program__iter(prog, obj, false);
8981 	} while (prog && prog_is_subprog(obj, prog));
8982 
8983 	return prog;
8984 }
8985 
8986 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
8987 {
8988 	prog->prog_ifindex = ifindex;
8989 }
8990 
8991 const char *bpf_program__name(const struct bpf_program *prog)
8992 {
8993 	return prog->name;
8994 }
8995 
8996 const char *bpf_program__section_name(const struct bpf_program *prog)
8997 {
8998 	return prog->sec_name;
8999 }
9000 
9001 bool bpf_program__autoload(const struct bpf_program *prog)
9002 {
9003 	return prog->autoload;
9004 }
9005 
9006 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
9007 {
9008 	if (prog->obj->loaded)
9009 		return libbpf_err(-EINVAL);
9010 
9011 	prog->autoload = autoload;
9012 	return 0;
9013 }
9014 
9015 bool bpf_program__autoattach(const struct bpf_program *prog)
9016 {
9017 	return prog->autoattach;
9018 }
9019 
9020 void bpf_program__set_autoattach(struct bpf_program *prog, bool autoattach)
9021 {
9022 	prog->autoattach = autoattach;
9023 }
9024 
9025 const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
9026 {
9027 	return prog->insns;
9028 }
9029 
9030 size_t bpf_program__insn_cnt(const struct bpf_program *prog)
9031 {
9032 	return prog->insns_cnt;
9033 }
9034 
9035 int bpf_program__set_insns(struct bpf_program *prog,
9036 			   struct bpf_insn *new_insns, size_t new_insn_cnt)
9037 {
9038 	struct bpf_insn *insns;
9039 
9040 	if (prog->obj->loaded)
9041 		return -EBUSY;
9042 
9043 	insns = libbpf_reallocarray(prog->insns, new_insn_cnt, sizeof(*insns));
9044 	/* NULL is a valid return from reallocarray if the new count is zero */
9045 	if (!insns && new_insn_cnt) {
9046 		pr_warn("prog '%s': failed to realloc prog code\n", prog->name);
9047 		return -ENOMEM;
9048 	}
9049 	memcpy(insns, new_insns, new_insn_cnt * sizeof(*insns));
9050 
9051 	prog->insns = insns;
9052 	prog->insns_cnt = new_insn_cnt;
9053 	return 0;
9054 }
9055 
9056 int bpf_program__fd(const struct bpf_program *prog)
9057 {
9058 	if (!prog)
9059 		return libbpf_err(-EINVAL);
9060 
9061 	if (prog->fd < 0)
9062 		return libbpf_err(-ENOENT);
9063 
9064 	return prog->fd;
9065 }
9066 
9067 __alias(bpf_program__type)
9068 enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog);
9069 
9070 enum bpf_prog_type bpf_program__type(const struct bpf_program *prog)
9071 {
9072 	return prog->type;
9073 }
9074 
9075 static size_t custom_sec_def_cnt;
9076 static struct bpf_sec_def *custom_sec_defs;
9077 static struct bpf_sec_def custom_fallback_def;
9078 static bool has_custom_fallback_def;
9079 static int last_custom_sec_def_handler_id;
9080 
9081 int bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
9082 {
9083 	if (prog->obj->loaded)
9084 		return libbpf_err(-EBUSY);
9085 
9086 	/* if type is not changed, do nothing */
9087 	if (prog->type == type)
9088 		return 0;
9089 
9090 	prog->type = type;
9091 
9092 	/* If a program type was changed, we need to reset associated SEC()
9093 	 * handler, as it will be invalid now. The only exception is a generic
9094 	 * fallback handler, which by definition is program type-agnostic and
9095 	 * is a catch-all custom handler, optionally set by the application,
9096 	 * so should be able to handle any type of BPF program.
9097 	 */
9098 	if (prog->sec_def != &custom_fallback_def)
9099 		prog->sec_def = NULL;
9100 	return 0;
9101 }
9102 
9103 __alias(bpf_program__expected_attach_type)
9104 enum bpf_attach_type bpf_program__get_expected_attach_type(const struct bpf_program *prog);
9105 
9106 enum bpf_attach_type bpf_program__expected_attach_type(const struct bpf_program *prog)
9107 {
9108 	return prog->expected_attach_type;
9109 }
9110 
9111 int bpf_program__set_expected_attach_type(struct bpf_program *prog,
9112 					   enum bpf_attach_type type)
9113 {
9114 	if (prog->obj->loaded)
9115 		return libbpf_err(-EBUSY);
9116 
9117 	prog->expected_attach_type = type;
9118 	return 0;
9119 }
9120 
9121 __u32 bpf_program__flags(const struct bpf_program *prog)
9122 {
9123 	return prog->prog_flags;
9124 }
9125 
9126 int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
9127 {
9128 	if (prog->obj->loaded)
9129 		return libbpf_err(-EBUSY);
9130 
9131 	prog->prog_flags = flags;
9132 	return 0;
9133 }
9134 
9135 __u32 bpf_program__log_level(const struct bpf_program *prog)
9136 {
9137 	return prog->log_level;
9138 }
9139 
9140 int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
9141 {
9142 	if (prog->obj->loaded)
9143 		return libbpf_err(-EBUSY);
9144 
9145 	prog->log_level = log_level;
9146 	return 0;
9147 }
9148 
9149 const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
9150 {
9151 	*log_size = prog->log_size;
9152 	return prog->log_buf;
9153 }
9154 
9155 int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
9156 {
9157 	if (log_size && !log_buf)
9158 		return -EINVAL;
9159 	if (prog->log_size > UINT_MAX)
9160 		return -EINVAL;
9161 	if (prog->obj->loaded)
9162 		return -EBUSY;
9163 
9164 	prog->log_buf = log_buf;
9165 	prog->log_size = log_size;
9166 	return 0;
9167 }
9168 
9169 #define SEC_DEF(sec_pfx, ptype, atype, flags, ...) {			    \
9170 	.sec = (char *)sec_pfx,						    \
9171 	.prog_type = BPF_PROG_TYPE_##ptype,				    \
9172 	.expected_attach_type = atype,					    \
9173 	.cookie = (long)(flags),					    \
9174 	.prog_prepare_load_fn = libbpf_prepare_prog_load,		    \
9175 	__VA_ARGS__							    \
9176 }
9177 
9178 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9179 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9180 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9181 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9182 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9183 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9184 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9185 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9186 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9187 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9188 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9189 
9190 static const struct bpf_sec_def section_defs[] = {
9191 	SEC_DEF("socket",		SOCKET_FILTER, 0, SEC_NONE),
9192 	SEC_DEF("sk_reuseport/migrate",	SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE),
9193 	SEC_DEF("sk_reuseport",		SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE),
9194 	SEC_DEF("kprobe+",		KPROBE,	0, SEC_NONE, attach_kprobe),
9195 	SEC_DEF("uprobe+",		KPROBE,	0, SEC_NONE, attach_uprobe),
9196 	SEC_DEF("uprobe.s+",		KPROBE,	0, SEC_SLEEPABLE, attach_uprobe),
9197 	SEC_DEF("kretprobe+",		KPROBE, 0, SEC_NONE, attach_kprobe),
9198 	SEC_DEF("uretprobe+",		KPROBE, 0, SEC_NONE, attach_uprobe),
9199 	SEC_DEF("uretprobe.s+",		KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
9200 	SEC_DEF("kprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
9201 	SEC_DEF("kretprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
9202 	SEC_DEF("uprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
9203 	SEC_DEF("uretprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
9204 	SEC_DEF("uprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
9205 	SEC_DEF("uretprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
9206 	SEC_DEF("ksyscall+",		KPROBE,	0, SEC_NONE, attach_ksyscall),
9207 	SEC_DEF("kretsyscall+",		KPROBE, 0, SEC_NONE, attach_ksyscall),
9208 	SEC_DEF("usdt+",		KPROBE,	0, SEC_USDT, attach_usdt),
9209 	SEC_DEF("usdt.s+",		KPROBE,	0, SEC_USDT | SEC_SLEEPABLE, attach_usdt),
9210 	SEC_DEF("tc/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE), /* alias for tcx */
9211 	SEC_DEF("tc/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),  /* alias for tcx */
9212 	SEC_DEF("tcx/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE),
9213 	SEC_DEF("tcx/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),
9214 	SEC_DEF("tc",			SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
9215 	SEC_DEF("classifier",		SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
9216 	SEC_DEF("action",		SCHED_ACT, 0, SEC_NONE), /* deprecated / legacy, use tcx */
9217 	SEC_DEF("netkit/primary",	SCHED_CLS, BPF_NETKIT_PRIMARY, SEC_NONE),
9218 	SEC_DEF("netkit/peer",		SCHED_CLS, BPF_NETKIT_PEER, SEC_NONE),
9219 	SEC_DEF("tracepoint+",		TRACEPOINT, 0, SEC_NONE, attach_tp),
9220 	SEC_DEF("tp+",			TRACEPOINT, 0, SEC_NONE, attach_tp),
9221 	SEC_DEF("raw_tracepoint+",	RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
9222 	SEC_DEF("raw_tp+",		RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
9223 	SEC_DEF("raw_tracepoint.w+",	RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
9224 	SEC_DEF("raw_tp.w+",		RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
9225 	SEC_DEF("tp_btf+",		TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
9226 	SEC_DEF("fentry+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
9227 	SEC_DEF("fmod_ret+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
9228 	SEC_DEF("fexit+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
9229 	SEC_DEF("fentry.s+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
9230 	SEC_DEF("fmod_ret.s+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
9231 	SEC_DEF("fexit.s+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
9232 	SEC_DEF("freplace+",		EXT, 0, SEC_ATTACH_BTF, attach_trace),
9233 	SEC_DEF("lsm+",			LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
9234 	SEC_DEF("lsm.s+",		LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
9235 	SEC_DEF("lsm_cgroup+",		LSM, BPF_LSM_CGROUP, SEC_ATTACH_BTF),
9236 	SEC_DEF("iter+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
9237 	SEC_DEF("iter.s+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_iter),
9238 	SEC_DEF("syscall",		SYSCALL, 0, SEC_SLEEPABLE),
9239 	SEC_DEF("xdp.frags/devmap",	XDP, BPF_XDP_DEVMAP, SEC_XDP_FRAGS),
9240 	SEC_DEF("xdp/devmap",		XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
9241 	SEC_DEF("xdp.frags/cpumap",	XDP, BPF_XDP_CPUMAP, SEC_XDP_FRAGS),
9242 	SEC_DEF("xdp/cpumap",		XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
9243 	SEC_DEF("xdp.frags",		XDP, BPF_XDP, SEC_XDP_FRAGS),
9244 	SEC_DEF("xdp",			XDP, BPF_XDP, SEC_ATTACHABLE_OPT),
9245 	SEC_DEF("perf_event",		PERF_EVENT, 0, SEC_NONE),
9246 	SEC_DEF("lwt_in",		LWT_IN, 0, SEC_NONE),
9247 	SEC_DEF("lwt_out",		LWT_OUT, 0, SEC_NONE),
9248 	SEC_DEF("lwt_xmit",		LWT_XMIT, 0, SEC_NONE),
9249 	SEC_DEF("lwt_seg6local",	LWT_SEG6LOCAL, 0, SEC_NONE),
9250 	SEC_DEF("sockops",		SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT),
9251 	SEC_DEF("sk_skb/stream_parser",	SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT),
9252 	SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT),
9253 	SEC_DEF("sk_skb",		SK_SKB, 0, SEC_NONE),
9254 	SEC_DEF("sk_msg",		SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT),
9255 	SEC_DEF("lirc_mode2",		LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT),
9256 	SEC_DEF("flow_dissector",	FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT),
9257 	SEC_DEF("cgroup_skb/ingress",	CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT),
9258 	SEC_DEF("cgroup_skb/egress",	CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT),
9259 	SEC_DEF("cgroup/skb",		CGROUP_SKB, 0, SEC_NONE),
9260 	SEC_DEF("cgroup/sock_create",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE),
9261 	SEC_DEF("cgroup/sock_release",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE),
9262 	SEC_DEF("cgroup/sock",		CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT),
9263 	SEC_DEF("cgroup/post_bind4",	CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE),
9264 	SEC_DEF("cgroup/post_bind6",	CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE),
9265 	SEC_DEF("cgroup/bind4",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE),
9266 	SEC_DEF("cgroup/bind6",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE),
9267 	SEC_DEF("cgroup/connect4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE),
9268 	SEC_DEF("cgroup/connect6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE),
9269 	SEC_DEF("cgroup/connect_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_CONNECT, SEC_ATTACHABLE),
9270 	SEC_DEF("cgroup/sendmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE),
9271 	SEC_DEF("cgroup/sendmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE),
9272 	SEC_DEF("cgroup/sendmsg_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_SENDMSG, SEC_ATTACHABLE),
9273 	SEC_DEF("cgroup/recvmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE),
9274 	SEC_DEF("cgroup/recvmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE),
9275 	SEC_DEF("cgroup/recvmsg_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_RECVMSG, SEC_ATTACHABLE),
9276 	SEC_DEF("cgroup/getpeername4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE),
9277 	SEC_DEF("cgroup/getpeername6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE),
9278 	SEC_DEF("cgroup/getpeername_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETPEERNAME, SEC_ATTACHABLE),
9279 	SEC_DEF("cgroup/getsockname4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE),
9280 	SEC_DEF("cgroup/getsockname6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE),
9281 	SEC_DEF("cgroup/getsockname_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETSOCKNAME, SEC_ATTACHABLE),
9282 	SEC_DEF("cgroup/sysctl",	CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE),
9283 	SEC_DEF("cgroup/getsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE),
9284 	SEC_DEF("cgroup/setsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE),
9285 	SEC_DEF("cgroup/dev",		CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT),
9286 	SEC_DEF("struct_ops+",		STRUCT_OPS, 0, SEC_NONE),
9287 	SEC_DEF("struct_ops.s+",	STRUCT_OPS, 0, SEC_SLEEPABLE),
9288 	SEC_DEF("sk_lookup",		SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE),
9289 	SEC_DEF("netfilter",		NETFILTER, BPF_NETFILTER, SEC_NONE),
9290 };
9291 
9292 int libbpf_register_prog_handler(const char *sec,
9293 				 enum bpf_prog_type prog_type,
9294 				 enum bpf_attach_type exp_attach_type,
9295 				 const struct libbpf_prog_handler_opts *opts)
9296 {
9297 	struct bpf_sec_def *sec_def;
9298 
9299 	if (!OPTS_VALID(opts, libbpf_prog_handler_opts))
9300 		return libbpf_err(-EINVAL);
9301 
9302 	if (last_custom_sec_def_handler_id == INT_MAX) /* prevent overflow */
9303 		return libbpf_err(-E2BIG);
9304 
9305 	if (sec) {
9306 		sec_def = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt + 1,
9307 					      sizeof(*sec_def));
9308 		if (!sec_def)
9309 			return libbpf_err(-ENOMEM);
9310 
9311 		custom_sec_defs = sec_def;
9312 		sec_def = &custom_sec_defs[custom_sec_def_cnt];
9313 	} else {
9314 		if (has_custom_fallback_def)
9315 			return libbpf_err(-EBUSY);
9316 
9317 		sec_def = &custom_fallback_def;
9318 	}
9319 
9320 	sec_def->sec = sec ? strdup(sec) : NULL;
9321 	if (sec && !sec_def->sec)
9322 		return libbpf_err(-ENOMEM);
9323 
9324 	sec_def->prog_type = prog_type;
9325 	sec_def->expected_attach_type = exp_attach_type;
9326 	sec_def->cookie = OPTS_GET(opts, cookie, 0);
9327 
9328 	sec_def->prog_setup_fn = OPTS_GET(opts, prog_setup_fn, NULL);
9329 	sec_def->prog_prepare_load_fn = OPTS_GET(opts, prog_prepare_load_fn, NULL);
9330 	sec_def->prog_attach_fn = OPTS_GET(opts, prog_attach_fn, NULL);
9331 
9332 	sec_def->handler_id = ++last_custom_sec_def_handler_id;
9333 
9334 	if (sec)
9335 		custom_sec_def_cnt++;
9336 	else
9337 		has_custom_fallback_def = true;
9338 
9339 	return sec_def->handler_id;
9340 }
9341 
9342 int libbpf_unregister_prog_handler(int handler_id)
9343 {
9344 	struct bpf_sec_def *sec_defs;
9345 	int i;
9346 
9347 	if (handler_id <= 0)
9348 		return libbpf_err(-EINVAL);
9349 
9350 	if (has_custom_fallback_def && custom_fallback_def.handler_id == handler_id) {
9351 		memset(&custom_fallback_def, 0, sizeof(custom_fallback_def));
9352 		has_custom_fallback_def = false;
9353 		return 0;
9354 	}
9355 
9356 	for (i = 0; i < custom_sec_def_cnt; i++) {
9357 		if (custom_sec_defs[i].handler_id == handler_id)
9358 			break;
9359 	}
9360 
9361 	if (i == custom_sec_def_cnt)
9362 		return libbpf_err(-ENOENT);
9363 
9364 	free(custom_sec_defs[i].sec);
9365 	for (i = i + 1; i < custom_sec_def_cnt; i++)
9366 		custom_sec_defs[i - 1] = custom_sec_defs[i];
9367 	custom_sec_def_cnt--;
9368 
9369 	/* try to shrink the array, but it's ok if we couldn't */
9370 	sec_defs = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt, sizeof(*sec_defs));
9371 	/* if new count is zero, reallocarray can return a valid NULL result;
9372 	 * in this case the previous pointer will be freed, so we *have to*
9373 	 * reassign old pointer to the new value (even if it's NULL)
9374 	 */
9375 	if (sec_defs || custom_sec_def_cnt == 0)
9376 		custom_sec_defs = sec_defs;
9377 
9378 	return 0;
9379 }
9380 
9381 static bool sec_def_matches(const struct bpf_sec_def *sec_def, const char *sec_name)
9382 {
9383 	size_t len = strlen(sec_def->sec);
9384 
9385 	/* "type/" always has to have proper SEC("type/extras") form */
9386 	if (sec_def->sec[len - 1] == '/') {
9387 		if (str_has_pfx(sec_name, sec_def->sec))
9388 			return true;
9389 		return false;
9390 	}
9391 
9392 	/* "type+" means it can be either exact SEC("type") or
9393 	 * well-formed SEC("type/extras") with proper '/' separator
9394 	 */
9395 	if (sec_def->sec[len - 1] == '+') {
9396 		len--;
9397 		/* not even a prefix */
9398 		if (strncmp(sec_name, sec_def->sec, len) != 0)
9399 			return false;
9400 		/* exact match or has '/' separator */
9401 		if (sec_name[len] == '\0' || sec_name[len] == '/')
9402 			return true;
9403 		return false;
9404 	}
9405 
9406 	return strcmp(sec_name, sec_def->sec) == 0;
9407 }
9408 
9409 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
9410 {
9411 	const struct bpf_sec_def *sec_def;
9412 	int i, n;
9413 
9414 	n = custom_sec_def_cnt;
9415 	for (i = 0; i < n; i++) {
9416 		sec_def = &custom_sec_defs[i];
9417 		if (sec_def_matches(sec_def, sec_name))
9418 			return sec_def;
9419 	}
9420 
9421 	n = ARRAY_SIZE(section_defs);
9422 	for (i = 0; i < n; i++) {
9423 		sec_def = &section_defs[i];
9424 		if (sec_def_matches(sec_def, sec_name))
9425 			return sec_def;
9426 	}
9427 
9428 	if (has_custom_fallback_def)
9429 		return &custom_fallback_def;
9430 
9431 	return NULL;
9432 }
9433 
9434 #define MAX_TYPE_NAME_SIZE 32
9435 
9436 static char *libbpf_get_type_names(bool attach_type)
9437 {
9438 	int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
9439 	char *buf;
9440 
9441 	buf = malloc(len);
9442 	if (!buf)
9443 		return NULL;
9444 
9445 	buf[0] = '\0';
9446 	/* Forge string buf with all available names */
9447 	for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
9448 		const struct bpf_sec_def *sec_def = &section_defs[i];
9449 
9450 		if (attach_type) {
9451 			if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
9452 				continue;
9453 
9454 			if (!(sec_def->cookie & SEC_ATTACHABLE))
9455 				continue;
9456 		}
9457 
9458 		if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
9459 			free(buf);
9460 			return NULL;
9461 		}
9462 		strcat(buf, " ");
9463 		strcat(buf, section_defs[i].sec);
9464 	}
9465 
9466 	return buf;
9467 }
9468 
9469 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
9470 			     enum bpf_attach_type *expected_attach_type)
9471 {
9472 	const struct bpf_sec_def *sec_def;
9473 	char *type_names;
9474 
9475 	if (!name)
9476 		return libbpf_err(-EINVAL);
9477 
9478 	sec_def = find_sec_def(name);
9479 	if (sec_def) {
9480 		*prog_type = sec_def->prog_type;
9481 		*expected_attach_type = sec_def->expected_attach_type;
9482 		return 0;
9483 	}
9484 
9485 	pr_debug("failed to guess program type from ELF section '%s'\n", name);
9486 	type_names = libbpf_get_type_names(false);
9487 	if (type_names != NULL) {
9488 		pr_debug("supported section(type) names are:%s\n", type_names);
9489 		free(type_names);
9490 	}
9491 
9492 	return libbpf_err(-ESRCH);
9493 }
9494 
9495 const char *libbpf_bpf_attach_type_str(enum bpf_attach_type t)
9496 {
9497 	if (t < 0 || t >= ARRAY_SIZE(attach_type_name))
9498 		return NULL;
9499 
9500 	return attach_type_name[t];
9501 }
9502 
9503 const char *libbpf_bpf_link_type_str(enum bpf_link_type t)
9504 {
9505 	if (t < 0 || t >= ARRAY_SIZE(link_type_name))
9506 		return NULL;
9507 
9508 	return link_type_name[t];
9509 }
9510 
9511 const char *libbpf_bpf_map_type_str(enum bpf_map_type t)
9512 {
9513 	if (t < 0 || t >= ARRAY_SIZE(map_type_name))
9514 		return NULL;
9515 
9516 	return map_type_name[t];
9517 }
9518 
9519 const char *libbpf_bpf_prog_type_str(enum bpf_prog_type t)
9520 {
9521 	if (t < 0 || t >= ARRAY_SIZE(prog_type_name))
9522 		return NULL;
9523 
9524 	return prog_type_name[t];
9525 }
9526 
9527 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
9528 						     int sec_idx,
9529 						     size_t offset)
9530 {
9531 	struct bpf_map *map;
9532 	size_t i;
9533 
9534 	for (i = 0; i < obj->nr_maps; i++) {
9535 		map = &obj->maps[i];
9536 		if (!bpf_map__is_struct_ops(map))
9537 			continue;
9538 		if (map->sec_idx == sec_idx &&
9539 		    map->sec_offset <= offset &&
9540 		    offset - map->sec_offset < map->def.value_size)
9541 			return map;
9542 	}
9543 
9544 	return NULL;
9545 }
9546 
9547 /* Collect the reloc from ELF and populate the st_ops->progs[] */
9548 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
9549 					    Elf64_Shdr *shdr, Elf_Data *data)
9550 {
9551 	const struct btf_member *member;
9552 	struct bpf_struct_ops *st_ops;
9553 	struct bpf_program *prog;
9554 	unsigned int shdr_idx;
9555 	const struct btf *btf;
9556 	struct bpf_map *map;
9557 	unsigned int moff, insn_idx;
9558 	const char *name;
9559 	__u32 member_idx;
9560 	Elf64_Sym *sym;
9561 	Elf64_Rel *rel;
9562 	int i, nrels;
9563 
9564 	btf = obj->btf;
9565 	nrels = shdr->sh_size / shdr->sh_entsize;
9566 	for (i = 0; i < nrels; i++) {
9567 		rel = elf_rel_by_idx(data, i);
9568 		if (!rel) {
9569 			pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
9570 			return -LIBBPF_ERRNO__FORMAT;
9571 		}
9572 
9573 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
9574 		if (!sym) {
9575 			pr_warn("struct_ops reloc: symbol %zx not found\n",
9576 				(size_t)ELF64_R_SYM(rel->r_info));
9577 			return -LIBBPF_ERRNO__FORMAT;
9578 		}
9579 
9580 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
9581 		map = find_struct_ops_map_by_offset(obj, shdr->sh_info, rel->r_offset);
9582 		if (!map) {
9583 			pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
9584 				(size_t)rel->r_offset);
9585 			return -EINVAL;
9586 		}
9587 
9588 		moff = rel->r_offset - map->sec_offset;
9589 		shdr_idx = sym->st_shndx;
9590 		st_ops = map->st_ops;
9591 		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",
9592 			 map->name,
9593 			 (long long)(rel->r_info >> 32),
9594 			 (long long)sym->st_value,
9595 			 shdr_idx, (size_t)rel->r_offset,
9596 			 map->sec_offset, sym->st_name, name);
9597 
9598 		if (shdr_idx >= SHN_LORESERVE) {
9599 			pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
9600 				map->name, (size_t)rel->r_offset, shdr_idx);
9601 			return -LIBBPF_ERRNO__RELOC;
9602 		}
9603 		if (sym->st_value % BPF_INSN_SZ) {
9604 			pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
9605 				map->name, (unsigned long long)sym->st_value);
9606 			return -LIBBPF_ERRNO__FORMAT;
9607 		}
9608 		insn_idx = sym->st_value / BPF_INSN_SZ;
9609 
9610 		member = find_member_by_offset(st_ops->type, moff * 8);
9611 		if (!member) {
9612 			pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
9613 				map->name, moff);
9614 			return -EINVAL;
9615 		}
9616 		member_idx = member - btf_members(st_ops->type);
9617 		name = btf__name_by_offset(btf, member->name_off);
9618 
9619 		if (!resolve_func_ptr(btf, member->type, NULL)) {
9620 			pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
9621 				map->name, name);
9622 			return -EINVAL;
9623 		}
9624 
9625 		prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
9626 		if (!prog) {
9627 			pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
9628 				map->name, shdr_idx, name);
9629 			return -EINVAL;
9630 		}
9631 
9632 		/* prevent the use of BPF prog with invalid type */
9633 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
9634 			pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
9635 				map->name, prog->name);
9636 			return -EINVAL;
9637 		}
9638 
9639 		/* if we haven't yet processed this BPF program, record proper
9640 		 * attach_btf_id and member_idx
9641 		 */
9642 		if (!prog->attach_btf_id) {
9643 			prog->attach_btf_id = st_ops->type_id;
9644 			prog->expected_attach_type = member_idx;
9645 		}
9646 
9647 		/* struct_ops BPF prog can be re-used between multiple
9648 		 * .struct_ops & .struct_ops.link as long as it's the
9649 		 * same struct_ops struct definition and the same
9650 		 * function pointer field
9651 		 */
9652 		if (prog->attach_btf_id != st_ops->type_id ||
9653 		    prog->expected_attach_type != member_idx) {
9654 			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",
9655 				map->name, prog->name, prog->sec_name, prog->type,
9656 				prog->attach_btf_id, prog->expected_attach_type, name);
9657 			return -EINVAL;
9658 		}
9659 
9660 		st_ops->progs[member_idx] = prog;
9661 	}
9662 
9663 	return 0;
9664 }
9665 
9666 #define BTF_TRACE_PREFIX "btf_trace_"
9667 #define BTF_LSM_PREFIX "bpf_lsm_"
9668 #define BTF_ITER_PREFIX "bpf_iter_"
9669 #define BTF_MAX_NAME_SIZE 128
9670 
9671 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
9672 				const char **prefix, int *kind)
9673 {
9674 	switch (attach_type) {
9675 	case BPF_TRACE_RAW_TP:
9676 		*prefix = BTF_TRACE_PREFIX;
9677 		*kind = BTF_KIND_TYPEDEF;
9678 		break;
9679 	case BPF_LSM_MAC:
9680 	case BPF_LSM_CGROUP:
9681 		*prefix = BTF_LSM_PREFIX;
9682 		*kind = BTF_KIND_FUNC;
9683 		break;
9684 	case BPF_TRACE_ITER:
9685 		*prefix = BTF_ITER_PREFIX;
9686 		*kind = BTF_KIND_FUNC;
9687 		break;
9688 	default:
9689 		*prefix = "";
9690 		*kind = BTF_KIND_FUNC;
9691 	}
9692 }
9693 
9694 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
9695 				   const char *name, __u32 kind)
9696 {
9697 	char btf_type_name[BTF_MAX_NAME_SIZE];
9698 	int ret;
9699 
9700 	ret = snprintf(btf_type_name, sizeof(btf_type_name),
9701 		       "%s%s", prefix, name);
9702 	/* snprintf returns the number of characters written excluding the
9703 	 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
9704 	 * indicates truncation.
9705 	 */
9706 	if (ret < 0 || ret >= sizeof(btf_type_name))
9707 		return -ENAMETOOLONG;
9708 	return btf__find_by_name_kind(btf, btf_type_name, kind);
9709 }
9710 
9711 static inline int find_attach_btf_id(struct btf *btf, const char *name,
9712 				     enum bpf_attach_type attach_type)
9713 {
9714 	const char *prefix;
9715 	int kind;
9716 
9717 	btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
9718 	return find_btf_by_prefix_kind(btf, prefix, name, kind);
9719 }
9720 
9721 int libbpf_find_vmlinux_btf_id(const char *name,
9722 			       enum bpf_attach_type attach_type)
9723 {
9724 	struct btf *btf;
9725 	int err;
9726 
9727 	btf = btf__load_vmlinux_btf();
9728 	err = libbpf_get_error(btf);
9729 	if (err) {
9730 		pr_warn("vmlinux BTF is not found\n");
9731 		return libbpf_err(err);
9732 	}
9733 
9734 	err = find_attach_btf_id(btf, name, attach_type);
9735 	if (err <= 0)
9736 		pr_warn("%s is not found in vmlinux BTF\n", name);
9737 
9738 	btf__free(btf);
9739 	return libbpf_err(err);
9740 }
9741 
9742 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
9743 {
9744 	struct bpf_prog_info info;
9745 	__u32 info_len = sizeof(info);
9746 	struct btf *btf;
9747 	int err;
9748 
9749 	memset(&info, 0, info_len);
9750 	err = bpf_prog_get_info_by_fd(attach_prog_fd, &info, &info_len);
9751 	if (err) {
9752 		pr_warn("failed bpf_prog_get_info_by_fd for FD %d: %d\n",
9753 			attach_prog_fd, err);
9754 		return err;
9755 	}
9756 
9757 	err = -EINVAL;
9758 	if (!info.btf_id) {
9759 		pr_warn("The target program doesn't have BTF\n");
9760 		goto out;
9761 	}
9762 	btf = btf__load_from_kernel_by_id(info.btf_id);
9763 	err = libbpf_get_error(btf);
9764 	if (err) {
9765 		pr_warn("Failed to get BTF %d of the program: %d\n", info.btf_id, err);
9766 		goto out;
9767 	}
9768 	err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
9769 	btf__free(btf);
9770 	if (err <= 0) {
9771 		pr_warn("%s is not found in prog's BTF\n", name);
9772 		goto out;
9773 	}
9774 out:
9775 	return err;
9776 }
9777 
9778 static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
9779 			      enum bpf_attach_type attach_type,
9780 			      int *btf_obj_fd, int *btf_type_id)
9781 {
9782 	int ret, i;
9783 
9784 	ret = find_attach_btf_id(obj->btf_vmlinux, attach_name, attach_type);
9785 	if (ret > 0) {
9786 		*btf_obj_fd = 0; /* vmlinux BTF */
9787 		*btf_type_id = ret;
9788 		return 0;
9789 	}
9790 	if (ret != -ENOENT)
9791 		return ret;
9792 
9793 	ret = load_module_btfs(obj);
9794 	if (ret)
9795 		return ret;
9796 
9797 	for (i = 0; i < obj->btf_module_cnt; i++) {
9798 		const struct module_btf *mod = &obj->btf_modules[i];
9799 
9800 		ret = find_attach_btf_id(mod->btf, attach_name, attach_type);
9801 		if (ret > 0) {
9802 			*btf_obj_fd = mod->fd;
9803 			*btf_type_id = ret;
9804 			return 0;
9805 		}
9806 		if (ret == -ENOENT)
9807 			continue;
9808 
9809 		return ret;
9810 	}
9811 
9812 	return -ESRCH;
9813 }
9814 
9815 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
9816 				     int *btf_obj_fd, int *btf_type_id)
9817 {
9818 	enum bpf_attach_type attach_type = prog->expected_attach_type;
9819 	__u32 attach_prog_fd = prog->attach_prog_fd;
9820 	int err = 0;
9821 
9822 	/* BPF program's BTF ID */
9823 	if (prog->type == BPF_PROG_TYPE_EXT || attach_prog_fd) {
9824 		if (!attach_prog_fd) {
9825 			pr_warn("prog '%s': attach program FD is not set\n", prog->name);
9826 			return -EINVAL;
9827 		}
9828 		err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd);
9829 		if (err < 0) {
9830 			pr_warn("prog '%s': failed to find BPF program (FD %d) BTF ID for '%s': %d\n",
9831 				 prog->name, attach_prog_fd, attach_name, err);
9832 			return err;
9833 		}
9834 		*btf_obj_fd = 0;
9835 		*btf_type_id = err;
9836 		return 0;
9837 	}
9838 
9839 	/* kernel/module BTF ID */
9840 	if (prog->obj->gen_loader) {
9841 		bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
9842 		*btf_obj_fd = 0;
9843 		*btf_type_id = 1;
9844 	} else {
9845 		err = find_kernel_btf_id(prog->obj, attach_name, attach_type, btf_obj_fd, btf_type_id);
9846 	}
9847 	if (err) {
9848 		pr_warn("prog '%s': failed to find kernel BTF type ID of '%s': %d\n",
9849 			prog->name, attach_name, err);
9850 		return err;
9851 	}
9852 	return 0;
9853 }
9854 
9855 int libbpf_attach_type_by_name(const char *name,
9856 			       enum bpf_attach_type *attach_type)
9857 {
9858 	char *type_names;
9859 	const struct bpf_sec_def *sec_def;
9860 
9861 	if (!name)
9862 		return libbpf_err(-EINVAL);
9863 
9864 	sec_def = find_sec_def(name);
9865 	if (!sec_def) {
9866 		pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
9867 		type_names = libbpf_get_type_names(true);
9868 		if (type_names != NULL) {
9869 			pr_debug("attachable section(type) names are:%s\n", type_names);
9870 			free(type_names);
9871 		}
9872 
9873 		return libbpf_err(-EINVAL);
9874 	}
9875 
9876 	if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
9877 		return libbpf_err(-EINVAL);
9878 	if (!(sec_def->cookie & SEC_ATTACHABLE))
9879 		return libbpf_err(-EINVAL);
9880 
9881 	*attach_type = sec_def->expected_attach_type;
9882 	return 0;
9883 }
9884 
9885 int bpf_map__fd(const struct bpf_map *map)
9886 {
9887 	if (!map)
9888 		return libbpf_err(-EINVAL);
9889 	if (!map_is_created(map))
9890 		return -1;
9891 	return map->fd;
9892 }
9893 
9894 static bool map_uses_real_name(const struct bpf_map *map)
9895 {
9896 	/* Since libbpf started to support custom .data.* and .rodata.* maps,
9897 	 * their user-visible name differs from kernel-visible name. Users see
9898 	 * such map's corresponding ELF section name as a map name.
9899 	 * This check distinguishes .data/.rodata from .data.* and .rodata.*
9900 	 * maps to know which name has to be returned to the user.
9901 	 */
9902 	if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
9903 		return true;
9904 	if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
9905 		return true;
9906 	return false;
9907 }
9908 
9909 const char *bpf_map__name(const struct bpf_map *map)
9910 {
9911 	if (!map)
9912 		return NULL;
9913 
9914 	if (map_uses_real_name(map))
9915 		return map->real_name;
9916 
9917 	return map->name;
9918 }
9919 
9920 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
9921 {
9922 	return map->def.type;
9923 }
9924 
9925 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
9926 {
9927 	if (map_is_created(map))
9928 		return libbpf_err(-EBUSY);
9929 	map->def.type = type;
9930 	return 0;
9931 }
9932 
9933 __u32 bpf_map__map_flags(const struct bpf_map *map)
9934 {
9935 	return map->def.map_flags;
9936 }
9937 
9938 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
9939 {
9940 	if (map_is_created(map))
9941 		return libbpf_err(-EBUSY);
9942 	map->def.map_flags = flags;
9943 	return 0;
9944 }
9945 
9946 __u64 bpf_map__map_extra(const struct bpf_map *map)
9947 {
9948 	return map->map_extra;
9949 }
9950 
9951 int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
9952 {
9953 	if (map_is_created(map))
9954 		return libbpf_err(-EBUSY);
9955 	map->map_extra = map_extra;
9956 	return 0;
9957 }
9958 
9959 __u32 bpf_map__numa_node(const struct bpf_map *map)
9960 {
9961 	return map->numa_node;
9962 }
9963 
9964 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
9965 {
9966 	if (map_is_created(map))
9967 		return libbpf_err(-EBUSY);
9968 	map->numa_node = numa_node;
9969 	return 0;
9970 }
9971 
9972 __u32 bpf_map__key_size(const struct bpf_map *map)
9973 {
9974 	return map->def.key_size;
9975 }
9976 
9977 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
9978 {
9979 	if (map_is_created(map))
9980 		return libbpf_err(-EBUSY);
9981 	map->def.key_size = size;
9982 	return 0;
9983 }
9984 
9985 __u32 bpf_map__value_size(const struct bpf_map *map)
9986 {
9987 	return map->def.value_size;
9988 }
9989 
9990 static int map_btf_datasec_resize(struct bpf_map *map, __u32 size)
9991 {
9992 	struct btf *btf;
9993 	struct btf_type *datasec_type, *var_type;
9994 	struct btf_var_secinfo *var;
9995 	const struct btf_type *array_type;
9996 	const struct btf_array *array;
9997 	int vlen, element_sz, new_array_id;
9998 	__u32 nr_elements;
9999 
10000 	/* check btf existence */
10001 	btf = bpf_object__btf(map->obj);
10002 	if (!btf)
10003 		return -ENOENT;
10004 
10005 	/* verify map is datasec */
10006 	datasec_type = btf_type_by_id(btf, bpf_map__btf_value_type_id(map));
10007 	if (!btf_is_datasec(datasec_type)) {
10008 		pr_warn("map '%s': cannot be resized, map value type is not a datasec\n",
10009 			bpf_map__name(map));
10010 		return -EINVAL;
10011 	}
10012 
10013 	/* verify datasec has at least one var */
10014 	vlen = btf_vlen(datasec_type);
10015 	if (vlen == 0) {
10016 		pr_warn("map '%s': cannot be resized, map value datasec is empty\n",
10017 			bpf_map__name(map));
10018 		return -EINVAL;
10019 	}
10020 
10021 	/* verify last var in the datasec is an array */
10022 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
10023 	var_type = btf_type_by_id(btf, var->type);
10024 	array_type = skip_mods_and_typedefs(btf, var_type->type, NULL);
10025 	if (!btf_is_array(array_type)) {
10026 		pr_warn("map '%s': cannot be resized, last var must be an array\n",
10027 			bpf_map__name(map));
10028 		return -EINVAL;
10029 	}
10030 
10031 	/* verify request size aligns with array */
10032 	array = btf_array(array_type);
10033 	element_sz = btf__resolve_size(btf, array->type);
10034 	if (element_sz <= 0 || (size - var->offset) % element_sz != 0) {
10035 		pr_warn("map '%s': cannot be resized, element size (%d) doesn't align with new total size (%u)\n",
10036 			bpf_map__name(map), element_sz, size);
10037 		return -EINVAL;
10038 	}
10039 
10040 	/* create a new array based on the existing array, but with new length */
10041 	nr_elements = (size - var->offset) / element_sz;
10042 	new_array_id = btf__add_array(btf, array->index_type, array->type, nr_elements);
10043 	if (new_array_id < 0)
10044 		return new_array_id;
10045 
10046 	/* adding a new btf type invalidates existing pointers to btf objects,
10047 	 * so refresh pointers before proceeding
10048 	 */
10049 	datasec_type = btf_type_by_id(btf, map->btf_value_type_id);
10050 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
10051 	var_type = btf_type_by_id(btf, var->type);
10052 
10053 	/* finally update btf info */
10054 	datasec_type->size = size;
10055 	var->size = size - var->offset;
10056 	var_type->type = new_array_id;
10057 
10058 	return 0;
10059 }
10060 
10061 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
10062 {
10063 	if (map->obj->loaded || map->reused)
10064 		return libbpf_err(-EBUSY);
10065 
10066 	if (map->mmaped) {
10067 		int err;
10068 		size_t mmap_old_sz, mmap_new_sz;
10069 
10070 		mmap_old_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
10071 		mmap_new_sz = bpf_map_mmap_sz(size, map->def.max_entries);
10072 		err = bpf_map_mmap_resize(map, mmap_old_sz, mmap_new_sz);
10073 		if (err) {
10074 			pr_warn("map '%s': failed to resize memory-mapped region: %d\n",
10075 				bpf_map__name(map), err);
10076 			return err;
10077 		}
10078 		err = map_btf_datasec_resize(map, size);
10079 		if (err && err != -ENOENT) {
10080 			pr_warn("map '%s': failed to adjust resized BTF, clearing BTF key/value info: %d\n",
10081 				bpf_map__name(map), err);
10082 			map->btf_value_type_id = 0;
10083 			map->btf_key_type_id = 0;
10084 		}
10085 	}
10086 
10087 	map->def.value_size = size;
10088 	return 0;
10089 }
10090 
10091 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
10092 {
10093 	return map ? map->btf_key_type_id : 0;
10094 }
10095 
10096 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
10097 {
10098 	return map ? map->btf_value_type_id : 0;
10099 }
10100 
10101 int bpf_map__set_initial_value(struct bpf_map *map,
10102 			       const void *data, size_t size)
10103 {
10104 	if (map->obj->loaded || map->reused)
10105 		return libbpf_err(-EBUSY);
10106 
10107 	if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG ||
10108 	    size != map->def.value_size)
10109 		return libbpf_err(-EINVAL);
10110 
10111 	memcpy(map->mmaped, data, size);
10112 	return 0;
10113 }
10114 
10115 void *bpf_map__initial_value(struct bpf_map *map, size_t *psize)
10116 {
10117 	if (!map->mmaped)
10118 		return NULL;
10119 	*psize = map->def.value_size;
10120 	return map->mmaped;
10121 }
10122 
10123 bool bpf_map__is_internal(const struct bpf_map *map)
10124 {
10125 	return map->libbpf_type != LIBBPF_MAP_UNSPEC;
10126 }
10127 
10128 __u32 bpf_map__ifindex(const struct bpf_map *map)
10129 {
10130 	return map->map_ifindex;
10131 }
10132 
10133 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
10134 {
10135 	if (map_is_created(map))
10136 		return libbpf_err(-EBUSY);
10137 	map->map_ifindex = ifindex;
10138 	return 0;
10139 }
10140 
10141 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
10142 {
10143 	if (!bpf_map_type__is_map_in_map(map->def.type)) {
10144 		pr_warn("error: unsupported map type\n");
10145 		return libbpf_err(-EINVAL);
10146 	}
10147 	if (map->inner_map_fd != -1) {
10148 		pr_warn("error: inner_map_fd already specified\n");
10149 		return libbpf_err(-EINVAL);
10150 	}
10151 	if (map->inner_map) {
10152 		bpf_map__destroy(map->inner_map);
10153 		zfree(&map->inner_map);
10154 	}
10155 	map->inner_map_fd = fd;
10156 	return 0;
10157 }
10158 
10159 static struct bpf_map *
10160 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
10161 {
10162 	ssize_t idx;
10163 	struct bpf_map *s, *e;
10164 
10165 	if (!obj || !obj->maps)
10166 		return errno = EINVAL, NULL;
10167 
10168 	s = obj->maps;
10169 	e = obj->maps + obj->nr_maps;
10170 
10171 	if ((m < s) || (m >= e)) {
10172 		pr_warn("error in %s: map handler doesn't belong to object\n",
10173 			 __func__);
10174 		return errno = EINVAL, NULL;
10175 	}
10176 
10177 	idx = (m - obj->maps) + i;
10178 	if (idx >= obj->nr_maps || idx < 0)
10179 		return NULL;
10180 	return &obj->maps[idx];
10181 }
10182 
10183 struct bpf_map *
10184 bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
10185 {
10186 	if (prev == NULL)
10187 		return obj->maps;
10188 
10189 	return __bpf_map__iter(prev, obj, 1);
10190 }
10191 
10192 struct bpf_map *
10193 bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
10194 {
10195 	if (next == NULL) {
10196 		if (!obj->nr_maps)
10197 			return NULL;
10198 		return obj->maps + obj->nr_maps - 1;
10199 	}
10200 
10201 	return __bpf_map__iter(next, obj, -1);
10202 }
10203 
10204 struct bpf_map *
10205 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
10206 {
10207 	struct bpf_map *pos;
10208 
10209 	bpf_object__for_each_map(pos, obj) {
10210 		/* if it's a special internal map name (which always starts
10211 		 * with dot) then check if that special name matches the
10212 		 * real map name (ELF section name)
10213 		 */
10214 		if (name[0] == '.') {
10215 			if (pos->real_name && strcmp(pos->real_name, name) == 0)
10216 				return pos;
10217 			continue;
10218 		}
10219 		/* otherwise map name has to be an exact match */
10220 		if (map_uses_real_name(pos)) {
10221 			if (strcmp(pos->real_name, name) == 0)
10222 				return pos;
10223 			continue;
10224 		}
10225 		if (strcmp(pos->name, name) == 0)
10226 			return pos;
10227 	}
10228 	return errno = ENOENT, NULL;
10229 }
10230 
10231 int
10232 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
10233 {
10234 	return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
10235 }
10236 
10237 static int validate_map_op(const struct bpf_map *map, size_t key_sz,
10238 			   size_t value_sz, bool check_value_sz)
10239 {
10240 	if (!map_is_created(map)) /* map is not yet created */
10241 		return -ENOENT;
10242 
10243 	if (map->def.key_size != key_sz) {
10244 		pr_warn("map '%s': unexpected key size %zu provided, expected %u\n",
10245 			map->name, key_sz, map->def.key_size);
10246 		return -EINVAL;
10247 	}
10248 
10249 	if (!check_value_sz)
10250 		return 0;
10251 
10252 	switch (map->def.type) {
10253 	case BPF_MAP_TYPE_PERCPU_ARRAY:
10254 	case BPF_MAP_TYPE_PERCPU_HASH:
10255 	case BPF_MAP_TYPE_LRU_PERCPU_HASH:
10256 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: {
10257 		int num_cpu = libbpf_num_possible_cpus();
10258 		size_t elem_sz = roundup(map->def.value_size, 8);
10259 
10260 		if (value_sz != num_cpu * elem_sz) {
10261 			pr_warn("map '%s': unexpected value size %zu provided for per-CPU map, expected %d * %zu = %zd\n",
10262 				map->name, value_sz, num_cpu, elem_sz, num_cpu * elem_sz);
10263 			return -EINVAL;
10264 		}
10265 		break;
10266 	}
10267 	default:
10268 		if (map->def.value_size != value_sz) {
10269 			pr_warn("map '%s': unexpected value size %zu provided, expected %u\n",
10270 				map->name, value_sz, map->def.value_size);
10271 			return -EINVAL;
10272 		}
10273 		break;
10274 	}
10275 	return 0;
10276 }
10277 
10278 int bpf_map__lookup_elem(const struct bpf_map *map,
10279 			 const void *key, size_t key_sz,
10280 			 void *value, size_t value_sz, __u64 flags)
10281 {
10282 	int err;
10283 
10284 	err = validate_map_op(map, key_sz, value_sz, true);
10285 	if (err)
10286 		return libbpf_err(err);
10287 
10288 	return bpf_map_lookup_elem_flags(map->fd, key, value, flags);
10289 }
10290 
10291 int bpf_map__update_elem(const struct bpf_map *map,
10292 			 const void *key, size_t key_sz,
10293 			 const void *value, size_t value_sz, __u64 flags)
10294 {
10295 	int err;
10296 
10297 	err = validate_map_op(map, key_sz, value_sz, true);
10298 	if (err)
10299 		return libbpf_err(err);
10300 
10301 	return bpf_map_update_elem(map->fd, key, value, flags);
10302 }
10303 
10304 int bpf_map__delete_elem(const struct bpf_map *map,
10305 			 const void *key, size_t key_sz, __u64 flags)
10306 {
10307 	int err;
10308 
10309 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
10310 	if (err)
10311 		return libbpf_err(err);
10312 
10313 	return bpf_map_delete_elem_flags(map->fd, key, flags);
10314 }
10315 
10316 int bpf_map__lookup_and_delete_elem(const struct bpf_map *map,
10317 				    const void *key, size_t key_sz,
10318 				    void *value, size_t value_sz, __u64 flags)
10319 {
10320 	int err;
10321 
10322 	err = validate_map_op(map, key_sz, value_sz, true);
10323 	if (err)
10324 		return libbpf_err(err);
10325 
10326 	return bpf_map_lookup_and_delete_elem_flags(map->fd, key, value, flags);
10327 }
10328 
10329 int bpf_map__get_next_key(const struct bpf_map *map,
10330 			  const void *cur_key, void *next_key, size_t key_sz)
10331 {
10332 	int err;
10333 
10334 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
10335 	if (err)
10336 		return libbpf_err(err);
10337 
10338 	return bpf_map_get_next_key(map->fd, cur_key, next_key);
10339 }
10340 
10341 long libbpf_get_error(const void *ptr)
10342 {
10343 	if (!IS_ERR_OR_NULL(ptr))
10344 		return 0;
10345 
10346 	if (IS_ERR(ptr))
10347 		errno = -PTR_ERR(ptr);
10348 
10349 	/* If ptr == NULL, then errno should be already set by the failing
10350 	 * API, because libbpf never returns NULL on success and it now always
10351 	 * sets errno on error. So no extra errno handling for ptr == NULL
10352 	 * case.
10353 	 */
10354 	return -errno;
10355 }
10356 
10357 /* Replace link's underlying BPF program with the new one */
10358 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
10359 {
10360 	int ret;
10361 
10362 	ret = bpf_link_update(bpf_link__fd(link), bpf_program__fd(prog), NULL);
10363 	return libbpf_err_errno(ret);
10364 }
10365 
10366 /* Release "ownership" of underlying BPF resource (typically, BPF program
10367  * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
10368  * link, when destructed through bpf_link__destroy() call won't attempt to
10369  * detach/unregisted that BPF resource. This is useful in situations where,
10370  * say, attached BPF program has to outlive userspace program that attached it
10371  * in the system. Depending on type of BPF program, though, there might be
10372  * additional steps (like pinning BPF program in BPF FS) necessary to ensure
10373  * exit of userspace program doesn't trigger automatic detachment and clean up
10374  * inside the kernel.
10375  */
10376 void bpf_link__disconnect(struct bpf_link *link)
10377 {
10378 	link->disconnected = true;
10379 }
10380 
10381 int bpf_link__destroy(struct bpf_link *link)
10382 {
10383 	int err = 0;
10384 
10385 	if (IS_ERR_OR_NULL(link))
10386 		return 0;
10387 
10388 	if (!link->disconnected && link->detach)
10389 		err = link->detach(link);
10390 	if (link->pin_path)
10391 		free(link->pin_path);
10392 	if (link->dealloc)
10393 		link->dealloc(link);
10394 	else
10395 		free(link);
10396 
10397 	return libbpf_err(err);
10398 }
10399 
10400 int bpf_link__fd(const struct bpf_link *link)
10401 {
10402 	return link->fd;
10403 }
10404 
10405 const char *bpf_link__pin_path(const struct bpf_link *link)
10406 {
10407 	return link->pin_path;
10408 }
10409 
10410 static int bpf_link__detach_fd(struct bpf_link *link)
10411 {
10412 	return libbpf_err_errno(close(link->fd));
10413 }
10414 
10415 struct bpf_link *bpf_link__open(const char *path)
10416 {
10417 	struct bpf_link *link;
10418 	int fd;
10419 
10420 	fd = bpf_obj_get(path);
10421 	if (fd < 0) {
10422 		fd = -errno;
10423 		pr_warn("failed to open link at %s: %d\n", path, fd);
10424 		return libbpf_err_ptr(fd);
10425 	}
10426 
10427 	link = calloc(1, sizeof(*link));
10428 	if (!link) {
10429 		close(fd);
10430 		return libbpf_err_ptr(-ENOMEM);
10431 	}
10432 	link->detach = &bpf_link__detach_fd;
10433 	link->fd = fd;
10434 
10435 	link->pin_path = strdup(path);
10436 	if (!link->pin_path) {
10437 		bpf_link__destroy(link);
10438 		return libbpf_err_ptr(-ENOMEM);
10439 	}
10440 
10441 	return link;
10442 }
10443 
10444 int bpf_link__detach(struct bpf_link *link)
10445 {
10446 	return bpf_link_detach(link->fd) ? -errno : 0;
10447 }
10448 
10449 int bpf_link__pin(struct bpf_link *link, const char *path)
10450 {
10451 	int err;
10452 
10453 	if (link->pin_path)
10454 		return libbpf_err(-EBUSY);
10455 	err = make_parent_dir(path);
10456 	if (err)
10457 		return libbpf_err(err);
10458 	err = check_path(path);
10459 	if (err)
10460 		return libbpf_err(err);
10461 
10462 	link->pin_path = strdup(path);
10463 	if (!link->pin_path)
10464 		return libbpf_err(-ENOMEM);
10465 
10466 	if (bpf_obj_pin(link->fd, link->pin_path)) {
10467 		err = -errno;
10468 		zfree(&link->pin_path);
10469 		return libbpf_err(err);
10470 	}
10471 
10472 	pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
10473 	return 0;
10474 }
10475 
10476 int bpf_link__unpin(struct bpf_link *link)
10477 {
10478 	int err;
10479 
10480 	if (!link->pin_path)
10481 		return libbpf_err(-EINVAL);
10482 
10483 	err = unlink(link->pin_path);
10484 	if (err != 0)
10485 		return -errno;
10486 
10487 	pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
10488 	zfree(&link->pin_path);
10489 	return 0;
10490 }
10491 
10492 struct bpf_link_perf {
10493 	struct bpf_link link;
10494 	int perf_event_fd;
10495 	/* legacy kprobe support: keep track of probe identifier and type */
10496 	char *legacy_probe_name;
10497 	bool legacy_is_kprobe;
10498 	bool legacy_is_retprobe;
10499 };
10500 
10501 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
10502 static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
10503 
10504 static int bpf_link_perf_detach(struct bpf_link *link)
10505 {
10506 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10507 	int err = 0;
10508 
10509 	if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
10510 		err = -errno;
10511 
10512 	if (perf_link->perf_event_fd != link->fd)
10513 		close(perf_link->perf_event_fd);
10514 	close(link->fd);
10515 
10516 	/* legacy uprobe/kprobe needs to be removed after perf event fd closure */
10517 	if (perf_link->legacy_probe_name) {
10518 		if (perf_link->legacy_is_kprobe) {
10519 			err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
10520 							 perf_link->legacy_is_retprobe);
10521 		} else {
10522 			err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
10523 							 perf_link->legacy_is_retprobe);
10524 		}
10525 	}
10526 
10527 	return err;
10528 }
10529 
10530 static void bpf_link_perf_dealloc(struct bpf_link *link)
10531 {
10532 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10533 
10534 	free(perf_link->legacy_probe_name);
10535 	free(perf_link);
10536 }
10537 
10538 struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
10539 						     const struct bpf_perf_event_opts *opts)
10540 {
10541 	char errmsg[STRERR_BUFSIZE];
10542 	struct bpf_link_perf *link;
10543 	int prog_fd, link_fd = -1, err;
10544 	bool force_ioctl_attach;
10545 
10546 	if (!OPTS_VALID(opts, bpf_perf_event_opts))
10547 		return libbpf_err_ptr(-EINVAL);
10548 
10549 	if (pfd < 0) {
10550 		pr_warn("prog '%s': invalid perf event FD %d\n",
10551 			prog->name, pfd);
10552 		return libbpf_err_ptr(-EINVAL);
10553 	}
10554 	prog_fd = bpf_program__fd(prog);
10555 	if (prog_fd < 0) {
10556 		pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
10557 			prog->name);
10558 		return libbpf_err_ptr(-EINVAL);
10559 	}
10560 
10561 	link = calloc(1, sizeof(*link));
10562 	if (!link)
10563 		return libbpf_err_ptr(-ENOMEM);
10564 	link->link.detach = &bpf_link_perf_detach;
10565 	link->link.dealloc = &bpf_link_perf_dealloc;
10566 	link->perf_event_fd = pfd;
10567 
10568 	force_ioctl_attach = OPTS_GET(opts, force_ioctl_attach, false);
10569 	if (kernel_supports(prog->obj, FEAT_PERF_LINK) && !force_ioctl_attach) {
10570 		DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
10571 			.perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
10572 
10573 		link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
10574 		if (link_fd < 0) {
10575 			err = -errno;
10576 			pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %d (%s)\n",
10577 				prog->name, pfd,
10578 				err, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10579 			goto err_out;
10580 		}
10581 		link->link.fd = link_fd;
10582 	} else {
10583 		if (OPTS_GET(opts, bpf_cookie, 0)) {
10584 			pr_warn("prog '%s': user context value is not supported\n", prog->name);
10585 			err = -EOPNOTSUPP;
10586 			goto err_out;
10587 		}
10588 
10589 		if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
10590 			err = -errno;
10591 			pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
10592 				prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10593 			if (err == -EPROTO)
10594 				pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
10595 					prog->name, pfd);
10596 			goto err_out;
10597 		}
10598 		link->link.fd = pfd;
10599 	}
10600 	if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
10601 		err = -errno;
10602 		pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
10603 			prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10604 		goto err_out;
10605 	}
10606 
10607 	return &link->link;
10608 err_out:
10609 	if (link_fd >= 0)
10610 		close(link_fd);
10611 	free(link);
10612 	return libbpf_err_ptr(err);
10613 }
10614 
10615 struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
10616 {
10617 	return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
10618 }
10619 
10620 /*
10621  * this function is expected to parse integer in the range of [0, 2^31-1] from
10622  * given file using scanf format string fmt. If actual parsed value is
10623  * negative, the result might be indistinguishable from error
10624  */
10625 static int parse_uint_from_file(const char *file, const char *fmt)
10626 {
10627 	char buf[STRERR_BUFSIZE];
10628 	int err, ret;
10629 	FILE *f;
10630 
10631 	f = fopen(file, "re");
10632 	if (!f) {
10633 		err = -errno;
10634 		pr_debug("failed to open '%s': %s\n", file,
10635 			 libbpf_strerror_r(err, buf, sizeof(buf)));
10636 		return err;
10637 	}
10638 	err = fscanf(f, fmt, &ret);
10639 	if (err != 1) {
10640 		err = err == EOF ? -EIO : -errno;
10641 		pr_debug("failed to parse '%s': %s\n", file,
10642 			libbpf_strerror_r(err, buf, sizeof(buf)));
10643 		fclose(f);
10644 		return err;
10645 	}
10646 	fclose(f);
10647 	return ret;
10648 }
10649 
10650 static int determine_kprobe_perf_type(void)
10651 {
10652 	const char *file = "/sys/bus/event_source/devices/kprobe/type";
10653 
10654 	return parse_uint_from_file(file, "%d\n");
10655 }
10656 
10657 static int determine_uprobe_perf_type(void)
10658 {
10659 	const char *file = "/sys/bus/event_source/devices/uprobe/type";
10660 
10661 	return parse_uint_from_file(file, "%d\n");
10662 }
10663 
10664 static int determine_kprobe_retprobe_bit(void)
10665 {
10666 	const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
10667 
10668 	return parse_uint_from_file(file, "config:%d\n");
10669 }
10670 
10671 static int determine_uprobe_retprobe_bit(void)
10672 {
10673 	const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
10674 
10675 	return parse_uint_from_file(file, "config:%d\n");
10676 }
10677 
10678 #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
10679 #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
10680 
10681 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
10682 				 uint64_t offset, int pid, size_t ref_ctr_off)
10683 {
10684 	const size_t attr_sz = sizeof(struct perf_event_attr);
10685 	struct perf_event_attr attr;
10686 	char errmsg[STRERR_BUFSIZE];
10687 	int type, pfd;
10688 
10689 	if ((__u64)ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
10690 		return -EINVAL;
10691 
10692 	memset(&attr, 0, attr_sz);
10693 
10694 	type = uprobe ? determine_uprobe_perf_type()
10695 		      : determine_kprobe_perf_type();
10696 	if (type < 0) {
10697 		pr_warn("failed to determine %s perf type: %s\n",
10698 			uprobe ? "uprobe" : "kprobe",
10699 			libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
10700 		return type;
10701 	}
10702 	if (retprobe) {
10703 		int bit = uprobe ? determine_uprobe_retprobe_bit()
10704 				 : determine_kprobe_retprobe_bit();
10705 
10706 		if (bit < 0) {
10707 			pr_warn("failed to determine %s retprobe bit: %s\n",
10708 				uprobe ? "uprobe" : "kprobe",
10709 				libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
10710 			return bit;
10711 		}
10712 		attr.config |= 1 << bit;
10713 	}
10714 	attr.size = attr_sz;
10715 	attr.type = type;
10716 	attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
10717 	attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
10718 	attr.config2 = offset;		 /* kprobe_addr or probe_offset */
10719 
10720 	/* pid filter is meaningful only for uprobes */
10721 	pfd = syscall(__NR_perf_event_open, &attr,
10722 		      pid < 0 ? -1 : pid /* pid */,
10723 		      pid == -1 ? 0 : -1 /* cpu */,
10724 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
10725 	return pfd >= 0 ? pfd : -errno;
10726 }
10727 
10728 static int append_to_file(const char *file, const char *fmt, ...)
10729 {
10730 	int fd, n, err = 0;
10731 	va_list ap;
10732 	char buf[1024];
10733 
10734 	va_start(ap, fmt);
10735 	n = vsnprintf(buf, sizeof(buf), fmt, ap);
10736 	va_end(ap);
10737 
10738 	if (n < 0 || n >= sizeof(buf))
10739 		return -EINVAL;
10740 
10741 	fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
10742 	if (fd < 0)
10743 		return -errno;
10744 
10745 	if (write(fd, buf, n) < 0)
10746 		err = -errno;
10747 
10748 	close(fd);
10749 	return err;
10750 }
10751 
10752 #define DEBUGFS "/sys/kernel/debug/tracing"
10753 #define TRACEFS "/sys/kernel/tracing"
10754 
10755 static bool use_debugfs(void)
10756 {
10757 	static int has_debugfs = -1;
10758 
10759 	if (has_debugfs < 0)
10760 		has_debugfs = faccessat(AT_FDCWD, DEBUGFS, F_OK, AT_EACCESS) == 0;
10761 
10762 	return has_debugfs == 1;
10763 }
10764 
10765 static const char *tracefs_path(void)
10766 {
10767 	return use_debugfs() ? DEBUGFS : TRACEFS;
10768 }
10769 
10770 static const char *tracefs_kprobe_events(void)
10771 {
10772 	return use_debugfs() ? DEBUGFS"/kprobe_events" : TRACEFS"/kprobe_events";
10773 }
10774 
10775 static const char *tracefs_uprobe_events(void)
10776 {
10777 	return use_debugfs() ? DEBUGFS"/uprobe_events" : TRACEFS"/uprobe_events";
10778 }
10779 
10780 static const char *tracefs_available_filter_functions(void)
10781 {
10782 	return use_debugfs() ? DEBUGFS"/available_filter_functions"
10783 			     : TRACEFS"/available_filter_functions";
10784 }
10785 
10786 static const char *tracefs_available_filter_functions_addrs(void)
10787 {
10788 	return use_debugfs() ? DEBUGFS"/available_filter_functions_addrs"
10789 			     : TRACEFS"/available_filter_functions_addrs";
10790 }
10791 
10792 static void gen_kprobe_legacy_event_name(char *buf, size_t buf_sz,
10793 					 const char *kfunc_name, size_t offset)
10794 {
10795 	static int index = 0;
10796 	int i;
10797 
10798 	snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx_%d", getpid(), kfunc_name, offset,
10799 		 __sync_fetch_and_add(&index, 1));
10800 
10801 	/* sanitize binary_path in the probe name */
10802 	for (i = 0; buf[i]; i++) {
10803 		if (!isalnum(buf[i]))
10804 			buf[i] = '_';
10805 	}
10806 }
10807 
10808 static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
10809 				   const char *kfunc_name, size_t offset)
10810 {
10811 	return append_to_file(tracefs_kprobe_events(), "%c:%s/%s %s+0x%zx",
10812 			      retprobe ? 'r' : 'p',
10813 			      retprobe ? "kretprobes" : "kprobes",
10814 			      probe_name, kfunc_name, offset);
10815 }
10816 
10817 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
10818 {
10819 	return append_to_file(tracefs_kprobe_events(), "-:%s/%s",
10820 			      retprobe ? "kretprobes" : "kprobes", probe_name);
10821 }
10822 
10823 static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
10824 {
10825 	char file[256];
10826 
10827 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
10828 		 tracefs_path(), retprobe ? "kretprobes" : "kprobes", probe_name);
10829 
10830 	return parse_uint_from_file(file, "%d\n");
10831 }
10832 
10833 static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
10834 					 const char *kfunc_name, size_t offset, int pid)
10835 {
10836 	const size_t attr_sz = sizeof(struct perf_event_attr);
10837 	struct perf_event_attr attr;
10838 	char errmsg[STRERR_BUFSIZE];
10839 	int type, pfd, err;
10840 
10841 	err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
10842 	if (err < 0) {
10843 		pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
10844 			kfunc_name, offset,
10845 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10846 		return err;
10847 	}
10848 	type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
10849 	if (type < 0) {
10850 		err = type;
10851 		pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
10852 			kfunc_name, offset,
10853 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10854 		goto err_clean_legacy;
10855 	}
10856 
10857 	memset(&attr, 0, attr_sz);
10858 	attr.size = attr_sz;
10859 	attr.config = type;
10860 	attr.type = PERF_TYPE_TRACEPOINT;
10861 
10862 	pfd = syscall(__NR_perf_event_open, &attr,
10863 		      pid < 0 ? -1 : pid, /* pid */
10864 		      pid == -1 ? 0 : -1, /* cpu */
10865 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
10866 	if (pfd < 0) {
10867 		err = -errno;
10868 		pr_warn("legacy kprobe perf_event_open() failed: %s\n",
10869 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10870 		goto err_clean_legacy;
10871 	}
10872 	return pfd;
10873 
10874 err_clean_legacy:
10875 	/* Clear the newly added legacy kprobe_event */
10876 	remove_kprobe_event_legacy(probe_name, retprobe);
10877 	return err;
10878 }
10879 
10880 static const char *arch_specific_syscall_pfx(void)
10881 {
10882 #if defined(__x86_64__)
10883 	return "x64";
10884 #elif defined(__i386__)
10885 	return "ia32";
10886 #elif defined(__s390x__)
10887 	return "s390x";
10888 #elif defined(__s390__)
10889 	return "s390";
10890 #elif defined(__arm__)
10891 	return "arm";
10892 #elif defined(__aarch64__)
10893 	return "arm64";
10894 #elif defined(__mips__)
10895 	return "mips";
10896 #elif defined(__riscv)
10897 	return "riscv";
10898 #elif defined(__powerpc__)
10899 	return "powerpc";
10900 #elif defined(__powerpc64__)
10901 	return "powerpc64";
10902 #else
10903 	return NULL;
10904 #endif
10905 }
10906 
10907 static int probe_kern_syscall_wrapper(void)
10908 {
10909 	char syscall_name[64];
10910 	const char *ksys_pfx;
10911 
10912 	ksys_pfx = arch_specific_syscall_pfx();
10913 	if (!ksys_pfx)
10914 		return 0;
10915 
10916 	snprintf(syscall_name, sizeof(syscall_name), "__%s_sys_bpf", ksys_pfx);
10917 
10918 	if (determine_kprobe_perf_type() >= 0) {
10919 		int pfd;
10920 
10921 		pfd = perf_event_open_probe(false, false, syscall_name, 0, getpid(), 0);
10922 		if (pfd >= 0)
10923 			close(pfd);
10924 
10925 		return pfd >= 0 ? 1 : 0;
10926 	} else { /* legacy mode */
10927 		char probe_name[128];
10928 
10929 		gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name), syscall_name, 0);
10930 		if (add_kprobe_event_legacy(probe_name, false, syscall_name, 0) < 0)
10931 			return 0;
10932 
10933 		(void)remove_kprobe_event_legacy(probe_name, false);
10934 		return 1;
10935 	}
10936 }
10937 
10938 struct bpf_link *
10939 bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
10940 				const char *func_name,
10941 				const struct bpf_kprobe_opts *opts)
10942 {
10943 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
10944 	enum probe_attach_mode attach_mode;
10945 	char errmsg[STRERR_BUFSIZE];
10946 	char *legacy_probe = NULL;
10947 	struct bpf_link *link;
10948 	size_t offset;
10949 	bool retprobe, legacy;
10950 	int pfd, err;
10951 
10952 	if (!OPTS_VALID(opts, bpf_kprobe_opts))
10953 		return libbpf_err_ptr(-EINVAL);
10954 
10955 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
10956 	retprobe = OPTS_GET(opts, retprobe, false);
10957 	offset = OPTS_GET(opts, offset, 0);
10958 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10959 
10960 	legacy = determine_kprobe_perf_type() < 0;
10961 	switch (attach_mode) {
10962 	case PROBE_ATTACH_MODE_LEGACY:
10963 		legacy = true;
10964 		pe_opts.force_ioctl_attach = true;
10965 		break;
10966 	case PROBE_ATTACH_MODE_PERF:
10967 		if (legacy)
10968 			return libbpf_err_ptr(-ENOTSUP);
10969 		pe_opts.force_ioctl_attach = true;
10970 		break;
10971 	case PROBE_ATTACH_MODE_LINK:
10972 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
10973 			return libbpf_err_ptr(-ENOTSUP);
10974 		break;
10975 	case PROBE_ATTACH_MODE_DEFAULT:
10976 		break;
10977 	default:
10978 		return libbpf_err_ptr(-EINVAL);
10979 	}
10980 
10981 	if (!legacy) {
10982 		pfd = perf_event_open_probe(false /* uprobe */, retprobe,
10983 					    func_name, offset,
10984 					    -1 /* pid */, 0 /* ref_ctr_off */);
10985 	} else {
10986 		char probe_name[256];
10987 
10988 		gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name),
10989 					     func_name, offset);
10990 
10991 		legacy_probe = strdup(probe_name);
10992 		if (!legacy_probe)
10993 			return libbpf_err_ptr(-ENOMEM);
10994 
10995 		pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
10996 						    offset, -1 /* pid */);
10997 	}
10998 	if (pfd < 0) {
10999 		err = -errno;
11000 		pr_warn("prog '%s': failed to create %s '%s+0x%zx' perf event: %s\n",
11001 			prog->name, retprobe ? "kretprobe" : "kprobe",
11002 			func_name, offset,
11003 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11004 		goto err_out;
11005 	}
11006 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11007 	err = libbpf_get_error(link);
11008 	if (err) {
11009 		close(pfd);
11010 		pr_warn("prog '%s': failed to attach to %s '%s+0x%zx': %s\n",
11011 			prog->name, retprobe ? "kretprobe" : "kprobe",
11012 			func_name, offset,
11013 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11014 		goto err_clean_legacy;
11015 	}
11016 	if (legacy) {
11017 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
11018 
11019 		perf_link->legacy_probe_name = legacy_probe;
11020 		perf_link->legacy_is_kprobe = true;
11021 		perf_link->legacy_is_retprobe = retprobe;
11022 	}
11023 
11024 	return link;
11025 
11026 err_clean_legacy:
11027 	if (legacy)
11028 		remove_kprobe_event_legacy(legacy_probe, retprobe);
11029 err_out:
11030 	free(legacy_probe);
11031 	return libbpf_err_ptr(err);
11032 }
11033 
11034 struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
11035 					    bool retprobe,
11036 					    const char *func_name)
11037 {
11038 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
11039 		.retprobe = retprobe,
11040 	);
11041 
11042 	return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
11043 }
11044 
11045 struct bpf_link *bpf_program__attach_ksyscall(const struct bpf_program *prog,
11046 					      const char *syscall_name,
11047 					      const struct bpf_ksyscall_opts *opts)
11048 {
11049 	LIBBPF_OPTS(bpf_kprobe_opts, kprobe_opts);
11050 	char func_name[128];
11051 
11052 	if (!OPTS_VALID(opts, bpf_ksyscall_opts))
11053 		return libbpf_err_ptr(-EINVAL);
11054 
11055 	if (kernel_supports(prog->obj, FEAT_SYSCALL_WRAPPER)) {
11056 		/* arch_specific_syscall_pfx() should never return NULL here
11057 		 * because it is guarded by kernel_supports(). However, since
11058 		 * compiler does not know that we have an explicit conditional
11059 		 * as well.
11060 		 */
11061 		snprintf(func_name, sizeof(func_name), "__%s_sys_%s",
11062 			 arch_specific_syscall_pfx() ? : "", syscall_name);
11063 	} else {
11064 		snprintf(func_name, sizeof(func_name), "__se_sys_%s", syscall_name);
11065 	}
11066 
11067 	kprobe_opts.retprobe = OPTS_GET(opts, retprobe, false);
11068 	kprobe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11069 
11070 	return bpf_program__attach_kprobe_opts(prog, func_name, &kprobe_opts);
11071 }
11072 
11073 /* Adapted from perf/util/string.c */
11074 bool glob_match(const char *str, const char *pat)
11075 {
11076 	while (*str && *pat && *pat != '*') {
11077 		if (*pat == '?') {      /* Matches any single character */
11078 			str++;
11079 			pat++;
11080 			continue;
11081 		}
11082 		if (*str != *pat)
11083 			return false;
11084 		str++;
11085 		pat++;
11086 	}
11087 	/* Check wild card */
11088 	if (*pat == '*') {
11089 		while (*pat == '*')
11090 			pat++;
11091 		if (!*pat) /* Tail wild card matches all */
11092 			return true;
11093 		while (*str)
11094 			if (glob_match(str++, pat))
11095 				return true;
11096 	}
11097 	return !*str && !*pat;
11098 }
11099 
11100 struct kprobe_multi_resolve {
11101 	const char *pattern;
11102 	unsigned long *addrs;
11103 	size_t cap;
11104 	size_t cnt;
11105 };
11106 
11107 struct avail_kallsyms_data {
11108 	char **syms;
11109 	size_t cnt;
11110 	struct kprobe_multi_resolve *res;
11111 };
11112 
11113 static int avail_func_cmp(const void *a, const void *b)
11114 {
11115 	return strcmp(*(const char **)a, *(const char **)b);
11116 }
11117 
11118 static int avail_kallsyms_cb(unsigned long long sym_addr, char sym_type,
11119 			     const char *sym_name, void *ctx)
11120 {
11121 	struct avail_kallsyms_data *data = ctx;
11122 	struct kprobe_multi_resolve *res = data->res;
11123 	int err;
11124 
11125 	if (!bsearch(&sym_name, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp))
11126 		return 0;
11127 
11128 	err = libbpf_ensure_mem((void **)&res->addrs, &res->cap, sizeof(*res->addrs), res->cnt + 1);
11129 	if (err)
11130 		return err;
11131 
11132 	res->addrs[res->cnt++] = (unsigned long)sym_addr;
11133 	return 0;
11134 }
11135 
11136 static int libbpf_available_kallsyms_parse(struct kprobe_multi_resolve *res)
11137 {
11138 	const char *available_functions_file = tracefs_available_filter_functions();
11139 	struct avail_kallsyms_data data;
11140 	char sym_name[500];
11141 	FILE *f;
11142 	int err = 0, ret, i;
11143 	char **syms = NULL;
11144 	size_t cap = 0, cnt = 0;
11145 
11146 	f = fopen(available_functions_file, "re");
11147 	if (!f) {
11148 		err = -errno;
11149 		pr_warn("failed to open %s: %d\n", available_functions_file, err);
11150 		return err;
11151 	}
11152 
11153 	while (true) {
11154 		char *name;
11155 
11156 		ret = fscanf(f, "%499s%*[^\n]\n", sym_name);
11157 		if (ret == EOF && feof(f))
11158 			break;
11159 
11160 		if (ret != 1) {
11161 			pr_warn("failed to parse available_filter_functions entry: %d\n", ret);
11162 			err = -EINVAL;
11163 			goto cleanup;
11164 		}
11165 
11166 		if (!glob_match(sym_name, res->pattern))
11167 			continue;
11168 
11169 		err = libbpf_ensure_mem((void **)&syms, &cap, sizeof(*syms), cnt + 1);
11170 		if (err)
11171 			goto cleanup;
11172 
11173 		name = strdup(sym_name);
11174 		if (!name) {
11175 			err = -errno;
11176 			goto cleanup;
11177 		}
11178 
11179 		syms[cnt++] = name;
11180 	}
11181 
11182 	/* no entries found, bail out */
11183 	if (cnt == 0) {
11184 		err = -ENOENT;
11185 		goto cleanup;
11186 	}
11187 
11188 	/* sort available functions */
11189 	qsort(syms, cnt, sizeof(*syms), avail_func_cmp);
11190 
11191 	data.syms = syms;
11192 	data.res = res;
11193 	data.cnt = cnt;
11194 	libbpf_kallsyms_parse(avail_kallsyms_cb, &data);
11195 
11196 	if (res->cnt == 0)
11197 		err = -ENOENT;
11198 
11199 cleanup:
11200 	for (i = 0; i < cnt; i++)
11201 		free((char *)syms[i]);
11202 	free(syms);
11203 
11204 	fclose(f);
11205 	return err;
11206 }
11207 
11208 static bool has_available_filter_functions_addrs(void)
11209 {
11210 	return access(tracefs_available_filter_functions_addrs(), R_OK) != -1;
11211 }
11212 
11213 static int libbpf_available_kprobes_parse(struct kprobe_multi_resolve *res)
11214 {
11215 	const char *available_path = tracefs_available_filter_functions_addrs();
11216 	char sym_name[500];
11217 	FILE *f;
11218 	int ret, err = 0;
11219 	unsigned long long sym_addr;
11220 
11221 	f = fopen(available_path, "re");
11222 	if (!f) {
11223 		err = -errno;
11224 		pr_warn("failed to open %s: %d\n", available_path, err);
11225 		return err;
11226 	}
11227 
11228 	while (true) {
11229 		ret = fscanf(f, "%llx %499s%*[^\n]\n", &sym_addr, sym_name);
11230 		if (ret == EOF && feof(f))
11231 			break;
11232 
11233 		if (ret != 2) {
11234 			pr_warn("failed to parse available_filter_functions_addrs entry: %d\n",
11235 				ret);
11236 			err = -EINVAL;
11237 			goto cleanup;
11238 		}
11239 
11240 		if (!glob_match(sym_name, res->pattern))
11241 			continue;
11242 
11243 		err = libbpf_ensure_mem((void **)&res->addrs, &res->cap,
11244 					sizeof(*res->addrs), res->cnt + 1);
11245 		if (err)
11246 			goto cleanup;
11247 
11248 		res->addrs[res->cnt++] = (unsigned long)sym_addr;
11249 	}
11250 
11251 	if (res->cnt == 0)
11252 		err = -ENOENT;
11253 
11254 cleanup:
11255 	fclose(f);
11256 	return err;
11257 }
11258 
11259 struct bpf_link *
11260 bpf_program__attach_kprobe_multi_opts(const struct bpf_program *prog,
11261 				      const char *pattern,
11262 				      const struct bpf_kprobe_multi_opts *opts)
11263 {
11264 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
11265 	struct kprobe_multi_resolve res = {
11266 		.pattern = pattern,
11267 	};
11268 	struct bpf_link *link = NULL;
11269 	char errmsg[STRERR_BUFSIZE];
11270 	const unsigned long *addrs;
11271 	int err, link_fd, prog_fd;
11272 	const __u64 *cookies;
11273 	const char **syms;
11274 	bool retprobe;
11275 	size_t cnt;
11276 
11277 	if (!OPTS_VALID(opts, bpf_kprobe_multi_opts))
11278 		return libbpf_err_ptr(-EINVAL);
11279 
11280 	syms    = OPTS_GET(opts, syms, false);
11281 	addrs   = OPTS_GET(opts, addrs, false);
11282 	cnt     = OPTS_GET(opts, cnt, false);
11283 	cookies = OPTS_GET(opts, cookies, false);
11284 
11285 	if (!pattern && !addrs && !syms)
11286 		return libbpf_err_ptr(-EINVAL);
11287 	if (pattern && (addrs || syms || cookies || cnt))
11288 		return libbpf_err_ptr(-EINVAL);
11289 	if (!pattern && !cnt)
11290 		return libbpf_err_ptr(-EINVAL);
11291 	if (addrs && syms)
11292 		return libbpf_err_ptr(-EINVAL);
11293 
11294 	if (pattern) {
11295 		if (has_available_filter_functions_addrs())
11296 			err = libbpf_available_kprobes_parse(&res);
11297 		else
11298 			err = libbpf_available_kallsyms_parse(&res);
11299 		if (err)
11300 			goto error;
11301 		addrs = res.addrs;
11302 		cnt = res.cnt;
11303 	}
11304 
11305 	retprobe = OPTS_GET(opts, retprobe, false);
11306 
11307 	lopts.kprobe_multi.syms = syms;
11308 	lopts.kprobe_multi.addrs = addrs;
11309 	lopts.kprobe_multi.cookies = cookies;
11310 	lopts.kprobe_multi.cnt = cnt;
11311 	lopts.kprobe_multi.flags = retprobe ? BPF_F_KPROBE_MULTI_RETURN : 0;
11312 
11313 	link = calloc(1, sizeof(*link));
11314 	if (!link) {
11315 		err = -ENOMEM;
11316 		goto error;
11317 	}
11318 	link->detach = &bpf_link__detach_fd;
11319 
11320 	prog_fd = bpf_program__fd(prog);
11321 	link_fd = bpf_link_create(prog_fd, 0, BPF_TRACE_KPROBE_MULTI, &lopts);
11322 	if (link_fd < 0) {
11323 		err = -errno;
11324 		pr_warn("prog '%s': failed to attach: %s\n",
11325 			prog->name, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11326 		goto error;
11327 	}
11328 	link->fd = link_fd;
11329 	free(res.addrs);
11330 	return link;
11331 
11332 error:
11333 	free(link);
11334 	free(res.addrs);
11335 	return libbpf_err_ptr(err);
11336 }
11337 
11338 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11339 {
11340 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
11341 	unsigned long offset = 0;
11342 	const char *func_name;
11343 	char *func;
11344 	int n;
11345 
11346 	*link = NULL;
11347 
11348 	/* no auto-attach for SEC("kprobe") and SEC("kretprobe") */
11349 	if (strcmp(prog->sec_name, "kprobe") == 0 || strcmp(prog->sec_name, "kretprobe") == 0)
11350 		return 0;
11351 
11352 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
11353 	if (opts.retprobe)
11354 		func_name = prog->sec_name + sizeof("kretprobe/") - 1;
11355 	else
11356 		func_name = prog->sec_name + sizeof("kprobe/") - 1;
11357 
11358 	n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
11359 	if (n < 1) {
11360 		pr_warn("kprobe name is invalid: %s\n", func_name);
11361 		return -EINVAL;
11362 	}
11363 	if (opts.retprobe && offset != 0) {
11364 		free(func);
11365 		pr_warn("kretprobes do not support offset specification\n");
11366 		return -EINVAL;
11367 	}
11368 
11369 	opts.offset = offset;
11370 	*link = bpf_program__attach_kprobe_opts(prog, func, &opts);
11371 	free(func);
11372 	return libbpf_get_error(*link);
11373 }
11374 
11375 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11376 {
11377 	LIBBPF_OPTS(bpf_ksyscall_opts, opts);
11378 	const char *syscall_name;
11379 
11380 	*link = NULL;
11381 
11382 	/* no auto-attach for SEC("ksyscall") and SEC("kretsyscall") */
11383 	if (strcmp(prog->sec_name, "ksyscall") == 0 || strcmp(prog->sec_name, "kretsyscall") == 0)
11384 		return 0;
11385 
11386 	opts.retprobe = str_has_pfx(prog->sec_name, "kretsyscall/");
11387 	if (opts.retprobe)
11388 		syscall_name = prog->sec_name + sizeof("kretsyscall/") - 1;
11389 	else
11390 		syscall_name = prog->sec_name + sizeof("ksyscall/") - 1;
11391 
11392 	*link = bpf_program__attach_ksyscall(prog, syscall_name, &opts);
11393 	return *link ? 0 : -errno;
11394 }
11395 
11396 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11397 {
11398 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts);
11399 	const char *spec;
11400 	char *pattern;
11401 	int n;
11402 
11403 	*link = NULL;
11404 
11405 	/* no auto-attach for SEC("kprobe.multi") and SEC("kretprobe.multi") */
11406 	if (strcmp(prog->sec_name, "kprobe.multi") == 0 ||
11407 	    strcmp(prog->sec_name, "kretprobe.multi") == 0)
11408 		return 0;
11409 
11410 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe.multi/");
11411 	if (opts.retprobe)
11412 		spec = prog->sec_name + sizeof("kretprobe.multi/") - 1;
11413 	else
11414 		spec = prog->sec_name + sizeof("kprobe.multi/") - 1;
11415 
11416 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
11417 	if (n < 1) {
11418 		pr_warn("kprobe multi pattern is invalid: %s\n", pattern);
11419 		return -EINVAL;
11420 	}
11421 
11422 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
11423 	free(pattern);
11424 	return libbpf_get_error(*link);
11425 }
11426 
11427 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11428 {
11429 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
11430 	LIBBPF_OPTS(bpf_uprobe_multi_opts, opts);
11431 	int n, ret = -EINVAL;
11432 
11433 	*link = NULL;
11434 
11435 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
11436 		   &probe_type, &binary_path, &func_name);
11437 	switch (n) {
11438 	case 1:
11439 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
11440 		ret = 0;
11441 		break;
11442 	case 3:
11443 		opts.retprobe = strcmp(probe_type, "uretprobe.multi") == 0;
11444 		*link = bpf_program__attach_uprobe_multi(prog, -1, binary_path, func_name, &opts);
11445 		ret = libbpf_get_error(*link);
11446 		break;
11447 	default:
11448 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
11449 			prog->sec_name);
11450 		break;
11451 	}
11452 	free(probe_type);
11453 	free(binary_path);
11454 	free(func_name);
11455 	return ret;
11456 }
11457 
11458 static void gen_uprobe_legacy_event_name(char *buf, size_t buf_sz,
11459 					 const char *binary_path, uint64_t offset)
11460 {
11461 	int i;
11462 
11463 	snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx", getpid(), binary_path, (size_t)offset);
11464 
11465 	/* sanitize binary_path in the probe name */
11466 	for (i = 0; buf[i]; i++) {
11467 		if (!isalnum(buf[i]))
11468 			buf[i] = '_';
11469 	}
11470 }
11471 
11472 static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
11473 					  const char *binary_path, size_t offset)
11474 {
11475 	return append_to_file(tracefs_uprobe_events(), "%c:%s/%s %s:0x%zx",
11476 			      retprobe ? 'r' : 'p',
11477 			      retprobe ? "uretprobes" : "uprobes",
11478 			      probe_name, binary_path, offset);
11479 }
11480 
11481 static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
11482 {
11483 	return append_to_file(tracefs_uprobe_events(), "-:%s/%s",
11484 			      retprobe ? "uretprobes" : "uprobes", probe_name);
11485 }
11486 
11487 static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
11488 {
11489 	char file[512];
11490 
11491 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11492 		 tracefs_path(), retprobe ? "uretprobes" : "uprobes", probe_name);
11493 
11494 	return parse_uint_from_file(file, "%d\n");
11495 }
11496 
11497 static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
11498 					 const char *binary_path, size_t offset, int pid)
11499 {
11500 	const size_t attr_sz = sizeof(struct perf_event_attr);
11501 	struct perf_event_attr attr;
11502 	int type, pfd, err;
11503 
11504 	err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
11505 	if (err < 0) {
11506 		pr_warn("failed to add legacy uprobe event for %s:0x%zx: %d\n",
11507 			binary_path, (size_t)offset, err);
11508 		return err;
11509 	}
11510 	type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
11511 	if (type < 0) {
11512 		err = type;
11513 		pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %d\n",
11514 			binary_path, offset, err);
11515 		goto err_clean_legacy;
11516 	}
11517 
11518 	memset(&attr, 0, attr_sz);
11519 	attr.size = attr_sz;
11520 	attr.config = type;
11521 	attr.type = PERF_TYPE_TRACEPOINT;
11522 
11523 	pfd = syscall(__NR_perf_event_open, &attr,
11524 		      pid < 0 ? -1 : pid, /* pid */
11525 		      pid == -1 ? 0 : -1, /* cpu */
11526 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
11527 	if (pfd < 0) {
11528 		err = -errno;
11529 		pr_warn("legacy uprobe perf_event_open() failed: %d\n", err);
11530 		goto err_clean_legacy;
11531 	}
11532 	return pfd;
11533 
11534 err_clean_legacy:
11535 	/* Clear the newly added legacy uprobe_event */
11536 	remove_uprobe_event_legacy(probe_name, retprobe);
11537 	return err;
11538 }
11539 
11540 /* Find offset of function name in archive specified by path. Currently
11541  * supported are .zip files that do not compress their contents, as used on
11542  * Android in the form of APKs, for example. "file_name" is the name of the ELF
11543  * file inside the archive. "func_name" matches symbol name or name@@LIB for
11544  * library functions.
11545  *
11546  * An overview of the APK format specifically provided here:
11547  * https://en.wikipedia.org/w/index.php?title=Apk_(file_format)&oldid=1139099120#Package_contents
11548  */
11549 static long elf_find_func_offset_from_archive(const char *archive_path, const char *file_name,
11550 					      const char *func_name)
11551 {
11552 	struct zip_archive *archive;
11553 	struct zip_entry entry;
11554 	long ret;
11555 	Elf *elf;
11556 
11557 	archive = zip_archive_open(archive_path);
11558 	if (IS_ERR(archive)) {
11559 		ret = PTR_ERR(archive);
11560 		pr_warn("zip: failed to open %s: %ld\n", archive_path, ret);
11561 		return ret;
11562 	}
11563 
11564 	ret = zip_archive_find_entry(archive, file_name, &entry);
11565 	if (ret) {
11566 		pr_warn("zip: could not find archive member %s in %s: %ld\n", file_name,
11567 			archive_path, ret);
11568 		goto out;
11569 	}
11570 	pr_debug("zip: found entry for %s in %s at 0x%lx\n", file_name, archive_path,
11571 		 (unsigned long)entry.data_offset);
11572 
11573 	if (entry.compression) {
11574 		pr_warn("zip: entry %s of %s is compressed and cannot be handled\n", file_name,
11575 			archive_path);
11576 		ret = -LIBBPF_ERRNO__FORMAT;
11577 		goto out;
11578 	}
11579 
11580 	elf = elf_memory((void *)entry.data, entry.data_length);
11581 	if (!elf) {
11582 		pr_warn("elf: could not read elf file %s from %s: %s\n", file_name, archive_path,
11583 			elf_errmsg(-1));
11584 		ret = -LIBBPF_ERRNO__LIBELF;
11585 		goto out;
11586 	}
11587 
11588 	ret = elf_find_func_offset(elf, file_name, func_name);
11589 	if (ret > 0) {
11590 		pr_debug("elf: symbol address match for %s of %s in %s: 0x%x + 0x%lx = 0x%lx\n",
11591 			 func_name, file_name, archive_path, entry.data_offset, ret,
11592 			 ret + entry.data_offset);
11593 		ret += entry.data_offset;
11594 	}
11595 	elf_end(elf);
11596 
11597 out:
11598 	zip_archive_close(archive);
11599 	return ret;
11600 }
11601 
11602 static const char *arch_specific_lib_paths(void)
11603 {
11604 	/*
11605 	 * Based on https://packages.debian.org/sid/libc6.
11606 	 *
11607 	 * Assume that the traced program is built for the same architecture
11608 	 * as libbpf, which should cover the vast majority of cases.
11609 	 */
11610 #if defined(__x86_64__)
11611 	return "/lib/x86_64-linux-gnu";
11612 #elif defined(__i386__)
11613 	return "/lib/i386-linux-gnu";
11614 #elif defined(__s390x__)
11615 	return "/lib/s390x-linux-gnu";
11616 #elif defined(__s390__)
11617 	return "/lib/s390-linux-gnu";
11618 #elif defined(__arm__) && defined(__SOFTFP__)
11619 	return "/lib/arm-linux-gnueabi";
11620 #elif defined(__arm__) && !defined(__SOFTFP__)
11621 	return "/lib/arm-linux-gnueabihf";
11622 #elif defined(__aarch64__)
11623 	return "/lib/aarch64-linux-gnu";
11624 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 64
11625 	return "/lib/mips64el-linux-gnuabi64";
11626 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 32
11627 	return "/lib/mipsel-linux-gnu";
11628 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
11629 	return "/lib/powerpc64le-linux-gnu";
11630 #elif defined(__sparc__) && defined(__arch64__)
11631 	return "/lib/sparc64-linux-gnu";
11632 #elif defined(__riscv) && __riscv_xlen == 64
11633 	return "/lib/riscv64-linux-gnu";
11634 #else
11635 	return NULL;
11636 #endif
11637 }
11638 
11639 /* Get full path to program/shared library. */
11640 static int resolve_full_path(const char *file, char *result, size_t result_sz)
11641 {
11642 	const char *search_paths[3] = {};
11643 	int i, perm;
11644 
11645 	if (str_has_sfx(file, ".so") || strstr(file, ".so.")) {
11646 		search_paths[0] = getenv("LD_LIBRARY_PATH");
11647 		search_paths[1] = "/usr/lib64:/usr/lib";
11648 		search_paths[2] = arch_specific_lib_paths();
11649 		perm = R_OK;
11650 	} else {
11651 		search_paths[0] = getenv("PATH");
11652 		search_paths[1] = "/usr/bin:/usr/sbin";
11653 		perm = R_OK | X_OK;
11654 	}
11655 
11656 	for (i = 0; i < ARRAY_SIZE(search_paths); i++) {
11657 		const char *s;
11658 
11659 		if (!search_paths[i])
11660 			continue;
11661 		for (s = search_paths[i]; s != NULL; s = strchr(s, ':')) {
11662 			char *next_path;
11663 			int seg_len;
11664 
11665 			if (s[0] == ':')
11666 				s++;
11667 			next_path = strchr(s, ':');
11668 			seg_len = next_path ? next_path - s : strlen(s);
11669 			if (!seg_len)
11670 				continue;
11671 			snprintf(result, result_sz, "%.*s/%s", seg_len, s, file);
11672 			/* ensure it has required permissions */
11673 			if (faccessat(AT_FDCWD, result, perm, AT_EACCESS) < 0)
11674 				continue;
11675 			pr_debug("resolved '%s' to '%s'\n", file, result);
11676 			return 0;
11677 		}
11678 	}
11679 	return -ENOENT;
11680 }
11681 
11682 struct bpf_link *
11683 bpf_program__attach_uprobe_multi(const struct bpf_program *prog,
11684 				 pid_t pid,
11685 				 const char *path,
11686 				 const char *func_pattern,
11687 				 const struct bpf_uprobe_multi_opts *opts)
11688 {
11689 	const unsigned long *ref_ctr_offsets = NULL, *offsets = NULL;
11690 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
11691 	unsigned long *resolved_offsets = NULL;
11692 	int err = 0, link_fd, prog_fd;
11693 	struct bpf_link *link = NULL;
11694 	char errmsg[STRERR_BUFSIZE];
11695 	char full_path[PATH_MAX];
11696 	const __u64 *cookies;
11697 	const char **syms;
11698 	size_t cnt;
11699 
11700 	if (!OPTS_VALID(opts, bpf_uprobe_multi_opts))
11701 		return libbpf_err_ptr(-EINVAL);
11702 
11703 	syms = OPTS_GET(opts, syms, NULL);
11704 	offsets = OPTS_GET(opts, offsets, NULL);
11705 	ref_ctr_offsets = OPTS_GET(opts, ref_ctr_offsets, NULL);
11706 	cookies = OPTS_GET(opts, cookies, NULL);
11707 	cnt = OPTS_GET(opts, cnt, 0);
11708 
11709 	/*
11710 	 * User can specify 2 mutually exclusive set of inputs:
11711 	 *
11712 	 * 1) use only path/func_pattern/pid arguments
11713 	 *
11714 	 * 2) use path/pid with allowed combinations of:
11715 	 *    syms/offsets/ref_ctr_offsets/cookies/cnt
11716 	 *
11717 	 *    - syms and offsets are mutually exclusive
11718 	 *    - ref_ctr_offsets and cookies are optional
11719 	 *
11720 	 * Any other usage results in error.
11721 	 */
11722 
11723 	if (!path)
11724 		return libbpf_err_ptr(-EINVAL);
11725 	if (!func_pattern && cnt == 0)
11726 		return libbpf_err_ptr(-EINVAL);
11727 
11728 	if (func_pattern) {
11729 		if (syms || offsets || ref_ctr_offsets || cookies || cnt)
11730 			return libbpf_err_ptr(-EINVAL);
11731 	} else {
11732 		if (!!syms == !!offsets)
11733 			return libbpf_err_ptr(-EINVAL);
11734 	}
11735 
11736 	if (func_pattern) {
11737 		if (!strchr(path, '/')) {
11738 			err = resolve_full_path(path, full_path, sizeof(full_path));
11739 			if (err) {
11740 				pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11741 					prog->name, path, err);
11742 				return libbpf_err_ptr(err);
11743 			}
11744 			path = full_path;
11745 		}
11746 
11747 		err = elf_resolve_pattern_offsets(path, func_pattern,
11748 						  &resolved_offsets, &cnt);
11749 		if (err < 0)
11750 			return libbpf_err_ptr(err);
11751 		offsets = resolved_offsets;
11752 	} else if (syms) {
11753 		err = elf_resolve_syms_offsets(path, cnt, syms, &resolved_offsets, STT_FUNC);
11754 		if (err < 0)
11755 			return libbpf_err_ptr(err);
11756 		offsets = resolved_offsets;
11757 	}
11758 
11759 	lopts.uprobe_multi.path = path;
11760 	lopts.uprobe_multi.offsets = offsets;
11761 	lopts.uprobe_multi.ref_ctr_offsets = ref_ctr_offsets;
11762 	lopts.uprobe_multi.cookies = cookies;
11763 	lopts.uprobe_multi.cnt = cnt;
11764 	lopts.uprobe_multi.flags = OPTS_GET(opts, retprobe, false) ? BPF_F_UPROBE_MULTI_RETURN : 0;
11765 
11766 	if (pid == 0)
11767 		pid = getpid();
11768 	if (pid > 0)
11769 		lopts.uprobe_multi.pid = pid;
11770 
11771 	link = calloc(1, sizeof(*link));
11772 	if (!link) {
11773 		err = -ENOMEM;
11774 		goto error;
11775 	}
11776 	link->detach = &bpf_link__detach_fd;
11777 
11778 	prog_fd = bpf_program__fd(prog);
11779 	link_fd = bpf_link_create(prog_fd, 0, BPF_TRACE_UPROBE_MULTI, &lopts);
11780 	if (link_fd < 0) {
11781 		err = -errno;
11782 		pr_warn("prog '%s': failed to attach multi-uprobe: %s\n",
11783 			prog->name, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11784 		goto error;
11785 	}
11786 	link->fd = link_fd;
11787 	free(resolved_offsets);
11788 	return link;
11789 
11790 error:
11791 	free(resolved_offsets);
11792 	free(link);
11793 	return libbpf_err_ptr(err);
11794 }
11795 
11796 LIBBPF_API struct bpf_link *
11797 bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
11798 				const char *binary_path, size_t func_offset,
11799 				const struct bpf_uprobe_opts *opts)
11800 {
11801 	const char *archive_path = NULL, *archive_sep = NULL;
11802 	char errmsg[STRERR_BUFSIZE], *legacy_probe = NULL;
11803 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11804 	enum probe_attach_mode attach_mode;
11805 	char full_path[PATH_MAX];
11806 	struct bpf_link *link;
11807 	size_t ref_ctr_off;
11808 	int pfd, err;
11809 	bool retprobe, legacy;
11810 	const char *func_name;
11811 
11812 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
11813 		return libbpf_err_ptr(-EINVAL);
11814 
11815 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
11816 	retprobe = OPTS_GET(opts, retprobe, false);
11817 	ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
11818 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11819 
11820 	if (!binary_path)
11821 		return libbpf_err_ptr(-EINVAL);
11822 
11823 	/* Check if "binary_path" refers to an archive. */
11824 	archive_sep = strstr(binary_path, "!/");
11825 	if (archive_sep) {
11826 		full_path[0] = '\0';
11827 		libbpf_strlcpy(full_path, binary_path,
11828 			       min(sizeof(full_path), (size_t)(archive_sep - binary_path + 1)));
11829 		archive_path = full_path;
11830 		binary_path = archive_sep + 2;
11831 	} else if (!strchr(binary_path, '/')) {
11832 		err = resolve_full_path(binary_path, full_path, sizeof(full_path));
11833 		if (err) {
11834 			pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11835 				prog->name, binary_path, err);
11836 			return libbpf_err_ptr(err);
11837 		}
11838 		binary_path = full_path;
11839 	}
11840 	func_name = OPTS_GET(opts, func_name, NULL);
11841 	if (func_name) {
11842 		long sym_off;
11843 
11844 		if (archive_path) {
11845 			sym_off = elf_find_func_offset_from_archive(archive_path, binary_path,
11846 								    func_name);
11847 			binary_path = archive_path;
11848 		} else {
11849 			sym_off = elf_find_func_offset_from_file(binary_path, func_name);
11850 		}
11851 		if (sym_off < 0)
11852 			return libbpf_err_ptr(sym_off);
11853 		func_offset += sym_off;
11854 	}
11855 
11856 	legacy = determine_uprobe_perf_type() < 0;
11857 	switch (attach_mode) {
11858 	case PROBE_ATTACH_MODE_LEGACY:
11859 		legacy = true;
11860 		pe_opts.force_ioctl_attach = true;
11861 		break;
11862 	case PROBE_ATTACH_MODE_PERF:
11863 		if (legacy)
11864 			return libbpf_err_ptr(-ENOTSUP);
11865 		pe_opts.force_ioctl_attach = true;
11866 		break;
11867 	case PROBE_ATTACH_MODE_LINK:
11868 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
11869 			return libbpf_err_ptr(-ENOTSUP);
11870 		break;
11871 	case PROBE_ATTACH_MODE_DEFAULT:
11872 		break;
11873 	default:
11874 		return libbpf_err_ptr(-EINVAL);
11875 	}
11876 
11877 	if (!legacy) {
11878 		pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
11879 					    func_offset, pid, ref_ctr_off);
11880 	} else {
11881 		char probe_name[PATH_MAX + 64];
11882 
11883 		if (ref_ctr_off)
11884 			return libbpf_err_ptr(-EINVAL);
11885 
11886 		gen_uprobe_legacy_event_name(probe_name, sizeof(probe_name),
11887 					     binary_path, func_offset);
11888 
11889 		legacy_probe = strdup(probe_name);
11890 		if (!legacy_probe)
11891 			return libbpf_err_ptr(-ENOMEM);
11892 
11893 		pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
11894 						    binary_path, func_offset, pid);
11895 	}
11896 	if (pfd < 0) {
11897 		err = -errno;
11898 		pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
11899 			prog->name, retprobe ? "uretprobe" : "uprobe",
11900 			binary_path, func_offset,
11901 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11902 		goto err_out;
11903 	}
11904 
11905 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11906 	err = libbpf_get_error(link);
11907 	if (err) {
11908 		close(pfd);
11909 		pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
11910 			prog->name, retprobe ? "uretprobe" : "uprobe",
11911 			binary_path, func_offset,
11912 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11913 		goto err_clean_legacy;
11914 	}
11915 	if (legacy) {
11916 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
11917 
11918 		perf_link->legacy_probe_name = legacy_probe;
11919 		perf_link->legacy_is_kprobe = false;
11920 		perf_link->legacy_is_retprobe = retprobe;
11921 	}
11922 	return link;
11923 
11924 err_clean_legacy:
11925 	if (legacy)
11926 		remove_uprobe_event_legacy(legacy_probe, retprobe);
11927 err_out:
11928 	free(legacy_probe);
11929 	return libbpf_err_ptr(err);
11930 }
11931 
11932 /* Format of u[ret]probe section definition supporting auto-attach:
11933  * u[ret]probe/binary:function[+offset]
11934  *
11935  * binary can be an absolute/relative path or a filename; the latter is resolved to a
11936  * full binary path via bpf_program__attach_uprobe_opts.
11937  *
11938  * Specifying uprobe+ ensures we carry out strict matching; either "uprobe" must be
11939  * specified (and auto-attach is not possible) or the above format is specified for
11940  * auto-attach.
11941  */
11942 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11943 {
11944 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts);
11945 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL, *func_off;
11946 	int n, c, ret = -EINVAL;
11947 	long offset = 0;
11948 
11949 	*link = NULL;
11950 
11951 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
11952 		   &probe_type, &binary_path, &func_name);
11953 	switch (n) {
11954 	case 1:
11955 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
11956 		ret = 0;
11957 		break;
11958 	case 2:
11959 		pr_warn("prog '%s': section '%s' missing ':function[+offset]' specification\n",
11960 			prog->name, prog->sec_name);
11961 		break;
11962 	case 3:
11963 		/* check if user specifies `+offset`, if yes, this should be
11964 		 * the last part of the string, make sure sscanf read to EOL
11965 		 */
11966 		func_off = strrchr(func_name, '+');
11967 		if (func_off) {
11968 			n = sscanf(func_off, "+%li%n", &offset, &c);
11969 			if (n == 1 && *(func_off + c) == '\0')
11970 				func_off[0] = '\0';
11971 			else
11972 				offset = 0;
11973 		}
11974 		opts.retprobe = strcmp(probe_type, "uretprobe") == 0 ||
11975 				strcmp(probe_type, "uretprobe.s") == 0;
11976 		if (opts.retprobe && offset != 0) {
11977 			pr_warn("prog '%s': uretprobes do not support offset specification\n",
11978 				prog->name);
11979 			break;
11980 		}
11981 		opts.func_name = func_name;
11982 		*link = bpf_program__attach_uprobe_opts(prog, -1, binary_path, offset, &opts);
11983 		ret = libbpf_get_error(*link);
11984 		break;
11985 	default:
11986 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
11987 			prog->sec_name);
11988 		break;
11989 	}
11990 	free(probe_type);
11991 	free(binary_path);
11992 	free(func_name);
11993 
11994 	return ret;
11995 }
11996 
11997 struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
11998 					    bool retprobe, pid_t pid,
11999 					    const char *binary_path,
12000 					    size_t func_offset)
12001 {
12002 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
12003 
12004 	return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
12005 }
12006 
12007 struct bpf_link *bpf_program__attach_usdt(const struct bpf_program *prog,
12008 					  pid_t pid, const char *binary_path,
12009 					  const char *usdt_provider, const char *usdt_name,
12010 					  const struct bpf_usdt_opts *opts)
12011 {
12012 	char resolved_path[512];
12013 	struct bpf_object *obj = prog->obj;
12014 	struct bpf_link *link;
12015 	__u64 usdt_cookie;
12016 	int err;
12017 
12018 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
12019 		return libbpf_err_ptr(-EINVAL);
12020 
12021 	if (bpf_program__fd(prog) < 0) {
12022 		pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
12023 			prog->name);
12024 		return libbpf_err_ptr(-EINVAL);
12025 	}
12026 
12027 	if (!binary_path)
12028 		return libbpf_err_ptr(-EINVAL);
12029 
12030 	if (!strchr(binary_path, '/')) {
12031 		err = resolve_full_path(binary_path, resolved_path, sizeof(resolved_path));
12032 		if (err) {
12033 			pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
12034 				prog->name, binary_path, err);
12035 			return libbpf_err_ptr(err);
12036 		}
12037 		binary_path = resolved_path;
12038 	}
12039 
12040 	/* USDT manager is instantiated lazily on first USDT attach. It will
12041 	 * be destroyed together with BPF object in bpf_object__close().
12042 	 */
12043 	if (IS_ERR(obj->usdt_man))
12044 		return libbpf_ptr(obj->usdt_man);
12045 	if (!obj->usdt_man) {
12046 		obj->usdt_man = usdt_manager_new(obj);
12047 		if (IS_ERR(obj->usdt_man))
12048 			return libbpf_ptr(obj->usdt_man);
12049 	}
12050 
12051 	usdt_cookie = OPTS_GET(opts, usdt_cookie, 0);
12052 	link = usdt_manager_attach_usdt(obj->usdt_man, prog, pid, binary_path,
12053 					usdt_provider, usdt_name, usdt_cookie);
12054 	err = libbpf_get_error(link);
12055 	if (err)
12056 		return libbpf_err_ptr(err);
12057 	return link;
12058 }
12059 
12060 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12061 {
12062 	char *path = NULL, *provider = NULL, *name = NULL;
12063 	const char *sec_name;
12064 	int n, err;
12065 
12066 	sec_name = bpf_program__section_name(prog);
12067 	if (strcmp(sec_name, "usdt") == 0) {
12068 		/* no auto-attach for just SEC("usdt") */
12069 		*link = NULL;
12070 		return 0;
12071 	}
12072 
12073 	n = sscanf(sec_name, "usdt/%m[^:]:%m[^:]:%m[^:]", &path, &provider, &name);
12074 	if (n != 3) {
12075 		pr_warn("invalid section '%s', expected SEC(\"usdt/<path>:<provider>:<name>\")\n",
12076 			sec_name);
12077 		err = -EINVAL;
12078 	} else {
12079 		*link = bpf_program__attach_usdt(prog, -1 /* any process */, path,
12080 						 provider, name, NULL);
12081 		err = libbpf_get_error(*link);
12082 	}
12083 	free(path);
12084 	free(provider);
12085 	free(name);
12086 	return err;
12087 }
12088 
12089 static int determine_tracepoint_id(const char *tp_category,
12090 				   const char *tp_name)
12091 {
12092 	char file[PATH_MAX];
12093 	int ret;
12094 
12095 	ret = snprintf(file, sizeof(file), "%s/events/%s/%s/id",
12096 		       tracefs_path(), tp_category, tp_name);
12097 	if (ret < 0)
12098 		return -errno;
12099 	if (ret >= sizeof(file)) {
12100 		pr_debug("tracepoint %s/%s path is too long\n",
12101 			 tp_category, tp_name);
12102 		return -E2BIG;
12103 	}
12104 	return parse_uint_from_file(file, "%d\n");
12105 }
12106 
12107 static int perf_event_open_tracepoint(const char *tp_category,
12108 				      const char *tp_name)
12109 {
12110 	const size_t attr_sz = sizeof(struct perf_event_attr);
12111 	struct perf_event_attr attr;
12112 	char errmsg[STRERR_BUFSIZE];
12113 	int tp_id, pfd, err;
12114 
12115 	tp_id = determine_tracepoint_id(tp_category, tp_name);
12116 	if (tp_id < 0) {
12117 		pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
12118 			tp_category, tp_name,
12119 			libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
12120 		return tp_id;
12121 	}
12122 
12123 	memset(&attr, 0, attr_sz);
12124 	attr.type = PERF_TYPE_TRACEPOINT;
12125 	attr.size = attr_sz;
12126 	attr.config = tp_id;
12127 
12128 	pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
12129 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
12130 	if (pfd < 0) {
12131 		err = -errno;
12132 		pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
12133 			tp_category, tp_name,
12134 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
12135 		return err;
12136 	}
12137 	return pfd;
12138 }
12139 
12140 struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
12141 						     const char *tp_category,
12142 						     const char *tp_name,
12143 						     const struct bpf_tracepoint_opts *opts)
12144 {
12145 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
12146 	char errmsg[STRERR_BUFSIZE];
12147 	struct bpf_link *link;
12148 	int pfd, err;
12149 
12150 	if (!OPTS_VALID(opts, bpf_tracepoint_opts))
12151 		return libbpf_err_ptr(-EINVAL);
12152 
12153 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
12154 
12155 	pfd = perf_event_open_tracepoint(tp_category, tp_name);
12156 	if (pfd < 0) {
12157 		pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
12158 			prog->name, tp_category, tp_name,
12159 			libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
12160 		return libbpf_err_ptr(pfd);
12161 	}
12162 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
12163 	err = libbpf_get_error(link);
12164 	if (err) {
12165 		close(pfd);
12166 		pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
12167 			prog->name, tp_category, tp_name,
12168 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
12169 		return libbpf_err_ptr(err);
12170 	}
12171 	return link;
12172 }
12173 
12174 struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
12175 						const char *tp_category,
12176 						const char *tp_name)
12177 {
12178 	return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
12179 }
12180 
12181 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12182 {
12183 	char *sec_name, *tp_cat, *tp_name;
12184 
12185 	*link = NULL;
12186 
12187 	/* no auto-attach for SEC("tp") or SEC("tracepoint") */
12188 	if (strcmp(prog->sec_name, "tp") == 0 || strcmp(prog->sec_name, "tracepoint") == 0)
12189 		return 0;
12190 
12191 	sec_name = strdup(prog->sec_name);
12192 	if (!sec_name)
12193 		return -ENOMEM;
12194 
12195 	/* extract "tp/<category>/<name>" or "tracepoint/<category>/<name>" */
12196 	if (str_has_pfx(prog->sec_name, "tp/"))
12197 		tp_cat = sec_name + sizeof("tp/") - 1;
12198 	else
12199 		tp_cat = sec_name + sizeof("tracepoint/") - 1;
12200 	tp_name = strchr(tp_cat, '/');
12201 	if (!tp_name) {
12202 		free(sec_name);
12203 		return -EINVAL;
12204 	}
12205 	*tp_name = '\0';
12206 	tp_name++;
12207 
12208 	*link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
12209 	free(sec_name);
12210 	return libbpf_get_error(*link);
12211 }
12212 
12213 struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
12214 						    const char *tp_name)
12215 {
12216 	char errmsg[STRERR_BUFSIZE];
12217 	struct bpf_link *link;
12218 	int prog_fd, pfd;
12219 
12220 	prog_fd = bpf_program__fd(prog);
12221 	if (prog_fd < 0) {
12222 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12223 		return libbpf_err_ptr(-EINVAL);
12224 	}
12225 
12226 	link = calloc(1, sizeof(*link));
12227 	if (!link)
12228 		return libbpf_err_ptr(-ENOMEM);
12229 	link->detach = &bpf_link__detach_fd;
12230 
12231 	pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
12232 	if (pfd < 0) {
12233 		pfd = -errno;
12234 		free(link);
12235 		pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
12236 			prog->name, tp_name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
12237 		return libbpf_err_ptr(pfd);
12238 	}
12239 	link->fd = pfd;
12240 	return link;
12241 }
12242 
12243 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12244 {
12245 	static const char *const prefixes[] = {
12246 		"raw_tp",
12247 		"raw_tracepoint",
12248 		"raw_tp.w",
12249 		"raw_tracepoint.w",
12250 	};
12251 	size_t i;
12252 	const char *tp_name = NULL;
12253 
12254 	*link = NULL;
12255 
12256 	for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
12257 		size_t pfx_len;
12258 
12259 		if (!str_has_pfx(prog->sec_name, prefixes[i]))
12260 			continue;
12261 
12262 		pfx_len = strlen(prefixes[i]);
12263 		/* no auto-attach case of, e.g., SEC("raw_tp") */
12264 		if (prog->sec_name[pfx_len] == '\0')
12265 			return 0;
12266 
12267 		if (prog->sec_name[pfx_len] != '/')
12268 			continue;
12269 
12270 		tp_name = prog->sec_name + pfx_len + 1;
12271 		break;
12272 	}
12273 
12274 	if (!tp_name) {
12275 		pr_warn("prog '%s': invalid section name '%s'\n",
12276 			prog->name, prog->sec_name);
12277 		return -EINVAL;
12278 	}
12279 
12280 	*link = bpf_program__attach_raw_tracepoint(prog, tp_name);
12281 	return libbpf_get_error(*link);
12282 }
12283 
12284 /* Common logic for all BPF program types that attach to a btf_id */
12285 static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog,
12286 						   const struct bpf_trace_opts *opts)
12287 {
12288 	LIBBPF_OPTS(bpf_link_create_opts, link_opts);
12289 	char errmsg[STRERR_BUFSIZE];
12290 	struct bpf_link *link;
12291 	int prog_fd, pfd;
12292 
12293 	if (!OPTS_VALID(opts, bpf_trace_opts))
12294 		return libbpf_err_ptr(-EINVAL);
12295 
12296 	prog_fd = bpf_program__fd(prog);
12297 	if (prog_fd < 0) {
12298 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12299 		return libbpf_err_ptr(-EINVAL);
12300 	}
12301 
12302 	link = calloc(1, sizeof(*link));
12303 	if (!link)
12304 		return libbpf_err_ptr(-ENOMEM);
12305 	link->detach = &bpf_link__detach_fd;
12306 
12307 	/* libbpf is smart enough to redirect to BPF_RAW_TRACEPOINT_OPEN on old kernels */
12308 	link_opts.tracing.cookie = OPTS_GET(opts, cookie, 0);
12309 	pfd = bpf_link_create(prog_fd, 0, bpf_program__expected_attach_type(prog), &link_opts);
12310 	if (pfd < 0) {
12311 		pfd = -errno;
12312 		free(link);
12313 		pr_warn("prog '%s': failed to attach: %s\n",
12314 			prog->name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
12315 		return libbpf_err_ptr(pfd);
12316 	}
12317 	link->fd = pfd;
12318 	return link;
12319 }
12320 
12321 struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
12322 {
12323 	return bpf_program__attach_btf_id(prog, NULL);
12324 }
12325 
12326 struct bpf_link *bpf_program__attach_trace_opts(const struct bpf_program *prog,
12327 						const struct bpf_trace_opts *opts)
12328 {
12329 	return bpf_program__attach_btf_id(prog, opts);
12330 }
12331 
12332 struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
12333 {
12334 	return bpf_program__attach_btf_id(prog, NULL);
12335 }
12336 
12337 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12338 {
12339 	*link = bpf_program__attach_trace(prog);
12340 	return libbpf_get_error(*link);
12341 }
12342 
12343 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12344 {
12345 	*link = bpf_program__attach_lsm(prog);
12346 	return libbpf_get_error(*link);
12347 }
12348 
12349 static struct bpf_link *
12350 bpf_program_attach_fd(const struct bpf_program *prog,
12351 		      int target_fd, const char *target_name,
12352 		      const struct bpf_link_create_opts *opts)
12353 {
12354 	enum bpf_attach_type attach_type;
12355 	char errmsg[STRERR_BUFSIZE];
12356 	struct bpf_link *link;
12357 	int prog_fd, link_fd;
12358 
12359 	prog_fd = bpf_program__fd(prog);
12360 	if (prog_fd < 0) {
12361 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12362 		return libbpf_err_ptr(-EINVAL);
12363 	}
12364 
12365 	link = calloc(1, sizeof(*link));
12366 	if (!link)
12367 		return libbpf_err_ptr(-ENOMEM);
12368 	link->detach = &bpf_link__detach_fd;
12369 
12370 	attach_type = bpf_program__expected_attach_type(prog);
12371 	link_fd = bpf_link_create(prog_fd, target_fd, attach_type, opts);
12372 	if (link_fd < 0) {
12373 		link_fd = -errno;
12374 		free(link);
12375 		pr_warn("prog '%s': failed to attach to %s: %s\n",
12376 			prog->name, target_name,
12377 			libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
12378 		return libbpf_err_ptr(link_fd);
12379 	}
12380 	link->fd = link_fd;
12381 	return link;
12382 }
12383 
12384 struct bpf_link *
12385 bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
12386 {
12387 	return bpf_program_attach_fd(prog, cgroup_fd, "cgroup", NULL);
12388 }
12389 
12390 struct bpf_link *
12391 bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
12392 {
12393 	return bpf_program_attach_fd(prog, netns_fd, "netns", NULL);
12394 }
12395 
12396 struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
12397 {
12398 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
12399 	return bpf_program_attach_fd(prog, ifindex, "xdp", NULL);
12400 }
12401 
12402 struct bpf_link *
12403 bpf_program__attach_tcx(const struct bpf_program *prog, int ifindex,
12404 			const struct bpf_tcx_opts *opts)
12405 {
12406 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12407 	__u32 relative_id;
12408 	int relative_fd;
12409 
12410 	if (!OPTS_VALID(opts, bpf_tcx_opts))
12411 		return libbpf_err_ptr(-EINVAL);
12412 
12413 	relative_id = OPTS_GET(opts, relative_id, 0);
12414 	relative_fd = OPTS_GET(opts, relative_fd, 0);
12415 
12416 	/* validate we don't have unexpected combinations of non-zero fields */
12417 	if (!ifindex) {
12418 		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
12419 			prog->name);
12420 		return libbpf_err_ptr(-EINVAL);
12421 	}
12422 	if (relative_fd && relative_id) {
12423 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
12424 			prog->name);
12425 		return libbpf_err_ptr(-EINVAL);
12426 	}
12427 
12428 	link_create_opts.tcx.expected_revision = OPTS_GET(opts, expected_revision, 0);
12429 	link_create_opts.tcx.relative_fd = relative_fd;
12430 	link_create_opts.tcx.relative_id = relative_id;
12431 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
12432 
12433 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
12434 	return bpf_program_attach_fd(prog, ifindex, "tcx", &link_create_opts);
12435 }
12436 
12437 struct bpf_link *
12438 bpf_program__attach_netkit(const struct bpf_program *prog, int ifindex,
12439 			   const struct bpf_netkit_opts *opts)
12440 {
12441 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12442 	__u32 relative_id;
12443 	int relative_fd;
12444 
12445 	if (!OPTS_VALID(opts, bpf_netkit_opts))
12446 		return libbpf_err_ptr(-EINVAL);
12447 
12448 	relative_id = OPTS_GET(opts, relative_id, 0);
12449 	relative_fd = OPTS_GET(opts, relative_fd, 0);
12450 
12451 	/* validate we don't have unexpected combinations of non-zero fields */
12452 	if (!ifindex) {
12453 		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
12454 			prog->name);
12455 		return libbpf_err_ptr(-EINVAL);
12456 	}
12457 	if (relative_fd && relative_id) {
12458 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
12459 			prog->name);
12460 		return libbpf_err_ptr(-EINVAL);
12461 	}
12462 
12463 	link_create_opts.netkit.expected_revision = OPTS_GET(opts, expected_revision, 0);
12464 	link_create_opts.netkit.relative_fd = relative_fd;
12465 	link_create_opts.netkit.relative_id = relative_id;
12466 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
12467 
12468 	return bpf_program_attach_fd(prog, ifindex, "netkit", &link_create_opts);
12469 }
12470 
12471 struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
12472 					      int target_fd,
12473 					      const char *attach_func_name)
12474 {
12475 	int btf_id;
12476 
12477 	if (!!target_fd != !!attach_func_name) {
12478 		pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
12479 			prog->name);
12480 		return libbpf_err_ptr(-EINVAL);
12481 	}
12482 
12483 	if (prog->type != BPF_PROG_TYPE_EXT) {
12484 		pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace",
12485 			prog->name);
12486 		return libbpf_err_ptr(-EINVAL);
12487 	}
12488 
12489 	if (target_fd) {
12490 		LIBBPF_OPTS(bpf_link_create_opts, target_opts);
12491 
12492 		btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd);
12493 		if (btf_id < 0)
12494 			return libbpf_err_ptr(btf_id);
12495 
12496 		target_opts.target_btf_id = btf_id;
12497 
12498 		return bpf_program_attach_fd(prog, target_fd, "freplace",
12499 					     &target_opts);
12500 	} else {
12501 		/* no target, so use raw_tracepoint_open for compatibility
12502 		 * with old kernels
12503 		 */
12504 		return bpf_program__attach_trace(prog);
12505 	}
12506 }
12507 
12508 struct bpf_link *
12509 bpf_program__attach_iter(const struct bpf_program *prog,
12510 			 const struct bpf_iter_attach_opts *opts)
12511 {
12512 	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12513 	char errmsg[STRERR_BUFSIZE];
12514 	struct bpf_link *link;
12515 	int prog_fd, link_fd;
12516 	__u32 target_fd = 0;
12517 
12518 	if (!OPTS_VALID(opts, bpf_iter_attach_opts))
12519 		return libbpf_err_ptr(-EINVAL);
12520 
12521 	link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
12522 	link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
12523 
12524 	prog_fd = bpf_program__fd(prog);
12525 	if (prog_fd < 0) {
12526 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12527 		return libbpf_err_ptr(-EINVAL);
12528 	}
12529 
12530 	link = calloc(1, sizeof(*link));
12531 	if (!link)
12532 		return libbpf_err_ptr(-ENOMEM);
12533 	link->detach = &bpf_link__detach_fd;
12534 
12535 	link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
12536 				  &link_create_opts);
12537 	if (link_fd < 0) {
12538 		link_fd = -errno;
12539 		free(link);
12540 		pr_warn("prog '%s': failed to attach to iterator: %s\n",
12541 			prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
12542 		return libbpf_err_ptr(link_fd);
12543 	}
12544 	link->fd = link_fd;
12545 	return link;
12546 }
12547 
12548 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12549 {
12550 	*link = bpf_program__attach_iter(prog, NULL);
12551 	return libbpf_get_error(*link);
12552 }
12553 
12554 struct bpf_link *bpf_program__attach_netfilter(const struct bpf_program *prog,
12555 					       const struct bpf_netfilter_opts *opts)
12556 {
12557 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
12558 	struct bpf_link *link;
12559 	int prog_fd, link_fd;
12560 
12561 	if (!OPTS_VALID(opts, bpf_netfilter_opts))
12562 		return libbpf_err_ptr(-EINVAL);
12563 
12564 	prog_fd = bpf_program__fd(prog);
12565 	if (prog_fd < 0) {
12566 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12567 		return libbpf_err_ptr(-EINVAL);
12568 	}
12569 
12570 	link = calloc(1, sizeof(*link));
12571 	if (!link)
12572 		return libbpf_err_ptr(-ENOMEM);
12573 
12574 	link->detach = &bpf_link__detach_fd;
12575 
12576 	lopts.netfilter.pf = OPTS_GET(opts, pf, 0);
12577 	lopts.netfilter.hooknum = OPTS_GET(opts, hooknum, 0);
12578 	lopts.netfilter.priority = OPTS_GET(opts, priority, 0);
12579 	lopts.netfilter.flags = OPTS_GET(opts, flags, 0);
12580 
12581 	link_fd = bpf_link_create(prog_fd, 0, BPF_NETFILTER, &lopts);
12582 	if (link_fd < 0) {
12583 		char errmsg[STRERR_BUFSIZE];
12584 
12585 		link_fd = -errno;
12586 		free(link);
12587 		pr_warn("prog '%s': failed to attach to netfilter: %s\n",
12588 			prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
12589 		return libbpf_err_ptr(link_fd);
12590 	}
12591 	link->fd = link_fd;
12592 
12593 	return link;
12594 }
12595 
12596 struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
12597 {
12598 	struct bpf_link *link = NULL;
12599 	int err;
12600 
12601 	if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
12602 		return libbpf_err_ptr(-EOPNOTSUPP);
12603 
12604 	err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, &link);
12605 	if (err)
12606 		return libbpf_err_ptr(err);
12607 
12608 	/* When calling bpf_program__attach() explicitly, auto-attach support
12609 	 * is expected to work, so NULL returned link is considered an error.
12610 	 * This is different for skeleton's attach, see comment in
12611 	 * bpf_object__attach_skeleton().
12612 	 */
12613 	if (!link)
12614 		return libbpf_err_ptr(-EOPNOTSUPP);
12615 
12616 	return link;
12617 }
12618 
12619 struct bpf_link_struct_ops {
12620 	struct bpf_link link;
12621 	int map_fd;
12622 };
12623 
12624 static int bpf_link__detach_struct_ops(struct bpf_link *link)
12625 {
12626 	struct bpf_link_struct_ops *st_link;
12627 	__u32 zero = 0;
12628 
12629 	st_link = container_of(link, struct bpf_link_struct_ops, link);
12630 
12631 	if (st_link->map_fd < 0)
12632 		/* w/o a real link */
12633 		return bpf_map_delete_elem(link->fd, &zero);
12634 
12635 	return close(link->fd);
12636 }
12637 
12638 struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
12639 {
12640 	struct bpf_link_struct_ops *link;
12641 	__u32 zero = 0;
12642 	int err, fd;
12643 
12644 	if (!bpf_map__is_struct_ops(map) || map->fd == -1)
12645 		return libbpf_err_ptr(-EINVAL);
12646 
12647 	link = calloc(1, sizeof(*link));
12648 	if (!link)
12649 		return libbpf_err_ptr(-EINVAL);
12650 
12651 	/* kern_vdata should be prepared during the loading phase. */
12652 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
12653 	/* It can be EBUSY if the map has been used to create or
12654 	 * update a link before.  We don't allow updating the value of
12655 	 * a struct_ops once it is set.  That ensures that the value
12656 	 * never changed.  So, it is safe to skip EBUSY.
12657 	 */
12658 	if (err && (!(map->def.map_flags & BPF_F_LINK) || err != -EBUSY)) {
12659 		free(link);
12660 		return libbpf_err_ptr(err);
12661 	}
12662 
12663 	link->link.detach = bpf_link__detach_struct_ops;
12664 
12665 	if (!(map->def.map_flags & BPF_F_LINK)) {
12666 		/* w/o a real link */
12667 		link->link.fd = map->fd;
12668 		link->map_fd = -1;
12669 		return &link->link;
12670 	}
12671 
12672 	fd = bpf_link_create(map->fd, 0, BPF_STRUCT_OPS, NULL);
12673 	if (fd < 0) {
12674 		free(link);
12675 		return libbpf_err_ptr(fd);
12676 	}
12677 
12678 	link->link.fd = fd;
12679 	link->map_fd = map->fd;
12680 
12681 	return &link->link;
12682 }
12683 
12684 /*
12685  * Swap the back struct_ops of a link with a new struct_ops map.
12686  */
12687 int bpf_link__update_map(struct bpf_link *link, const struct bpf_map *map)
12688 {
12689 	struct bpf_link_struct_ops *st_ops_link;
12690 	__u32 zero = 0;
12691 	int err;
12692 
12693 	if (!bpf_map__is_struct_ops(map) || !map_is_created(map))
12694 		return -EINVAL;
12695 
12696 	st_ops_link = container_of(link, struct bpf_link_struct_ops, link);
12697 	/* Ensure the type of a link is correct */
12698 	if (st_ops_link->map_fd < 0)
12699 		return -EINVAL;
12700 
12701 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
12702 	/* It can be EBUSY if the map has been used to create or
12703 	 * update a link before.  We don't allow updating the value of
12704 	 * a struct_ops once it is set.  That ensures that the value
12705 	 * never changed.  So, it is safe to skip EBUSY.
12706 	 */
12707 	if (err && err != -EBUSY)
12708 		return err;
12709 
12710 	err = bpf_link_update(link->fd, map->fd, NULL);
12711 	if (err < 0)
12712 		return err;
12713 
12714 	st_ops_link->map_fd = map->fd;
12715 
12716 	return 0;
12717 }
12718 
12719 typedef enum bpf_perf_event_ret (*bpf_perf_event_print_t)(struct perf_event_header *hdr,
12720 							  void *private_data);
12721 
12722 static enum bpf_perf_event_ret
12723 perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
12724 		       void **copy_mem, size_t *copy_size,
12725 		       bpf_perf_event_print_t fn, void *private_data)
12726 {
12727 	struct perf_event_mmap_page *header = mmap_mem;
12728 	__u64 data_head = ring_buffer_read_head(header);
12729 	__u64 data_tail = header->data_tail;
12730 	void *base = ((__u8 *)header) + page_size;
12731 	int ret = LIBBPF_PERF_EVENT_CONT;
12732 	struct perf_event_header *ehdr;
12733 	size_t ehdr_size;
12734 
12735 	while (data_head != data_tail) {
12736 		ehdr = base + (data_tail & (mmap_size - 1));
12737 		ehdr_size = ehdr->size;
12738 
12739 		if (((void *)ehdr) + ehdr_size > base + mmap_size) {
12740 			void *copy_start = ehdr;
12741 			size_t len_first = base + mmap_size - copy_start;
12742 			size_t len_secnd = ehdr_size - len_first;
12743 
12744 			if (*copy_size < ehdr_size) {
12745 				free(*copy_mem);
12746 				*copy_mem = malloc(ehdr_size);
12747 				if (!*copy_mem) {
12748 					*copy_size = 0;
12749 					ret = LIBBPF_PERF_EVENT_ERROR;
12750 					break;
12751 				}
12752 				*copy_size = ehdr_size;
12753 			}
12754 
12755 			memcpy(*copy_mem, copy_start, len_first);
12756 			memcpy(*copy_mem + len_first, base, len_secnd);
12757 			ehdr = *copy_mem;
12758 		}
12759 
12760 		ret = fn(ehdr, private_data);
12761 		data_tail += ehdr_size;
12762 		if (ret != LIBBPF_PERF_EVENT_CONT)
12763 			break;
12764 	}
12765 
12766 	ring_buffer_write_tail(header, data_tail);
12767 	return libbpf_err(ret);
12768 }
12769 
12770 struct perf_buffer;
12771 
12772 struct perf_buffer_params {
12773 	struct perf_event_attr *attr;
12774 	/* if event_cb is specified, it takes precendence */
12775 	perf_buffer_event_fn event_cb;
12776 	/* sample_cb and lost_cb are higher-level common-case callbacks */
12777 	perf_buffer_sample_fn sample_cb;
12778 	perf_buffer_lost_fn lost_cb;
12779 	void *ctx;
12780 	int cpu_cnt;
12781 	int *cpus;
12782 	int *map_keys;
12783 };
12784 
12785 struct perf_cpu_buf {
12786 	struct perf_buffer *pb;
12787 	void *base; /* mmap()'ed memory */
12788 	void *buf; /* for reconstructing segmented data */
12789 	size_t buf_size;
12790 	int fd;
12791 	int cpu;
12792 	int map_key;
12793 };
12794 
12795 struct perf_buffer {
12796 	perf_buffer_event_fn event_cb;
12797 	perf_buffer_sample_fn sample_cb;
12798 	perf_buffer_lost_fn lost_cb;
12799 	void *ctx; /* passed into callbacks */
12800 
12801 	size_t page_size;
12802 	size_t mmap_size;
12803 	struct perf_cpu_buf **cpu_bufs;
12804 	struct epoll_event *events;
12805 	int cpu_cnt; /* number of allocated CPU buffers */
12806 	int epoll_fd; /* perf event FD */
12807 	int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
12808 };
12809 
12810 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
12811 				      struct perf_cpu_buf *cpu_buf)
12812 {
12813 	if (!cpu_buf)
12814 		return;
12815 	if (cpu_buf->base &&
12816 	    munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
12817 		pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
12818 	if (cpu_buf->fd >= 0) {
12819 		ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
12820 		close(cpu_buf->fd);
12821 	}
12822 	free(cpu_buf->buf);
12823 	free(cpu_buf);
12824 }
12825 
12826 void perf_buffer__free(struct perf_buffer *pb)
12827 {
12828 	int i;
12829 
12830 	if (IS_ERR_OR_NULL(pb))
12831 		return;
12832 	if (pb->cpu_bufs) {
12833 		for (i = 0; i < pb->cpu_cnt; i++) {
12834 			struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
12835 
12836 			if (!cpu_buf)
12837 				continue;
12838 
12839 			bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
12840 			perf_buffer__free_cpu_buf(pb, cpu_buf);
12841 		}
12842 		free(pb->cpu_bufs);
12843 	}
12844 	if (pb->epoll_fd >= 0)
12845 		close(pb->epoll_fd);
12846 	free(pb->events);
12847 	free(pb);
12848 }
12849 
12850 static struct perf_cpu_buf *
12851 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
12852 			  int cpu, int map_key)
12853 {
12854 	struct perf_cpu_buf *cpu_buf;
12855 	char msg[STRERR_BUFSIZE];
12856 	int err;
12857 
12858 	cpu_buf = calloc(1, sizeof(*cpu_buf));
12859 	if (!cpu_buf)
12860 		return ERR_PTR(-ENOMEM);
12861 
12862 	cpu_buf->pb = pb;
12863 	cpu_buf->cpu = cpu;
12864 	cpu_buf->map_key = map_key;
12865 
12866 	cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
12867 			      -1, PERF_FLAG_FD_CLOEXEC);
12868 	if (cpu_buf->fd < 0) {
12869 		err = -errno;
12870 		pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
12871 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
12872 		goto error;
12873 	}
12874 
12875 	cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
12876 			     PROT_READ | PROT_WRITE, MAP_SHARED,
12877 			     cpu_buf->fd, 0);
12878 	if (cpu_buf->base == MAP_FAILED) {
12879 		cpu_buf->base = NULL;
12880 		err = -errno;
12881 		pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
12882 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
12883 		goto error;
12884 	}
12885 
12886 	if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
12887 		err = -errno;
12888 		pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
12889 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
12890 		goto error;
12891 	}
12892 
12893 	return cpu_buf;
12894 
12895 error:
12896 	perf_buffer__free_cpu_buf(pb, cpu_buf);
12897 	return (struct perf_cpu_buf *)ERR_PTR(err);
12898 }
12899 
12900 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
12901 					      struct perf_buffer_params *p);
12902 
12903 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
12904 				     perf_buffer_sample_fn sample_cb,
12905 				     perf_buffer_lost_fn lost_cb,
12906 				     void *ctx,
12907 				     const struct perf_buffer_opts *opts)
12908 {
12909 	const size_t attr_sz = sizeof(struct perf_event_attr);
12910 	struct perf_buffer_params p = {};
12911 	struct perf_event_attr attr;
12912 	__u32 sample_period;
12913 
12914 	if (!OPTS_VALID(opts, perf_buffer_opts))
12915 		return libbpf_err_ptr(-EINVAL);
12916 
12917 	sample_period = OPTS_GET(opts, sample_period, 1);
12918 	if (!sample_period)
12919 		sample_period = 1;
12920 
12921 	memset(&attr, 0, attr_sz);
12922 	attr.size = attr_sz;
12923 	attr.config = PERF_COUNT_SW_BPF_OUTPUT;
12924 	attr.type = PERF_TYPE_SOFTWARE;
12925 	attr.sample_type = PERF_SAMPLE_RAW;
12926 	attr.sample_period = sample_period;
12927 	attr.wakeup_events = sample_period;
12928 
12929 	p.attr = &attr;
12930 	p.sample_cb = sample_cb;
12931 	p.lost_cb = lost_cb;
12932 	p.ctx = ctx;
12933 
12934 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
12935 }
12936 
12937 struct perf_buffer *perf_buffer__new_raw(int map_fd, size_t page_cnt,
12938 					 struct perf_event_attr *attr,
12939 					 perf_buffer_event_fn event_cb, void *ctx,
12940 					 const struct perf_buffer_raw_opts *opts)
12941 {
12942 	struct perf_buffer_params p = {};
12943 
12944 	if (!attr)
12945 		return libbpf_err_ptr(-EINVAL);
12946 
12947 	if (!OPTS_VALID(opts, perf_buffer_raw_opts))
12948 		return libbpf_err_ptr(-EINVAL);
12949 
12950 	p.attr = attr;
12951 	p.event_cb = event_cb;
12952 	p.ctx = ctx;
12953 	p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
12954 	p.cpus = OPTS_GET(opts, cpus, NULL);
12955 	p.map_keys = OPTS_GET(opts, map_keys, NULL);
12956 
12957 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
12958 }
12959 
12960 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
12961 					      struct perf_buffer_params *p)
12962 {
12963 	const char *online_cpus_file = "/sys/devices/system/cpu/online";
12964 	struct bpf_map_info map;
12965 	char msg[STRERR_BUFSIZE];
12966 	struct perf_buffer *pb;
12967 	bool *online = NULL;
12968 	__u32 map_info_len;
12969 	int err, i, j, n;
12970 
12971 	if (page_cnt == 0 || (page_cnt & (page_cnt - 1))) {
12972 		pr_warn("page count should be power of two, but is %zu\n",
12973 			page_cnt);
12974 		return ERR_PTR(-EINVAL);
12975 	}
12976 
12977 	/* best-effort sanity checks */
12978 	memset(&map, 0, sizeof(map));
12979 	map_info_len = sizeof(map);
12980 	err = bpf_map_get_info_by_fd(map_fd, &map, &map_info_len);
12981 	if (err) {
12982 		err = -errno;
12983 		/* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
12984 		 * -EBADFD, -EFAULT, or -E2BIG on real error
12985 		 */
12986 		if (err != -EINVAL) {
12987 			pr_warn("failed to get map info for map FD %d: %s\n",
12988 				map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
12989 			return ERR_PTR(err);
12990 		}
12991 		pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
12992 			 map_fd);
12993 	} else {
12994 		if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
12995 			pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
12996 				map.name);
12997 			return ERR_PTR(-EINVAL);
12998 		}
12999 	}
13000 
13001 	pb = calloc(1, sizeof(*pb));
13002 	if (!pb)
13003 		return ERR_PTR(-ENOMEM);
13004 
13005 	pb->event_cb = p->event_cb;
13006 	pb->sample_cb = p->sample_cb;
13007 	pb->lost_cb = p->lost_cb;
13008 	pb->ctx = p->ctx;
13009 
13010 	pb->page_size = getpagesize();
13011 	pb->mmap_size = pb->page_size * page_cnt;
13012 	pb->map_fd = map_fd;
13013 
13014 	pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
13015 	if (pb->epoll_fd < 0) {
13016 		err = -errno;
13017 		pr_warn("failed to create epoll instance: %s\n",
13018 			libbpf_strerror_r(err, msg, sizeof(msg)));
13019 		goto error;
13020 	}
13021 
13022 	if (p->cpu_cnt > 0) {
13023 		pb->cpu_cnt = p->cpu_cnt;
13024 	} else {
13025 		pb->cpu_cnt = libbpf_num_possible_cpus();
13026 		if (pb->cpu_cnt < 0) {
13027 			err = pb->cpu_cnt;
13028 			goto error;
13029 		}
13030 		if (map.max_entries && map.max_entries < pb->cpu_cnt)
13031 			pb->cpu_cnt = map.max_entries;
13032 	}
13033 
13034 	pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
13035 	if (!pb->events) {
13036 		err = -ENOMEM;
13037 		pr_warn("failed to allocate events: out of memory\n");
13038 		goto error;
13039 	}
13040 	pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
13041 	if (!pb->cpu_bufs) {
13042 		err = -ENOMEM;
13043 		pr_warn("failed to allocate buffers: out of memory\n");
13044 		goto error;
13045 	}
13046 
13047 	err = parse_cpu_mask_file(online_cpus_file, &online, &n);
13048 	if (err) {
13049 		pr_warn("failed to get online CPU mask: %d\n", err);
13050 		goto error;
13051 	}
13052 
13053 	for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
13054 		struct perf_cpu_buf *cpu_buf;
13055 		int cpu, map_key;
13056 
13057 		cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
13058 		map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
13059 
13060 		/* in case user didn't explicitly requested particular CPUs to
13061 		 * be attached to, skip offline/not present CPUs
13062 		 */
13063 		if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
13064 			continue;
13065 
13066 		cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
13067 		if (IS_ERR(cpu_buf)) {
13068 			err = PTR_ERR(cpu_buf);
13069 			goto error;
13070 		}
13071 
13072 		pb->cpu_bufs[j] = cpu_buf;
13073 
13074 		err = bpf_map_update_elem(pb->map_fd, &map_key,
13075 					  &cpu_buf->fd, 0);
13076 		if (err) {
13077 			err = -errno;
13078 			pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
13079 				cpu, map_key, cpu_buf->fd,
13080 				libbpf_strerror_r(err, msg, sizeof(msg)));
13081 			goto error;
13082 		}
13083 
13084 		pb->events[j].events = EPOLLIN;
13085 		pb->events[j].data.ptr = cpu_buf;
13086 		if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
13087 			      &pb->events[j]) < 0) {
13088 			err = -errno;
13089 			pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
13090 				cpu, cpu_buf->fd,
13091 				libbpf_strerror_r(err, msg, sizeof(msg)));
13092 			goto error;
13093 		}
13094 		j++;
13095 	}
13096 	pb->cpu_cnt = j;
13097 	free(online);
13098 
13099 	return pb;
13100 
13101 error:
13102 	free(online);
13103 	if (pb)
13104 		perf_buffer__free(pb);
13105 	return ERR_PTR(err);
13106 }
13107 
13108 struct perf_sample_raw {
13109 	struct perf_event_header header;
13110 	uint32_t size;
13111 	char data[];
13112 };
13113 
13114 struct perf_sample_lost {
13115 	struct perf_event_header header;
13116 	uint64_t id;
13117 	uint64_t lost;
13118 	uint64_t sample_id;
13119 };
13120 
13121 static enum bpf_perf_event_ret
13122 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
13123 {
13124 	struct perf_cpu_buf *cpu_buf = ctx;
13125 	struct perf_buffer *pb = cpu_buf->pb;
13126 	void *data = e;
13127 
13128 	/* user wants full control over parsing perf event */
13129 	if (pb->event_cb)
13130 		return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
13131 
13132 	switch (e->type) {
13133 	case PERF_RECORD_SAMPLE: {
13134 		struct perf_sample_raw *s = data;
13135 
13136 		if (pb->sample_cb)
13137 			pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
13138 		break;
13139 	}
13140 	case PERF_RECORD_LOST: {
13141 		struct perf_sample_lost *s = data;
13142 
13143 		if (pb->lost_cb)
13144 			pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
13145 		break;
13146 	}
13147 	default:
13148 		pr_warn("unknown perf sample type %d\n", e->type);
13149 		return LIBBPF_PERF_EVENT_ERROR;
13150 	}
13151 	return LIBBPF_PERF_EVENT_CONT;
13152 }
13153 
13154 static int perf_buffer__process_records(struct perf_buffer *pb,
13155 					struct perf_cpu_buf *cpu_buf)
13156 {
13157 	enum bpf_perf_event_ret ret;
13158 
13159 	ret = perf_event_read_simple(cpu_buf->base, pb->mmap_size,
13160 				     pb->page_size, &cpu_buf->buf,
13161 				     &cpu_buf->buf_size,
13162 				     perf_buffer__process_record, cpu_buf);
13163 	if (ret != LIBBPF_PERF_EVENT_CONT)
13164 		return ret;
13165 	return 0;
13166 }
13167 
13168 int perf_buffer__epoll_fd(const struct perf_buffer *pb)
13169 {
13170 	return pb->epoll_fd;
13171 }
13172 
13173 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
13174 {
13175 	int i, cnt, err;
13176 
13177 	cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
13178 	if (cnt < 0)
13179 		return -errno;
13180 
13181 	for (i = 0; i < cnt; i++) {
13182 		struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
13183 
13184 		err = perf_buffer__process_records(pb, cpu_buf);
13185 		if (err) {
13186 			pr_warn("error while processing records: %d\n", err);
13187 			return libbpf_err(err);
13188 		}
13189 	}
13190 	return cnt;
13191 }
13192 
13193 /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
13194  * manager.
13195  */
13196 size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
13197 {
13198 	return pb->cpu_cnt;
13199 }
13200 
13201 /*
13202  * Return perf_event FD of a ring buffer in *buf_idx* slot of
13203  * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
13204  * select()/poll()/epoll() Linux syscalls.
13205  */
13206 int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
13207 {
13208 	struct perf_cpu_buf *cpu_buf;
13209 
13210 	if (buf_idx >= pb->cpu_cnt)
13211 		return libbpf_err(-EINVAL);
13212 
13213 	cpu_buf = pb->cpu_bufs[buf_idx];
13214 	if (!cpu_buf)
13215 		return libbpf_err(-ENOENT);
13216 
13217 	return cpu_buf->fd;
13218 }
13219 
13220 int perf_buffer__buffer(struct perf_buffer *pb, int buf_idx, void **buf, size_t *buf_size)
13221 {
13222 	struct perf_cpu_buf *cpu_buf;
13223 
13224 	if (buf_idx >= pb->cpu_cnt)
13225 		return libbpf_err(-EINVAL);
13226 
13227 	cpu_buf = pb->cpu_bufs[buf_idx];
13228 	if (!cpu_buf)
13229 		return libbpf_err(-ENOENT);
13230 
13231 	*buf = cpu_buf->base;
13232 	*buf_size = pb->mmap_size;
13233 	return 0;
13234 }
13235 
13236 /*
13237  * Consume data from perf ring buffer corresponding to slot *buf_idx* in
13238  * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
13239  * consume, do nothing and return success.
13240  * Returns:
13241  *   - 0 on success;
13242  *   - <0 on failure.
13243  */
13244 int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
13245 {
13246 	struct perf_cpu_buf *cpu_buf;
13247 
13248 	if (buf_idx >= pb->cpu_cnt)
13249 		return libbpf_err(-EINVAL);
13250 
13251 	cpu_buf = pb->cpu_bufs[buf_idx];
13252 	if (!cpu_buf)
13253 		return libbpf_err(-ENOENT);
13254 
13255 	return perf_buffer__process_records(pb, cpu_buf);
13256 }
13257 
13258 int perf_buffer__consume(struct perf_buffer *pb)
13259 {
13260 	int i, err;
13261 
13262 	for (i = 0; i < pb->cpu_cnt; i++) {
13263 		struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
13264 
13265 		if (!cpu_buf)
13266 			continue;
13267 
13268 		err = perf_buffer__process_records(pb, cpu_buf);
13269 		if (err) {
13270 			pr_warn("perf_buffer: failed to process records in buffer #%d: %d\n", i, err);
13271 			return libbpf_err(err);
13272 		}
13273 	}
13274 	return 0;
13275 }
13276 
13277 int bpf_program__set_attach_target(struct bpf_program *prog,
13278 				   int attach_prog_fd,
13279 				   const char *attach_func_name)
13280 {
13281 	int btf_obj_fd = 0, btf_id = 0, err;
13282 
13283 	if (!prog || attach_prog_fd < 0)
13284 		return libbpf_err(-EINVAL);
13285 
13286 	if (prog->obj->loaded)
13287 		return libbpf_err(-EINVAL);
13288 
13289 	if (attach_prog_fd && !attach_func_name) {
13290 		/* remember attach_prog_fd and let bpf_program__load() find
13291 		 * BTF ID during the program load
13292 		 */
13293 		prog->attach_prog_fd = attach_prog_fd;
13294 		return 0;
13295 	}
13296 
13297 	if (attach_prog_fd) {
13298 		btf_id = libbpf_find_prog_btf_id(attach_func_name,
13299 						 attach_prog_fd);
13300 		if (btf_id < 0)
13301 			return libbpf_err(btf_id);
13302 	} else {
13303 		if (!attach_func_name)
13304 			return libbpf_err(-EINVAL);
13305 
13306 		/* load btf_vmlinux, if not yet */
13307 		err = bpf_object__load_vmlinux_btf(prog->obj, true);
13308 		if (err)
13309 			return libbpf_err(err);
13310 		err = find_kernel_btf_id(prog->obj, attach_func_name,
13311 					 prog->expected_attach_type,
13312 					 &btf_obj_fd, &btf_id);
13313 		if (err)
13314 			return libbpf_err(err);
13315 	}
13316 
13317 	prog->attach_btf_id = btf_id;
13318 	prog->attach_btf_obj_fd = btf_obj_fd;
13319 	prog->attach_prog_fd = attach_prog_fd;
13320 	return 0;
13321 }
13322 
13323 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
13324 {
13325 	int err = 0, n, len, start, end = -1;
13326 	bool *tmp;
13327 
13328 	*mask = NULL;
13329 	*mask_sz = 0;
13330 
13331 	/* Each sub string separated by ',' has format \d+-\d+ or \d+ */
13332 	while (*s) {
13333 		if (*s == ',' || *s == '\n') {
13334 			s++;
13335 			continue;
13336 		}
13337 		n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
13338 		if (n <= 0 || n > 2) {
13339 			pr_warn("Failed to get CPU range %s: %d\n", s, n);
13340 			err = -EINVAL;
13341 			goto cleanup;
13342 		} else if (n == 1) {
13343 			end = start;
13344 		}
13345 		if (start < 0 || start > end) {
13346 			pr_warn("Invalid CPU range [%d,%d] in %s\n",
13347 				start, end, s);
13348 			err = -EINVAL;
13349 			goto cleanup;
13350 		}
13351 		tmp = realloc(*mask, end + 1);
13352 		if (!tmp) {
13353 			err = -ENOMEM;
13354 			goto cleanup;
13355 		}
13356 		*mask = tmp;
13357 		memset(tmp + *mask_sz, 0, start - *mask_sz);
13358 		memset(tmp + start, 1, end - start + 1);
13359 		*mask_sz = end + 1;
13360 		s += len;
13361 	}
13362 	if (!*mask_sz) {
13363 		pr_warn("Empty CPU range\n");
13364 		return -EINVAL;
13365 	}
13366 	return 0;
13367 cleanup:
13368 	free(*mask);
13369 	*mask = NULL;
13370 	return err;
13371 }
13372 
13373 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
13374 {
13375 	int fd, err = 0, len;
13376 	char buf[128];
13377 
13378 	fd = open(fcpu, O_RDONLY | O_CLOEXEC);
13379 	if (fd < 0) {
13380 		err = -errno;
13381 		pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
13382 		return err;
13383 	}
13384 	len = read(fd, buf, sizeof(buf));
13385 	close(fd);
13386 	if (len <= 0) {
13387 		err = len ? -errno : -EINVAL;
13388 		pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
13389 		return err;
13390 	}
13391 	if (len >= sizeof(buf)) {
13392 		pr_warn("CPU mask is too big in file %s\n", fcpu);
13393 		return -E2BIG;
13394 	}
13395 	buf[len] = '\0';
13396 
13397 	return parse_cpu_mask_str(buf, mask, mask_sz);
13398 }
13399 
13400 int libbpf_num_possible_cpus(void)
13401 {
13402 	static const char *fcpu = "/sys/devices/system/cpu/possible";
13403 	static int cpus;
13404 	int err, n, i, tmp_cpus;
13405 	bool *mask;
13406 
13407 	tmp_cpus = READ_ONCE(cpus);
13408 	if (tmp_cpus > 0)
13409 		return tmp_cpus;
13410 
13411 	err = parse_cpu_mask_file(fcpu, &mask, &n);
13412 	if (err)
13413 		return libbpf_err(err);
13414 
13415 	tmp_cpus = 0;
13416 	for (i = 0; i < n; i++) {
13417 		if (mask[i])
13418 			tmp_cpus++;
13419 	}
13420 	free(mask);
13421 
13422 	WRITE_ONCE(cpus, tmp_cpus);
13423 	return tmp_cpus;
13424 }
13425 
13426 static int populate_skeleton_maps(const struct bpf_object *obj,
13427 				  struct bpf_map_skeleton *maps,
13428 				  size_t map_cnt)
13429 {
13430 	int i;
13431 
13432 	for (i = 0; i < map_cnt; i++) {
13433 		struct bpf_map **map = maps[i].map;
13434 		const char *name = maps[i].name;
13435 		void **mmaped = maps[i].mmaped;
13436 
13437 		*map = bpf_object__find_map_by_name(obj, name);
13438 		if (!*map) {
13439 			pr_warn("failed to find skeleton map '%s'\n", name);
13440 			return -ESRCH;
13441 		}
13442 
13443 		/* externs shouldn't be pre-setup from user code */
13444 		if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
13445 			*mmaped = (*map)->mmaped;
13446 	}
13447 	return 0;
13448 }
13449 
13450 static int populate_skeleton_progs(const struct bpf_object *obj,
13451 				   struct bpf_prog_skeleton *progs,
13452 				   size_t prog_cnt)
13453 {
13454 	int i;
13455 
13456 	for (i = 0; i < prog_cnt; i++) {
13457 		struct bpf_program **prog = progs[i].prog;
13458 		const char *name = progs[i].name;
13459 
13460 		*prog = bpf_object__find_program_by_name(obj, name);
13461 		if (!*prog) {
13462 			pr_warn("failed to find skeleton program '%s'\n", name);
13463 			return -ESRCH;
13464 		}
13465 	}
13466 	return 0;
13467 }
13468 
13469 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
13470 			      const struct bpf_object_open_opts *opts)
13471 {
13472 	DECLARE_LIBBPF_OPTS(bpf_object_open_opts, skel_opts,
13473 		.object_name = s->name,
13474 	);
13475 	struct bpf_object *obj;
13476 	int err;
13477 
13478 	/* Attempt to preserve opts->object_name, unless overriden by user
13479 	 * explicitly. Overwriting object name for skeletons is discouraged,
13480 	 * as it breaks global data maps, because they contain object name
13481 	 * prefix as their own map name prefix. When skeleton is generated,
13482 	 * bpftool is making an assumption that this name will stay the same.
13483 	 */
13484 	if (opts) {
13485 		memcpy(&skel_opts, opts, sizeof(*opts));
13486 		if (!opts->object_name)
13487 			skel_opts.object_name = s->name;
13488 	}
13489 
13490 	obj = bpf_object__open_mem(s->data, s->data_sz, &skel_opts);
13491 	err = libbpf_get_error(obj);
13492 	if (err) {
13493 		pr_warn("failed to initialize skeleton BPF object '%s': %d\n",
13494 			s->name, err);
13495 		return libbpf_err(err);
13496 	}
13497 
13498 	*s->obj = obj;
13499 	err = populate_skeleton_maps(obj, s->maps, s->map_cnt);
13500 	if (err) {
13501 		pr_warn("failed to populate skeleton maps for '%s': %d\n", s->name, err);
13502 		return libbpf_err(err);
13503 	}
13504 
13505 	err = populate_skeleton_progs(obj, s->progs, s->prog_cnt);
13506 	if (err) {
13507 		pr_warn("failed to populate skeleton progs for '%s': %d\n", s->name, err);
13508 		return libbpf_err(err);
13509 	}
13510 
13511 	return 0;
13512 }
13513 
13514 int bpf_object__open_subskeleton(struct bpf_object_subskeleton *s)
13515 {
13516 	int err, len, var_idx, i;
13517 	const char *var_name;
13518 	const struct bpf_map *map;
13519 	struct btf *btf;
13520 	__u32 map_type_id;
13521 	const struct btf_type *map_type, *var_type;
13522 	const struct bpf_var_skeleton *var_skel;
13523 	struct btf_var_secinfo *var;
13524 
13525 	if (!s->obj)
13526 		return libbpf_err(-EINVAL);
13527 
13528 	btf = bpf_object__btf(s->obj);
13529 	if (!btf) {
13530 		pr_warn("subskeletons require BTF at runtime (object %s)\n",
13531 			bpf_object__name(s->obj));
13532 		return libbpf_err(-errno);
13533 	}
13534 
13535 	err = populate_skeleton_maps(s->obj, s->maps, s->map_cnt);
13536 	if (err) {
13537 		pr_warn("failed to populate subskeleton maps: %d\n", err);
13538 		return libbpf_err(err);
13539 	}
13540 
13541 	err = populate_skeleton_progs(s->obj, s->progs, s->prog_cnt);
13542 	if (err) {
13543 		pr_warn("failed to populate subskeleton maps: %d\n", err);
13544 		return libbpf_err(err);
13545 	}
13546 
13547 	for (var_idx = 0; var_idx < s->var_cnt; var_idx++) {
13548 		var_skel = &s->vars[var_idx];
13549 		map = *var_skel->map;
13550 		map_type_id = bpf_map__btf_value_type_id(map);
13551 		map_type = btf__type_by_id(btf, map_type_id);
13552 
13553 		if (!btf_is_datasec(map_type)) {
13554 			pr_warn("type for map '%1$s' is not a datasec: %2$s",
13555 				bpf_map__name(map),
13556 				__btf_kind_str(btf_kind(map_type)));
13557 			return libbpf_err(-EINVAL);
13558 		}
13559 
13560 		len = btf_vlen(map_type);
13561 		var = btf_var_secinfos(map_type);
13562 		for (i = 0; i < len; i++, var++) {
13563 			var_type = btf__type_by_id(btf, var->type);
13564 			var_name = btf__name_by_offset(btf, var_type->name_off);
13565 			if (strcmp(var_name, var_skel->name) == 0) {
13566 				*var_skel->addr = map->mmaped + var->offset;
13567 				break;
13568 			}
13569 		}
13570 	}
13571 	return 0;
13572 }
13573 
13574 void bpf_object__destroy_subskeleton(struct bpf_object_subskeleton *s)
13575 {
13576 	if (!s)
13577 		return;
13578 	free(s->maps);
13579 	free(s->progs);
13580 	free(s->vars);
13581 	free(s);
13582 }
13583 
13584 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
13585 {
13586 	int i, err;
13587 
13588 	err = bpf_object__load(*s->obj);
13589 	if (err) {
13590 		pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
13591 		return libbpf_err(err);
13592 	}
13593 
13594 	for (i = 0; i < s->map_cnt; i++) {
13595 		struct bpf_map *map = *s->maps[i].map;
13596 		size_t mmap_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
13597 		int prot, map_fd = map->fd;
13598 		void **mmaped = s->maps[i].mmaped;
13599 
13600 		if (!mmaped)
13601 			continue;
13602 
13603 		if (!(map->def.map_flags & BPF_F_MMAPABLE)) {
13604 			*mmaped = NULL;
13605 			continue;
13606 		}
13607 
13608 		if (map->def.map_flags & BPF_F_RDONLY_PROG)
13609 			prot = PROT_READ;
13610 		else
13611 			prot = PROT_READ | PROT_WRITE;
13612 
13613 		/* Remap anonymous mmap()-ed "map initialization image" as
13614 		 * a BPF map-backed mmap()-ed memory, but preserving the same
13615 		 * memory address. This will cause kernel to change process'
13616 		 * page table to point to a different piece of kernel memory,
13617 		 * but from userspace point of view memory address (and its
13618 		 * contents, being identical at this point) will stay the
13619 		 * same. This mapping will be released by bpf_object__close()
13620 		 * as per normal clean up procedure, so we don't need to worry
13621 		 * about it from skeleton's clean up perspective.
13622 		 */
13623 		*mmaped = mmap(map->mmaped, mmap_sz, prot, MAP_SHARED | MAP_FIXED, map_fd, 0);
13624 		if (*mmaped == MAP_FAILED) {
13625 			err = -errno;
13626 			*mmaped = NULL;
13627 			pr_warn("failed to re-mmap() map '%s': %d\n",
13628 				 bpf_map__name(map), err);
13629 			return libbpf_err(err);
13630 		}
13631 	}
13632 
13633 	return 0;
13634 }
13635 
13636 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
13637 {
13638 	int i, err;
13639 
13640 	for (i = 0; i < s->prog_cnt; i++) {
13641 		struct bpf_program *prog = *s->progs[i].prog;
13642 		struct bpf_link **link = s->progs[i].link;
13643 
13644 		if (!prog->autoload || !prog->autoattach)
13645 			continue;
13646 
13647 		/* auto-attaching not supported for this program */
13648 		if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
13649 			continue;
13650 
13651 		/* if user already set the link manually, don't attempt auto-attach */
13652 		if (*link)
13653 			continue;
13654 
13655 		err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, link);
13656 		if (err) {
13657 			pr_warn("prog '%s': failed to auto-attach: %d\n",
13658 				bpf_program__name(prog), err);
13659 			return libbpf_err(err);
13660 		}
13661 
13662 		/* It's possible that for some SEC() definitions auto-attach
13663 		 * is supported in some cases (e.g., if definition completely
13664 		 * specifies target information), but is not in other cases.
13665 		 * SEC("uprobe") is one such case. If user specified target
13666 		 * binary and function name, such BPF program can be
13667 		 * auto-attached. But if not, it shouldn't trigger skeleton's
13668 		 * attach to fail. It should just be skipped.
13669 		 * attach_fn signals such case with returning 0 (no error) and
13670 		 * setting link to NULL.
13671 		 */
13672 	}
13673 
13674 	return 0;
13675 }
13676 
13677 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
13678 {
13679 	int i;
13680 
13681 	for (i = 0; i < s->prog_cnt; i++) {
13682 		struct bpf_link **link = s->progs[i].link;
13683 
13684 		bpf_link__destroy(*link);
13685 		*link = NULL;
13686 	}
13687 }
13688 
13689 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
13690 {
13691 	if (!s)
13692 		return;
13693 
13694 	if (s->progs)
13695 		bpf_object__detach_skeleton(s);
13696 	if (s->obj)
13697 		bpf_object__close(*s->obj);
13698 	free(s->maps);
13699 	free(s->progs);
13700 	free(s);
13701 }
13702