• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
2 
3 /*
4  * Common eBPF ELF object loading operations.
5  *
6  * Copyright (C) 2013-2015 Alexei Starovoitov <ast@kernel.org>
7  * Copyright (C) 2015 Wang Nan <wangnan0@huawei.com>
8  * Copyright (C) 2015 Huawei Inc.
9  * Copyright (C) 2017 Nicira, Inc.
10  * Copyright (C) 2019 Isovalent, Inc.
11  */
12 
13 #ifndef _GNU_SOURCE
14 #define _GNU_SOURCE
15 #endif
16 #include <stdlib.h>
17 #include <stdio.h>
18 #include <stdarg.h>
19 #include <libgen.h>
20 #include <inttypes.h>
21 #include <limits.h>
22 #include <string.h>
23 #include <unistd.h>
24 #include <endian.h>
25 #include <fcntl.h>
26 #include <errno.h>
27 #include <ctype.h>
28 #include <asm/unistd.h>
29 #include <linux/err.h>
30 #include <linux/kernel.h>
31 #include <linux/bpf.h>
32 #include <linux/btf.h>
33 #include <linux/filter.h>
34 #include <linux/limits.h>
35 #include <linux/perf_event.h>
36 #include <linux/ring_buffer.h>
37 #include <linux/version.h>
38 #include <sys/epoll.h>
39 #include <sys/ioctl.h>
40 #include <sys/mman.h>
41 #include <sys/stat.h>
42 #include <sys/types.h>
43 #include <sys/vfs.h>
44 #include <sys/utsname.h>
45 #include <sys/resource.h>
46 #ifdef HAVE_LIBELF
47 #include <libelf.h>
48 #include <gelf.h>
49 #endif
50 
51 #include <zlib.h>
52 
53 #include "libbpf.h"
54 #include "bpf.h"
55 #include "btf.h"
56 #include "str_error.h"
57 #include "libbpf_internal.h"
58 #include "hashmap.h"
59 #include "bpf_gen_internal.h"
60 #include "zip.h"
61 
62 #ifndef BPF_FS_MAGIC
63 #define BPF_FS_MAGIC		0xcafe4a11
64 #endif
65 
66 #define BPF_INSN_SZ (sizeof(struct bpf_insn))
67 
68 /* vsprintf() in __base_pr() uses nonliteral format string. It may break
69  * compilation if user enables corresponding warning. Disable it explicitly.
70  */
71 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
72 
73 #define __printf(a, b)	__attribute__((format(printf, a, b)))
74 
75 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj);
76 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog);
77 
78 static const char * const attach_type_name[] = {
79 	[BPF_CGROUP_INET_INGRESS]	= "cgroup_inet_ingress",
80 	[BPF_CGROUP_INET_EGRESS]	= "cgroup_inet_egress",
81 	[BPF_CGROUP_INET_SOCK_CREATE]	= "cgroup_inet_sock_create",
82 	[BPF_CGROUP_INET_SOCK_RELEASE]	= "cgroup_inet_sock_release",
83 	[BPF_CGROUP_SOCK_OPS]		= "cgroup_sock_ops",
84 	[BPF_CGROUP_DEVICE]		= "cgroup_device",
85 	[BPF_CGROUP_INET4_BIND]		= "cgroup_inet4_bind",
86 	[BPF_CGROUP_INET6_BIND]		= "cgroup_inet6_bind",
87 	[BPF_CGROUP_INET4_CONNECT]	= "cgroup_inet4_connect",
88 	[BPF_CGROUP_INET6_CONNECT]	= "cgroup_inet6_connect",
89 	[BPF_CGROUP_UNIX_CONNECT]       = "cgroup_unix_connect",
90 	[BPF_CGROUP_INET4_POST_BIND]	= "cgroup_inet4_post_bind",
91 	[BPF_CGROUP_INET6_POST_BIND]	= "cgroup_inet6_post_bind",
92 	[BPF_CGROUP_INET4_GETPEERNAME]	= "cgroup_inet4_getpeername",
93 	[BPF_CGROUP_INET6_GETPEERNAME]	= "cgroup_inet6_getpeername",
94 	[BPF_CGROUP_UNIX_GETPEERNAME]	= "cgroup_unix_getpeername",
95 	[BPF_CGROUP_INET4_GETSOCKNAME]	= "cgroup_inet4_getsockname",
96 	[BPF_CGROUP_INET6_GETSOCKNAME]	= "cgroup_inet6_getsockname",
97 	[BPF_CGROUP_UNIX_GETSOCKNAME]	= "cgroup_unix_getsockname",
98 	[BPF_CGROUP_UDP4_SENDMSG]	= "cgroup_udp4_sendmsg",
99 	[BPF_CGROUP_UDP6_SENDMSG]	= "cgroup_udp6_sendmsg",
100 	[BPF_CGROUP_UNIX_SENDMSG]	= "cgroup_unix_sendmsg",
101 	[BPF_CGROUP_SYSCTL]		= "cgroup_sysctl",
102 	[BPF_CGROUP_UDP4_RECVMSG]	= "cgroup_udp4_recvmsg",
103 	[BPF_CGROUP_UDP6_RECVMSG]	= "cgroup_udp6_recvmsg",
104 	[BPF_CGROUP_UNIX_RECVMSG]	= "cgroup_unix_recvmsg",
105 	[BPF_CGROUP_GETSOCKOPT]		= "cgroup_getsockopt",
106 	[BPF_CGROUP_SETSOCKOPT]		= "cgroup_setsockopt",
107 	[BPF_SK_SKB_STREAM_PARSER]	= "sk_skb_stream_parser",
108 	[BPF_SK_SKB_STREAM_VERDICT]	= "sk_skb_stream_verdict",
109 	[BPF_SK_SKB_VERDICT]		= "sk_skb_verdict",
110 	[BPF_SK_MSG_VERDICT]		= "sk_msg_verdict",
111 	[BPF_LIRC_MODE2]		= "lirc_mode2",
112 	[BPF_FLOW_DISSECTOR]		= "flow_dissector",
113 	[BPF_TRACE_RAW_TP]		= "trace_raw_tp",
114 	[BPF_TRACE_FENTRY]		= "trace_fentry",
115 	[BPF_TRACE_FEXIT]		= "trace_fexit",
116 	[BPF_MODIFY_RETURN]		= "modify_return",
117 	[BPF_LSM_MAC]			= "lsm_mac",
118 	[BPF_LSM_CGROUP]		= "lsm_cgroup",
119 	[BPF_SK_LOOKUP]			= "sk_lookup",
120 	[BPF_TRACE_ITER]		= "trace_iter",
121 	[BPF_XDP_DEVMAP]		= "xdp_devmap",
122 	[BPF_XDP_CPUMAP]		= "xdp_cpumap",
123 	[BPF_XDP]			= "xdp",
124 	[BPF_SK_REUSEPORT_SELECT]	= "sk_reuseport_select",
125 	[BPF_SK_REUSEPORT_SELECT_OR_MIGRATE]	= "sk_reuseport_select_or_migrate",
126 	[BPF_PERF_EVENT]		= "perf_event",
127 	[BPF_TRACE_KPROBE_MULTI]	= "trace_kprobe_multi",
128 	[BPF_STRUCT_OPS]		= "struct_ops",
129 	[BPF_NETFILTER]			= "netfilter",
130 	[BPF_TCX_INGRESS]		= "tcx_ingress",
131 	[BPF_TCX_EGRESS]		= "tcx_egress",
132 	[BPF_TRACE_UPROBE_MULTI]	= "trace_uprobe_multi",
133 	[BPF_NETKIT_PRIMARY]		= "netkit_primary",
134 	[BPF_NETKIT_PEER]		= "netkit_peer",
135 };
136 
137 static const char * const link_type_name[] = {
138 	[BPF_LINK_TYPE_UNSPEC]			= "unspec",
139 	[BPF_LINK_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
140 	[BPF_LINK_TYPE_TRACING]			= "tracing",
141 	[BPF_LINK_TYPE_CGROUP]			= "cgroup",
142 	[BPF_LINK_TYPE_ITER]			= "iter",
143 	[BPF_LINK_TYPE_NETNS]			= "netns",
144 	[BPF_LINK_TYPE_XDP]			= "xdp",
145 	[BPF_LINK_TYPE_PERF_EVENT]		= "perf_event",
146 	[BPF_LINK_TYPE_KPROBE_MULTI]		= "kprobe_multi",
147 	[BPF_LINK_TYPE_STRUCT_OPS]		= "struct_ops",
148 	[BPF_LINK_TYPE_NETFILTER]		= "netfilter",
149 	[BPF_LINK_TYPE_TCX]			= "tcx",
150 	[BPF_LINK_TYPE_UPROBE_MULTI]		= "uprobe_multi",
151 	[BPF_LINK_TYPE_NETKIT]			= "netkit",
152 };
153 
154 static const char * const map_type_name[] = {
155 	[BPF_MAP_TYPE_UNSPEC]			= "unspec",
156 	[BPF_MAP_TYPE_HASH]			= "hash",
157 	[BPF_MAP_TYPE_ARRAY]			= "array",
158 	[BPF_MAP_TYPE_PROG_ARRAY]		= "prog_array",
159 	[BPF_MAP_TYPE_PERF_EVENT_ARRAY]		= "perf_event_array",
160 	[BPF_MAP_TYPE_PERCPU_HASH]		= "percpu_hash",
161 	[BPF_MAP_TYPE_PERCPU_ARRAY]		= "percpu_array",
162 	[BPF_MAP_TYPE_STACK_TRACE]		= "stack_trace",
163 	[BPF_MAP_TYPE_CGROUP_ARRAY]		= "cgroup_array",
164 	[BPF_MAP_TYPE_LRU_HASH]			= "lru_hash",
165 	[BPF_MAP_TYPE_LRU_PERCPU_HASH]		= "lru_percpu_hash",
166 	[BPF_MAP_TYPE_LPM_TRIE]			= "lpm_trie",
167 	[BPF_MAP_TYPE_ARRAY_OF_MAPS]		= "array_of_maps",
168 	[BPF_MAP_TYPE_HASH_OF_MAPS]		= "hash_of_maps",
169 	[BPF_MAP_TYPE_DEVMAP]			= "devmap",
170 	[BPF_MAP_TYPE_DEVMAP_HASH]		= "devmap_hash",
171 	[BPF_MAP_TYPE_SOCKMAP]			= "sockmap",
172 	[BPF_MAP_TYPE_CPUMAP]			= "cpumap",
173 	[BPF_MAP_TYPE_XSKMAP]			= "xskmap",
174 	[BPF_MAP_TYPE_SOCKHASH]			= "sockhash",
175 	[BPF_MAP_TYPE_CGROUP_STORAGE]		= "cgroup_storage",
176 	[BPF_MAP_TYPE_REUSEPORT_SOCKARRAY]	= "reuseport_sockarray",
177 	[BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE]	= "percpu_cgroup_storage",
178 	[BPF_MAP_TYPE_QUEUE]			= "queue",
179 	[BPF_MAP_TYPE_STACK]			= "stack",
180 	[BPF_MAP_TYPE_SK_STORAGE]		= "sk_storage",
181 	[BPF_MAP_TYPE_STRUCT_OPS]		= "struct_ops",
182 	[BPF_MAP_TYPE_RINGBUF]			= "ringbuf",
183 	[BPF_MAP_TYPE_INODE_STORAGE]		= "inode_storage",
184 	[BPF_MAP_TYPE_TASK_STORAGE]		= "task_storage",
185 	[BPF_MAP_TYPE_BLOOM_FILTER]		= "bloom_filter",
186 	[BPF_MAP_TYPE_USER_RINGBUF]             = "user_ringbuf",
187 	[BPF_MAP_TYPE_CGRP_STORAGE]		= "cgrp_storage",
188 };
189 
190 static const char * const prog_type_name[] = {
191 	[BPF_PROG_TYPE_UNSPEC]			= "unspec",
192 	[BPF_PROG_TYPE_SOCKET_FILTER]		= "socket_filter",
193 	[BPF_PROG_TYPE_KPROBE]			= "kprobe",
194 	[BPF_PROG_TYPE_SCHED_CLS]		= "sched_cls",
195 	[BPF_PROG_TYPE_SCHED_ACT]		= "sched_act",
196 	[BPF_PROG_TYPE_TRACEPOINT]		= "tracepoint",
197 	[BPF_PROG_TYPE_XDP]			= "xdp",
198 	[BPF_PROG_TYPE_PERF_EVENT]		= "perf_event",
199 	[BPF_PROG_TYPE_CGROUP_SKB]		= "cgroup_skb",
200 	[BPF_PROG_TYPE_CGROUP_SOCK]		= "cgroup_sock",
201 	[BPF_PROG_TYPE_LWT_IN]			= "lwt_in",
202 	[BPF_PROG_TYPE_LWT_OUT]			= "lwt_out",
203 	[BPF_PROG_TYPE_LWT_XMIT]		= "lwt_xmit",
204 	[BPF_PROG_TYPE_SOCK_OPS]		= "sock_ops",
205 	[BPF_PROG_TYPE_SK_SKB]			= "sk_skb",
206 	[BPF_PROG_TYPE_CGROUP_DEVICE]		= "cgroup_device",
207 	[BPF_PROG_TYPE_SK_MSG]			= "sk_msg",
208 	[BPF_PROG_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
209 	[BPF_PROG_TYPE_CGROUP_SOCK_ADDR]	= "cgroup_sock_addr",
210 	[BPF_PROG_TYPE_LWT_SEG6LOCAL]		= "lwt_seg6local",
211 	[BPF_PROG_TYPE_LIRC_MODE2]		= "lirc_mode2",
212 	[BPF_PROG_TYPE_SK_REUSEPORT]		= "sk_reuseport",
213 	[BPF_PROG_TYPE_FLOW_DISSECTOR]		= "flow_dissector",
214 	[BPF_PROG_TYPE_CGROUP_SYSCTL]		= "cgroup_sysctl",
215 	[BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE]	= "raw_tracepoint_writable",
216 	[BPF_PROG_TYPE_CGROUP_SOCKOPT]		= "cgroup_sockopt",
217 	[BPF_PROG_TYPE_TRACING]			= "tracing",
218 	[BPF_PROG_TYPE_STRUCT_OPS]		= "struct_ops",
219 	[BPF_PROG_TYPE_EXT]			= "ext",
220 	[BPF_PROG_TYPE_LSM]			= "lsm",
221 	[BPF_PROG_TYPE_SK_LOOKUP]		= "sk_lookup",
222 	[BPF_PROG_TYPE_SYSCALL]			= "syscall",
223 	[BPF_PROG_TYPE_NETFILTER]		= "netfilter",
224 };
225 
__base_pr(enum libbpf_print_level level,const char * format,va_list args)226 static int __base_pr(enum libbpf_print_level level, const char *format,
227 		     va_list args)
228 {
229 	if (level == LIBBPF_DEBUG)
230 		return 0;
231 
232 	return vfprintf(stderr, format, args);
233 }
234 
235 static libbpf_print_fn_t __libbpf_pr = __base_pr;
236 
libbpf_set_print(libbpf_print_fn_t fn)237 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
238 {
239 	libbpf_print_fn_t old_print_fn;
240 
241 	old_print_fn = __atomic_exchange_n(&__libbpf_pr, fn, __ATOMIC_RELAXED);
242 
243 	return old_print_fn;
244 }
245 
246 __printf(2, 3)
libbpf_print(enum libbpf_print_level level,const char * format,...)247 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
248 {
249 	va_list args;
250 	int old_errno;
251 	libbpf_print_fn_t print_fn;
252 
253 	print_fn = __atomic_load_n(&__libbpf_pr, __ATOMIC_RELAXED);
254 	if (!print_fn)
255 		return;
256 
257 	old_errno = errno;
258 
259 	va_start(args, format);
260 	__libbpf_pr(level, format, args);
261 	va_end(args);
262 
263 	errno = old_errno;
264 }
265 
pr_perm_msg(int err)266 static void pr_perm_msg(int err)
267 {
268 	struct rlimit limit;
269 	char buf[100];
270 
271 	if (err != -EPERM || geteuid() != 0)
272 		return;
273 
274 	err = getrlimit(RLIMIT_MEMLOCK, &limit);
275 	if (err)
276 		return;
277 
278 	if (limit.rlim_cur == RLIM_INFINITY)
279 		return;
280 
281 	if (limit.rlim_cur < 1024)
282 		snprintf(buf, sizeof(buf), "%zu bytes", (size_t)limit.rlim_cur);
283 	else if (limit.rlim_cur < 1024*1024)
284 		snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
285 	else
286 		snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
287 
288 	pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
289 		buf);
290 }
291 
292 #define STRERR_BUFSIZE  128
293 
294 /* Copied from tools/perf/util/util.h */
295 #ifndef zfree
296 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
297 #endif
298 
299 #ifndef zclose
300 # define zclose(fd) ({			\
301 	int ___err = 0;			\
302 	if ((fd) >= 0)			\
303 		___err = close((fd));	\
304 	fd = -1;			\
305 	___err; })
306 #endif
307 
ptr_to_u64(const void * ptr)308 static inline __u64 ptr_to_u64(const void *ptr)
309 {
310 	return (__u64) (unsigned long) ptr;
311 }
312 
libbpf_set_strict_mode(enum libbpf_strict_mode mode)313 int libbpf_set_strict_mode(enum libbpf_strict_mode mode)
314 {
315 	/* as of v1.0 libbpf_set_strict_mode() is a no-op */
316 	return 0;
317 }
318 
libbpf_major_version(void)319 __u32 libbpf_major_version(void)
320 {
321 	return LIBBPF_MAJOR_VERSION;
322 }
323 
libbpf_minor_version(void)324 __u32 libbpf_minor_version(void)
325 {
326 	return LIBBPF_MINOR_VERSION;
327 }
328 
libbpf_version_string(void)329 const char *libbpf_version_string(void)
330 {
331 #define __S(X) #X
332 #define _S(X) __S(X)
333 	return  "v" _S(LIBBPF_MAJOR_VERSION) "." _S(LIBBPF_MINOR_VERSION);
334 #undef _S
335 #undef __S
336 }
337 
338 enum reloc_type {
339 	RELO_LD64,
340 	RELO_CALL,
341 	RELO_DATA,
342 	RELO_EXTERN_LD64,
343 	RELO_EXTERN_CALL,
344 	RELO_SUBPROG_ADDR,
345 	RELO_CORE,
346 };
347 
348 struct reloc_desc {
349 	enum reloc_type type;
350 	int insn_idx;
351 	union {
352 		const struct bpf_core_relo *core_relo; /* used when type == RELO_CORE */
353 		struct {
354 			int map_idx;
355 			int sym_off;
356 			int ext_idx;
357 		};
358 	};
359 };
360 
361 /* stored as sec_def->cookie for all libbpf-supported SEC()s */
362 enum sec_def_flags {
363 	SEC_NONE = 0,
364 	/* expected_attach_type is optional, if kernel doesn't support that */
365 	SEC_EXP_ATTACH_OPT = 1,
366 	/* legacy, only used by libbpf_get_type_names() and
367 	 * libbpf_attach_type_by_name(), not used by libbpf itself at all.
368 	 * This used to be associated with cgroup (and few other) BPF programs
369 	 * that were attachable through BPF_PROG_ATTACH command. Pretty
370 	 * meaningless nowadays, though.
371 	 */
372 	SEC_ATTACHABLE = 2,
373 	SEC_ATTACHABLE_OPT = SEC_ATTACHABLE | SEC_EXP_ATTACH_OPT,
374 	/* attachment target is specified through BTF ID in either kernel or
375 	 * other BPF program's BTF object
376 	 */
377 	SEC_ATTACH_BTF = 4,
378 	/* BPF program type allows sleeping/blocking in kernel */
379 	SEC_SLEEPABLE = 8,
380 	/* BPF program support non-linear XDP buffer */
381 	SEC_XDP_FRAGS = 16,
382 	/* Setup proper attach type for usdt probes. */
383 	SEC_USDT = 32,
384 };
385 
386 struct bpf_sec_def {
387 	char *sec;
388 	enum bpf_prog_type prog_type;
389 	enum bpf_attach_type expected_attach_type;
390 	long cookie;
391 	int handler_id;
392 
393 	libbpf_prog_setup_fn_t prog_setup_fn;
394 	libbpf_prog_prepare_load_fn_t prog_prepare_load_fn;
395 	libbpf_prog_attach_fn_t prog_attach_fn;
396 };
397 
398 /*
399  * bpf_prog should be a better name but it has been used in
400  * linux/filter.h.
401  */
402 struct bpf_program {
403 	char *name;
404 	char *sec_name;
405 	size_t sec_idx;
406 	const struct bpf_sec_def *sec_def;
407 	/* this program's instruction offset (in number of instructions)
408 	 * within its containing ELF section
409 	 */
410 	size_t sec_insn_off;
411 	/* number of original instructions in ELF section belonging to this
412 	 * program, not taking into account subprogram instructions possible
413 	 * appended later during relocation
414 	 */
415 	size_t sec_insn_cnt;
416 	/* Offset (in number of instructions) of the start of instruction
417 	 * belonging to this BPF program  within its containing main BPF
418 	 * program. For the entry-point (main) BPF program, this is always
419 	 * zero. For a sub-program, this gets reset before each of main BPF
420 	 * programs are processed and relocated and is used to determined
421 	 * whether sub-program was already appended to the main program, and
422 	 * if yes, at which instruction offset.
423 	 */
424 	size_t sub_insn_off;
425 
426 	/* instructions that belong to BPF program; insns[0] is located at
427 	 * sec_insn_off instruction within its ELF section in ELF file, so
428 	 * when mapping ELF file instruction index to the local instruction,
429 	 * one needs to subtract sec_insn_off; and vice versa.
430 	 */
431 	struct bpf_insn *insns;
432 	/* actual number of instruction in this BPF program's image; for
433 	 * entry-point BPF programs this includes the size of main program
434 	 * itself plus all the used sub-programs, appended at the end
435 	 */
436 	size_t insns_cnt;
437 
438 	struct reloc_desc *reloc_desc;
439 	int nr_reloc;
440 
441 	/* BPF verifier log settings */
442 	char *log_buf;
443 	size_t log_size;
444 	__u32 log_level;
445 
446 	struct bpf_object *obj;
447 
448 	int fd;
449 	bool autoload;
450 	bool autoattach;
451 	bool sym_global;
452 	bool mark_btf_static;
453 	enum bpf_prog_type type;
454 	enum bpf_attach_type expected_attach_type;
455 	int exception_cb_idx;
456 
457 	int prog_ifindex;
458 	__u32 attach_btf_obj_fd;
459 	__u32 attach_btf_id;
460 	__u32 attach_prog_fd;
461 
462 	void *func_info;
463 	__u32 func_info_rec_size;
464 	__u32 func_info_cnt;
465 
466 	void *line_info;
467 	__u32 line_info_rec_size;
468 	__u32 line_info_cnt;
469 	__u32 prog_flags;
470 };
471 
472 struct bpf_struct_ops {
473 	const char *tname;
474 	const struct btf_type *type;
475 	struct bpf_program **progs;
476 	__u32 *kern_func_off;
477 	/* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
478 	void *data;
479 	/* e.g. struct bpf_struct_ops_tcp_congestion_ops in
480 	 *      btf_vmlinux's format.
481 	 * struct bpf_struct_ops_tcp_congestion_ops {
482 	 *	[... some other kernel fields ...]
483 	 *	struct tcp_congestion_ops data;
484 	 * }
485 	 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
486 	 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
487 	 * from "data".
488 	 */
489 	void *kern_vdata;
490 	__u32 type_id;
491 };
492 
493 #define DATA_SEC ".data"
494 #define BSS_SEC ".bss"
495 #define RODATA_SEC ".rodata"
496 #define KCONFIG_SEC ".kconfig"
497 #define KSYMS_SEC ".ksyms"
498 #define STRUCT_OPS_SEC ".struct_ops"
499 #define STRUCT_OPS_LINK_SEC ".struct_ops.link"
500 
501 enum libbpf_map_type {
502 	LIBBPF_MAP_UNSPEC,
503 	LIBBPF_MAP_DATA,
504 	LIBBPF_MAP_BSS,
505 	LIBBPF_MAP_RODATA,
506 	LIBBPF_MAP_KCONFIG,
507 };
508 
509 struct bpf_map_def {
510 	unsigned int type;
511 	unsigned int key_size;
512 	unsigned int value_size;
513 	unsigned int max_entries;
514 	unsigned int map_flags;
515 };
516 
517 struct bpf_map {
518 	struct bpf_object *obj;
519 	char *name;
520 	/* real_name is defined for special internal maps (.rodata*,
521 	 * .data*, .bss, .kconfig) and preserves their original ELF section
522 	 * name. This is important to be able to find corresponding BTF
523 	 * DATASEC information.
524 	 */
525 	char *real_name;
526 	int fd;
527 	int sec_idx;
528 	size_t sec_offset;
529 	int map_ifindex;
530 	int inner_map_fd;
531 	struct bpf_map_def def;
532 	__u32 numa_node;
533 	__u32 btf_var_idx;
534 	__u32 btf_key_type_id;
535 	__u32 btf_value_type_id;
536 	__u32 btf_vmlinux_value_type_id;
537 	enum libbpf_map_type libbpf_type;
538 	void *mmaped;
539 	struct bpf_struct_ops *st_ops;
540 	struct bpf_map *inner_map;
541 	void **init_slots;
542 	int init_slots_sz;
543 	char *pin_path;
544 	bool pinned;
545 	bool reused;
546 	bool autocreate;
547 	__u64 map_extra;
548 };
549 
550 enum extern_type {
551 	EXT_UNKNOWN,
552 	EXT_KCFG,
553 	EXT_KSYM,
554 };
555 
556 enum kcfg_type {
557 	KCFG_UNKNOWN,
558 	KCFG_CHAR,
559 	KCFG_BOOL,
560 	KCFG_INT,
561 	KCFG_TRISTATE,
562 	KCFG_CHAR_ARR,
563 };
564 
565 struct extern_desc {
566 	enum extern_type type;
567 	int sym_idx;
568 	int btf_id;
569 	int sec_btf_id;
570 	const char *name;
571 	char *essent_name;
572 	bool is_set;
573 	bool is_weak;
574 	union {
575 		struct {
576 			enum kcfg_type type;
577 			int sz;
578 			int align;
579 			int data_off;
580 			bool is_signed;
581 		} kcfg;
582 		struct {
583 			unsigned long long addr;
584 
585 			/* target btf_id of the corresponding kernel var. */
586 			int kernel_btf_obj_fd;
587 			int kernel_btf_id;
588 
589 			/* local btf_id of the ksym extern's type. */
590 			__u32 type_id;
591 			/* BTF fd index to be patched in for insn->off, this is
592 			 * 0 for vmlinux BTF, index in obj->fd_array for module
593 			 * BTF
594 			 */
595 			__s16 btf_fd_idx;
596 		} ksym;
597 	};
598 };
599 
600 struct module_btf {
601 	struct btf *btf;
602 	char *name;
603 	__u32 id;
604 	int fd;
605 	int fd_array_idx;
606 };
607 
608 enum sec_type {
609 	SEC_UNUSED = 0,
610 	SEC_RELO,
611 	SEC_BSS,
612 	SEC_DATA,
613 	SEC_RODATA,
614 };
615 
616 struct elf_sec_desc {
617 	enum sec_type sec_type;
618 #if defined HAVE_LIBELF
619 	Elf64_Shdr *shdr;
620 #elif defined HAVE_ELFIO
621 	psection_t psection;
622 	Elf_Data realdata;
623 #endif
624 	Elf_Data *data;
625 };
626 
627 struct elf_state {
628 	int fd;
629 	const void *obj_buf;
630 	size_t obj_buf_sz;
631 #if defined HAVE_LIBELF
632 	Elf *elf;
633 #elif defined HAVE_ELFIO
634 	pelfio_t elf;
635 	Elf64_Ehdr eheader;
636 	pstring_t shstring;
637 	pstring_t strstring;
638 	Elf_Data realsymbols;
639 	Elf_Data realst_ops_data;
640 	Elf_Data realst_ops_link_data;
641 #endif
642 	Elf64_Ehdr *ehdr;
643 	Elf_Data *symbols;
644 	Elf_Data *st_ops_data;
645 	Elf_Data *st_ops_link_data;
646 	size_t shstrndx; /* section index for section name strings */
647 	size_t strtabidx;
648 	struct elf_sec_desc *secs;
649 	size_t sec_cnt;
650 	int btf_maps_shndx;
651 	__u32 btf_maps_sec_btf_id;
652 	int text_shndx;
653 	int symbols_shndx;
654 	int st_ops_shndx;
655 	int st_ops_link_shndx;
656 };
657 
658 struct usdt_manager;
659 
660 struct bpf_object {
661 	char name[BPF_OBJ_NAME_LEN];
662 	char license[64];
663 	__u32 kern_version;
664 
665 	struct bpf_program *programs;
666 	size_t nr_programs;
667 	struct bpf_map *maps;
668 	size_t nr_maps;
669 	size_t maps_cap;
670 
671 	char *kconfig;
672 	struct extern_desc *externs;
673 	int nr_extern;
674 	int kconfig_map_idx;
675 
676 	bool loaded;
677 	bool has_subcalls;
678 	bool has_rodata;
679 
680 	struct bpf_gen *gen_loader;
681 
682 	/* Information when doing ELF related work. Only valid if efile.elf is not NULL */
683 	struct elf_state efile;
684 
685 	struct btf *btf;
686 	struct btf_ext *btf_ext;
687 
688 	/* Parse and load BTF vmlinux if any of the programs in the object need
689 	 * it at load time.
690 	 */
691 	struct btf *btf_vmlinux;
692 	/* Path to the custom BTF to be used for BPF CO-RE relocations as an
693 	 * override for vmlinux BTF.
694 	 */
695 	char *btf_custom_path;
696 	/* vmlinux BTF override for CO-RE relocations */
697 	struct btf *btf_vmlinux_override;
698 	/* Lazily initialized kernel module BTFs */
699 	struct module_btf *btf_modules;
700 	bool btf_modules_loaded;
701 	size_t btf_module_cnt;
702 	size_t btf_module_cap;
703 
704 	/* optional log settings passed to BPF_BTF_LOAD and BPF_PROG_LOAD commands */
705 	char *log_buf;
706 	size_t log_size;
707 	__u32 log_level;
708 
709 	int *fd_array;
710 	size_t fd_array_cap;
711 	size_t fd_array_cnt;
712 
713 	struct usdt_manager *usdt_man;
714 
715 	char path[];
716 };
717 
718 static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
719 static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
720 #ifdef HAVE_LIBELF
721 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
722 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
723 #endif
724 #if defined HAVE_LIBELF
725 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn);
726 #elif defined HAVE_ELFIO
727 static Elf64_Shdr *elf_sec_hdr_by_idx(const struct bpf_object *obj, size_t idx, Elf64_Shdr *sheader);
728 #endif
729 #if defined HAVE_LIBELF
730 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
731 #elif defined HAVE_ELFIO
732 static const char *elf_sec_name_by_idx(const struct bpf_object *obj, size_t idx);
733 #endif
734 #if defined HAVE_LIBELF
735 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
736 #elif defined HAVE_ELFIO
737 static Elf_Data *elf_sec_data_by_name(const struct bpf_object *obj, const char *name, Elf_Data *data);
738 static Elf_Data *elf_sec_data_by_idx(const struct bpf_object *obj, size_t idx, Elf_Data *data);
739 #endif
740 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx);
741 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx);
742 
bpf_program__unload(struct bpf_program * prog)743 void bpf_program__unload(struct bpf_program *prog)
744 {
745 	if (!prog)
746 		return;
747 
748 	zclose(prog->fd);
749 
750 	zfree(&prog->func_info);
751 	zfree(&prog->line_info);
752 }
753 
bpf_program__exit(struct bpf_program * prog)754 static void bpf_program__exit(struct bpf_program *prog)
755 {
756 	if (!prog)
757 		return;
758 
759 	bpf_program__unload(prog);
760 	zfree(&prog->name);
761 	zfree(&prog->sec_name);
762 	zfree(&prog->insns);
763 	zfree(&prog->reloc_desc);
764 
765 	prog->nr_reloc = 0;
766 	prog->insns_cnt = 0;
767 	prog->sec_idx = -1;
768 }
769 
insn_is_subprog_call(const struct bpf_insn * insn)770 static bool insn_is_subprog_call(const struct bpf_insn *insn)
771 {
772 	return BPF_CLASS(insn->code) == BPF_JMP &&
773 	       BPF_OP(insn->code) == BPF_CALL &&
774 	       BPF_SRC(insn->code) == BPF_K &&
775 	       insn->src_reg == BPF_PSEUDO_CALL &&
776 	       insn->dst_reg == 0 &&
777 	       insn->off == 0;
778 }
779 
is_call_insn(const struct bpf_insn * insn)780 static bool is_call_insn(const struct bpf_insn *insn)
781 {
782 	return insn->code == (BPF_JMP | BPF_CALL);
783 }
784 
insn_is_pseudo_func(struct bpf_insn * insn)785 static bool insn_is_pseudo_func(struct bpf_insn *insn)
786 {
787 	return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
788 }
789 
790 static int
bpf_object__init_prog(struct bpf_object * obj,struct bpf_program * prog,const char * name,size_t sec_idx,const char * sec_name,size_t sec_off,void * insn_data,size_t insn_data_sz)791 bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
792 		      const char *name, size_t sec_idx, const char *sec_name,
793 		      size_t sec_off, void *insn_data, size_t insn_data_sz)
794 {
795 	if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
796 		pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
797 			sec_name, name, sec_off, insn_data_sz);
798 		return -EINVAL;
799 	}
800 
801 	memset(prog, 0, sizeof(*prog));
802 	prog->obj = obj;
803 
804 	prog->sec_idx = sec_idx;
805 	prog->sec_insn_off = sec_off / BPF_INSN_SZ;
806 	prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
807 	/* insns_cnt can later be increased by appending used subprograms */
808 	prog->insns_cnt = prog->sec_insn_cnt;
809 
810 	prog->type = BPF_PROG_TYPE_UNSPEC;
811 	prog->fd = -1;
812 	prog->exception_cb_idx = -1;
813 
814 	/* libbpf's convention for SEC("?abc...") is that it's just like
815 	 * SEC("abc...") but the corresponding bpf_program starts out with
816 	 * autoload set to false.
817 	 */
818 	if (sec_name[0] == '?') {
819 		prog->autoload = false;
820 		/* from now on forget there was ? in section name */
821 		sec_name++;
822 	} else {
823 		prog->autoload = true;
824 	}
825 
826 	prog->autoattach = true;
827 
828 	/* inherit object's log_level */
829 	prog->log_level = obj->log_level;
830 
831 	prog->sec_name = strdup(sec_name);
832 	if (!prog->sec_name)
833 		goto errout;
834 
835 	prog->name = strdup(name);
836 	if (!prog->name)
837 		goto errout;
838 
839 	prog->insns = malloc(insn_data_sz);
840 	if (!prog->insns)
841 		goto errout;
842 	memcpy(prog->insns, insn_data, insn_data_sz);
843 
844 	return 0;
845 errout:
846 	pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
847 	bpf_program__exit(prog);
848 	return -ENOMEM;
849 }
850 
851 static int
bpf_object__add_programs(struct bpf_object * obj,Elf_Data * sec_data,const char * sec_name,int sec_idx)852 bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
853 			 const char *sec_name, int sec_idx)
854 {
855 	Elf_Data *symbols = obj->efile.symbols;
856 	struct bpf_program *prog, *progs;
857 	void *data = sec_data->d_buf;
858 	size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
859 	int nr_progs, err, i;
860 	const char *name;
861 	Elf64_Sym *sym;
862 
863 	progs = obj->programs;
864 	nr_progs = obj->nr_programs;
865 	nr_syms = symbols->d_size / sizeof(Elf64_Sym);
866 
867 	for (i = 0; i < nr_syms; i++) {
868 		sym = elf_sym_by_idx(obj, i);
869 
870 		if (sym->st_shndx != sec_idx)
871 			continue;
872 		if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC)
873 			continue;
874 
875 		prog_sz = sym->st_size;
876 		sec_off = sym->st_value;
877 
878 		name = elf_sym_str(obj, sym->st_name);
879 		if (!name) {
880 			pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
881 				sec_name, sec_off);
882 			return -LIBBPF_ERRNO__FORMAT;
883 		}
884 
885 		if (sec_off + prog_sz > sec_sz || sec_off + prog_sz < sec_off) {
886 			pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
887 				sec_name, sec_off);
888 			return -LIBBPF_ERRNO__FORMAT;
889 		}
890 
891 		if (sec_idx != obj->efile.text_shndx && ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
892 			pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
893 			return -ENOTSUP;
894 		}
895 
896 		pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
897 			 sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
898 
899 		progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
900 		if (!progs) {
901 			/*
902 			 * In this case the original obj->programs
903 			 * is still valid, so don't need special treat for
904 			 * bpf_close_object().
905 			 */
906 			pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
907 				sec_name, name);
908 			return -ENOMEM;
909 		}
910 		obj->programs = progs;
911 
912 		prog = &progs[nr_progs];
913 
914 		err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
915 					    sec_off, data + sec_off, prog_sz);
916 		if (err)
917 			return err;
918 
919 		if (ELF64_ST_BIND(sym->st_info) != STB_LOCAL)
920 			prog->sym_global = true;
921 
922 		/* if function is a global/weak symbol, but has restricted
923 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
924 		 * as static to enable more permissive BPF verification mode
925 		 * with more outside context available to BPF verifier
926 		 */
927 		if (prog->sym_global && (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
928 		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL))
929 			prog->mark_btf_static = true;
930 
931 		nr_progs++;
932 		obj->nr_programs = nr_progs;
933 	}
934 
935 	return 0;
936 }
937 
938 static const struct btf_member *
find_member_by_offset(const struct btf_type * t,__u32 bit_offset)939 find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
940 {
941 	struct btf_member *m;
942 	int i;
943 
944 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
945 		if (btf_member_bit_offset(t, i) == bit_offset)
946 			return m;
947 	}
948 
949 	return NULL;
950 }
951 
952 static const struct btf_member *
find_member_by_name(const struct btf * btf,const struct btf_type * t,const char * name)953 find_member_by_name(const struct btf *btf, const struct btf_type *t,
954 		    const char *name)
955 {
956 	struct btf_member *m;
957 	int i;
958 
959 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
960 		if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
961 			return m;
962 	}
963 
964 	return NULL;
965 }
966 
967 #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
968 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
969 				   const char *name, __u32 kind);
970 
971 static int
find_struct_ops_kern_types(const struct btf * btf,const char * tname,const struct btf_type ** type,__u32 * type_id,const struct btf_type ** vtype,__u32 * vtype_id,const struct btf_member ** data_member)972 find_struct_ops_kern_types(const struct btf *btf, const char *tname,
973 			   const struct btf_type **type, __u32 *type_id,
974 			   const struct btf_type **vtype, __u32 *vtype_id,
975 			   const struct btf_member **data_member)
976 {
977 	const struct btf_type *kern_type, *kern_vtype;
978 	const struct btf_member *kern_data_member;
979 	__s32 kern_vtype_id, kern_type_id;
980 	__u32 i;
981 
982 	kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
983 	if (kern_type_id < 0) {
984 		pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n",
985 			tname);
986 		return kern_type_id;
987 	}
988 	kern_type = btf__type_by_id(btf, kern_type_id);
989 
990 	/* Find the corresponding "map_value" type that will be used
991 	 * in map_update(BPF_MAP_TYPE_STRUCT_OPS).  For example,
992 	 * find "struct bpf_struct_ops_tcp_congestion_ops" from the
993 	 * btf_vmlinux.
994 	 */
995 	kern_vtype_id = find_btf_by_prefix_kind(btf, STRUCT_OPS_VALUE_PREFIX,
996 						tname, BTF_KIND_STRUCT);
997 	if (kern_vtype_id < 0) {
998 		pr_warn("struct_ops init_kern: struct %s%s is not found in kernel BTF\n",
999 			STRUCT_OPS_VALUE_PREFIX, tname);
1000 		return kern_vtype_id;
1001 	}
1002 	kern_vtype = btf__type_by_id(btf, kern_vtype_id);
1003 
1004 	/* Find "struct tcp_congestion_ops" from
1005 	 * struct bpf_struct_ops_tcp_congestion_ops {
1006 	 *	[ ... ]
1007 	 *	struct tcp_congestion_ops data;
1008 	 * }
1009 	 */
1010 	kern_data_member = btf_members(kern_vtype);
1011 	for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
1012 		if (kern_data_member->type == kern_type_id)
1013 			break;
1014 	}
1015 	if (i == btf_vlen(kern_vtype)) {
1016 		pr_warn("struct_ops init_kern: struct %s data is not found in struct %s%s\n",
1017 			tname, STRUCT_OPS_VALUE_PREFIX, tname);
1018 		return -EINVAL;
1019 	}
1020 
1021 	*type = kern_type;
1022 	*type_id = kern_type_id;
1023 	*vtype = kern_vtype;
1024 	*vtype_id = kern_vtype_id;
1025 	*data_member = kern_data_member;
1026 
1027 	return 0;
1028 }
1029 
bpf_map__is_struct_ops(const struct bpf_map * map)1030 static bool bpf_map__is_struct_ops(const struct bpf_map *map)
1031 {
1032 	return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
1033 }
1034 
1035 /* Init the map's fields that depend on kern_btf */
bpf_map__init_kern_struct_ops(struct bpf_map * map,const struct btf * btf,const struct btf * kern_btf)1036 static int bpf_map__init_kern_struct_ops(struct bpf_map *map,
1037 					 const struct btf *btf,
1038 					 const struct btf *kern_btf)
1039 {
1040 	const struct btf_member *member, *kern_member, *kern_data_member;
1041 	const struct btf_type *type, *kern_type, *kern_vtype;
1042 	__u32 i, kern_type_id, kern_vtype_id, kern_data_off;
1043 	struct bpf_struct_ops *st_ops;
1044 	void *data, *kern_data;
1045 	const char *tname;
1046 	int err;
1047 
1048 	st_ops = map->st_ops;
1049 	type = st_ops->type;
1050 	tname = st_ops->tname;
1051 	err = find_struct_ops_kern_types(kern_btf, tname,
1052 					 &kern_type, &kern_type_id,
1053 					 &kern_vtype, &kern_vtype_id,
1054 					 &kern_data_member);
1055 	if (err)
1056 		return err;
1057 
1058 	pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
1059 		 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
1060 
1061 	map->def.value_size = kern_vtype->size;
1062 	map->btf_vmlinux_value_type_id = kern_vtype_id;
1063 
1064 	st_ops->kern_vdata = calloc(1, kern_vtype->size);
1065 	if (!st_ops->kern_vdata)
1066 		return -ENOMEM;
1067 
1068 	data = st_ops->data;
1069 	kern_data_off = kern_data_member->offset / 8;
1070 	kern_data = st_ops->kern_vdata + kern_data_off;
1071 
1072 	member = btf_members(type);
1073 	for (i = 0; i < btf_vlen(type); i++, member++) {
1074 		const struct btf_type *mtype, *kern_mtype;
1075 		__u32 mtype_id, kern_mtype_id;
1076 		void *mdata, *kern_mdata;
1077 		__s64 msize, kern_msize;
1078 		__u32 moff, kern_moff;
1079 		__u32 kern_member_idx;
1080 		const char *mname;
1081 
1082 		mname = btf__name_by_offset(btf, member->name_off);
1083 		kern_member = find_member_by_name(kern_btf, kern_type, mname);
1084 		if (!kern_member) {
1085 			pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
1086 				map->name, mname);
1087 			return -ENOTSUP;
1088 		}
1089 
1090 		kern_member_idx = kern_member - btf_members(kern_type);
1091 		if (btf_member_bitfield_size(type, i) ||
1092 		    btf_member_bitfield_size(kern_type, kern_member_idx)) {
1093 			pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
1094 				map->name, mname);
1095 			return -ENOTSUP;
1096 		}
1097 
1098 		moff = member->offset / 8;
1099 		kern_moff = kern_member->offset / 8;
1100 
1101 		mdata = data + moff;
1102 		kern_mdata = kern_data + kern_moff;
1103 
1104 		mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
1105 		kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
1106 						    &kern_mtype_id);
1107 		if (BTF_INFO_KIND(mtype->info) !=
1108 		    BTF_INFO_KIND(kern_mtype->info)) {
1109 			pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
1110 				map->name, mname, BTF_INFO_KIND(mtype->info),
1111 				BTF_INFO_KIND(kern_mtype->info));
1112 			return -ENOTSUP;
1113 		}
1114 
1115 		if (btf_is_ptr(mtype)) {
1116 			struct bpf_program *prog;
1117 
1118 			prog = st_ops->progs[i];
1119 			if (!prog)
1120 				continue;
1121 
1122 			kern_mtype = skip_mods_and_typedefs(kern_btf,
1123 							    kern_mtype->type,
1124 							    &kern_mtype_id);
1125 
1126 			/* mtype->type must be a func_proto which was
1127 			 * guaranteed in bpf_object__collect_st_ops_relos(),
1128 			 * so only check kern_mtype for func_proto here.
1129 			 */
1130 			if (!btf_is_func_proto(kern_mtype)) {
1131 				pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
1132 					map->name, mname);
1133 				return -ENOTSUP;
1134 			}
1135 
1136 			prog->attach_btf_id = kern_type_id;
1137 			prog->expected_attach_type = kern_member_idx;
1138 
1139 			st_ops->kern_func_off[i] = kern_data_off + kern_moff;
1140 
1141 			pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
1142 				 map->name, mname, prog->name, moff,
1143 				 kern_moff);
1144 
1145 			continue;
1146 		}
1147 
1148 		msize = btf__resolve_size(btf, mtype_id);
1149 		kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
1150 		if (msize < 0 || kern_msize < 0 || msize != kern_msize) {
1151 			pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
1152 				map->name, mname, (ssize_t)msize,
1153 				(ssize_t)kern_msize);
1154 			return -ENOTSUP;
1155 		}
1156 
1157 		pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
1158 			 map->name, mname, (unsigned int)msize,
1159 			 moff, kern_moff);
1160 		memcpy(kern_mdata, mdata, msize);
1161 	}
1162 
1163 	return 0;
1164 }
1165 
bpf_object__init_kern_struct_ops_maps(struct bpf_object * obj)1166 static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
1167 {
1168 	struct bpf_map *map;
1169 	size_t i;
1170 	int err;
1171 
1172 	for (i = 0; i < obj->nr_maps; i++) {
1173 		map = &obj->maps[i];
1174 
1175 		if (!bpf_map__is_struct_ops(map))
1176 			continue;
1177 
1178 		err = bpf_map__init_kern_struct_ops(map, obj->btf,
1179 						    obj->btf_vmlinux);
1180 		if (err)
1181 			return err;
1182 	}
1183 
1184 	return 0;
1185 }
1186 
init_struct_ops_maps(struct bpf_object * obj,const char * sec_name,int shndx,Elf_Data * data,__u32 map_flags)1187 static int init_struct_ops_maps(struct bpf_object *obj, const char *sec_name,
1188 				int shndx, Elf_Data *data, __u32 map_flags)
1189 {
1190 	const struct btf_type *type, *datasec;
1191 	const struct btf_var_secinfo *vsi;
1192 	struct bpf_struct_ops *st_ops;
1193 	const char *tname, *var_name;
1194 	__s32 type_id, datasec_id;
1195 	const struct btf *btf;
1196 	struct bpf_map *map;
1197 	__u32 i;
1198 
1199 	if (shndx == -1)
1200 		return 0;
1201 
1202 	btf = obj->btf;
1203 	datasec_id = btf__find_by_name_kind(btf, sec_name,
1204 					    BTF_KIND_DATASEC);
1205 	if (datasec_id < 0) {
1206 		pr_warn("struct_ops init: DATASEC %s not found\n",
1207 			sec_name);
1208 		return -EINVAL;
1209 	}
1210 
1211 	datasec = btf__type_by_id(btf, datasec_id);
1212 	vsi = btf_var_secinfos(datasec);
1213 	for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
1214 		type = btf__type_by_id(obj->btf, vsi->type);
1215 		var_name = btf__name_by_offset(obj->btf, type->name_off);
1216 
1217 		type_id = btf__resolve_type(obj->btf, vsi->type);
1218 		if (type_id < 0) {
1219 			pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
1220 				vsi->type, sec_name);
1221 			return -EINVAL;
1222 		}
1223 
1224 		type = btf__type_by_id(obj->btf, type_id);
1225 		tname = btf__name_by_offset(obj->btf, type->name_off);
1226 		if (!tname[0]) {
1227 			pr_warn("struct_ops init: anonymous type is not supported\n");
1228 			return -ENOTSUP;
1229 		}
1230 		if (!btf_is_struct(type)) {
1231 			pr_warn("struct_ops init: %s is not a struct\n", tname);
1232 			return -EINVAL;
1233 		}
1234 
1235 		map = bpf_object__add_map(obj);
1236 		if (IS_ERR(map))
1237 			return PTR_ERR(map);
1238 
1239 		map->sec_idx = shndx;
1240 		map->sec_offset = vsi->offset;
1241 		map->name = strdup(var_name);
1242 		if (!map->name)
1243 			return -ENOMEM;
1244 
1245 		map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
1246 		map->def.key_size = sizeof(int);
1247 		map->def.value_size = type->size;
1248 		map->def.max_entries = 1;
1249 		map->def.map_flags = map_flags;
1250 
1251 		map->st_ops = calloc(1, sizeof(*map->st_ops));
1252 		if (!map->st_ops)
1253 			return -ENOMEM;
1254 		st_ops = map->st_ops;
1255 		st_ops->data = malloc(type->size);
1256 		st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1257 		st_ops->kern_func_off = malloc(btf_vlen(type) *
1258 					       sizeof(*st_ops->kern_func_off));
1259 		if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1260 			return -ENOMEM;
1261 
1262 		if (vsi->offset + type->size > data->d_size) {
1263 			pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1264 				var_name, sec_name);
1265 			return -EINVAL;
1266 		}
1267 
1268 		memcpy(st_ops->data,
1269 		       data->d_buf + vsi->offset,
1270 		       type->size);
1271 		st_ops->tname = tname;
1272 		st_ops->type = type;
1273 		st_ops->type_id = type_id;
1274 
1275 		pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
1276 			 tname, type_id, var_name, vsi->offset);
1277 	}
1278 
1279 	return 0;
1280 }
1281 
bpf_object_init_struct_ops(struct bpf_object * obj)1282 static int bpf_object_init_struct_ops(struct bpf_object *obj)
1283 {
1284 	int err;
1285 
1286 	err = init_struct_ops_maps(obj, STRUCT_OPS_SEC, obj->efile.st_ops_shndx,
1287 				   obj->efile.st_ops_data, 0);
1288 	err = err ?: init_struct_ops_maps(obj, STRUCT_OPS_LINK_SEC,
1289 					  obj->efile.st_ops_link_shndx,
1290 					  obj->efile.st_ops_link_data,
1291 					  BPF_F_LINK);
1292 	return err;
1293 }
1294 
bpf_object__new(const char * path,const void * obj_buf,size_t obj_buf_sz,const char * obj_name)1295 static struct bpf_object *bpf_object__new(const char *path,
1296 					  const void *obj_buf,
1297 					  size_t obj_buf_sz,
1298 					  const char *obj_name)
1299 {
1300 	struct bpf_object *obj;
1301 	char *end;
1302 
1303 	obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1304 	if (!obj) {
1305 		pr_warn("alloc memory failed for %s\n", path);
1306 		return ERR_PTR(-ENOMEM);
1307 	}
1308 
1309 	strcpy(obj->path, path);
1310 	if (obj_name) {
1311 		libbpf_strlcpy(obj->name, obj_name, sizeof(obj->name));
1312 	} else {
1313 		/* Using basename() GNU version which doesn't modify arg. */
1314 		libbpf_strlcpy(obj->name, basename((void *)path), sizeof(obj->name));
1315 		end = strchr(obj->name, '.');
1316 		if (end)
1317 			*end = 0;
1318 	}
1319 
1320 	obj->efile.fd = -1;
1321 	/*
1322 	 * Caller of this function should also call
1323 	 * bpf_object__elf_finish() after data collection to return
1324 	 * obj_buf to user. If not, we should duplicate the buffer to
1325 	 * avoid user freeing them before elf finish.
1326 	 */
1327 	obj->efile.obj_buf = obj_buf;
1328 	obj->efile.obj_buf_sz = obj_buf_sz;
1329 	obj->efile.btf_maps_shndx = -1;
1330 	obj->efile.st_ops_shndx = -1;
1331 	obj->efile.st_ops_link_shndx = -1;
1332 	obj->kconfig_map_idx = -1;
1333 
1334 	obj->kern_version = get_kernel_version();
1335 	obj->loaded = false;
1336 
1337 	return obj;
1338 }
1339 
bpf_object__elf_finish(struct bpf_object * obj)1340 static void bpf_object__elf_finish(struct bpf_object *obj)
1341 {
1342 	if (!obj->efile.elf)
1343 		return;
1344 #if defined HAVE_LIBELF
1345 	elf_end(obj->efile.elf);
1346 #elif defined HAVE_ELFIO
1347 		if (obj->efile.shstring) {
1348 			elfio_string_section_accessor_delete(obj->efile.shstring);
1349 		}
1350 		if (obj->efile.strstring) {
1351 			elfio_string_section_accessor_delete(obj->efile.strstring);
1352 		}
1353 		elfio_delete(obj->efile.elf);
1354 #endif
1355 	obj->efile.elf = NULL;
1356 	obj->efile.symbols = NULL;
1357 	obj->efile.st_ops_data = NULL;
1358 	obj->efile.st_ops_link_data = NULL;
1359 
1360 	zfree(&obj->efile.secs);
1361 	obj->efile.sec_cnt = 0;
1362 	zclose(obj->efile.fd);
1363 	obj->efile.obj_buf = NULL;
1364 	obj->efile.obj_buf_sz = 0;
1365 }
1366 
bpf_object__elf_init(struct bpf_object * obj)1367 static int bpf_object__elf_init(struct bpf_object *obj)
1368 {
1369 	Elf64_Ehdr *ehdr;
1370 	int err = 0;
1371 #ifdef HAVE_LIBELF
1372 	Elf *elf;
1373 #elif defined HAVE_ELFIO
1374 	pelfio_t elf;
1375 #endif
1376 
1377 	if (obj->efile.elf) {
1378 		pr_warn("elf: init internal error\n");
1379 		return -LIBBPF_ERRNO__LIBELF;
1380 	}
1381 
1382 	if (obj->efile.obj_buf_sz > 0) {
1383 		/* obj_buf should have been validated by bpf_object__open_mem(). */
1384 #ifdef HAVE_LIBELF
1385 		elf = elf_memory((char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
1386 #elif defined HAVE_ELFIO
1387 		char  memfd_path[PATH_MAX] = {0};
1388 		elf = elfio_new();
1389 		int fdm = syscall(__NR_memfd_create, "bpfelf", MFD_CLOEXEC);
1390 		ftruncate(fdm, obj->efile.obj_buf_sz);
1391 		write(fdm, (char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
1392 		snprintf(memfd_path, PATH_MAX, "/proc/self/fd/%d", fdm);
1393 		elfio_load(elf, memfd_path);
1394 #endif
1395 	} else {
1396 		obj->efile.fd = open(obj->path, O_RDONLY | O_CLOEXEC);
1397 		if (obj->efile.fd < 0) {
1398 			char errmsg[STRERR_BUFSIZE], *cp;
1399 
1400 			err = -errno;
1401 			cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
1402 			pr_warn("elf: failed to open %s: %s\n", obj->path, cp);
1403 			return err;
1404 		}
1405 #ifdef HAVE_LIBELF
1406 		elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1407 #endif
1408 	}
1409 
1410 	if (!elf) {
1411 		pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
1412 		err = -LIBBPF_ERRNO__LIBELF;
1413 		goto errout;
1414 	}
1415 
1416 	obj->efile.elf = elf;
1417 #ifdef HAVE_LIBELF
1418 	if (elf_kind(elf) != ELF_K_ELF) {
1419 		err = -LIBBPF_ERRNO__FORMAT;
1420 		pr_warn("elf: '%s' is not a proper ELF object\n", obj->path);
1421 		goto errout;
1422 	}
1423 
1424 	if (gelf_getclass(elf) != ELFCLASS64) {
1425 #elif defined HAVE_ELFIO
1426 	if (elfio_get_class(elf) != ELFCLASS64 ) {
1427 #endif
1428 		err = -LIBBPF_ERRNO__FORMAT;
1429 		pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path);
1430 		goto errout;
1431 	}
1432 #ifdef HAVE_LIBELF
1433 	obj->efile.ehdr = ehdr = elf64_getehdr(elf);
1434 #elif defined HAVE_ELFIO
1435 	obj->efile.ehdr = ehdr = (Elf64_Ehdr*)obj->efile.obj_buf;
1436 #endif
1437 	if (!obj->efile.ehdr) {
1438 		pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
1439 		err = -LIBBPF_ERRNO__FORMAT;
1440 		goto errout;
1441 	}
1442 
1443 #ifdef HAVE_LIBELF
1444 	if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
1445 		pr_warn("elf: failed to get section names section index for %s: %s\n",
1446 			obj->path, elf_errmsg(-1));
1447 		err = -LIBBPF_ERRNO__FORMAT;
1448 		goto errout;
1449 	}
1450 
1451 	/* Elf is corrupted/truncated, avoid calling elf_strptr. */
1452 	if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
1453 		pr_warn("elf: failed to get section names strings from %s: %s\n",
1454 			obj->path, elf_errmsg(-1));
1455 		err = -LIBBPF_ERRNO__FORMAT;
1456 		goto errout;
1457 	}
1458 #elif defined HAVE_ELFIO
1459      obj->efile.shstrndx = elfio_get_section_name_str_index(elf);
1460 #endif
1461 	/* Old LLVM set e_machine to EM_NONE */
1462 	if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
1463 		pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
1464 		err = -LIBBPF_ERRNO__FORMAT;
1465 		goto errout;
1466 	}
1467 
1468 	return 0;
1469 errout:
1470 	bpf_object__elf_finish(obj);
1471 	return err;
1472 }
1473 
1474 static int bpf_object__check_endianness(struct bpf_object *obj)
1475 {
1476 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1477 	if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2LSB)
1478 		return 0;
1479 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1480 	if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2MSB)
1481 		return 0;
1482 #else
1483 # error "Unrecognized __BYTE_ORDER__"
1484 #endif
1485 	pr_warn("elf: endianness mismatch in %s.\n", obj->path);
1486 	return -LIBBPF_ERRNO__ENDIAN;
1487 }
1488 
1489 static int
1490 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1491 {
1492 	if (!data) {
1493 		pr_warn("invalid license section in %s\n", obj->path);
1494 		return -LIBBPF_ERRNO__FORMAT;
1495 	}
1496 	/* libbpf_strlcpy() only copies first N - 1 bytes, so size + 1 won't
1497 	 * go over allowed ELF data section buffer
1498 	 */
1499 	libbpf_strlcpy(obj->license, data, min(size + 1, sizeof(obj->license)));
1500 	pr_debug("license of %s is %s\n", obj->path, obj->license);
1501 	return 0;
1502 }
1503 
1504 static int
1505 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1506 {
1507 	__u32 kver;
1508 
1509 	if (!data || size != sizeof(kver)) {
1510 		pr_warn("invalid kver section in %s\n", obj->path);
1511 		return -LIBBPF_ERRNO__FORMAT;
1512 	}
1513 	memcpy(&kver, data, sizeof(kver));
1514 	obj->kern_version = kver;
1515 	pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1516 	return 0;
1517 }
1518 
1519 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1520 {
1521 	if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1522 	    type == BPF_MAP_TYPE_HASH_OF_MAPS)
1523 		return true;
1524 	return false;
1525 }
1526 
1527 static int find_elf_sec_sz(const struct bpf_object *obj, const char *name, __u32 *size)
1528 {
1529 	Elf_Data *data;
1530 #ifdef HAVE_LIBELF
1531 	Elf_Scn *scn;
1532 #endif
1533 
1534 	if (!name)
1535 		return -EINVAL;
1536 #if defined HAVE_LIBELF
1537 	scn = elf_sec_by_name(obj, name);
1538 	data = elf_sec_data(obj, scn);
1539 #elif defined HAVE_ELFIO
1540 	Elf_Data realdata;
1541 	data = &realdata;
1542 	data = elf_sec_data_by_name(obj, name, data);
1543 #endif
1544 	if (data) {
1545 		*size = data->d_size;
1546 		return 0; /* found it */
1547 	}
1548 
1549 	return -ENOENT;
1550 }
1551 
1552 static Elf64_Sym *find_elf_var_sym(const struct bpf_object *obj, const char *name)
1553 {
1554 	Elf_Data *symbols = obj->efile.symbols;
1555 	const char *sname;
1556 	size_t si;
1557 
1558 	for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
1559 		Elf64_Sym *sym = elf_sym_by_idx(obj, si);
1560 
1561 		if (ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)
1562 			continue;
1563 
1564 		if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL &&
1565 		    ELF64_ST_BIND(sym->st_info) != STB_WEAK)
1566 			continue;
1567 
1568 		sname = elf_sym_str(obj, sym->st_name);
1569 		if (!sname) {
1570 			pr_warn("failed to get sym name string for var %s\n", name);
1571 			return ERR_PTR(-EIO);
1572 		}
1573 		if (strcmp(name, sname) == 0)
1574 			return sym;
1575 	}
1576 
1577 	return ERR_PTR(-ENOENT);
1578 }
1579 
1580 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1581 {
1582 	struct bpf_map *map;
1583 	int err;
1584 
1585 	err = libbpf_ensure_mem((void **)&obj->maps, &obj->maps_cap,
1586 				sizeof(*obj->maps), obj->nr_maps + 1);
1587 	if (err)
1588 		return ERR_PTR(err);
1589 
1590 	map = &obj->maps[obj->nr_maps++];
1591 	map->obj = obj;
1592 	map->fd = -1;
1593 	map->inner_map_fd = -1;
1594 	map->autocreate = true;
1595 
1596 	return map;
1597 }
1598 
1599 static size_t bpf_map_mmap_sz(unsigned int value_sz, unsigned int max_entries)
1600 {
1601 	const long page_sz = sysconf(_SC_PAGE_SIZE);
1602 	size_t map_sz;
1603 
1604 	map_sz = (size_t)roundup(value_sz, 8) * max_entries;
1605 	map_sz = roundup(map_sz, page_sz);
1606 	return map_sz;
1607 }
1608 
1609 static int bpf_map_mmap_resize(struct bpf_map *map, size_t old_sz, size_t new_sz)
1610 {
1611 	void *mmaped;
1612 
1613 	if (!map->mmaped)
1614 		return -EINVAL;
1615 
1616 	if (old_sz == new_sz)
1617 		return 0;
1618 
1619 	mmaped = mmap(NULL, new_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1620 	if (mmaped == MAP_FAILED)
1621 		return -errno;
1622 
1623 	memcpy(mmaped, map->mmaped, min(old_sz, new_sz));
1624 	munmap(map->mmaped, old_sz);
1625 	map->mmaped = mmaped;
1626 	return 0;
1627 }
1628 
1629 static char *internal_map_name(struct bpf_object *obj, const char *real_name)
1630 {
1631 	char map_name[BPF_OBJ_NAME_LEN], *p;
1632 	int pfx_len, sfx_len = max((size_t)7, strlen(real_name));
1633 
1634 	/* This is one of the more confusing parts of libbpf for various
1635 	 * reasons, some of which are historical. The original idea for naming
1636 	 * internal names was to include as much of BPF object name prefix as
1637 	 * possible, so that it can be distinguished from similar internal
1638 	 * maps of a different BPF object.
1639 	 * As an example, let's say we have bpf_object named 'my_object_name'
1640 	 * and internal map corresponding to '.rodata' ELF section. The final
1641 	 * map name advertised to user and to the kernel will be
1642 	 * 'my_objec.rodata', taking first 8 characters of object name and
1643 	 * entire 7 characters of '.rodata'.
1644 	 * Somewhat confusingly, if internal map ELF section name is shorter
1645 	 * than 7 characters, e.g., '.bss', we still reserve 7 characters
1646 	 * for the suffix, even though we only have 4 actual characters, and
1647 	 * resulting map will be called 'my_objec.bss', not even using all 15
1648 	 * characters allowed by the kernel. Oh well, at least the truncated
1649 	 * object name is somewhat consistent in this case. But if the map
1650 	 * name is '.kconfig', we'll still have entirety of '.kconfig' added
1651 	 * (8 chars) and thus will be left with only first 7 characters of the
1652 	 * object name ('my_obje'). Happy guessing, user, that the final map
1653 	 * name will be "my_obje.kconfig".
1654 	 * Now, with libbpf starting to support arbitrarily named .rodata.*
1655 	 * and .data.* data sections, it's possible that ELF section name is
1656 	 * longer than allowed 15 chars, so we now need to be careful to take
1657 	 * only up to 15 first characters of ELF name, taking no BPF object
1658 	 * name characters at all. So '.rodata.abracadabra' will result in
1659 	 * '.rodata.abracad' kernel and user-visible name.
1660 	 * We need to keep this convoluted logic intact for .data, .bss and
1661 	 * .rodata maps, but for new custom .data.custom and .rodata.custom
1662 	 * maps we use their ELF names as is, not prepending bpf_object name
1663 	 * in front. We still need to truncate them to 15 characters for the
1664 	 * kernel. Full name can be recovered for such maps by using DATASEC
1665 	 * BTF type associated with such map's value type, though.
1666 	 */
1667 	if (sfx_len >= BPF_OBJ_NAME_LEN)
1668 		sfx_len = BPF_OBJ_NAME_LEN - 1;
1669 
1670 	/* if there are two or more dots in map name, it's a custom dot map */
1671 	if (strchr(real_name + 1, '.') != NULL)
1672 		pfx_len = 0;
1673 	else
1674 		pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
1675 
1676 	snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1677 		 sfx_len, real_name);
1678 
1679 	/* sanitise map name to characters allowed by kernel */
1680 	for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1681 		if (!isalnum(*p) && *p != '_' && *p != '.')
1682 			*p = '_';
1683 
1684 	return strdup(map_name);
1685 }
1686 
1687 static int
1688 map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map);
1689 
1690 /* Internal BPF map is mmap()'able only if at least one of corresponding
1691  * DATASEC's VARs are to be exposed through BPF skeleton. I.e., it's a GLOBAL
1692  * variable and it's not marked as __hidden (which turns it into, effectively,
1693  * a STATIC variable).
1694  */
1695 static bool map_is_mmapable(struct bpf_object *obj, struct bpf_map *map)
1696 {
1697 	const struct btf_type *t, *vt;
1698 	struct btf_var_secinfo *vsi;
1699 	int i, n;
1700 
1701 	if (!map->btf_value_type_id)
1702 		return false;
1703 
1704 	t = btf__type_by_id(obj->btf, map->btf_value_type_id);
1705 	if (!btf_is_datasec(t))
1706 		return false;
1707 
1708 	vsi = btf_var_secinfos(t);
1709 	for (i = 0, n = btf_vlen(t); i < n; i++, vsi++) {
1710 		vt = btf__type_by_id(obj->btf, vsi->type);
1711 		if (!btf_is_var(vt))
1712 			continue;
1713 
1714 		if (btf_var(vt)->linkage != BTF_VAR_STATIC)
1715 			return true;
1716 	}
1717 
1718 	return false;
1719 }
1720 
1721 static int
1722 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
1723 			      const char *real_name, int sec_idx, void *data, size_t data_sz)
1724 {
1725 	struct bpf_map_def *def;
1726 	struct bpf_map *map;
1727 	size_t mmap_sz;
1728 	int err;
1729 
1730 	map = bpf_object__add_map(obj);
1731 	if (IS_ERR(map))
1732 		return PTR_ERR(map);
1733 
1734 	map->libbpf_type = type;
1735 	map->sec_idx = sec_idx;
1736 	map->sec_offset = 0;
1737 	map->real_name = strdup(real_name);
1738 	map->name = internal_map_name(obj, real_name);
1739 	if (!map->real_name || !map->name) {
1740 		zfree(&map->real_name);
1741 		zfree(&map->name);
1742 		return -ENOMEM;
1743 	}
1744 
1745 	def = &map->def;
1746 	def->type = BPF_MAP_TYPE_ARRAY;
1747 	def->key_size = sizeof(int);
1748 	def->value_size = data_sz;
1749 	def->max_entries = 1;
1750 	def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
1751 			 ? BPF_F_RDONLY_PROG : 0;
1752 
1753 	/* failures are fine because of maps like .rodata.str1.1 */
1754 	(void) map_fill_btf_type_info(obj, map);
1755 
1756 	if (map_is_mmapable(obj, map))
1757 		def->map_flags |= BPF_F_MMAPABLE;
1758 
1759 	pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
1760 		 map->name, map->sec_idx, map->sec_offset, def->map_flags);
1761 
1762 	mmap_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
1763 	map->mmaped = mmap(NULL, mmap_sz, PROT_READ | PROT_WRITE,
1764 			   MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1765 	if (map->mmaped == MAP_FAILED) {
1766 		err = -errno;
1767 		map->mmaped = NULL;
1768 		pr_warn("failed to alloc map '%s' content buffer: %d\n",
1769 			map->name, err);
1770 		zfree(&map->real_name);
1771 		zfree(&map->name);
1772 		return err;
1773 	}
1774 
1775 	if (data)
1776 		memcpy(map->mmaped, data, data_sz);
1777 
1778 	pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
1779 	return 0;
1780 }
1781 
1782 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
1783 {
1784 	struct elf_sec_desc *sec_desc;
1785 	const char *sec_name;
1786 	int err = 0, sec_idx;
1787 
1788 	/*
1789 	 * Populate obj->maps with libbpf internal maps.
1790 	 */
1791 	for (sec_idx = 1; sec_idx < obj->efile.sec_cnt; sec_idx++) {
1792 		sec_desc = &obj->efile.secs[sec_idx];
1793 
1794 		/* Skip recognized sections with size 0. */
1795 		if (!sec_desc->data || sec_desc->data->d_size == 0)
1796 			continue;
1797 
1798 		switch (sec_desc->sec_type) {
1799 		case SEC_DATA:
1800 #if defined HAVE_LIBELF
1801 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1802 #elif defined HAVE_ELFIO
1803 			sec_name = elf_sec_name_by_idx(obj, sec_idx);
1804 #endif
1805 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
1806 							    sec_name, sec_idx,
1807 							    sec_desc->data->d_buf,
1808 							    sec_desc->data->d_size);
1809 			break;
1810 		case SEC_RODATA:
1811 			obj->has_rodata = true;
1812 #if defined HAVE_LIBELF
1813 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1814 #elif defined HAVE_ELFIO
1815 			sec_name = elf_sec_name_by_idx(obj, sec_idx);
1816 #endif
1817 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
1818 							    sec_name, sec_idx,
1819 							    sec_desc->data->d_buf,
1820 							    sec_desc->data->d_size);
1821 			break;
1822 		case SEC_BSS:
1823 #if defined HAVE_LIBELF
1824 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1825 #elif defined HAVE_ELFIO
1826 			sec_name = elf_sec_name_by_idx(obj, sec_idx);
1827 #endif
1828 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
1829 							    sec_name, sec_idx,
1830 							    NULL,
1831 							    sec_desc->data->d_size);
1832 			break;
1833 		default:
1834 			/* skip */
1835 			break;
1836 		}
1837 		if (err)
1838 			return err;
1839 	}
1840 	return 0;
1841 }
1842 
1843 
1844 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
1845 					       const void *name)
1846 {
1847 	int i;
1848 
1849 	for (i = 0; i < obj->nr_extern; i++) {
1850 		if (strcmp(obj->externs[i].name, name) == 0)
1851 			return &obj->externs[i];
1852 	}
1853 	return NULL;
1854 }
1855 
1856 static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
1857 			      char value)
1858 {
1859 	switch (ext->kcfg.type) {
1860 	case KCFG_BOOL:
1861 		if (value == 'm') {
1862 			pr_warn("extern (kcfg) '%s': value '%c' implies tristate or char type\n",
1863 				ext->name, value);
1864 			return -EINVAL;
1865 		}
1866 		*(bool *)ext_val = value == 'y' ? true : false;
1867 		break;
1868 	case KCFG_TRISTATE:
1869 		if (value == 'y')
1870 			*(enum libbpf_tristate *)ext_val = TRI_YES;
1871 		else if (value == 'm')
1872 			*(enum libbpf_tristate *)ext_val = TRI_MODULE;
1873 		else /* value == 'n' */
1874 			*(enum libbpf_tristate *)ext_val = TRI_NO;
1875 		break;
1876 	case KCFG_CHAR:
1877 		*(char *)ext_val = value;
1878 		break;
1879 	case KCFG_UNKNOWN:
1880 	case KCFG_INT:
1881 	case KCFG_CHAR_ARR:
1882 	default:
1883 		pr_warn("extern (kcfg) '%s': value '%c' implies bool, tristate, or char type\n",
1884 			ext->name, value);
1885 		return -EINVAL;
1886 	}
1887 	ext->is_set = true;
1888 	return 0;
1889 }
1890 
1891 static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
1892 			      const char *value)
1893 {
1894 	size_t len;
1895 
1896 	if (ext->kcfg.type != KCFG_CHAR_ARR) {
1897 		pr_warn("extern (kcfg) '%s': value '%s' implies char array type\n",
1898 			ext->name, value);
1899 		return -EINVAL;
1900 	}
1901 
1902 	len = strlen(value);
1903 	if (len < 2 || value[len - 1] != '"') {
1904 		pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
1905 			ext->name, value);
1906 		return -EINVAL;
1907 	}
1908 
1909 	/* strip quotes */
1910 	len -= 2;
1911 	if (len >= ext->kcfg.sz) {
1912 		pr_warn("extern (kcfg) '%s': long string '%s' of (%zu bytes) truncated to %d bytes\n",
1913 			ext->name, value, len, ext->kcfg.sz - 1);
1914 		len = ext->kcfg.sz - 1;
1915 	}
1916 	memcpy(ext_val, value + 1, len);
1917 	ext_val[len] = '\0';
1918 	ext->is_set = true;
1919 	return 0;
1920 }
1921 
1922 static int parse_u64(const char *value, __u64 *res)
1923 {
1924 	char *value_end;
1925 	int err;
1926 
1927 	errno = 0;
1928 	*res = strtoull(value, &value_end, 0);
1929 	if (errno) {
1930 		err = -errno;
1931 		pr_warn("failed to parse '%s' as integer: %d\n", value, err);
1932 		return err;
1933 	}
1934 	if (*value_end) {
1935 		pr_warn("failed to parse '%s' as integer completely\n", value);
1936 		return -EINVAL;
1937 	}
1938 	return 0;
1939 }
1940 
1941 static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
1942 {
1943 	int bit_sz = ext->kcfg.sz * 8;
1944 
1945 	if (ext->kcfg.sz == 8)
1946 		return true;
1947 
1948 	/* Validate that value stored in u64 fits in integer of `ext->sz`
1949 	 * bytes size without any loss of information. If the target integer
1950 	 * is signed, we rely on the following limits of integer type of
1951 	 * Y bits and subsequent transformation:
1952 	 *
1953 	 *     -2^(Y-1) <= X           <= 2^(Y-1) - 1
1954 	 *            0 <= X + 2^(Y-1) <= 2^Y - 1
1955 	 *            0 <= X + 2^(Y-1) <  2^Y
1956 	 *
1957 	 *  For unsigned target integer, check that all the (64 - Y) bits are
1958 	 *  zero.
1959 	 */
1960 	if (ext->kcfg.is_signed)
1961 		return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
1962 	else
1963 		return (v >> bit_sz) == 0;
1964 }
1965 
1966 static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
1967 			      __u64 value)
1968 {
1969 	if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR &&
1970 	    ext->kcfg.type != KCFG_BOOL) {
1971 		pr_warn("extern (kcfg) '%s': value '%llu' implies integer, char, or boolean type\n",
1972 			ext->name, (unsigned long long)value);
1973 		return -EINVAL;
1974 	}
1975 	if (ext->kcfg.type == KCFG_BOOL && value > 1) {
1976 		pr_warn("extern (kcfg) '%s': value '%llu' isn't boolean compatible\n",
1977 			ext->name, (unsigned long long)value);
1978 		return -EINVAL;
1979 
1980 	}
1981 	if (!is_kcfg_value_in_range(ext, value)) {
1982 		pr_warn("extern (kcfg) '%s': value '%llu' doesn't fit in %d bytes\n",
1983 			ext->name, (unsigned long long)value, ext->kcfg.sz);
1984 		return -ERANGE;
1985 	}
1986 	switch (ext->kcfg.sz) {
1987 	case 1:
1988 		*(__u8 *)ext_val = value;
1989 		break;
1990 	case 2:
1991 		*(__u16 *)ext_val = value;
1992 		break;
1993 	case 4:
1994 		*(__u32 *)ext_val = value;
1995 		break;
1996 	case 8:
1997 		*(__u64 *)ext_val = value;
1998 		break;
1999 	default:
2000 		return -EINVAL;
2001 	}
2002 	ext->is_set = true;
2003 	return 0;
2004 }
2005 
2006 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
2007 					    char *buf, void *data)
2008 {
2009 	struct extern_desc *ext;
2010 	char *sep, *value;
2011 	int len, err = 0;
2012 	void *ext_val;
2013 	__u64 num;
2014 
2015 	if (!str_has_pfx(buf, "CONFIG_"))
2016 		return 0;
2017 
2018 	sep = strchr(buf, '=');
2019 	if (!sep) {
2020 		pr_warn("failed to parse '%s': no separator\n", buf);
2021 		return -EINVAL;
2022 	}
2023 
2024 	/* Trim ending '\n' */
2025 	len = strlen(buf);
2026 	if (buf[len - 1] == '\n')
2027 		buf[len - 1] = '\0';
2028 	/* Split on '=' and ensure that a value is present. */
2029 	*sep = '\0';
2030 	if (!sep[1]) {
2031 		*sep = '=';
2032 		pr_warn("failed to parse '%s': no value\n", buf);
2033 		return -EINVAL;
2034 	}
2035 
2036 	ext = find_extern_by_name(obj, buf);
2037 	if (!ext || ext->is_set)
2038 		return 0;
2039 
2040 	ext_val = data + ext->kcfg.data_off;
2041 	value = sep + 1;
2042 
2043 	switch (*value) {
2044 	case 'y': case 'n': case 'm':
2045 		err = set_kcfg_value_tri(ext, ext_val, *value);
2046 		break;
2047 	case '"':
2048 		err = set_kcfg_value_str(ext, ext_val, value);
2049 		break;
2050 	default:
2051 		/* assume integer */
2052 		err = parse_u64(value, &num);
2053 		if (err) {
2054 			pr_warn("extern (kcfg) '%s': value '%s' isn't a valid integer\n", ext->name, value);
2055 			return err;
2056 		}
2057 		if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
2058 			pr_warn("extern (kcfg) '%s': value '%s' implies integer type\n", ext->name, value);
2059 			return -EINVAL;
2060 		}
2061 		err = set_kcfg_value_num(ext, ext_val, num);
2062 		break;
2063 	}
2064 	if (err)
2065 		return err;
2066 	pr_debug("extern (kcfg) '%s': set to %s\n", ext->name, value);
2067 	return 0;
2068 }
2069 
2070 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
2071 {
2072 	char buf[PATH_MAX];
2073 	struct utsname uts;
2074 	int len, err = 0;
2075 	gzFile file;
2076 
2077 	uname(&uts);
2078 	len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
2079 	if (len < 0)
2080 		return -EINVAL;
2081 	else if (len >= PATH_MAX)
2082 		return -ENAMETOOLONG;
2083 
2084 	/* gzopen also accepts uncompressed files. */
2085 	file = gzopen(buf, "re");
2086 	if (!file)
2087 		file = gzopen("/proc/config.gz", "re");
2088 
2089 	if (!file) {
2090 		pr_warn("failed to open system Kconfig\n");
2091 		return -ENOENT;
2092 	}
2093 
2094 	while (gzgets(file, buf, sizeof(buf))) {
2095 		err = bpf_object__process_kconfig_line(obj, buf, data);
2096 		if (err) {
2097 			pr_warn("error parsing system Kconfig line '%s': %d\n",
2098 				buf, err);
2099 			goto out;
2100 		}
2101 	}
2102 
2103 out:
2104 	gzclose(file);
2105 	return err;
2106 }
2107 
2108 static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
2109 					const char *config, void *data)
2110 {
2111 	char buf[PATH_MAX];
2112 	int err = 0;
2113 	FILE *file;
2114 
2115 	file = fmemopen((void *)config, strlen(config), "r");
2116 	if (!file) {
2117 		err = -errno;
2118 		pr_warn("failed to open in-memory Kconfig: %d\n", err);
2119 		return err;
2120 	}
2121 
2122 	while (fgets(buf, sizeof(buf), file)) {
2123 		err = bpf_object__process_kconfig_line(obj, buf, data);
2124 		if (err) {
2125 			pr_warn("error parsing in-memory Kconfig line '%s': %d\n",
2126 				buf, err);
2127 			break;
2128 		}
2129 	}
2130 
2131 	fclose(file);
2132 	return err;
2133 }
2134 
2135 static int bpf_object__init_kconfig_map(struct bpf_object *obj)
2136 {
2137 	struct extern_desc *last_ext = NULL, *ext;
2138 	size_t map_sz;
2139 	int i, err;
2140 
2141 	for (i = 0; i < obj->nr_extern; i++) {
2142 		ext = &obj->externs[i];
2143 		if (ext->type == EXT_KCFG)
2144 			last_ext = ext;
2145 	}
2146 
2147 	if (!last_ext)
2148 		return 0;
2149 
2150 	map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
2151 	err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
2152 					    ".kconfig", obj->efile.symbols_shndx,
2153 					    NULL, map_sz);
2154 	if (err)
2155 		return err;
2156 
2157 	obj->kconfig_map_idx = obj->nr_maps - 1;
2158 
2159 	return 0;
2160 }
2161 
2162 const struct btf_type *
2163 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
2164 {
2165 	const struct btf_type *t = btf__type_by_id(btf, id);
2166 
2167 	if (res_id)
2168 		*res_id = id;
2169 
2170 	while (btf_is_mod(t) || btf_is_typedef(t)) {
2171 		if (res_id)
2172 			*res_id = t->type;
2173 		t = btf__type_by_id(btf, t->type);
2174 	}
2175 
2176 	return t;
2177 }
2178 
2179 static const struct btf_type *
2180 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
2181 {
2182 	const struct btf_type *t;
2183 
2184 	t = skip_mods_and_typedefs(btf, id, NULL);
2185 	if (!btf_is_ptr(t))
2186 		return NULL;
2187 
2188 	t = skip_mods_and_typedefs(btf, t->type, res_id);
2189 
2190 	return btf_is_func_proto(t) ? t : NULL;
2191 }
2192 
2193 static const char *__btf_kind_str(__u16 kind)
2194 {
2195 	switch (kind) {
2196 	case BTF_KIND_UNKN: return "void";
2197 	case BTF_KIND_INT: return "int";
2198 	case BTF_KIND_PTR: return "ptr";
2199 	case BTF_KIND_ARRAY: return "array";
2200 	case BTF_KIND_STRUCT: return "struct";
2201 	case BTF_KIND_UNION: return "union";
2202 	case BTF_KIND_ENUM: return "enum";
2203 	case BTF_KIND_FWD: return "fwd";
2204 	case BTF_KIND_TYPEDEF: return "typedef";
2205 	case BTF_KIND_VOLATILE: return "volatile";
2206 	case BTF_KIND_CONST: return "const";
2207 	case BTF_KIND_RESTRICT: return "restrict";
2208 	case BTF_KIND_FUNC: return "func";
2209 	case BTF_KIND_FUNC_PROTO: return "func_proto";
2210 	case BTF_KIND_VAR: return "var";
2211 	case BTF_KIND_DATASEC: return "datasec";
2212 	case BTF_KIND_FLOAT: return "float";
2213 	case BTF_KIND_DECL_TAG: return "decl_tag";
2214 	case BTF_KIND_TYPE_TAG: return "type_tag";
2215 	case BTF_KIND_ENUM64: return "enum64";
2216 	default: return "unknown";
2217 	}
2218 }
2219 
2220 const char *btf_kind_str(const struct btf_type *t)
2221 {
2222 	return __btf_kind_str(btf_kind(t));
2223 }
2224 
2225 /*
2226  * Fetch integer attribute of BTF map definition. Such attributes are
2227  * represented using a pointer to an array, in which dimensionality of array
2228  * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2229  * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2230  * type definition, while using only sizeof(void *) space in ELF data section.
2231  */
2232 static bool get_map_field_int(const char *map_name, const struct btf *btf,
2233 			      const struct btf_member *m, __u32 *res)
2234 {
2235 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2236 	const char *name = btf__name_by_offset(btf, m->name_off);
2237 	const struct btf_array *arr_info;
2238 	const struct btf_type *arr_t;
2239 
2240 	if (!btf_is_ptr(t)) {
2241 		pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2242 			map_name, name, btf_kind_str(t));
2243 		return false;
2244 	}
2245 
2246 	arr_t = btf__type_by_id(btf, t->type);
2247 	if (!arr_t) {
2248 		pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2249 			map_name, name, t->type);
2250 		return false;
2251 	}
2252 	if (!btf_is_array(arr_t)) {
2253 		pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2254 			map_name, name, btf_kind_str(arr_t));
2255 		return false;
2256 	}
2257 	arr_info = btf_array(arr_t);
2258 	*res = arr_info->nelems;
2259 	return true;
2260 }
2261 
2262 static int pathname_concat(char *buf, size_t buf_sz, const char *path, const char *name)
2263 {
2264 	int len;
2265 
2266 	len = snprintf(buf, buf_sz, "%s/%s", path, name);
2267 	if (len < 0)
2268 		return -EINVAL;
2269 	if (len >= buf_sz)
2270 		return -ENAMETOOLONG;
2271 
2272 	return 0;
2273 }
2274 
2275 static int build_map_pin_path(struct bpf_map *map, const char *path)
2276 {
2277 	char buf[PATH_MAX];
2278 	int err;
2279 
2280 	if (!path)
2281 		path = "/sys/fs/bpf";
2282 
2283 	err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
2284 	if (err)
2285 		return err;
2286 
2287 	return bpf_map__set_pin_path(map, buf);
2288 }
2289 
2290 /* should match definition in bpf_helpers.h */
2291 enum libbpf_pin_type {
2292 	LIBBPF_PIN_NONE,
2293 	/* PIN_BY_NAME: pin maps by name (in /sys/fs/bpf by default) */
2294 	LIBBPF_PIN_BY_NAME,
2295 };
2296 
2297 int parse_btf_map_def(const char *map_name, struct btf *btf,
2298 		      const struct btf_type *def_t, bool strict,
2299 		      struct btf_map_def *map_def, struct btf_map_def *inner_def)
2300 {
2301 	const struct btf_type *t;
2302 	const struct btf_member *m;
2303 	bool is_inner = inner_def == NULL;
2304 	int vlen, i;
2305 
2306 	vlen = btf_vlen(def_t);
2307 	m = btf_members(def_t);
2308 	for (i = 0; i < vlen; i++, m++) {
2309 		const char *name = btf__name_by_offset(btf, m->name_off);
2310 
2311 		if (!name) {
2312 			pr_warn("map '%s': invalid field #%d.\n", map_name, i);
2313 			return -EINVAL;
2314 		}
2315 		if (strcmp(name, "type") == 0) {
2316 			if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
2317 				return -EINVAL;
2318 			map_def->parts |= MAP_DEF_MAP_TYPE;
2319 		} else if (strcmp(name, "max_entries") == 0) {
2320 			if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
2321 				return -EINVAL;
2322 			map_def->parts |= MAP_DEF_MAX_ENTRIES;
2323 		} else if (strcmp(name, "map_flags") == 0) {
2324 			if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
2325 				return -EINVAL;
2326 			map_def->parts |= MAP_DEF_MAP_FLAGS;
2327 		} else if (strcmp(name, "numa_node") == 0) {
2328 			if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
2329 				return -EINVAL;
2330 			map_def->parts |= MAP_DEF_NUMA_NODE;
2331 		} else if (strcmp(name, "key_size") == 0) {
2332 			__u32 sz;
2333 
2334 			if (!get_map_field_int(map_name, btf, m, &sz))
2335 				return -EINVAL;
2336 			if (map_def->key_size && map_def->key_size != sz) {
2337 				pr_warn("map '%s': conflicting key size %u != %u.\n",
2338 					map_name, map_def->key_size, sz);
2339 				return -EINVAL;
2340 			}
2341 			map_def->key_size = sz;
2342 			map_def->parts |= MAP_DEF_KEY_SIZE;
2343 		} else if (strcmp(name, "key") == 0) {
2344 			__s64 sz;
2345 
2346 			t = btf__type_by_id(btf, m->type);
2347 			if (!t) {
2348 				pr_warn("map '%s': key type [%d] not found.\n",
2349 					map_name, m->type);
2350 				return -EINVAL;
2351 			}
2352 			if (!btf_is_ptr(t)) {
2353 				pr_warn("map '%s': key spec is not PTR: %s.\n",
2354 					map_name, btf_kind_str(t));
2355 				return -EINVAL;
2356 			}
2357 			sz = btf__resolve_size(btf, t->type);
2358 			if (sz < 0) {
2359 				pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2360 					map_name, t->type, (ssize_t)sz);
2361 				return sz;
2362 			}
2363 			if (map_def->key_size && map_def->key_size != sz) {
2364 				pr_warn("map '%s': conflicting key size %u != %zd.\n",
2365 					map_name, map_def->key_size, (ssize_t)sz);
2366 				return -EINVAL;
2367 			}
2368 			map_def->key_size = sz;
2369 			map_def->key_type_id = t->type;
2370 			map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
2371 		} else if (strcmp(name, "value_size") == 0) {
2372 			__u32 sz;
2373 
2374 			if (!get_map_field_int(map_name, btf, m, &sz))
2375 				return -EINVAL;
2376 			if (map_def->value_size && map_def->value_size != sz) {
2377 				pr_warn("map '%s': conflicting value size %u != %u.\n",
2378 					map_name, map_def->value_size, sz);
2379 				return -EINVAL;
2380 			}
2381 			map_def->value_size = sz;
2382 			map_def->parts |= MAP_DEF_VALUE_SIZE;
2383 		} else if (strcmp(name, "value") == 0) {
2384 			__s64 sz;
2385 
2386 			t = btf__type_by_id(btf, m->type);
2387 			if (!t) {
2388 				pr_warn("map '%s': value type [%d] not found.\n",
2389 					map_name, m->type);
2390 				return -EINVAL;
2391 			}
2392 			if (!btf_is_ptr(t)) {
2393 				pr_warn("map '%s': value spec is not PTR: %s.\n",
2394 					map_name, btf_kind_str(t));
2395 				return -EINVAL;
2396 			}
2397 			sz = btf__resolve_size(btf, t->type);
2398 			if (sz < 0) {
2399 				pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2400 					map_name, t->type, (ssize_t)sz);
2401 				return sz;
2402 			}
2403 			if (map_def->value_size && map_def->value_size != sz) {
2404 				pr_warn("map '%s': conflicting value size %u != %zd.\n",
2405 					map_name, map_def->value_size, (ssize_t)sz);
2406 				return -EINVAL;
2407 			}
2408 			map_def->value_size = sz;
2409 			map_def->value_type_id = t->type;
2410 			map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
2411 		}
2412 		else if (strcmp(name, "values") == 0) {
2413 			bool is_map_in_map = bpf_map_type__is_map_in_map(map_def->map_type);
2414 			bool is_prog_array = map_def->map_type == BPF_MAP_TYPE_PROG_ARRAY;
2415 			const char *desc = is_map_in_map ? "map-in-map inner" : "prog-array value";
2416 			char inner_map_name[128];
2417 			int err;
2418 
2419 			if (is_inner) {
2420 				pr_warn("map '%s': multi-level inner maps not supported.\n",
2421 					map_name);
2422 				return -ENOTSUP;
2423 			}
2424 			if (i != vlen - 1) {
2425 				pr_warn("map '%s': '%s' member should be last.\n",
2426 					map_name, name);
2427 				return -EINVAL;
2428 			}
2429 			if (!is_map_in_map && !is_prog_array) {
2430 				pr_warn("map '%s': should be map-in-map or prog-array.\n",
2431 					map_name);
2432 				return -ENOTSUP;
2433 			}
2434 			if (map_def->value_size && map_def->value_size != 4) {
2435 				pr_warn("map '%s': conflicting value size %u != 4.\n",
2436 					map_name, map_def->value_size);
2437 				return -EINVAL;
2438 			}
2439 			map_def->value_size = 4;
2440 			t = btf__type_by_id(btf, m->type);
2441 			if (!t) {
2442 				pr_warn("map '%s': %s type [%d] not found.\n",
2443 					map_name, desc, m->type);
2444 				return -EINVAL;
2445 			}
2446 			if (!btf_is_array(t) || btf_array(t)->nelems) {
2447 				pr_warn("map '%s': %s spec is not a zero-sized array.\n",
2448 					map_name, desc);
2449 				return -EINVAL;
2450 			}
2451 			t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
2452 			if (!btf_is_ptr(t)) {
2453 				pr_warn("map '%s': %s def is of unexpected kind %s.\n",
2454 					map_name, desc, btf_kind_str(t));
2455 				return -EINVAL;
2456 			}
2457 			t = skip_mods_and_typedefs(btf, t->type, NULL);
2458 			if (is_prog_array) {
2459 				if (!btf_is_func_proto(t)) {
2460 					pr_warn("map '%s': prog-array value def is of unexpected kind %s.\n",
2461 						map_name, btf_kind_str(t));
2462 					return -EINVAL;
2463 				}
2464 				continue;
2465 			}
2466 			if (!btf_is_struct(t)) {
2467 				pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2468 					map_name, btf_kind_str(t));
2469 				return -EINVAL;
2470 			}
2471 
2472 			snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2473 			err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
2474 			if (err)
2475 				return err;
2476 
2477 			map_def->parts |= MAP_DEF_INNER_MAP;
2478 		} else if (strcmp(name, "pinning") == 0) {
2479 			__u32 val;
2480 
2481 			if (is_inner) {
2482 				pr_warn("map '%s': inner def can't be pinned.\n", map_name);
2483 				return -EINVAL;
2484 			}
2485 			if (!get_map_field_int(map_name, btf, m, &val))
2486 				return -EINVAL;
2487 			if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
2488 				pr_warn("map '%s': invalid pinning value %u.\n",
2489 					map_name, val);
2490 				return -EINVAL;
2491 			}
2492 			map_def->pinning = val;
2493 			map_def->parts |= MAP_DEF_PINNING;
2494 		} else if (strcmp(name, "map_extra") == 0) {
2495 			__u32 map_extra;
2496 
2497 			if (!get_map_field_int(map_name, btf, m, &map_extra))
2498 				return -EINVAL;
2499 			map_def->map_extra = map_extra;
2500 			map_def->parts |= MAP_DEF_MAP_EXTRA;
2501 		} else {
2502 			if (strict) {
2503 				pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
2504 				return -ENOTSUP;
2505 			}
2506 			pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
2507 		}
2508 	}
2509 
2510 	if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2511 		pr_warn("map '%s': map type isn't specified.\n", map_name);
2512 		return -EINVAL;
2513 	}
2514 
2515 	return 0;
2516 }
2517 
2518 static size_t adjust_ringbuf_sz(size_t sz)
2519 {
2520 	__u32 page_sz = sysconf(_SC_PAGE_SIZE);
2521 	__u32 mul;
2522 
2523 	/* if user forgot to set any size, make sure they see error */
2524 	if (sz == 0)
2525 		return 0;
2526 	/* Kernel expects BPF_MAP_TYPE_RINGBUF's max_entries to be
2527 	 * a power-of-2 multiple of kernel's page size. If user diligently
2528 	 * satisified these conditions, pass the size through.
2529 	 */
2530 	if ((sz % page_sz) == 0 && is_pow_of_2(sz / page_sz))
2531 		return sz;
2532 
2533 	/* Otherwise find closest (page_sz * power_of_2) product bigger than
2534 	 * user-set size to satisfy both user size request and kernel
2535 	 * requirements and substitute correct max_entries for map creation.
2536 	 */
2537 	for (mul = 1; mul <= UINT_MAX / page_sz; mul <<= 1) {
2538 		if (mul * page_sz > sz)
2539 			return mul * page_sz;
2540 	}
2541 
2542 	/* if it's impossible to satisfy the conditions (i.e., user size is
2543 	 * very close to UINT_MAX but is not a power-of-2 multiple of
2544 	 * page_size) then just return original size and let kernel reject it
2545 	 */
2546 	return sz;
2547 }
2548 
2549 static bool map_is_ringbuf(const struct bpf_map *map)
2550 {
2551 	return map->def.type == BPF_MAP_TYPE_RINGBUF ||
2552 	       map->def.type == BPF_MAP_TYPE_USER_RINGBUF;
2553 }
2554 
2555 static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2556 {
2557 	map->def.type = def->map_type;
2558 	map->def.key_size = def->key_size;
2559 	map->def.value_size = def->value_size;
2560 	map->def.max_entries = def->max_entries;
2561 	map->def.map_flags = def->map_flags;
2562 	map->map_extra = def->map_extra;
2563 
2564 	map->numa_node = def->numa_node;
2565 	map->btf_key_type_id = def->key_type_id;
2566 	map->btf_value_type_id = def->value_type_id;
2567 
2568 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
2569 	if (map_is_ringbuf(map))
2570 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
2571 
2572 	if (def->parts & MAP_DEF_MAP_TYPE)
2573 		pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2574 
2575 	if (def->parts & MAP_DEF_KEY_TYPE)
2576 		pr_debug("map '%s': found key [%u], sz = %u.\n",
2577 			 map->name, def->key_type_id, def->key_size);
2578 	else if (def->parts & MAP_DEF_KEY_SIZE)
2579 		pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2580 
2581 	if (def->parts & MAP_DEF_VALUE_TYPE)
2582 		pr_debug("map '%s': found value [%u], sz = %u.\n",
2583 			 map->name, def->value_type_id, def->value_size);
2584 	else if (def->parts & MAP_DEF_VALUE_SIZE)
2585 		pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2586 
2587 	if (def->parts & MAP_DEF_MAX_ENTRIES)
2588 		pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2589 	if (def->parts & MAP_DEF_MAP_FLAGS)
2590 		pr_debug("map '%s': found map_flags = 0x%x.\n", map->name, def->map_flags);
2591 	if (def->parts & MAP_DEF_MAP_EXTRA)
2592 		pr_debug("map '%s': found map_extra = 0x%llx.\n", map->name,
2593 			 (unsigned long long)def->map_extra);
2594 	if (def->parts & MAP_DEF_PINNING)
2595 		pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2596 	if (def->parts & MAP_DEF_NUMA_NODE)
2597 		pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2598 
2599 	if (def->parts & MAP_DEF_INNER_MAP)
2600 		pr_debug("map '%s': found inner map definition.\n", map->name);
2601 }
2602 
2603 static const char *btf_var_linkage_str(__u32 linkage)
2604 {
2605 	switch (linkage) {
2606 	case BTF_VAR_STATIC: return "static";
2607 	case BTF_VAR_GLOBAL_ALLOCATED: return "global";
2608 	case BTF_VAR_GLOBAL_EXTERN: return "extern";
2609 	default: return "unknown";
2610 	}
2611 }
2612 
2613 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2614 					 const struct btf_type *sec,
2615 					 int var_idx, int sec_idx,
2616 					 const Elf_Data *data, bool strict,
2617 					 const char *pin_root_path)
2618 {
2619 	struct btf_map_def map_def = {}, inner_def = {};
2620 	const struct btf_type *var, *def;
2621 	const struct btf_var_secinfo *vi;
2622 	const struct btf_var *var_extra;
2623 	const char *map_name;
2624 	struct bpf_map *map;
2625 	int err;
2626 
2627 	vi = btf_var_secinfos(sec) + var_idx;
2628 	var = btf__type_by_id(obj->btf, vi->type);
2629 	var_extra = btf_var(var);
2630 	map_name = btf__name_by_offset(obj->btf, var->name_off);
2631 
2632 	if (map_name == NULL || map_name[0] == '\0') {
2633 		pr_warn("map #%d: empty name.\n", var_idx);
2634 		return -EINVAL;
2635 	}
2636 	if ((__u64)vi->offset + vi->size > data->d_size) {
2637 		pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2638 		return -EINVAL;
2639 	}
2640 	if (!btf_is_var(var)) {
2641 		pr_warn("map '%s': unexpected var kind %s.\n",
2642 			map_name, btf_kind_str(var));
2643 		return -EINVAL;
2644 	}
2645 	if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
2646 		pr_warn("map '%s': unsupported map linkage %s.\n",
2647 			map_name, btf_var_linkage_str(var_extra->linkage));
2648 		return -EOPNOTSUPP;
2649 	}
2650 
2651 	def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2652 	if (!btf_is_struct(def)) {
2653 		pr_warn("map '%s': unexpected def kind %s.\n",
2654 			map_name, btf_kind_str(var));
2655 		return -EINVAL;
2656 	}
2657 	if (def->size > vi->size) {
2658 		pr_warn("map '%s': invalid def size.\n", map_name);
2659 		return -EINVAL;
2660 	}
2661 
2662 	map = bpf_object__add_map(obj);
2663 	if (IS_ERR(map))
2664 		return PTR_ERR(map);
2665 	map->name = strdup(map_name);
2666 	if (!map->name) {
2667 		pr_warn("map '%s': failed to alloc map name.\n", map_name);
2668 		return -ENOMEM;
2669 	}
2670 	map->libbpf_type = LIBBPF_MAP_UNSPEC;
2671 	map->def.type = BPF_MAP_TYPE_UNSPEC;
2672 	map->sec_idx = sec_idx;
2673 	map->sec_offset = vi->offset;
2674 	map->btf_var_idx = var_idx;
2675 	pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2676 		 map_name, map->sec_idx, map->sec_offset);
2677 
2678 	err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
2679 	if (err)
2680 		return err;
2681 
2682 	fill_map_from_def(map, &map_def);
2683 
2684 	if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
2685 		err = build_map_pin_path(map, pin_root_path);
2686 		if (err) {
2687 			pr_warn("map '%s': couldn't build pin path.\n", map->name);
2688 			return err;
2689 		}
2690 	}
2691 
2692 	if (map_def.parts & MAP_DEF_INNER_MAP) {
2693 		map->inner_map = calloc(1, sizeof(*map->inner_map));
2694 		if (!map->inner_map)
2695 			return -ENOMEM;
2696 		map->inner_map->fd = -1;
2697 		map->inner_map->sec_idx = sec_idx;
2698 		map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
2699 		if (!map->inner_map->name)
2700 			return -ENOMEM;
2701 		sprintf(map->inner_map->name, "%s.inner", map_name);
2702 
2703 		fill_map_from_def(map->inner_map, &inner_def);
2704 	}
2705 
2706 	err = map_fill_btf_type_info(obj, map);
2707 	if (err)
2708 		return err;
2709 
2710 	return 0;
2711 }
2712 
2713 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
2714 					  const char *pin_root_path)
2715 {
2716 	const struct btf_type *sec = NULL;
2717 	int nr_types, i, vlen, err;
2718 	const struct btf_type *t;
2719 	const char *name;
2720 	Elf_Data *data;
2721 #ifdef HAVE_LIBELF
2722 	Elf_Scn *scn;
2723 #endif
2724 
2725 	if (obj->efile.btf_maps_shndx < 0)
2726 		return 0;
2727 #if defined HAVE_LIBELF
2728 	scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
2729 	data = elf_sec_data(obj, scn);
2730 	if (!scn || !data) {
2731 #elif defined HAVE_ELFIO
2732 	Elf_Data realdata;
2733 	data = elf_sec_data_by_idx(obj, obj->efile.btf_maps_shndx, &realdata);
2734 	if (!data) {
2735 #endif
2736 		pr_warn("elf: failed to get %s map definitions for %s\n",
2737 			MAPS_ELF_SEC, obj->path);
2738 		return -EINVAL;
2739 	}
2740 
2741 	nr_types = btf__type_cnt(obj->btf);
2742 	for (i = 1; i < nr_types; i++) {
2743 		t = btf__type_by_id(obj->btf, i);
2744 		if (!btf_is_datasec(t))
2745 			continue;
2746 		name = btf__name_by_offset(obj->btf, t->name_off);
2747 		if (strcmp(name, MAPS_ELF_SEC) == 0) {
2748 			sec = t;
2749 			obj->efile.btf_maps_sec_btf_id = i;
2750 			break;
2751 		}
2752 	}
2753 
2754 	if (!sec) {
2755 		pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
2756 		return -ENOENT;
2757 	}
2758 
2759 	vlen = btf_vlen(sec);
2760 	for (i = 0; i < vlen; i++) {
2761 		err = bpf_object__init_user_btf_map(obj, sec, i,
2762 						    obj->efile.btf_maps_shndx,
2763 						    data, strict,
2764 						    pin_root_path);
2765 		if (err)
2766 			return err;
2767 	}
2768 
2769 	return 0;
2770 }
2771 
2772 static int bpf_object__init_maps(struct bpf_object *obj,
2773 				 const struct bpf_object_open_opts *opts)
2774 {
2775 	const char *pin_root_path;
2776 	bool strict;
2777 	int err = 0;
2778 
2779 	strict = !OPTS_GET(opts, relaxed_maps, false);
2780 	pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
2781 
2782 	err = bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
2783 	err = err ?: bpf_object__init_global_data_maps(obj);
2784 	err = err ?: bpf_object__init_kconfig_map(obj);
2785 	err = err ?: bpf_object_init_struct_ops(obj);
2786 
2787 	return err;
2788 }
2789 
2790 static bool section_have_execinstr(struct bpf_object *obj, int idx)
2791 {
2792 	Elf64_Shdr *sh;
2793 #if defined HAVE_LIBELF
2794 	sh = elf_sec_hdr(obj, elf_sec_by_idx(obj, idx));
2795 #elif defined HAVE_ELFIO
2796 	Elf64_Shdr header;
2797 	sh = elf_sec_hdr_by_idx(obj, idx, &header);
2798 #endif
2799 	if (!sh)
2800 		return false;
2801 
2802 	return sh->sh_flags & SHF_EXECINSTR;
2803 }
2804 
2805 static bool btf_needs_sanitization(struct bpf_object *obj)
2806 {
2807 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2808 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2809 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2810 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2811 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2812 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2813 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
2814 
2815 	return !has_func || !has_datasec || !has_func_global || !has_float ||
2816 	       !has_decl_tag || !has_type_tag || !has_enum64;
2817 }
2818 
2819 static int bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *btf)
2820 {
2821 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2822 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2823 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2824 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2825 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2826 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2827 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
2828 	int enum64_placeholder_id = 0;
2829 	struct btf_type *t;
2830 	int i, j, vlen;
2831 
2832 	for (i = 1; i < btf__type_cnt(btf); i++) {
2833 		t = (struct btf_type *)btf__type_by_id(btf, i);
2834 
2835 		if ((!has_datasec && btf_is_var(t)) || (!has_decl_tag && btf_is_decl_tag(t))) {
2836 			/* replace VAR/DECL_TAG with INT */
2837 			t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
2838 			/*
2839 			 * using size = 1 is the safest choice, 4 will be too
2840 			 * big and cause kernel BTF validation failure if
2841 			 * original variable took less than 4 bytes
2842 			 */
2843 			t->size = 1;
2844 			*(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
2845 		} else if (!has_datasec && btf_is_datasec(t)) {
2846 			/* replace DATASEC with STRUCT */
2847 			const struct btf_var_secinfo *v = btf_var_secinfos(t);
2848 			struct btf_member *m = btf_members(t);
2849 			struct btf_type *vt;
2850 			char *name;
2851 
2852 			name = (char *)btf__name_by_offset(btf, t->name_off);
2853 			while (*name) {
2854 				if (*name == '.')
2855 					*name = '_';
2856 				name++;
2857 			}
2858 
2859 			vlen = btf_vlen(t);
2860 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
2861 			for (j = 0; j < vlen; j++, v++, m++) {
2862 				/* order of field assignments is important */
2863 				m->offset = v->offset * 8;
2864 				m->type = v->type;
2865 				/* preserve variable name as member name */
2866 				vt = (void *)btf__type_by_id(btf, v->type);
2867 				m->name_off = vt->name_off;
2868 			}
2869 		} else if (!has_func && btf_is_func_proto(t)) {
2870 			/* replace FUNC_PROTO with ENUM */
2871 			vlen = btf_vlen(t);
2872 			t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
2873 			t->size = sizeof(__u32); /* kernel enforced */
2874 		} else if (!has_func && btf_is_func(t)) {
2875 			/* replace FUNC with TYPEDEF */
2876 			t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
2877 		} else if (!has_func_global && btf_is_func(t)) {
2878 			/* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
2879 			t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
2880 		} else if (!has_float && btf_is_float(t)) {
2881 			/* replace FLOAT with an equally-sized empty STRUCT;
2882 			 * since C compilers do not accept e.g. "float" as a
2883 			 * valid struct name, make it anonymous
2884 			 */
2885 			t->name_off = 0;
2886 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
2887 		} else if (!has_type_tag && btf_is_type_tag(t)) {
2888 			/* replace TYPE_TAG with a CONST */
2889 			t->name_off = 0;
2890 			t->info = BTF_INFO_ENC(BTF_KIND_CONST, 0, 0);
2891 		} else if (!has_enum64 && btf_is_enum(t)) {
2892 			/* clear the kflag */
2893 			t->info = btf_type_info(btf_kind(t), btf_vlen(t), false);
2894 		} else if (!has_enum64 && btf_is_enum64(t)) {
2895 			/* replace ENUM64 with a union */
2896 			struct btf_member *m;
2897 
2898 			if (enum64_placeholder_id == 0) {
2899 				enum64_placeholder_id = btf__add_int(btf, "enum64_placeholder", 1, 0);
2900 				if (enum64_placeholder_id < 0)
2901 					return enum64_placeholder_id;
2902 
2903 				t = (struct btf_type *)btf__type_by_id(btf, i);
2904 			}
2905 
2906 			m = btf_members(t);
2907 			vlen = btf_vlen(t);
2908 			t->info = BTF_INFO_ENC(BTF_KIND_UNION, 0, vlen);
2909 			for (j = 0; j < vlen; j++, m++) {
2910 				m->type = enum64_placeholder_id;
2911 				m->offset = 0;
2912 			}
2913 		}
2914 	}
2915 
2916 	return 0;
2917 }
2918 
2919 static bool libbpf_needs_btf(const struct bpf_object *obj)
2920 {
2921 	return obj->efile.btf_maps_shndx >= 0 ||
2922 	       obj->efile.st_ops_shndx >= 0 ||
2923 	       obj->efile.st_ops_link_shndx >= 0 ||
2924 	       obj->nr_extern > 0;
2925 }
2926 
2927 static bool kernel_needs_btf(const struct bpf_object *obj)
2928 {
2929 	return obj->efile.st_ops_shndx >= 0 || obj->efile.st_ops_link_shndx >= 0;
2930 }
2931 
2932 static int bpf_object__init_btf(struct bpf_object *obj,
2933 				Elf_Data *btf_data,
2934 				Elf_Data *btf_ext_data)
2935 {
2936 	int err = -ENOENT;
2937 
2938 	if (btf_data) {
2939 		obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
2940 		err = libbpf_get_error(obj->btf);
2941 		if (err) {
2942 			obj->btf = NULL;
2943 			pr_warn("Error loading ELF section %s: %d.\n", BTF_ELF_SEC, err);
2944 			goto out;
2945 		}
2946 		/* enforce 8-byte pointers for BPF-targeted BTFs */
2947 		btf__set_pointer_size(obj->btf, 8);
2948 	}
2949 	if (btf_ext_data) {
2950 		struct btf_ext_info *ext_segs[3];
2951 		int seg_num, sec_num;
2952 
2953 		if (!obj->btf) {
2954 			pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
2955 				 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
2956 			goto out;
2957 		}
2958 		obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
2959 		err = libbpf_get_error(obj->btf_ext);
2960 		if (err) {
2961 			pr_warn("Error loading ELF section %s: %d. Ignored and continue.\n",
2962 				BTF_EXT_ELF_SEC, err);
2963 			obj->btf_ext = NULL;
2964 			goto out;
2965 		}
2966 
2967 		/* setup .BTF.ext to ELF section mapping */
2968 		ext_segs[0] = &obj->btf_ext->func_info;
2969 		ext_segs[1] = &obj->btf_ext->line_info;
2970 		ext_segs[2] = &obj->btf_ext->core_relo_info;
2971 		for (seg_num = 0; seg_num < ARRAY_SIZE(ext_segs); seg_num++) {
2972 			struct btf_ext_info *seg = ext_segs[seg_num];
2973 			const struct btf_ext_info_sec *sec;
2974 			const char *sec_name;
2975 #ifdef HAVE_LIBELF
2976 			Elf_Scn *scn;
2977 #elif defined HAVE_ELFIO
2978 			psection_t sec_obj;
2979 #endif
2980 
2981 			if (seg->sec_cnt == 0)
2982 				continue;
2983 
2984 			seg->sec_idxs = calloc(seg->sec_cnt, sizeof(*seg->sec_idxs));
2985 			if (!seg->sec_idxs) {
2986 				err = -ENOMEM;
2987 				goto out;
2988 			}
2989 
2990 			sec_num = 0;
2991 			for_each_btf_ext_sec(seg, sec) {
2992 				/* preventively increment index to avoid doing
2993 				 * this before every continue below
2994 				 */
2995 				sec_num++;
2996 
2997 				sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
2998 				if (str_is_empty(sec_name))
2999 					continue;
3000 #ifdef  HAVE_LIBELF
3001 				scn = elf_sec_by_name(obj, sec_name);
3002 				if (!scn)
3003 					continue;
3004 #elif defined HAVE_ELFIO
3005 				pelfio_t elf = obj->efile.elf;
3006 				sec_obj = elfio_get_section_by_name(elf, sec_name);
3007 				if (!sec_obj)
3008 					continue;
3009 #endif
3010 #ifdef  HAVE_LIBELF
3011 				seg->sec_idxs[sec_num - 1] = elf_ndxscn(scn);
3012 #elif defined HAVE_ELFIO
3013 				seg->sec_idxs[sec_num - 1] = elfio_section_get_index(sec_obj);
3014 #endif
3015 			}
3016 		}
3017 	}
3018 out:
3019 	if (err && libbpf_needs_btf(obj)) {
3020 		pr_warn("BTF is required, but is missing or corrupted.\n");
3021 		return err;
3022 	}
3023 	return 0;
3024 }
3025 
3026 static int compare_vsi_off(const void *_a, const void *_b)
3027 {
3028 	const struct btf_var_secinfo *a = _a;
3029 	const struct btf_var_secinfo *b = _b;
3030 
3031 	return a->offset - b->offset;
3032 }
3033 
3034 static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
3035 			     struct btf_type *t)
3036 {
3037 	__u32 size = 0, i, vars = btf_vlen(t);
3038 	const char *sec_name = btf__name_by_offset(btf, t->name_off);
3039 	struct btf_var_secinfo *vsi;
3040 	bool fixup_offsets = false;
3041 	int err;
3042 
3043 	if (!sec_name) {
3044 		pr_debug("No name found in string section for DATASEC kind.\n");
3045 		return -ENOENT;
3046 	}
3047 
3048 	/* Extern-backing datasecs (.ksyms, .kconfig) have their size and
3049 	 * variable offsets set at the previous step. Further, not every
3050 	 * extern BTF VAR has corresponding ELF symbol preserved, so we skip
3051 	 * all fixups altogether for such sections and go straight to sorting
3052 	 * VARs within their DATASEC.
3053 	 */
3054 	if (strcmp(sec_name, KCONFIG_SEC) == 0 || strcmp(sec_name, KSYMS_SEC) == 0)
3055 		goto sort_vars;
3056 
3057 	/* Clang leaves DATASEC size and VAR offsets as zeroes, so we need to
3058 	 * fix this up. But BPF static linker already fixes this up and fills
3059 	 * all the sizes and offsets during static linking. So this step has
3060 	 * to be optional. But the STV_HIDDEN handling is non-optional for any
3061 	 * non-extern DATASEC, so the variable fixup loop below handles both
3062 	 * functions at the same time, paying the cost of BTF VAR <-> ELF
3063 	 * symbol matching just once.
3064 	 */
3065 	if (t->size == 0) {
3066 		err = find_elf_sec_sz(obj, sec_name, &size);
3067 		if (err || !size) {
3068 			pr_debug("sec '%s': failed to determine size from ELF: size %u, err %d\n",
3069 				 sec_name, size, err);
3070 			return -ENOENT;
3071 		}
3072 
3073 		t->size = size;
3074 		fixup_offsets = true;
3075 	}
3076 
3077 	for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
3078 		const struct btf_type *t_var;
3079 		struct btf_var *var;
3080 		const char *var_name;
3081 		Elf64_Sym *sym;
3082 
3083 		t_var = btf__type_by_id(btf, vsi->type);
3084 		if (!t_var || !btf_is_var(t_var)) {
3085 			pr_debug("sec '%s': unexpected non-VAR type found\n", sec_name);
3086 			return -EINVAL;
3087 		}
3088 
3089 		var = btf_var(t_var);
3090 		if (var->linkage == BTF_VAR_STATIC || var->linkage == BTF_VAR_GLOBAL_EXTERN)
3091 			continue;
3092 
3093 		var_name = btf__name_by_offset(btf, t_var->name_off);
3094 		if (!var_name) {
3095 			pr_debug("sec '%s': failed to find name of DATASEC's member #%d\n",
3096 				 sec_name, i);
3097 			return -ENOENT;
3098 		}
3099 
3100 		sym = find_elf_var_sym(obj, var_name);
3101 		if (IS_ERR(sym)) {
3102 			pr_debug("sec '%s': failed to find ELF symbol for VAR '%s'\n",
3103 				 sec_name, var_name);
3104 			return -ENOENT;
3105 		}
3106 
3107 		if (fixup_offsets)
3108 			vsi->offset = sym->st_value;
3109 
3110 		/* if variable is a global/weak symbol, but has restricted
3111 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF VAR
3112 		 * as static. This follows similar logic for functions (BPF
3113 		 * subprogs) and influences libbpf's further decisions about
3114 		 * whether to make global data BPF array maps as
3115 		 * BPF_F_MMAPABLE.
3116 		 */
3117 		if (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
3118 		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL)
3119 			var->linkage = BTF_VAR_STATIC;
3120 	}
3121 
3122 sort_vars:
3123 	qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
3124 	return 0;
3125 }
3126 
3127 static int bpf_object_fixup_btf(struct bpf_object *obj)
3128 {
3129 	int i, n, err = 0;
3130 
3131 	if (!obj->btf)
3132 		return 0;
3133 
3134 	n = btf__type_cnt(obj->btf);
3135 	for (i = 1; i < n; i++) {
3136 		struct btf_type *t = btf_type_by_id(obj->btf, i);
3137 
3138 		/* Loader needs to fix up some of the things compiler
3139 		 * couldn't get its hands on while emitting BTF. This
3140 		 * is section size and global variable offset. We use
3141 		 * the info from the ELF itself for this purpose.
3142 		 */
3143 		if (btf_is_datasec(t)) {
3144 			err = btf_fixup_datasec(obj, obj->btf, t);
3145 			if (err)
3146 				return err;
3147 		}
3148 	}
3149 
3150 	return 0;
3151 }
3152 
3153 static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
3154 {
3155 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
3156 	    prog->type == BPF_PROG_TYPE_LSM)
3157 		return true;
3158 
3159 	/* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
3160 	 * also need vmlinux BTF
3161 	 */
3162 	if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
3163 		return true;
3164 
3165 	return false;
3166 }
3167 
3168 static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
3169 {
3170 	struct bpf_program *prog;
3171 	int i;
3172 
3173 	/* CO-RE relocations need kernel BTF, only when btf_custom_path
3174 	 * is not specified
3175 	 */
3176 	if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
3177 		return true;
3178 
3179 	/* Support for typed ksyms needs kernel BTF */
3180 	for (i = 0; i < obj->nr_extern; i++) {
3181 		const struct extern_desc *ext;
3182 
3183 		ext = &obj->externs[i];
3184 		if (ext->type == EXT_KSYM && ext->ksym.type_id)
3185 			return true;
3186 	}
3187 
3188 	bpf_object__for_each_program(prog, obj) {
3189 		if (!prog->autoload)
3190 			continue;
3191 		if (prog_needs_vmlinux_btf(prog))
3192 			return true;
3193 	}
3194 
3195 	return false;
3196 }
3197 
3198 static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
3199 {
3200 	int err;
3201 
3202 	/* btf_vmlinux could be loaded earlier */
3203 	if (obj->btf_vmlinux || obj->gen_loader)
3204 		return 0;
3205 
3206 	if (!force && !obj_needs_vmlinux_btf(obj))
3207 		return 0;
3208 
3209 	obj->btf_vmlinux = btf__load_vmlinux_btf();
3210 	err = libbpf_get_error(obj->btf_vmlinux);
3211 	if (err) {
3212 		pr_warn("Error loading vmlinux BTF: %d\n", err);
3213 		obj->btf_vmlinux = NULL;
3214 		return err;
3215 	}
3216 	return 0;
3217 }
3218 
3219 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
3220 {
3221 	struct btf *kern_btf = obj->btf;
3222 	bool btf_mandatory, sanitize;
3223 	int i, err = 0;
3224 
3225 	if (!obj->btf)
3226 		return 0;
3227 
3228 	if (!kernel_supports(obj, FEAT_BTF)) {
3229 		if (kernel_needs_btf(obj)) {
3230 			err = -EOPNOTSUPP;
3231 			goto report;
3232 		}
3233 		pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
3234 		return 0;
3235 	}
3236 
3237 	/* Even though some subprogs are global/weak, user might prefer more
3238 	 * permissive BPF verification process that BPF verifier performs for
3239 	 * static functions, taking into account more context from the caller
3240 	 * functions. In such case, they need to mark such subprogs with
3241 	 * __attribute__((visibility("hidden"))) and libbpf will adjust
3242 	 * corresponding FUNC BTF type to be marked as static and trigger more
3243 	 * involved BPF verification process.
3244 	 */
3245 	for (i = 0; i < obj->nr_programs; i++) {
3246 		struct bpf_program *prog = &obj->programs[i];
3247 		struct btf_type *t;
3248 		const char *name;
3249 		int j, n;
3250 
3251 		if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
3252 			continue;
3253 
3254 		n = btf__type_cnt(obj->btf);
3255 		for (j = 1; j < n; j++) {
3256 			t = btf_type_by_id(obj->btf, j);
3257 			if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
3258 				continue;
3259 
3260 			name = btf__str_by_offset(obj->btf, t->name_off);
3261 			if (strcmp(name, prog->name) != 0)
3262 				continue;
3263 
3264 			t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
3265 			break;
3266 		}
3267 	}
3268 
3269 	if (!kernel_supports(obj, FEAT_BTF_DECL_TAG))
3270 		goto skip_exception_cb;
3271 	for (i = 0; i < obj->nr_programs; i++) {
3272 		struct bpf_program *prog = &obj->programs[i];
3273 		int j, k, n;
3274 
3275 		if (prog_is_subprog(obj, prog))
3276 			continue;
3277 		n = btf__type_cnt(obj->btf);
3278 		for (j = 1; j < n; j++) {
3279 			const char *str = "exception_callback:", *name;
3280 			size_t len = strlen(str);
3281 			struct btf_type *t;
3282 
3283 			t = btf_type_by_id(obj->btf, j);
3284 			if (!btf_is_decl_tag(t) || btf_decl_tag(t)->component_idx != -1)
3285 				continue;
3286 
3287 			name = btf__str_by_offset(obj->btf, t->name_off);
3288 			if (strncmp(name, str, len))
3289 				continue;
3290 
3291 			t = btf_type_by_id(obj->btf, t->type);
3292 			if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
3293 				pr_warn("prog '%s': exception_callback:<value> decl tag not applied to the main program\n",
3294 					prog->name);
3295 				return -EINVAL;
3296 			}
3297 			if (strcmp(prog->name, btf__str_by_offset(obj->btf, t->name_off)))
3298 				continue;
3299 			/* Multiple callbacks are specified for the same prog,
3300 			 * the verifier will eventually return an error for this
3301 			 * case, hence simply skip appending a subprog.
3302 			 */
3303 			if (prog->exception_cb_idx >= 0) {
3304 				prog->exception_cb_idx = -1;
3305 				break;
3306 			}
3307 
3308 			name += len;
3309 			if (str_is_empty(name)) {
3310 				pr_warn("prog '%s': exception_callback:<value> decl tag contains empty value\n",
3311 					prog->name);
3312 				return -EINVAL;
3313 			}
3314 
3315 			for (k = 0; k < obj->nr_programs; k++) {
3316 				struct bpf_program *subprog = &obj->programs[k];
3317 
3318 				if (!prog_is_subprog(obj, subprog))
3319 					continue;
3320 				if (strcmp(name, subprog->name))
3321 					continue;
3322 				/* Enforce non-hidden, as from verifier point of
3323 				 * view it expects global functions, whereas the
3324 				 * mark_btf_static fixes up linkage as static.
3325 				 */
3326 				if (!subprog->sym_global || subprog->mark_btf_static) {
3327 					pr_warn("prog '%s': exception callback %s must be a global non-hidden function\n",
3328 						prog->name, subprog->name);
3329 					return -EINVAL;
3330 				}
3331 				/* Let's see if we already saw a static exception callback with the same name */
3332 				if (prog->exception_cb_idx >= 0) {
3333 					pr_warn("prog '%s': multiple subprogs with same name as exception callback '%s'\n",
3334 					        prog->name, subprog->name);
3335 					return -EINVAL;
3336 				}
3337 				prog->exception_cb_idx = k;
3338 				break;
3339 			}
3340 
3341 			if (prog->exception_cb_idx >= 0)
3342 				continue;
3343 			pr_warn("prog '%s': cannot find exception callback '%s'\n", prog->name, name);
3344 			return -ENOENT;
3345 		}
3346 	}
3347 skip_exception_cb:
3348 
3349 	sanitize = btf_needs_sanitization(obj);
3350 	if (sanitize) {
3351 		const void *raw_data;
3352 		__u32 sz;
3353 
3354 		/* clone BTF to sanitize a copy and leave the original intact */
3355 		raw_data = btf__raw_data(obj->btf, &sz);
3356 		kern_btf = btf__new(raw_data, sz);
3357 		err = libbpf_get_error(kern_btf);
3358 		if (err)
3359 			return err;
3360 
3361 		/* enforce 8-byte pointers for BPF-targeted BTFs */
3362 		btf__set_pointer_size(obj->btf, 8);
3363 		err = bpf_object__sanitize_btf(obj, kern_btf);
3364 		if (err)
3365 			return err;
3366 	}
3367 
3368 	if (obj->gen_loader) {
3369 		__u32 raw_size = 0;
3370 		const void *raw_data = btf__raw_data(kern_btf, &raw_size);
3371 
3372 		if (!raw_data)
3373 			return -ENOMEM;
3374 		bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
3375 		/* Pretend to have valid FD to pass various fd >= 0 checks.
3376 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
3377 		 */
3378 		btf__set_fd(kern_btf, 0);
3379 	} else {
3380 		/* currently BPF_BTF_LOAD only supports log_level 1 */
3381 		err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
3382 					   obj->log_level ? 1 : 0);
3383 	}
3384 	if (sanitize) {
3385 		if (!err) {
3386 			/* move fd to libbpf's BTF */
3387 			btf__set_fd(obj->btf, btf__fd(kern_btf));
3388 			btf__set_fd(kern_btf, -1);
3389 		}
3390 		btf__free(kern_btf);
3391 	}
3392 report:
3393 	if (err) {
3394 		btf_mandatory = kernel_needs_btf(obj);
3395 		pr_warn("Error loading .BTF into kernel: %d. %s\n", err,
3396 			btf_mandatory ? "BTF is mandatory, can't proceed."
3397 				      : "BTF is optional, ignoring.");
3398 		if (!btf_mandatory)
3399 			err = 0;
3400 	}
3401 	return err;
3402 }
3403 
3404 static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
3405 {
3406 	const char *name;
3407 #if defined HAVE_LIBELF
3408 	name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
3409 #elif defined HAVE_ELFIO
3410 	name = elfio_string_get_string(obj->efile.strstring, off);
3411 #endif
3412 	if (!name) {
3413 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3414 			off, obj->path, elf_errmsg(-1));
3415 		return NULL;
3416 	}
3417 
3418 	return name;
3419 }
3420 
3421 static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
3422 {
3423 	const char *name;
3424 #if defined HAVE_LIBELF
3425 	name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
3426 #elif defined HAVE_ELFIO
3427 	name = elfio_string_get_string(obj->efile.shstring, off);
3428 #endif
3429 
3430 	if (!name) {
3431 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3432 			off, obj->path, elf_errmsg(-1));
3433 		return NULL;
3434 	}
3435 
3436 	return name;
3437 }
3438 
3439 #ifdef HAVE_LIBELF
3440 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
3441 {
3442 	Elf_Scn *scn;
3443 
3444 	scn = elf_getscn(obj->efile.elf, idx);
3445 	if (!scn) {
3446 		pr_warn("elf: failed to get section(%zu) from %s: %s\n",
3447 			idx, obj->path, elf_errmsg(-1));
3448 		return NULL;
3449 	}
3450 	return scn;
3451 }
3452 
3453 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
3454 {
3455 	Elf_Scn *scn = NULL;
3456 	Elf *elf = obj->efile.elf;
3457 	const char *sec_name;
3458 
3459 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3460 		sec_name = elf_sec_name(obj, scn);
3461 		if (!sec_name)
3462 			return NULL;
3463 
3464 		if (strcmp(sec_name, name) != 0)
3465 			continue;
3466 
3467 		return scn;
3468 	}
3469 	return NULL;
3470 }
3471 
3472 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn)
3473 {
3474 	Elf64_Shdr *shdr;
3475 
3476 	if (!scn)
3477 		return NULL;
3478 
3479 	shdr = elf64_getshdr(scn);
3480 	if (!shdr) {
3481 		pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
3482 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3483 		return NULL;
3484 	}
3485 
3486 	return shdr;
3487 }
3488 
3489 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
3490 {
3491 	const char *name;
3492 	Elf64_Shdr *sh;
3493 
3494 	if (!scn)
3495 		return NULL;
3496 
3497 	sh = elf_sec_hdr(obj, scn);
3498 	if (!sh)
3499 		return NULL;
3500 
3501 	name = elf_sec_str(obj, sh->sh_name);
3502 	if (!name) {
3503 		pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
3504 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3505 		return NULL;
3506 	}
3507 
3508 	return name;
3509 }
3510 #elif defined HAVE_ELFIO
3511 static Elf64_Shdr *elf_sec_hdr_by_idx(const struct bpf_object *obj, size_t idx, Elf64_Shdr *sheader)
3512 {
3513 	psection_t psection = elfio_get_section_by_index(obj->efile.elf, idx);
3514 
3515 	sheader->sh_name = elfio_section_get_name_string_offset(psection);
3516 	sheader->sh_type = elfio_section_get_type(psection);
3517 	sheader->sh_flags = elfio_section_get_flags(psection);
3518 	sheader->sh_addr = elfio_section_get_address(psection);
3519 	sheader->sh_offset = elfio_section_get_offset(psection);
3520 	sheader->sh_size = elfio_section_get_size(psection);
3521 	sheader->sh_link = elfio_section_get_link(psection);
3522 	sheader->sh_info = elfio_section_get_info(psection);
3523 	sheader->sh_addralign = elfio_section_get_addr_align(psection);
3524 	sheader->sh_entsize = elfio_section_get_entry_size(psection);
3525 
3526 	return sheader;
3527 }
3528 
3529 static const char *elf_sec_name_by_idx(const struct bpf_object *obj, size_t idx)
3530 {
3531 	const char *name;
3532 	Elf64_Shdr sh;
3533 
3534 	elf_sec_hdr_by_idx(obj, idx, &sh);
3535 
3536 	name = elf_sec_str(obj, sh.sh_name);
3537 	if (!name) {
3538 		pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
3539 			idx, obj->path, elf_errmsg(-1));
3540 		return NULL;
3541 	}
3542 
3543 	return name;
3544 }
3545 #endif
3546 
3547 #if defined HAVE_LIBELF
3548 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
3549 {
3550 	Elf_Data *data;
3551 
3552 	if (!scn)
3553 		return NULL;
3554 
3555 	data = elf_getdata(scn, 0);
3556 	if (!data) {
3557 		pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
3558 			elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
3559 			obj->path, elf_errmsg(-1));
3560 		return NULL;
3561 	}
3562 
3563 	return data;
3564 }
3565 #elif defined HAVE_ELFIO
3566 static Elf_Data *elf_sec_data_by_name(const struct bpf_object *obj, const char *name, Elf_Data *data)
3567 {
3568 	pelfio_t elf = obj->efile.elf;
3569 	psection_t psection_name = elfio_get_section_by_name(elf, name);
3570 	data->d_buf = (void*)elfio_section_get_data(psection_name);
3571 	data->d_size = elfio_section_get_size(psection_name);
3572 
3573 	return data;
3574 }
3575 
3576 static Elf_Data *elf_sec_data_by_idx(const struct bpf_object *obj, size_t idx, Elf_Data *data)
3577 {
3578 	pelfio_t elf = obj->efile.elf;
3579 	psection_t psection_index = elfio_get_section_by_index(elf, idx);
3580 	data->d_buf = (void*)elfio_section_get_data(psection_index);
3581 	data->d_size = elfio_section_get_size(psection_index);
3582 
3583 	return data;
3584 }
3585 #endif
3586 
3587 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx)
3588 {
3589 	if (idx >= obj->efile.symbols->d_size / sizeof(Elf64_Sym))
3590 		return NULL;
3591 
3592 	return (Elf64_Sym *)obj->efile.symbols->d_buf + idx;
3593 }
3594 
3595 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx)
3596 {
3597 	if (idx >= data->d_size / sizeof(Elf64_Rel))
3598 		return NULL;
3599 
3600 	return (Elf64_Rel *)data->d_buf + idx;
3601 }
3602 
3603 static bool is_sec_name_dwarf(const char *name)
3604 {
3605 	/* approximation, but the actual list is too long */
3606 	return str_has_pfx(name, ".debug_");
3607 }
3608 
3609 static bool ignore_elf_section(Elf64_Shdr *hdr, const char *name)
3610 {
3611 	/* no special handling of .strtab */
3612 	if (hdr->sh_type == SHT_STRTAB)
3613 		return true;
3614 
3615 	/* ignore .llvm_addrsig section as well */
3616 	if (hdr->sh_type == SHT_LLVM_ADDRSIG)
3617 		return true;
3618 
3619 	/* no subprograms will lead to an empty .text section, ignore it */
3620 	if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
3621 	    strcmp(name, ".text") == 0)
3622 		return true;
3623 
3624 	/* DWARF sections */
3625 	if (is_sec_name_dwarf(name))
3626 		return true;
3627 
3628 	if (str_has_pfx(name, ".rel")) {
3629 		name += sizeof(".rel") - 1;
3630 		/* DWARF section relocations */
3631 		if (is_sec_name_dwarf(name))
3632 			return true;
3633 
3634 		/* .BTF and .BTF.ext don't need relocations */
3635 		if (strcmp(name, BTF_ELF_SEC) == 0 ||
3636 		    strcmp(name, BTF_EXT_ELF_SEC) == 0)
3637 			return true;
3638 	}
3639 
3640 	return false;
3641 }
3642 
3643 static int cmp_progs(const void *_a, const void *_b)
3644 {
3645 	const struct bpf_program *a = _a;
3646 	const struct bpf_program *b = _b;
3647 
3648 	if (a->sec_idx != b->sec_idx)
3649 		return a->sec_idx < b->sec_idx ? -1 : 1;
3650 
3651 	/* sec_insn_off can't be the same within the section */
3652 	return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
3653 }
3654 
3655 static int bpf_object__elf_collect(struct bpf_object *obj)
3656 {
3657 	struct elf_sec_desc *sec_desc;
3658 #if defined HAVE_LIBELF
3659 	Elf *elf = obj->efile.elf;
3660 #elif defined HAVE_ELFIO
3661 	pelfio_t elf = obj->efile.elf;
3662 #endif
3663 	Elf_Data *btf_ext_data = NULL;
3664 	Elf_Data *btf_data = NULL;
3665 	int idx = 0, err = 0;
3666 	const char *name;
3667 	Elf_Data *data;
3668 #ifdef HAVE_LIBELF
3669 	Elf_Scn *scn;
3670 #endif
3671 	Elf64_Shdr *sh;
3672 #ifdef HAVE_ELFIO
3673 	Elf64_Shdr secHeader = {0};
3674 	sh = &secHeader;
3675 #endif
3676 
3677 	/* ELF section indices are 0-based, but sec #0 is special "invalid"
3678 	 * section. Since section count retrieved by elf_getshdrnum() does
3679 	 * include sec #0, it is already the necessary size of an array to keep
3680 	 * all the sections.
3681 	 */
3682 #ifdef HAVE_LIBELF
3683 	if (elf_getshdrnum(obj->efile.elf, &obj->efile.sec_cnt)) {
3684 		pr_warn("elf: failed to get the number of sections for %s: %s\n",
3685 			obj->path, elf_errmsg(-1));
3686 		return -LIBBPF_ERRNO__FORMAT;
3687 	}
3688 #elif defined HAVE_ELFIO
3689 	obj->efile.sec_cnt = elfio_get_sections_num(elf);
3690 #endif
3691 	obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs));
3692 	if (!obj->efile.secs)
3693 		return -ENOMEM;
3694 
3695 	/* a bunch of ELF parsing functionality depends on processing symbols,
3696 	 * so do the first pass and find the symbol table
3697 	 */
3698 #if defined HAVE_LIBELF
3699 	scn = NULL;
3700 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3701 		sh = elf_sec_hdr(obj, scn);
3702 #elif defined HAVE_ELFIO
3703 	int secno = elfio_get_sections_num(elf);
3704     for ( int i = 0; i < secno; i++ ) {
3705 		Elf_Data realdata;
3706 		sh = elf_sec_hdr_by_idx(obj, i, sh);
3707 #endif
3708 		if (!sh)
3709 			return -LIBBPF_ERRNO__FORMAT;
3710 
3711 		if (sh->sh_type == SHT_SYMTAB) {
3712 			if (obj->efile.symbols) {
3713 				pr_warn("elf: multiple symbol tables in %s\n", obj->path);
3714 				return -LIBBPF_ERRNO__FORMAT;
3715 			}
3716 #if defined HAVE_LIBELF
3717 			data = elf_sec_data(obj, scn);
3718 #elif defined HAVE_ELFIO
3719 			data = elf_sec_data_by_idx(obj, i, &realdata);
3720 #endif
3721 			if (!data)
3722 				return -LIBBPF_ERRNO__FORMAT;
3723 #ifdef HAVE_LIBELF
3724 			idx = elf_ndxscn(scn);
3725 #endif
3726 
3727 #if defined HAVE_LIBELF
3728 			obj->efile.symbols = data;
3729 #elif defined HAVE_ELFIO
3730 			obj->efile.realsymbols.d_buf = data->d_buf;
3731 			obj->efile.realsymbols.d_size = data->d_size;
3732 			obj->efile.symbols = &(obj->efile.realsymbols);
3733 #endif
3734 
3735 #if defined HAVE_LIBELF
3736 			obj->efile.symbols_shndx = idx;
3737 #elif defined HAVE_ELFIO
3738 			obj->efile.symbols_shndx = i;
3739 #endif
3740 			obj->efile.strtabidx = sh->sh_link;
3741 		}
3742 	}
3743 
3744 #ifdef HAVE_ELFIO
3745 	pstring_t shstring;
3746 	pstring_t strstring;
3747 
3748 	psection_t psection = elfio_get_section_by_index(elf, obj->efile.strtabidx);
3749 	if (!psection)
3750 		return -LIBBPF_ERRNO__FORMAT;
3751 	strstring = elfio_string_section_accessor_new(psection);
3752 
3753 	psection = elfio_get_section_by_index(elf, obj->efile.shstrndx);
3754 	if (!psection)
3755 		return -LIBBPF_ERRNO__FORMAT;
3756 	shstring = elfio_string_section_accessor_new(psection);
3757 
3758 	if (!strstring || !shstring)
3759 		return -LIBBPF_ERRNO__FORMAT;
3760 	obj->efile.strstring = strstring;
3761 	obj->efile.shstring = shstring;
3762 #endif
3763 
3764 	if (!obj->efile.symbols) {
3765 		pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
3766 			obj->path);
3767 		return -ENOENT;
3768 	}
3769 
3770 #ifdef HAVE_LIBELF
3771 	scn = NULL;
3772 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3773 #elif defined HAVE_ELFIO
3774 	for ( int i = 0; i < secno; i++ ) {
3775 		psection_t ptmpsection = elfio_get_section_by_index(elf, i);
3776 		elf_sec_hdr_by_idx(obj, i, sh);
3777 #endif
3778 
3779 #if defined HAVE_LIBELF
3780 		idx = elf_ndxscn(scn);
3781 #elif defined HAVE_ELFIO
3782 		idx = i;
3783 #endif
3784 		sec_desc = &obj->efile.secs[idx];
3785 
3786 #if defined HAVE_LIBELF
3787 		sh = elf_sec_hdr(obj, scn);
3788 #elif defined HAVE_ELFIO
3789 		sh = elf_sec_hdr_by_idx(obj, i, sh);
3790 #endif
3791 
3792 		if (!sh)
3793 			return -LIBBPF_ERRNO__FORMAT;
3794 
3795 		name = elf_sec_str(obj, sh->sh_name);
3796 		if (!name)
3797 			return -LIBBPF_ERRNO__FORMAT;
3798 
3799 		if (ignore_elf_section(sh, name))
3800 			continue;
3801 
3802 #if defined HAVE_LIBELF
3803 		data = elf_sec_data(obj, scn);
3804 #elif defined HAVE_ELFIO
3805 		data = elf_sec_data_by_idx(obj, i, &sec_desc->realdata);
3806 #endif
3807 		if (!data)
3808 			return -LIBBPF_ERRNO__FORMAT;
3809 
3810 		pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
3811 			 idx, name, (unsigned long)data->d_size,
3812 			 (int)sh->sh_link, (unsigned long)sh->sh_flags,
3813 			 (int)sh->sh_type);
3814 
3815 		if (strcmp(name, "license") == 0) {
3816 			err = bpf_object__init_license(obj, data->d_buf, data->d_size);
3817 			if (err)
3818 				return err;
3819 		} else if (strcmp(name, "version") == 0) {
3820 			err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
3821 			if (err)
3822 				return err;
3823 		} else if (strcmp(name, "maps") == 0) {
3824 			pr_warn("elf: legacy map definitions in 'maps' section are not supported by libbpf v1.0+\n");
3825 			return -ENOTSUP;
3826 		} else if (strcmp(name, MAPS_ELF_SEC) == 0) {
3827 			obj->efile.btf_maps_shndx = idx;
3828 		} else if (strcmp(name, BTF_ELF_SEC) == 0) {
3829 			if (sh->sh_type != SHT_PROGBITS)
3830 				return -LIBBPF_ERRNO__FORMAT;
3831 			btf_data = data;
3832 		} else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
3833 			if (sh->sh_type != SHT_PROGBITS)
3834 				return -LIBBPF_ERRNO__FORMAT;
3835 			btf_ext_data = data;
3836 		} else if (sh->sh_type == SHT_SYMTAB) {
3837 			/* already processed during the first pass above */
3838 		} else if (sh->sh_type == SHT_PROGBITS && data->d_size > 0) {
3839 			if (sh->sh_flags & SHF_EXECINSTR) {
3840 				if (strcmp(name, ".text") == 0)
3841 					obj->efile.text_shndx = idx;
3842 				err = bpf_object__add_programs(obj, data, name, idx);
3843 				if (err)
3844 					return err;
3845 			} else if (strcmp(name, DATA_SEC) == 0 ||
3846 				   str_has_pfx(name, DATA_SEC ".")) {
3847 				sec_desc->sec_type = SEC_DATA;
3848 #if defined HAVE_LIBELF
3849 				sec_desc->shdr = sh;
3850 				sec_desc->data = data;
3851 #elif defined HAVE_ELFIO
3852 				sec_desc->psection = ptmpsection;
3853 				sec_desc->realdata.d_buf = data->d_buf;
3854 				sec_desc->realdata.d_size = data->d_size;
3855 				sec_desc->data = &(sec_desc->realdata);
3856 #endif
3857 			} else if (strcmp(name, RODATA_SEC) == 0 ||
3858 				   str_has_pfx(name, RODATA_SEC ".")) {
3859 				sec_desc->sec_type = SEC_RODATA;
3860 #if defined HAVE_LIBELF
3861 				sec_desc->shdr = sh;
3862 				sec_desc->data = data;
3863 #elif defined HAVE_ELFIO
3864 				sec_desc->psection = ptmpsection;
3865 				sec_desc->realdata.d_buf = data->d_buf;
3866 				sec_desc->realdata.d_size = data->d_size;
3867 				sec_desc->data = &(sec_desc->realdata);
3868 #endif
3869 
3870 			} else if (strcmp(name, STRUCT_OPS_SEC) == 0) {
3871 #if defined HAVE_LIBELF
3872 				obj->efile.st_ops_data = data;
3873 #elif defined HAVE_ELFIO
3874 				obj->efile.realst_ops_data.d_buf = data->d_buf;
3875 				obj->efile.realst_ops_data.d_size = data->d_size;
3876 				obj->efile.st_ops_data = &(obj->efile.realst_ops_data);
3877 #endif
3878 				obj->efile.st_ops_shndx = idx;
3879 			} else if (strcmp(name, STRUCT_OPS_LINK_SEC) == 0) {
3880 #if defined HAVE_LIBELF
3881 				obj->efile.st_ops_link_data = data;
3882 #elif defined HAVE_ELFIO
3883 				obj->efile.realst_ops_link_data.d_buf = data->d_buf;
3884 				obj->efile.realst_ops_link_data.d_size = data->d_size;
3885 				obj->efile.st_ops_link_data = &(obj->efile.realst_ops_link_data);
3886 #endif
3887 				obj->efile.st_ops_link_shndx = idx;
3888 			} else {
3889 				pr_info("elf: skipping unrecognized data section(%d) %s\n",
3890 					idx, name);
3891 			}
3892 		} else if (sh->sh_type == SHT_REL) {
3893 			int targ_sec_idx = sh->sh_info; /* points to other section */
3894 
3895 			if (sh->sh_entsize != sizeof(Elf64_Rel) ||
3896 			    targ_sec_idx >= obj->efile.sec_cnt)
3897 				return -LIBBPF_ERRNO__FORMAT;
3898 
3899 			/* Only do relo for section with exec instructions */
3900 			if (!section_have_execinstr(obj, targ_sec_idx) &&
3901 			    strcmp(name, ".rel" STRUCT_OPS_SEC) &&
3902 			    strcmp(name, ".rel" STRUCT_OPS_LINK_SEC) &&
3903 			    strcmp(name, ".rel" MAPS_ELF_SEC)) {
3904 #if defined HAVE_LIBELF
3905 				pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
3906 					idx, name, targ_sec_idx,
3907 					elf_sec_name(obj, elf_sec_by_idx(obj, targ_sec_idx)) ?: "<?>");
3908 #elif defined HAVE_ELFIO
3909 				pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
3910 					idx, name, targ_sec_idx,
3911 					elf_sec_name_by_idx(obj, targ_sec_idx) ?: "<?>");
3912 #endif
3913 				continue;
3914 			}
3915 
3916 			sec_desc->sec_type = SEC_RELO;
3917 #if defined HAVE_LIBELF
3918 			sec_desc->shdr = sh;
3919 #elif defined HAVE_ELFIO
3920 			sec_desc->psection = ptmpsection;
3921 #endif
3922 			sec_desc->data = data;
3923 		} else if (sh->sh_type == SHT_NOBITS && (strcmp(name, BSS_SEC) == 0 ||
3924 							 str_has_pfx(name, BSS_SEC "."))) {
3925 			sec_desc->sec_type = SEC_BSS;
3926 #if defined HAVE_LIBELF
3927 			sec_desc->shdr = sh;
3928 #elif defined HAVE_ELFIO
3929 			sec_desc->psection = ptmpsection;
3930 #endif
3931 			sec_desc->data = data;
3932 		} else {
3933 			pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
3934 				(size_t)sh->sh_size);
3935 		}
3936 	}
3937 
3938 	if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
3939 		pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
3940 		return -LIBBPF_ERRNO__FORMAT;
3941 	}
3942 
3943 	/* sort BPF programs by section name and in-section instruction offset
3944 	 * for faster search
3945 	 */
3946 	if (obj->nr_programs)
3947 		qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
3948 
3949 	return bpf_object__init_btf(obj, btf_data, btf_ext_data);
3950 }
3951 
3952 static bool sym_is_extern(const Elf64_Sym *sym)
3953 {
3954 	int bind = ELF64_ST_BIND(sym->st_info);
3955 	/* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
3956 	return sym->st_shndx == SHN_UNDEF &&
3957 	       (bind == STB_GLOBAL || bind == STB_WEAK) &&
3958 	       ELF64_ST_TYPE(sym->st_info) == STT_NOTYPE;
3959 }
3960 
3961 static bool sym_is_subprog(const Elf64_Sym *sym, int text_shndx)
3962 {
3963 	int bind = ELF64_ST_BIND(sym->st_info);
3964 	int type = ELF64_ST_TYPE(sym->st_info);
3965 
3966 	/* in .text section */
3967 	if (sym->st_shndx != text_shndx)
3968 		return false;
3969 
3970 	/* local function */
3971 	if (bind == STB_LOCAL && type == STT_SECTION)
3972 		return true;
3973 
3974 	/* global function */
3975 	return (bind == STB_GLOBAL || bind == STB_WEAK) && type == STT_FUNC;
3976 }
3977 
3978 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
3979 {
3980 	const struct btf_type *t;
3981 	const char *tname;
3982 	int i, n;
3983 
3984 	if (!btf)
3985 		return -ESRCH;
3986 
3987 	n = btf__type_cnt(btf);
3988 	for (i = 1; i < n; i++) {
3989 		t = btf__type_by_id(btf, i);
3990 
3991 		if (!btf_is_var(t) && !btf_is_func(t))
3992 			continue;
3993 
3994 		tname = btf__name_by_offset(btf, t->name_off);
3995 		if (strcmp(tname, ext_name))
3996 			continue;
3997 
3998 		if (btf_is_var(t) &&
3999 		    btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
4000 			return -EINVAL;
4001 
4002 		if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
4003 			return -EINVAL;
4004 
4005 		return i;
4006 	}
4007 
4008 	return -ENOENT;
4009 }
4010 
4011 static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
4012 	const struct btf_var_secinfo *vs;
4013 	const struct btf_type *t;
4014 	int i, j, n;
4015 
4016 	if (!btf)
4017 		return -ESRCH;
4018 
4019 	n = btf__type_cnt(btf);
4020 	for (i = 1; i < n; i++) {
4021 		t = btf__type_by_id(btf, i);
4022 
4023 		if (!btf_is_datasec(t))
4024 			continue;
4025 
4026 		vs = btf_var_secinfos(t);
4027 		for (j = 0; j < btf_vlen(t); j++, vs++) {
4028 			if (vs->type == ext_btf_id)
4029 				return i;
4030 		}
4031 	}
4032 
4033 	return -ENOENT;
4034 }
4035 
4036 static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
4037 				     bool *is_signed)
4038 {
4039 	const struct btf_type *t;
4040 	const char *name;
4041 
4042 	t = skip_mods_and_typedefs(btf, id, NULL);
4043 	name = btf__name_by_offset(btf, t->name_off);
4044 
4045 	if (is_signed)
4046 		*is_signed = false;
4047 	switch (btf_kind(t)) {
4048 	case BTF_KIND_INT: {
4049 		int enc = btf_int_encoding(t);
4050 
4051 		if (enc & BTF_INT_BOOL)
4052 			return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
4053 		if (is_signed)
4054 			*is_signed = enc & BTF_INT_SIGNED;
4055 		if (t->size == 1)
4056 			return KCFG_CHAR;
4057 		if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
4058 			return KCFG_UNKNOWN;
4059 		return KCFG_INT;
4060 	}
4061 	case BTF_KIND_ENUM:
4062 		if (t->size != 4)
4063 			return KCFG_UNKNOWN;
4064 		if (strcmp(name, "libbpf_tristate"))
4065 			return KCFG_UNKNOWN;
4066 		return KCFG_TRISTATE;
4067 	case BTF_KIND_ENUM64:
4068 		if (strcmp(name, "libbpf_tristate"))
4069 			return KCFG_UNKNOWN;
4070 		return KCFG_TRISTATE;
4071 	case BTF_KIND_ARRAY:
4072 		if (btf_array(t)->nelems == 0)
4073 			return KCFG_UNKNOWN;
4074 		if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
4075 			return KCFG_UNKNOWN;
4076 		return KCFG_CHAR_ARR;
4077 	default:
4078 		return KCFG_UNKNOWN;
4079 	}
4080 }
4081 
4082 static int cmp_externs(const void *_a, const void *_b)
4083 {
4084 	const struct extern_desc *a = _a;
4085 	const struct extern_desc *b = _b;
4086 
4087 	if (a->type != b->type)
4088 		return a->type < b->type ? -1 : 1;
4089 
4090 	if (a->type == EXT_KCFG) {
4091 		/* descending order by alignment requirements */
4092 		if (a->kcfg.align != b->kcfg.align)
4093 			return a->kcfg.align > b->kcfg.align ? -1 : 1;
4094 		/* ascending order by size, within same alignment class */
4095 		if (a->kcfg.sz != b->kcfg.sz)
4096 			return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
4097 	}
4098 
4099 	/* resolve ties by name */
4100 	return strcmp(a->name, b->name);
4101 }
4102 
4103 static int find_int_btf_id(const struct btf *btf)
4104 {
4105 	const struct btf_type *t;
4106 	int i, n;
4107 
4108 	n = btf__type_cnt(btf);
4109 	for (i = 1; i < n; i++) {
4110 		t = btf__type_by_id(btf, i);
4111 
4112 		if (btf_is_int(t) && btf_int_bits(t) == 32)
4113 			return i;
4114 	}
4115 
4116 	return 0;
4117 }
4118 
4119 static int add_dummy_ksym_var(struct btf *btf)
4120 {
4121 	int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
4122 	const struct btf_var_secinfo *vs;
4123 	const struct btf_type *sec;
4124 
4125 	if (!btf)
4126 		return 0;
4127 
4128 	sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
4129 					    BTF_KIND_DATASEC);
4130 	if (sec_btf_id < 0)
4131 		return 0;
4132 
4133 	sec = btf__type_by_id(btf, sec_btf_id);
4134 	vs = btf_var_secinfos(sec);
4135 	for (i = 0; i < btf_vlen(sec); i++, vs++) {
4136 		const struct btf_type *vt;
4137 
4138 		vt = btf__type_by_id(btf, vs->type);
4139 		if (btf_is_func(vt))
4140 			break;
4141 	}
4142 
4143 	/* No func in ksyms sec.  No need to add dummy var. */
4144 	if (i == btf_vlen(sec))
4145 		return 0;
4146 
4147 	int_btf_id = find_int_btf_id(btf);
4148 	dummy_var_btf_id = btf__add_var(btf,
4149 					"dummy_ksym",
4150 					BTF_VAR_GLOBAL_ALLOCATED,
4151 					int_btf_id);
4152 	if (dummy_var_btf_id < 0)
4153 		pr_warn("cannot create a dummy_ksym var\n");
4154 
4155 	return dummy_var_btf_id;
4156 }
4157 
4158 static int bpf_object__collect_externs(struct bpf_object *obj)
4159 {
4160 	struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
4161 	const struct btf_type *t;
4162 	struct extern_desc *ext;
4163 	int i, n, off, dummy_var_btf_id;
4164 	const char *ext_name, *sec_name;
4165 	size_t ext_essent_len;
4166 #ifdef HAVE_LIBELF
4167 	Elf_Scn *scn;
4168 #endif
4169 	Elf64_Shdr *sh;
4170 	Elf64_Shdr shheader;
4171 
4172 	if (!obj->efile.symbols)
4173 		return 0;
4174 
4175 #if defined HAVE_LIBELF
4176 	scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
4177 	sh = elf_sec_hdr(obj, scn);
4178 #elif defined HAVE_ELFIO
4179 	sh = &shheader;
4180 	sh = elf_sec_hdr_by_idx(obj, obj->efile.symbols_shndx, sh);
4181 #endif
4182 
4183 	if (!sh || sh->sh_entsize != sizeof(Elf64_Sym))
4184 		return -LIBBPF_ERRNO__FORMAT;
4185 
4186 	dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
4187 	if (dummy_var_btf_id < 0)
4188 		return dummy_var_btf_id;
4189 
4190 	n = sh->sh_size / sh->sh_entsize;
4191 	pr_debug("looking for externs among %d symbols...\n", n);
4192 
4193 	for (i = 0; i < n; i++) {
4194 		Elf64_Sym *sym = elf_sym_by_idx(obj, i);
4195 
4196 		if (!sym)
4197 			return -LIBBPF_ERRNO__FORMAT;
4198 		if (!sym_is_extern(sym))
4199 			continue;
4200 		ext_name = elf_sym_str(obj, sym->st_name);
4201 		if (!ext_name || !ext_name[0])
4202 			continue;
4203 
4204 		ext = obj->externs;
4205 		ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
4206 		if (!ext)
4207 			return -ENOMEM;
4208 		obj->externs = ext;
4209 		ext = &ext[obj->nr_extern];
4210 		memset(ext, 0, sizeof(*ext));
4211 		obj->nr_extern++;
4212 
4213 		ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
4214 		if (ext->btf_id <= 0) {
4215 			pr_warn("failed to find BTF for extern '%s': %d\n",
4216 				ext_name, ext->btf_id);
4217 			return ext->btf_id;
4218 		}
4219 		t = btf__type_by_id(obj->btf, ext->btf_id);
4220 		ext->name = btf__name_by_offset(obj->btf, t->name_off);
4221 		ext->sym_idx = i;
4222 		ext->is_weak = ELF64_ST_BIND(sym->st_info) == STB_WEAK;
4223 
4224 		ext_essent_len = bpf_core_essential_name_len(ext->name);
4225 		ext->essent_name = NULL;
4226 		if (ext_essent_len != strlen(ext->name)) {
4227 			ext->essent_name = strndup(ext->name, ext_essent_len);
4228 			if (!ext->essent_name)
4229 				return -ENOMEM;
4230 		}
4231 
4232 		ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
4233 		if (ext->sec_btf_id <= 0) {
4234 			pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
4235 				ext_name, ext->btf_id, ext->sec_btf_id);
4236 			return ext->sec_btf_id;
4237 		}
4238 		sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
4239 		sec_name = btf__name_by_offset(obj->btf, sec->name_off);
4240 
4241 		if (strcmp(sec_name, KCONFIG_SEC) == 0) {
4242 			if (btf_is_func(t)) {
4243 				pr_warn("extern function %s is unsupported under %s section\n",
4244 					ext->name, KCONFIG_SEC);
4245 				return -ENOTSUP;
4246 			}
4247 			kcfg_sec = sec;
4248 			ext->type = EXT_KCFG;
4249 			ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
4250 			if (ext->kcfg.sz <= 0) {
4251 				pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
4252 					ext_name, ext->kcfg.sz);
4253 				return ext->kcfg.sz;
4254 			}
4255 			ext->kcfg.align = btf__align_of(obj->btf, t->type);
4256 			if (ext->kcfg.align <= 0) {
4257 				pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
4258 					ext_name, ext->kcfg.align);
4259 				return -EINVAL;
4260 			}
4261 			ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
4262 							&ext->kcfg.is_signed);
4263 			if (ext->kcfg.type == KCFG_UNKNOWN) {
4264 				pr_warn("extern (kcfg) '%s': type is unsupported\n", ext_name);
4265 				return -ENOTSUP;
4266 			}
4267 		} else if (strcmp(sec_name, KSYMS_SEC) == 0) {
4268 			ksym_sec = sec;
4269 			ext->type = EXT_KSYM;
4270 			skip_mods_and_typedefs(obj->btf, t->type,
4271 					       &ext->ksym.type_id);
4272 		} else {
4273 			pr_warn("unrecognized extern section '%s'\n", sec_name);
4274 			return -ENOTSUP;
4275 		}
4276 	}
4277 	pr_debug("collected %d externs total\n", obj->nr_extern);
4278 
4279 	if (!obj->nr_extern)
4280 		return 0;
4281 
4282 	/* sort externs by type, for kcfg ones also by (align, size, name) */
4283 	qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
4284 
4285 	/* for .ksyms section, we need to turn all externs into allocated
4286 	 * variables in BTF to pass kernel verification; we do this by
4287 	 * pretending that each extern is a 8-byte variable
4288 	 */
4289 	if (ksym_sec) {
4290 		/* find existing 4-byte integer type in BTF to use for fake
4291 		 * extern variables in DATASEC
4292 		 */
4293 		int int_btf_id = find_int_btf_id(obj->btf);
4294 		/* For extern function, a dummy_var added earlier
4295 		 * will be used to replace the vs->type and
4296 		 * its name string will be used to refill
4297 		 * the missing param's name.
4298 		 */
4299 		const struct btf_type *dummy_var;
4300 
4301 		dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
4302 		for (i = 0; i < obj->nr_extern; i++) {
4303 			ext = &obj->externs[i];
4304 			if (ext->type != EXT_KSYM)
4305 				continue;
4306 			pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
4307 				 i, ext->sym_idx, ext->name);
4308 		}
4309 
4310 		sec = ksym_sec;
4311 		n = btf_vlen(sec);
4312 		for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
4313 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4314 			struct btf_type *vt;
4315 
4316 			vt = (void *)btf__type_by_id(obj->btf, vs->type);
4317 			ext_name = btf__name_by_offset(obj->btf, vt->name_off);
4318 			ext = find_extern_by_name(obj, ext_name);
4319 			if (!ext) {
4320 				pr_warn("failed to find extern definition for BTF %s '%s'\n",
4321 					btf_kind_str(vt), ext_name);
4322 				return -ESRCH;
4323 			}
4324 			if (btf_is_func(vt)) {
4325 				const struct btf_type *func_proto;
4326 				struct btf_param *param;
4327 				int j;
4328 
4329 				func_proto = btf__type_by_id(obj->btf,
4330 							     vt->type);
4331 				param = btf_params(func_proto);
4332 				/* Reuse the dummy_var string if the
4333 				 * func proto does not have param name.
4334 				 */
4335 				for (j = 0; j < btf_vlen(func_proto); j++)
4336 					if (param[j].type && !param[j].name_off)
4337 						param[j].name_off =
4338 							dummy_var->name_off;
4339 				vs->type = dummy_var_btf_id;
4340 				vt->info &= ~0xffff;
4341 				vt->info |= BTF_FUNC_GLOBAL;
4342 			} else {
4343 				btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4344 				vt->type = int_btf_id;
4345 			}
4346 			vs->offset = off;
4347 			vs->size = sizeof(int);
4348 		}
4349 		sec->size = off;
4350 	}
4351 
4352 	if (kcfg_sec) {
4353 		sec = kcfg_sec;
4354 		/* for kcfg externs calculate their offsets within a .kconfig map */
4355 		off = 0;
4356 		for (i = 0; i < obj->nr_extern; i++) {
4357 			ext = &obj->externs[i];
4358 			if (ext->type != EXT_KCFG)
4359 				continue;
4360 
4361 			ext->kcfg.data_off = roundup(off, ext->kcfg.align);
4362 			off = ext->kcfg.data_off + ext->kcfg.sz;
4363 			pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
4364 				 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
4365 		}
4366 		sec->size = off;
4367 		n = btf_vlen(sec);
4368 		for (i = 0; i < n; i++) {
4369 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4370 
4371 			t = btf__type_by_id(obj->btf, vs->type);
4372 			ext_name = btf__name_by_offset(obj->btf, t->name_off);
4373 			ext = find_extern_by_name(obj, ext_name);
4374 			if (!ext) {
4375 				pr_warn("failed to find extern definition for BTF var '%s'\n",
4376 					ext_name);
4377 				return -ESRCH;
4378 			}
4379 			btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4380 			vs->offset = ext->kcfg.data_off;
4381 		}
4382 	}
4383 	return 0;
4384 }
4385 
4386 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog)
4387 {
4388 	return prog->sec_idx == obj->efile.text_shndx;
4389 }
4390 
4391 struct bpf_program *
4392 bpf_object__find_program_by_name(const struct bpf_object *obj,
4393 				 const char *name)
4394 {
4395 	struct bpf_program *prog;
4396 
4397 	bpf_object__for_each_program(prog, obj) {
4398 		if (prog_is_subprog(obj, prog))
4399 			continue;
4400 		if (!strcmp(prog->name, name))
4401 			return prog;
4402 	}
4403 	return errno = ENOENT, NULL;
4404 }
4405 
4406 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
4407 				      int shndx)
4408 {
4409 	switch (obj->efile.secs[shndx].sec_type) {
4410 	case SEC_BSS:
4411 	case SEC_DATA:
4412 	case SEC_RODATA:
4413 		return true;
4414 	default:
4415 		return false;
4416 	}
4417 }
4418 
4419 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
4420 				      int shndx)
4421 {
4422 	return shndx == obj->efile.btf_maps_shndx;
4423 }
4424 
4425 static enum libbpf_map_type
4426 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
4427 {
4428 	if (shndx == obj->efile.symbols_shndx)
4429 		return LIBBPF_MAP_KCONFIG;
4430 
4431 	switch (obj->efile.secs[shndx].sec_type) {
4432 	case SEC_BSS:
4433 		return LIBBPF_MAP_BSS;
4434 	case SEC_DATA:
4435 		return LIBBPF_MAP_DATA;
4436 	case SEC_RODATA:
4437 		return LIBBPF_MAP_RODATA;
4438 	default:
4439 		return LIBBPF_MAP_UNSPEC;
4440 	}
4441 }
4442 
4443 static int bpf_program__record_reloc(struct bpf_program *prog,
4444 				     struct reloc_desc *reloc_desc,
4445 				     __u32 insn_idx, const char *sym_name,
4446 				     const Elf64_Sym *sym, const Elf64_Rel *rel)
4447 {
4448 	struct bpf_insn *insn = &prog->insns[insn_idx];
4449 	size_t map_idx, nr_maps = prog->obj->nr_maps;
4450 	struct bpf_object *obj = prog->obj;
4451 	__u32 shdr_idx = sym->st_shndx;
4452 	enum libbpf_map_type type;
4453 	const char *sym_sec_name;
4454 	struct bpf_map *map;
4455 
4456 	if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
4457 		pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n",
4458 			prog->name, sym_name, insn_idx, insn->code);
4459 		return -LIBBPF_ERRNO__RELOC;
4460 	}
4461 
4462 	if (sym_is_extern(sym)) {
4463 		int sym_idx = ELF64_R_SYM(rel->r_info);
4464 		int i, n = obj->nr_extern;
4465 		struct extern_desc *ext;
4466 
4467 		for (i = 0; i < n; i++) {
4468 			ext = &obj->externs[i];
4469 			if (ext->sym_idx == sym_idx)
4470 				break;
4471 		}
4472 		if (i >= n) {
4473 			pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
4474 				prog->name, sym_name, sym_idx);
4475 			return -LIBBPF_ERRNO__RELOC;
4476 		}
4477 		pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
4478 			 prog->name, i, ext->name, ext->sym_idx, insn_idx);
4479 		if (insn->code == (BPF_JMP | BPF_CALL))
4480 			reloc_desc->type = RELO_EXTERN_CALL;
4481 		else
4482 			reloc_desc->type = RELO_EXTERN_LD64;
4483 		reloc_desc->insn_idx = insn_idx;
4484 		reloc_desc->ext_idx = i;
4485 		return 0;
4486 	}
4487 
4488 	/* sub-program call relocation */
4489 	if (is_call_insn(insn)) {
4490 		if (insn->src_reg != BPF_PSEUDO_CALL) {
4491 			pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
4492 			return -LIBBPF_ERRNO__RELOC;
4493 		}
4494 		/* text_shndx can be 0, if no default "main" program exists */
4495 		if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
4496 #if defined HAVE_LIBELF
4497 			sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4498 #elif defined HAVE_ELFIO
4499 			sym_sec_name = elf_sec_name_by_idx(obj, shdr_idx);
4500 #endif
4501 			pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
4502 				prog->name, sym_name, sym_sec_name);
4503 			return -LIBBPF_ERRNO__RELOC;
4504 		}
4505 		if (sym->st_value % BPF_INSN_SZ) {
4506 			pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
4507 				prog->name, sym_name, (size_t)sym->st_value);
4508 			return -LIBBPF_ERRNO__RELOC;
4509 		}
4510 		reloc_desc->type = RELO_CALL;
4511 		reloc_desc->insn_idx = insn_idx;
4512 		reloc_desc->sym_off = sym->st_value;
4513 		return 0;
4514 	}
4515 
4516 	if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
4517 		pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
4518 			prog->name, sym_name, shdr_idx);
4519 		return -LIBBPF_ERRNO__RELOC;
4520 	}
4521 
4522 	/* loading subprog addresses */
4523 	if (sym_is_subprog(sym, obj->efile.text_shndx)) {
4524 		/* global_func: sym->st_value = offset in the section, insn->imm = 0.
4525 		 * local_func: sym->st_value = 0, insn->imm = offset in the section.
4526 		 */
4527 		if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
4528 			pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
4529 				prog->name, sym_name, (size_t)sym->st_value, insn->imm);
4530 			return -LIBBPF_ERRNO__RELOC;
4531 		}
4532 
4533 		reloc_desc->type = RELO_SUBPROG_ADDR;
4534 		reloc_desc->insn_idx = insn_idx;
4535 		reloc_desc->sym_off = sym->st_value;
4536 		return 0;
4537 	}
4538 
4539 	type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
4540 #if defined HAVE_LIBELF
4541 	sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4542 #elif defined HAVE_ELFIO
4543 	sym_sec_name = elf_sec_name_by_idx(obj, shdr_idx);
4544 #endif
4545 	/* generic map reference relocation */
4546 	if (type == LIBBPF_MAP_UNSPEC) {
4547 		if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
4548 			pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
4549 				prog->name, sym_name, sym_sec_name);
4550 			return -LIBBPF_ERRNO__RELOC;
4551 		}
4552 		for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4553 			map = &obj->maps[map_idx];
4554 			if (map->libbpf_type != type ||
4555 			    map->sec_idx != sym->st_shndx ||
4556 			    map->sec_offset != sym->st_value)
4557 				continue;
4558 			pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n",
4559 				 prog->name, map_idx, map->name, map->sec_idx,
4560 				 map->sec_offset, insn_idx);
4561 			break;
4562 		}
4563 		if (map_idx >= nr_maps) {
4564 			pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
4565 				prog->name, sym_sec_name, (size_t)sym->st_value);
4566 			return -LIBBPF_ERRNO__RELOC;
4567 		}
4568 		reloc_desc->type = RELO_LD64;
4569 		reloc_desc->insn_idx = insn_idx;
4570 		reloc_desc->map_idx = map_idx;
4571 		reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
4572 		return 0;
4573 	}
4574 
4575 	/* global data map relocation */
4576 	if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
4577 		pr_warn("prog '%s': bad data relo against section '%s'\n",
4578 			prog->name, sym_sec_name);
4579 		return -LIBBPF_ERRNO__RELOC;
4580 	}
4581 	for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4582 		map = &obj->maps[map_idx];
4583 		if (map->libbpf_type != type || map->sec_idx != sym->st_shndx)
4584 			continue;
4585 		pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n",
4586 			 prog->name, map_idx, map->name, map->sec_idx,
4587 			 map->sec_offset, insn_idx);
4588 		break;
4589 	}
4590 	if (map_idx >= nr_maps) {
4591 		pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
4592 			prog->name, sym_sec_name);
4593 		return -LIBBPF_ERRNO__RELOC;
4594 	}
4595 
4596 	reloc_desc->type = RELO_DATA;
4597 	reloc_desc->insn_idx = insn_idx;
4598 	reloc_desc->map_idx = map_idx;
4599 	reloc_desc->sym_off = sym->st_value;
4600 	return 0;
4601 }
4602 
4603 static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
4604 {
4605 	return insn_idx >= prog->sec_insn_off &&
4606 	       insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
4607 }
4608 
4609 static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
4610 						 size_t sec_idx, size_t insn_idx)
4611 {
4612 	int l = 0, r = obj->nr_programs - 1, m;
4613 	struct bpf_program *prog;
4614 
4615 	if (!obj->nr_programs)
4616 		return NULL;
4617 
4618 	while (l < r) {
4619 		m = l + (r - l + 1) / 2;
4620 		prog = &obj->programs[m];
4621 
4622 		if (prog->sec_idx < sec_idx ||
4623 		    (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
4624 			l = m;
4625 		else
4626 			r = m - 1;
4627 	}
4628 	/* matching program could be at index l, but it still might be the
4629 	 * wrong one, so we need to double check conditions for the last time
4630 	 */
4631 	prog = &obj->programs[l];
4632 	if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
4633 		return prog;
4634 	return NULL;
4635 }
4636 
4637 static int
4638 bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
4639 {
4640 	const char *relo_sec_name, *sec_name;
4641 	size_t sec_idx = shdr->sh_info, sym_idx;
4642 	struct bpf_program *prog;
4643 	struct reloc_desc *relos;
4644 	int err, i, nrels;
4645 	const char *sym_name;
4646 	__u32 insn_idx;
4647 #ifdef HAVE_LIBELF
4648 	Elf_Scn *scn;
4649 #endif
4650 	Elf_Data *scn_data;
4651 	Elf64_Sym *sym;
4652 	Elf64_Rel *rel;
4653 
4654 	if (sec_idx >= obj->efile.sec_cnt)
4655 		return -EINVAL;
4656 
4657 #if defined HAVE_LIBELF
4658 	scn = elf_sec_by_idx(obj, sec_idx);
4659 	scn_data = elf_sec_data(obj, scn);
4660 
4661 	relo_sec_name = elf_sec_str(obj, shdr->sh_name);
4662 	sec_name = elf_sec_name(obj, scn);
4663 	if (!relo_sec_name || !sec_name)
4664 		return -EINVAL;
4665 #elif defined HAVE_ELFIO
4666 	Elf_Data realdata;
4667 	scn_data = elf_sec_data_by_idx(obj, sec_idx, &realdata);
4668 
4669 	relo_sec_name = elf_sec_str(obj, shdr->sh_name);
4670 	sec_name = elf_sec_name_by_idx(obj, sec_idx);
4671 	if (!relo_sec_name || !sec_name)
4672 		return -EINVAL;
4673 #endif
4674 
4675 	pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
4676 		 relo_sec_name, sec_idx, sec_name);
4677 	nrels = shdr->sh_size / shdr->sh_entsize;
4678 
4679 	for (i = 0; i < nrels; i++) {
4680 		rel = elf_rel_by_idx(data, i);
4681 		if (!rel) {
4682 			pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
4683 			return -LIBBPF_ERRNO__FORMAT;
4684 		}
4685 
4686 		sym_idx = ELF64_R_SYM(rel->r_info);
4687 		sym = elf_sym_by_idx(obj, sym_idx);
4688 		if (!sym) {
4689 			pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
4690 				relo_sec_name, sym_idx, i);
4691 			return -LIBBPF_ERRNO__FORMAT;
4692 		}
4693 
4694 		if (sym->st_shndx >= obj->efile.sec_cnt) {
4695 			pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
4696 				relo_sec_name, sym_idx, (size_t)sym->st_shndx, i);
4697 			return -LIBBPF_ERRNO__FORMAT;
4698 		}
4699 
4700 		if (rel->r_offset % BPF_INSN_SZ || rel->r_offset >= scn_data->d_size) {
4701 			pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
4702 				relo_sec_name, (size_t)rel->r_offset, i);
4703 			return -LIBBPF_ERRNO__FORMAT;
4704 		}
4705 
4706 		insn_idx = rel->r_offset / BPF_INSN_SZ;
4707 		/* relocations against static functions are recorded as
4708 		 * relocations against the section that contains a function;
4709 		 * in such case, symbol will be STT_SECTION and sym.st_name
4710 		 * will point to empty string (0), so fetch section name
4711 		 * instead
4712 		 */
4713 		if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
4714 #if defined HAVE_LIBELF
4715 			sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx));
4716 #elif defined HAVE_ELFIO
4717 			sym_name = elf_sec_name_by_idx(obj, sym->st_shndx);
4718 #endif
4719 		else
4720 			sym_name = elf_sym_str(obj, sym->st_name);
4721 		sym_name = sym_name ?: "<?";
4722 
4723 		pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
4724 			 relo_sec_name, i, insn_idx, sym_name);
4725 
4726 		prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
4727 		if (!prog) {
4728 			pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
4729 				relo_sec_name, i, sec_name, insn_idx);
4730 			continue;
4731 		}
4732 
4733 		relos = libbpf_reallocarray(prog->reloc_desc,
4734 					    prog->nr_reloc + 1, sizeof(*relos));
4735 		if (!relos)
4736 			return -ENOMEM;
4737 		prog->reloc_desc = relos;
4738 
4739 		/* adjust insn_idx to local BPF program frame of reference */
4740 		insn_idx -= prog->sec_insn_off;
4741 		err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
4742 						insn_idx, sym_name, sym, rel);
4743 		if (err)
4744 			return err;
4745 
4746 		prog->nr_reloc++;
4747 	}
4748 	return 0;
4749 }
4750 
4751 static int map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map)
4752 {
4753 	int id;
4754 
4755 	if (!obj->btf)
4756 		return -ENOENT;
4757 
4758 	/* if it's BTF-defined map, we don't need to search for type IDs.
4759 	 * For struct_ops map, it does not need btf_key_type_id and
4760 	 * btf_value_type_id.
4761 	 */
4762 	if (map->sec_idx == obj->efile.btf_maps_shndx || bpf_map__is_struct_ops(map))
4763 		return 0;
4764 
4765 	/*
4766 	 * LLVM annotates global data differently in BTF, that is,
4767 	 * only as '.data', '.bss' or '.rodata'.
4768 	 */
4769 	if (!bpf_map__is_internal(map))
4770 		return -ENOENT;
4771 
4772 	id = btf__find_by_name(obj->btf, map->real_name);
4773 	if (id < 0)
4774 		return id;
4775 
4776 	map->btf_key_type_id = 0;
4777 	map->btf_value_type_id = id;
4778 	return 0;
4779 }
4780 
4781 static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
4782 {
4783 	char file[PATH_MAX], buff[4096];
4784 	FILE *fp;
4785 	__u32 val;
4786 	int err;
4787 
4788 	snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
4789 	memset(info, 0, sizeof(*info));
4790 
4791 	fp = fopen(file, "re");
4792 	if (!fp) {
4793 		err = -errno;
4794 		pr_warn("failed to open %s: %d. No procfs support?\n", file,
4795 			err);
4796 		return err;
4797 	}
4798 
4799 	while (fgets(buff, sizeof(buff), fp)) {
4800 		if (sscanf(buff, "map_type:\t%u", &val) == 1)
4801 			info->type = val;
4802 		else if (sscanf(buff, "key_size:\t%u", &val) == 1)
4803 			info->key_size = val;
4804 		else if (sscanf(buff, "value_size:\t%u", &val) == 1)
4805 			info->value_size = val;
4806 		else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
4807 			info->max_entries = val;
4808 		else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
4809 			info->map_flags = val;
4810 	}
4811 
4812 	fclose(fp);
4813 
4814 	return 0;
4815 }
4816 
4817 bool bpf_map__autocreate(const struct bpf_map *map)
4818 {
4819 	return map->autocreate;
4820 }
4821 
4822 int bpf_map__set_autocreate(struct bpf_map *map, bool autocreate)
4823 {
4824 	if (map->obj->loaded)
4825 		return libbpf_err(-EBUSY);
4826 
4827 	map->autocreate = autocreate;
4828 	return 0;
4829 }
4830 
4831 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
4832 {
4833 	struct bpf_map_info info;
4834 	__u32 len = sizeof(info), name_len;
4835 	int new_fd, err;
4836 	char *new_name;
4837 
4838 	memset(&info, 0, len);
4839 	err = bpf_map_get_info_by_fd(fd, &info, &len);
4840 	if (err && errno == EINVAL)
4841 		err = bpf_get_map_info_from_fdinfo(fd, &info);
4842 	if (err)
4843 		return libbpf_err(err);
4844 
4845 	name_len = strlen(info.name);
4846 	if (name_len == BPF_OBJ_NAME_LEN - 1 && strncmp(map->name, info.name, name_len) == 0)
4847 		new_name = strdup(map->name);
4848 	else
4849 		new_name = strdup(info.name);
4850 
4851 	if (!new_name)
4852 		return libbpf_err(-errno);
4853 
4854 	/*
4855 	 * Like dup(), but make sure new FD is >= 3 and has O_CLOEXEC set.
4856 	 * This is similar to what we do in ensure_good_fd(), but without
4857 	 * closing original FD.
4858 	 */
4859 	new_fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
4860 	if (new_fd < 0) {
4861 		err = -errno;
4862 		goto err_free_new_name;
4863 	}
4864 
4865 	err = zclose(map->fd);
4866 	if (err) {
4867 		err = -errno;
4868 		goto err_close_new_fd;
4869 	}
4870 	free(map->name);
4871 
4872 	map->fd = new_fd;
4873 	map->name = new_name;
4874 	map->def.type = info.type;
4875 	map->def.key_size = info.key_size;
4876 	map->def.value_size = info.value_size;
4877 	map->def.max_entries = info.max_entries;
4878 	map->def.map_flags = info.map_flags;
4879 	map->btf_key_type_id = info.btf_key_type_id;
4880 	map->btf_value_type_id = info.btf_value_type_id;
4881 	map->reused = true;
4882 	map->map_extra = info.map_extra;
4883 
4884 	return 0;
4885 
4886 err_close_new_fd:
4887 	close(new_fd);
4888 err_free_new_name:
4889 	free(new_name);
4890 	return libbpf_err(err);
4891 }
4892 
4893 __u32 bpf_map__max_entries(const struct bpf_map *map)
4894 {
4895 	return map->def.max_entries;
4896 }
4897 
4898 struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
4899 {
4900 	if (!bpf_map_type__is_map_in_map(map->def.type))
4901 		return errno = EINVAL, NULL;
4902 
4903 	return map->inner_map;
4904 }
4905 
4906 int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
4907 {
4908 	if (map->obj->loaded)
4909 		return libbpf_err(-EBUSY);
4910 
4911 	map->def.max_entries = max_entries;
4912 
4913 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
4914 	if (map_is_ringbuf(map))
4915 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
4916 
4917 	return 0;
4918 }
4919 
4920 static int
4921 bpf_object__probe_loading(struct bpf_object *obj)
4922 {
4923 	char *cp, errmsg[STRERR_BUFSIZE];
4924 	struct bpf_insn insns[] = {
4925 		BPF_MOV64_IMM(BPF_REG_0, 0),
4926 		BPF_EXIT_INSN(),
4927 	};
4928 	int ret, insn_cnt = ARRAY_SIZE(insns);
4929 
4930 	if (obj->gen_loader)
4931 		return 0;
4932 
4933 	ret = bump_rlimit_memlock();
4934 	if (ret)
4935 		pr_warn("Failed to bump RLIMIT_MEMLOCK (err = %d), you might need to do it explicitly!\n", ret);
4936 
4937 	/* make sure basic loading works */
4938 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4939 	if (ret < 0)
4940 		ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
4941 	if (ret < 0) {
4942 		ret = errno;
4943 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4944 		pr_warn("Error in %s():%s(%d). Couldn't load trivial BPF "
4945 			"program. Make sure your kernel supports BPF "
4946 			"(CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is "
4947 			"set to big enough value.\n", __func__, cp, ret);
4948 		return -ret;
4949 	}
4950 	close(ret);
4951 
4952 	return 0;
4953 }
4954 
4955 static int probe_fd(int fd)
4956 {
4957 	if (fd >= 0)
4958 		close(fd);
4959 	return fd >= 0;
4960 }
4961 
4962 static int probe_kern_prog_name(void)
4963 {
4964 	const size_t attr_sz = offsetofend(union bpf_attr, prog_name);
4965 	struct bpf_insn insns[] = {
4966 		BPF_MOV64_IMM(BPF_REG_0, 0),
4967 		BPF_EXIT_INSN(),
4968 	};
4969 	union bpf_attr attr;
4970 	int ret;
4971 
4972 	memset(&attr, 0, attr_sz);
4973 	attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
4974 	attr.license = ptr_to_u64("GPL");
4975 	attr.insns = ptr_to_u64(insns);
4976 	attr.insn_cnt = (__u32)ARRAY_SIZE(insns);
4977 	libbpf_strlcpy(attr.prog_name, "libbpf_nametest", sizeof(attr.prog_name));
4978 
4979 	/* make sure loading with name works */
4980 	ret = sys_bpf_prog_load(&attr, attr_sz, PROG_LOAD_ATTEMPTS);
4981 	return probe_fd(ret);
4982 }
4983 
4984 static int probe_kern_global_data(void)
4985 {
4986 	char *cp, errmsg[STRERR_BUFSIZE];
4987 	struct bpf_insn insns[] = {
4988 		BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
4989 		BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
4990 		BPF_MOV64_IMM(BPF_REG_0, 0),
4991 		BPF_EXIT_INSN(),
4992 	};
4993 	int ret, map, insn_cnt = ARRAY_SIZE(insns);
4994 
4995 	map = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_global", sizeof(int), 32, 1, NULL);
4996 	if (map < 0) {
4997 		ret = -errno;
4998 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4999 		pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
5000 			__func__, cp, -ret);
5001 		return ret;
5002 	}
5003 
5004 	insns[0].imm = map;
5005 
5006 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
5007 	close(map);
5008 	return probe_fd(ret);
5009 }
5010 
5011 static int probe_kern_btf(void)
5012 {
5013 	static const char strs[] = "\0int";
5014 	__u32 types[] = {
5015 		/* int */
5016 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
5017 	};
5018 
5019 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
5020 					     strs, sizeof(strs)));
5021 }
5022 
5023 static int probe_kern_btf_func(void)
5024 {
5025 	static const char strs[] = "\0int\0x\0a";
5026 	/* void x(int a) {} */
5027 	__u32 types[] = {
5028 		/* int */
5029 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
5030 		/* FUNC_PROTO */                                /* [2] */
5031 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
5032 		BTF_PARAM_ENC(7, 1),
5033 		/* FUNC x */                                    /* [3] */
5034 		BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
5035 	};
5036 
5037 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
5038 					     strs, sizeof(strs)));
5039 }
5040 
5041 static int probe_kern_btf_func_global(void)
5042 {
5043 	static const char strs[] = "\0int\0x\0a";
5044 	/* static void x(int a) {} */
5045 	__u32 types[] = {
5046 		/* int */
5047 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
5048 		/* FUNC_PROTO */                                /* [2] */
5049 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
5050 		BTF_PARAM_ENC(7, 1),
5051 		/* FUNC x BTF_FUNC_GLOBAL */                    /* [3] */
5052 		BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, BTF_FUNC_GLOBAL), 2),
5053 	};
5054 
5055 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
5056 					     strs, sizeof(strs)));
5057 }
5058 
5059 static int probe_kern_btf_datasec(void)
5060 {
5061 	static const char strs[] = "\0x\0.data";
5062 	/* static int a; */
5063 	__u32 types[] = {
5064 		/* int */
5065 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
5066 		/* VAR x */                                     /* [2] */
5067 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
5068 		BTF_VAR_STATIC,
5069 		/* DATASEC val */                               /* [3] */
5070 		BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
5071 		BTF_VAR_SECINFO_ENC(2, 0, 4),
5072 	};
5073 
5074 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
5075 					     strs, sizeof(strs)));
5076 }
5077 
5078 static int probe_kern_btf_float(void)
5079 {
5080 	static const char strs[] = "\0float";
5081 	__u32 types[] = {
5082 		/* float */
5083 		BTF_TYPE_FLOAT_ENC(1, 4),
5084 	};
5085 
5086 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
5087 					     strs, sizeof(strs)));
5088 }
5089 
5090 static int probe_kern_btf_decl_tag(void)
5091 {
5092 	static const char strs[] = "\0tag";
5093 	__u32 types[] = {
5094 		/* int */
5095 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
5096 		/* VAR x */                                     /* [2] */
5097 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
5098 		BTF_VAR_STATIC,
5099 		/* attr */
5100 		BTF_TYPE_DECL_TAG_ENC(1, 2, -1),
5101 	};
5102 
5103 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
5104 					     strs, sizeof(strs)));
5105 }
5106 
5107 static int probe_kern_btf_type_tag(void)
5108 {
5109 	static const char strs[] = "\0tag";
5110 	__u32 types[] = {
5111 		/* int */
5112 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),		/* [1] */
5113 		/* attr */
5114 		BTF_TYPE_TYPE_TAG_ENC(1, 1),				/* [2] */
5115 		/* ptr */
5116 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_PTR, 0, 0), 2),	/* [3] */
5117 	};
5118 
5119 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
5120 					     strs, sizeof(strs)));
5121 }
5122 
5123 static int probe_kern_array_mmap(void)
5124 {
5125 	LIBBPF_OPTS(bpf_map_create_opts, opts, .map_flags = BPF_F_MMAPABLE);
5126 	int fd;
5127 
5128 	fd = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_mmap", sizeof(int), sizeof(int), 1, &opts);
5129 	return probe_fd(fd);
5130 }
5131 
5132 static int probe_kern_exp_attach_type(void)
5133 {
5134 	LIBBPF_OPTS(bpf_prog_load_opts, opts, .expected_attach_type = BPF_CGROUP_INET_SOCK_CREATE);
5135 	struct bpf_insn insns[] = {
5136 		BPF_MOV64_IMM(BPF_REG_0, 0),
5137 		BPF_EXIT_INSN(),
5138 	};
5139 	int fd, insn_cnt = ARRAY_SIZE(insns);
5140 
5141 	/* use any valid combination of program type and (optional)
5142 	 * non-zero expected attach type (i.e., not a BPF_CGROUP_INET_INGRESS)
5143 	 * to see if kernel supports expected_attach_type field for
5144 	 * BPF_PROG_LOAD command
5145 	 */
5146 	fd = bpf_prog_load(BPF_PROG_TYPE_CGROUP_SOCK, NULL, "GPL", insns, insn_cnt, &opts);
5147 	return probe_fd(fd);
5148 }
5149 
5150 static int probe_kern_probe_read_kernel(void)
5151 {
5152 	struct bpf_insn insns[] = {
5153 		BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),	/* r1 = r10 (fp) */
5154 		BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -8),	/* r1 += -8 */
5155 		BPF_MOV64_IMM(BPF_REG_2, 8),		/* r2 = 8 */
5156 		BPF_MOV64_IMM(BPF_REG_3, 0),		/* r3 = 0 */
5157 		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_probe_read_kernel),
5158 		BPF_EXIT_INSN(),
5159 	};
5160 	int fd, insn_cnt = ARRAY_SIZE(insns);
5161 
5162 	fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
5163 	return probe_fd(fd);
5164 }
5165 
5166 static int probe_prog_bind_map(void)
5167 {
5168 	char *cp, errmsg[STRERR_BUFSIZE];
5169 	struct bpf_insn insns[] = {
5170 		BPF_MOV64_IMM(BPF_REG_0, 0),
5171 		BPF_EXIT_INSN(),
5172 	};
5173 	int ret, map, prog, insn_cnt = ARRAY_SIZE(insns);
5174 
5175 	map = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_det_bind", sizeof(int), 32, 1, NULL);
5176 	if (map < 0) {
5177 		ret = -errno;
5178 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
5179 		pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
5180 			__func__, cp, -ret);
5181 		return ret;
5182 	}
5183 
5184 	prog = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
5185 	if (prog < 0) {
5186 		close(map);
5187 		return 0;
5188 	}
5189 
5190 	ret = bpf_prog_bind_map(prog, map, NULL);
5191 
5192 	close(map);
5193 	close(prog);
5194 
5195 	return ret >= 0;
5196 }
5197 
5198 static int probe_module_btf(void)
5199 {
5200 	static const char strs[] = "\0int";
5201 	__u32 types[] = {
5202 		/* int */
5203 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
5204 	};
5205 	struct bpf_btf_info info;
5206 	__u32 len = sizeof(info);
5207 	char name[16];
5208 	int fd, err;
5209 
5210 	fd = libbpf__load_raw_btf((char *)types, sizeof(types), strs, sizeof(strs));
5211 	if (fd < 0)
5212 		return 0; /* BTF not supported at all */
5213 
5214 	memset(&info, 0, sizeof(info));
5215 	info.name = ptr_to_u64(name);
5216 	info.name_len = sizeof(name);
5217 
5218 	/* check that BPF_OBJ_GET_INFO_BY_FD supports specifying name pointer;
5219 	 * kernel's module BTF support coincides with support for
5220 	 * name/name_len fields in struct bpf_btf_info.
5221 	 */
5222 	err = bpf_btf_get_info_by_fd(fd, &info, &len);
5223 	close(fd);
5224 	return !err;
5225 }
5226 
5227 static int probe_perf_link(void)
5228 {
5229 	struct bpf_insn insns[] = {
5230 		BPF_MOV64_IMM(BPF_REG_0, 0),
5231 		BPF_EXIT_INSN(),
5232 	};
5233 	int prog_fd, link_fd, err;
5234 
5235 	prog_fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL",
5236 				insns, ARRAY_SIZE(insns), NULL);
5237 	if (prog_fd < 0)
5238 		return -errno;
5239 
5240 	/* use invalid perf_event FD to get EBADF, if link is supported;
5241 	 * otherwise EINVAL should be returned
5242 	 */
5243 	link_fd = bpf_link_create(prog_fd, -1, BPF_PERF_EVENT, NULL);
5244 	err = -errno; /* close() can clobber errno */
5245 
5246 	if (link_fd >= 0)
5247 		close(link_fd);
5248 	close(prog_fd);
5249 
5250 	return link_fd < 0 && err == -EBADF;
5251 }
5252 
5253 static int probe_uprobe_multi_link(void)
5254 {
5255 	LIBBPF_OPTS(bpf_prog_load_opts, load_opts,
5256 		.expected_attach_type = BPF_TRACE_UPROBE_MULTI,
5257 	);
5258 	LIBBPF_OPTS(bpf_link_create_opts, link_opts);
5259 	struct bpf_insn insns[] = {
5260 		BPF_MOV64_IMM(BPF_REG_0, 0),
5261 		BPF_EXIT_INSN(),
5262 	};
5263 	int prog_fd, link_fd, err;
5264 	unsigned long offset = 0;
5265 
5266 	prog_fd = bpf_prog_load(BPF_PROG_TYPE_KPROBE, NULL, "GPL",
5267 				insns, ARRAY_SIZE(insns), &load_opts);
5268 	if (prog_fd < 0)
5269 		return -errno;
5270 
5271 	/* Creating uprobe in '/' binary should fail with -EBADF. */
5272 	link_opts.uprobe_multi.path = "/";
5273 	link_opts.uprobe_multi.offsets = &offset;
5274 	link_opts.uprobe_multi.cnt = 1;
5275 
5276 	link_fd = bpf_link_create(prog_fd, -1, BPF_TRACE_UPROBE_MULTI, &link_opts);
5277 	err = -errno; /* close() can clobber errno */
5278 
5279 	if (link_fd >= 0 || err != -EBADF) {
5280 		close(link_fd);
5281 		close(prog_fd);
5282 		return 0;
5283 	}
5284 
5285 	/* Initial multi-uprobe support in kernel didn't handle PID filtering
5286 	 * correctly (it was doing thread filtering, not process filtering).
5287 	 * So now we'll detect if PID filtering logic was fixed, and, if not,
5288 	 * we'll pretend multi-uprobes are not supported, if not.
5289 	 * Multi-uprobes are used in USDT attachment logic, and we need to be
5290 	 * conservative here, because multi-uprobe selection happens early at
5291 	 * load time, while the use of PID filtering is known late at
5292 	 * attachment time, at which point it's too late to undo multi-uprobe
5293 	 * selection.
5294 	 *
5295 	 * Creating uprobe with pid == -1 for (invalid) '/' binary will fail
5296 	 * early with -EINVAL on kernels with fixed PID filtering logic;
5297 	 * otherwise -ESRCH would be returned if passed correct binary path
5298 	 * (but we'll just get -BADF, of course).
5299 	 */
5300 	link_opts.uprobe_multi.pid = -1; /* invalid PID */
5301 	link_opts.uprobe_multi.path = "/"; /* invalid path */
5302 	link_opts.uprobe_multi.offsets = &offset;
5303 	link_opts.uprobe_multi.cnt = 1;
5304 
5305 	link_fd = bpf_link_create(prog_fd, -1, BPF_TRACE_UPROBE_MULTI, &link_opts);
5306 	err = -errno; /* close() can clobber errno */
5307 
5308 	if (link_fd >= 0)
5309 		close(link_fd);
5310 	close(prog_fd);
5311 
5312 	return link_fd < 0 && err == -EINVAL;
5313 }
5314 
5315 static int probe_kern_bpf_cookie(void)
5316 {
5317 	struct bpf_insn insns[] = {
5318 		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_get_attach_cookie),
5319 		BPF_EXIT_INSN(),
5320 	};
5321 	int ret, insn_cnt = ARRAY_SIZE(insns);
5322 
5323 	ret = bpf_prog_load(BPF_PROG_TYPE_KPROBE, NULL, "GPL", insns, insn_cnt, NULL);
5324 	return probe_fd(ret);
5325 }
5326 
5327 static int probe_kern_btf_enum64(void)
5328 {
5329 	static const char strs[] = "\0enum64";
5330 	__u32 types[] = {
5331 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_ENUM64, 0, 0), 8),
5332 	};
5333 
5334 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
5335 					     strs, sizeof(strs)));
5336 }
5337 
5338 static int probe_kern_syscall_wrapper(void);
5339 
5340 enum kern_feature_result {
5341 	FEAT_UNKNOWN = 0,
5342 	FEAT_SUPPORTED = 1,
5343 	FEAT_MISSING = 2,
5344 };
5345 
5346 typedef int (*feature_probe_fn)(void);
5347 
5348 static struct kern_feature_desc {
5349 	const char *desc;
5350 	feature_probe_fn probe;
5351 	enum kern_feature_result res;
5352 } feature_probes[__FEAT_CNT] = {
5353 	[FEAT_PROG_NAME] = {
5354 		"BPF program name", probe_kern_prog_name,
5355 	},
5356 	[FEAT_GLOBAL_DATA] = {
5357 		"global variables", probe_kern_global_data,
5358 	},
5359 	[FEAT_BTF] = {
5360 		"minimal BTF", probe_kern_btf,
5361 	},
5362 	[FEAT_BTF_FUNC] = {
5363 		"BTF functions", probe_kern_btf_func,
5364 	},
5365 	[FEAT_BTF_GLOBAL_FUNC] = {
5366 		"BTF global function", probe_kern_btf_func_global,
5367 	},
5368 	[FEAT_BTF_DATASEC] = {
5369 		"BTF data section and variable", probe_kern_btf_datasec,
5370 	},
5371 	[FEAT_ARRAY_MMAP] = {
5372 		"ARRAY map mmap()", probe_kern_array_mmap,
5373 	},
5374 	[FEAT_EXP_ATTACH_TYPE] = {
5375 		"BPF_PROG_LOAD expected_attach_type attribute",
5376 		probe_kern_exp_attach_type,
5377 	},
5378 	[FEAT_PROBE_READ_KERN] = {
5379 		"bpf_probe_read_kernel() helper", probe_kern_probe_read_kernel,
5380 	},
5381 	[FEAT_PROG_BIND_MAP] = {
5382 		"BPF_PROG_BIND_MAP support", probe_prog_bind_map,
5383 	},
5384 	[FEAT_MODULE_BTF] = {
5385 		"module BTF support", probe_module_btf,
5386 	},
5387 	[FEAT_BTF_FLOAT] = {
5388 		"BTF_KIND_FLOAT support", probe_kern_btf_float,
5389 	},
5390 	[FEAT_PERF_LINK] = {
5391 		"BPF perf link support", probe_perf_link,
5392 	},
5393 	[FEAT_BTF_DECL_TAG] = {
5394 		"BTF_KIND_DECL_TAG support", probe_kern_btf_decl_tag,
5395 	},
5396 	[FEAT_BTF_TYPE_TAG] = {
5397 		"BTF_KIND_TYPE_TAG support", probe_kern_btf_type_tag,
5398 	},
5399 	[FEAT_MEMCG_ACCOUNT] = {
5400 		"memcg-based memory accounting", probe_memcg_account,
5401 	},
5402 	[FEAT_BPF_COOKIE] = {
5403 		"BPF cookie support", probe_kern_bpf_cookie,
5404 	},
5405 	[FEAT_BTF_ENUM64] = {
5406 		"BTF_KIND_ENUM64 support", probe_kern_btf_enum64,
5407 	},
5408 	[FEAT_SYSCALL_WRAPPER] = {
5409 		"Kernel using syscall wrapper", probe_kern_syscall_wrapper,
5410 	},
5411 	[FEAT_UPROBE_MULTI_LINK] = {
5412 		"BPF multi-uprobe link support", probe_uprobe_multi_link,
5413 	},
5414 };
5415 
5416 bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
5417 {
5418 	struct kern_feature_desc *feat = &feature_probes[feat_id];
5419 	int ret;
5420 
5421 	if (obj && obj->gen_loader)
5422 		/* To generate loader program assume the latest kernel
5423 		 * to avoid doing extra prog_load, map_create syscalls.
5424 		 */
5425 		return true;
5426 
5427 	if (READ_ONCE(feat->res) == FEAT_UNKNOWN) {
5428 		ret = feat->probe();
5429 		if (ret > 0) {
5430 			WRITE_ONCE(feat->res, FEAT_SUPPORTED);
5431 		} else if (ret == 0) {
5432 			WRITE_ONCE(feat->res, FEAT_MISSING);
5433 		} else {
5434 			pr_warn("Detection of kernel %s support failed: %d\n", feat->desc, ret);
5435 			WRITE_ONCE(feat->res, FEAT_MISSING);
5436 		}
5437 	}
5438 
5439 	return READ_ONCE(feat->res) == FEAT_SUPPORTED;
5440 }
5441 
5442 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
5443 {
5444 	struct bpf_map_info map_info;
5445 	char msg[STRERR_BUFSIZE];
5446 	__u32 map_info_len = sizeof(map_info);
5447 	int err;
5448 
5449 	memset(&map_info, 0, map_info_len);
5450 	err = bpf_map_get_info_by_fd(map_fd, &map_info, &map_info_len);
5451 	if (err && errno == EINVAL)
5452 		err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
5453 	if (err) {
5454 		pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
5455 			libbpf_strerror_r(errno, msg, sizeof(msg)));
5456 		return false;
5457 	}
5458 
5459 	return (map_info.type == map->def.type &&
5460 		map_info.key_size == map->def.key_size &&
5461 		map_info.value_size == map->def.value_size &&
5462 		map_info.max_entries == map->def.max_entries &&
5463 		map_info.map_flags == map->def.map_flags &&
5464 		map_info.map_extra == map->map_extra);
5465 }
5466 
5467 static int
5468 bpf_object__reuse_map(struct bpf_map *map)
5469 {
5470 	char *cp, errmsg[STRERR_BUFSIZE];
5471 	int err, pin_fd;
5472 
5473 	pin_fd = bpf_obj_get(map->pin_path);
5474 	if (pin_fd < 0) {
5475 		err = -errno;
5476 		if (err == -ENOENT) {
5477 			pr_debug("found no pinned map to reuse at '%s'\n",
5478 				 map->pin_path);
5479 			return 0;
5480 		}
5481 
5482 		cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
5483 		pr_warn("couldn't retrieve pinned map '%s': %s\n",
5484 			map->pin_path, cp);
5485 		return err;
5486 	}
5487 
5488 	if (!map_is_reuse_compat(map, pin_fd)) {
5489 		pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
5490 			map->pin_path);
5491 		close(pin_fd);
5492 		return -EINVAL;
5493 	}
5494 
5495 	err = bpf_map__reuse_fd(map, pin_fd);
5496 	close(pin_fd);
5497 	if (err)
5498 		return err;
5499 
5500 	map->pinned = true;
5501 	pr_debug("reused pinned map at '%s'\n", map->pin_path);
5502 
5503 	return 0;
5504 }
5505 
5506 static int
5507 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
5508 {
5509 	enum libbpf_map_type map_type = map->libbpf_type;
5510 	char *cp, errmsg[STRERR_BUFSIZE];
5511 	int err, zero = 0;
5512 	size_t mmap_sz;
5513 
5514 	if (obj->gen_loader) {
5515 		bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
5516 					 map->mmaped, map->def.value_size);
5517 		if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
5518 			bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
5519 		return 0;
5520 	}
5521 	err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
5522 	if (err) {
5523 		err = -errno;
5524 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5525 		pr_warn("map '%s': failed to set initial contents: %s\n",
5526 			bpf_map__name(map), cp);
5527 		return err;
5528 	}
5529 
5530 	/* Freeze .rodata and .kconfig map as read-only from syscall side. */
5531 	if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
5532 		err = bpf_map_freeze(map->fd);
5533 		if (err) {
5534 			err = -errno;
5535 			cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5536 			pr_warn("map '%s': failed to freeze as read-only: %s\n",
5537 				bpf_map__name(map), cp);
5538 			return err;
5539 		}
5540 	}
5541 
5542 	/* Remap anonymous mmap()-ed "map initialization image" as
5543 	 * a BPF map-backed mmap()-ed memory, but preserving the same
5544 	 * memory address. This will cause kernel to change process'
5545 	 * page table to point to a different piece of kernel memory,
5546 	 * but from userspace point of view memory address (and its
5547 	 * contents, being identical at this point) will stay the
5548 	 * same. This mapping will be released by bpf_object__close()
5549 	 * as per normal clean up procedure.
5550 	 */
5551 	mmap_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
5552 	if (map->def.map_flags & BPF_F_MMAPABLE) {
5553 		void *mmaped;
5554 		int prot;
5555 
5556 		if (map->def.map_flags & BPF_F_RDONLY_PROG)
5557 			prot = PROT_READ;
5558 		else
5559 			prot = PROT_READ | PROT_WRITE;
5560 		mmaped = mmap(map->mmaped, mmap_sz, prot, MAP_SHARED | MAP_FIXED, map->fd, 0);
5561 		if (mmaped == MAP_FAILED) {
5562 			err = -errno;
5563 			pr_warn("map '%s': failed to re-mmap() contents: %d\n",
5564 				bpf_map__name(map), err);
5565 			return err;
5566 		}
5567 		map->mmaped = mmaped;
5568 	} else if (map->mmaped) {
5569 		munmap(map->mmaped, mmap_sz);
5570 		map->mmaped = NULL;
5571 	}
5572 
5573 	return 0;
5574 }
5575 
5576 static void bpf_map__destroy(struct bpf_map *map);
5577 
5578 static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
5579 {
5580 	LIBBPF_OPTS(bpf_map_create_opts, create_attr);
5581 	struct bpf_map_def *def = &map->def;
5582 	const char *map_name = NULL;
5583 	int err = 0;
5584 
5585 	if (kernel_supports(obj, FEAT_PROG_NAME))
5586 		map_name = map->name;
5587 	create_attr.map_ifindex = map->map_ifindex;
5588 	create_attr.map_flags = def->map_flags;
5589 	create_attr.numa_node = map->numa_node;
5590 	create_attr.map_extra = map->map_extra;
5591 
5592 	if (bpf_map__is_struct_ops(map))
5593 		create_attr.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
5594 
5595 	if (obj->btf && btf__fd(obj->btf) >= 0) {
5596 		create_attr.btf_fd = btf__fd(obj->btf);
5597 		create_attr.btf_key_type_id = map->btf_key_type_id;
5598 		create_attr.btf_value_type_id = map->btf_value_type_id;
5599 	}
5600 
5601 	if (bpf_map_type__is_map_in_map(def->type)) {
5602 		if (map->inner_map) {
5603 			err = bpf_object__create_map(obj, map->inner_map, true);
5604 			if (err) {
5605 				pr_warn("map '%s': failed to create inner map: %d\n",
5606 					map->name, err);
5607 				return err;
5608 			}
5609 			map->inner_map_fd = bpf_map__fd(map->inner_map);
5610 		}
5611 		if (map->inner_map_fd >= 0)
5612 			create_attr.inner_map_fd = map->inner_map_fd;
5613 	}
5614 
5615 	switch (def->type) {
5616 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5617 	case BPF_MAP_TYPE_CGROUP_ARRAY:
5618 	case BPF_MAP_TYPE_STACK_TRACE:
5619 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5620 	case BPF_MAP_TYPE_HASH_OF_MAPS:
5621 	case BPF_MAP_TYPE_DEVMAP:
5622 	case BPF_MAP_TYPE_DEVMAP_HASH:
5623 	case BPF_MAP_TYPE_CPUMAP:
5624 	case BPF_MAP_TYPE_XSKMAP:
5625 	case BPF_MAP_TYPE_SOCKMAP:
5626 	case BPF_MAP_TYPE_SOCKHASH:
5627 	case BPF_MAP_TYPE_QUEUE:
5628 	case BPF_MAP_TYPE_STACK:
5629 		create_attr.btf_fd = 0;
5630 		create_attr.btf_key_type_id = 0;
5631 		create_attr.btf_value_type_id = 0;
5632 		map->btf_key_type_id = 0;
5633 		map->btf_value_type_id = 0;
5634 		break;
5635 	default:
5636 		break;
5637 	}
5638 
5639 	if (obj->gen_loader) {
5640 		bpf_gen__map_create(obj->gen_loader, def->type, map_name,
5641 				    def->key_size, def->value_size, def->max_entries,
5642 				    &create_attr, is_inner ? -1 : map - obj->maps);
5643 		/* Pretend to have valid FD to pass various fd >= 0 checks.
5644 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
5645 		 */
5646 		map->fd = 0;
5647 	} else {
5648 		map->fd = bpf_map_create(def->type, map_name,
5649 					 def->key_size, def->value_size,
5650 					 def->max_entries, &create_attr);
5651 	}
5652 	if (map->fd < 0 && (create_attr.btf_key_type_id ||
5653 			    create_attr.btf_value_type_id)) {
5654 		char *cp, errmsg[STRERR_BUFSIZE];
5655 
5656 		err = -errno;
5657 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5658 		pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
5659 			map->name, cp, err);
5660 		create_attr.btf_fd = 0;
5661 		create_attr.btf_key_type_id = 0;
5662 		create_attr.btf_value_type_id = 0;
5663 		map->btf_key_type_id = 0;
5664 		map->btf_value_type_id = 0;
5665 		map->fd = bpf_map_create(def->type, map_name,
5666 					 def->key_size, def->value_size,
5667 					 def->max_entries, &create_attr);
5668 	}
5669 
5670 	err = map->fd < 0 ? -errno : 0;
5671 
5672 	if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
5673 		if (obj->gen_loader)
5674 			map->inner_map->fd = -1;
5675 		bpf_map__destroy(map->inner_map);
5676 		zfree(&map->inner_map);
5677 	}
5678 
5679 	return err;
5680 }
5681 
5682 static int init_map_in_map_slots(struct bpf_object *obj, struct bpf_map *map)
5683 {
5684 	const struct bpf_map *targ_map;
5685 	unsigned int i;
5686 	int fd, err = 0;
5687 
5688 	for (i = 0; i < map->init_slots_sz; i++) {
5689 		if (!map->init_slots[i])
5690 			continue;
5691 
5692 		targ_map = map->init_slots[i];
5693 		fd = bpf_map__fd(targ_map);
5694 
5695 		if (obj->gen_loader) {
5696 			bpf_gen__populate_outer_map(obj->gen_loader,
5697 						    map - obj->maps, i,
5698 						    targ_map - obj->maps);
5699 		} else {
5700 			err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5701 		}
5702 		if (err) {
5703 			err = -errno;
5704 			pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %d\n",
5705 				map->name, i, targ_map->name, fd, err);
5706 			return err;
5707 		}
5708 		pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
5709 			 map->name, i, targ_map->name, fd);
5710 	}
5711 
5712 	zfree(&map->init_slots);
5713 	map->init_slots_sz = 0;
5714 
5715 	return 0;
5716 }
5717 
5718 static int init_prog_array_slots(struct bpf_object *obj, struct bpf_map *map)
5719 {
5720 	const struct bpf_program *targ_prog;
5721 	unsigned int i;
5722 	int fd, err;
5723 
5724 	if (obj->gen_loader)
5725 		return -ENOTSUP;
5726 
5727 	for (i = 0; i < map->init_slots_sz; i++) {
5728 		if (!map->init_slots[i])
5729 			continue;
5730 
5731 		targ_prog = map->init_slots[i];
5732 		fd = bpf_program__fd(targ_prog);
5733 
5734 		err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5735 		if (err) {
5736 			err = -errno;
5737 			pr_warn("map '%s': failed to initialize slot [%d] to prog '%s' fd=%d: %d\n",
5738 				map->name, i, targ_prog->name, fd, err);
5739 			return err;
5740 		}
5741 		pr_debug("map '%s': slot [%d] set to prog '%s' fd=%d\n",
5742 			 map->name, i, targ_prog->name, fd);
5743 	}
5744 
5745 	zfree(&map->init_slots);
5746 	map->init_slots_sz = 0;
5747 
5748 	return 0;
5749 }
5750 
5751 static int bpf_object_init_prog_arrays(struct bpf_object *obj)
5752 {
5753 	struct bpf_map *map;
5754 	int i, err;
5755 
5756 	for (i = 0; i < obj->nr_maps; i++) {
5757 		map = &obj->maps[i];
5758 
5759 		if (!map->init_slots_sz || map->def.type != BPF_MAP_TYPE_PROG_ARRAY)
5760 			continue;
5761 
5762 		err = init_prog_array_slots(obj, map);
5763 		if (err < 0) {
5764 			zclose(map->fd);
5765 			return err;
5766 		}
5767 	}
5768 	return 0;
5769 }
5770 
5771 static int map_set_def_max_entries(struct bpf_map *map)
5772 {
5773 	if (map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !map->def.max_entries) {
5774 		int nr_cpus;
5775 
5776 		nr_cpus = libbpf_num_possible_cpus();
5777 		if (nr_cpus < 0) {
5778 			pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
5779 				map->name, nr_cpus);
5780 			return nr_cpus;
5781 		}
5782 		pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
5783 		map->def.max_entries = nr_cpus;
5784 	}
5785 
5786 	return 0;
5787 }
5788 
5789 static int
5790 bpf_object__create_maps(struct bpf_object *obj)
5791 {
5792 	struct bpf_map *map;
5793 	char *cp, errmsg[STRERR_BUFSIZE];
5794 	unsigned int i, j;
5795 	int err;
5796 	bool retried;
5797 
5798 	for (i = 0; i < obj->nr_maps; i++) {
5799 		map = &obj->maps[i];
5800 
5801 		/* To support old kernels, we skip creating global data maps
5802 		 * (.rodata, .data, .kconfig, etc); later on, during program
5803 		 * loading, if we detect that at least one of the to-be-loaded
5804 		 * programs is referencing any global data map, we'll error
5805 		 * out with program name and relocation index logged.
5806 		 * This approach allows to accommodate Clang emitting
5807 		 * unnecessary .rodata.str1.1 sections for string literals,
5808 		 * but also it allows to have CO-RE applications that use
5809 		 * global variables in some of BPF programs, but not others.
5810 		 * If those global variable-using programs are not loaded at
5811 		 * runtime due to bpf_program__set_autoload(prog, false),
5812 		 * bpf_object loading will succeed just fine even on old
5813 		 * kernels.
5814 		 */
5815 		if (bpf_map__is_internal(map) && !kernel_supports(obj, FEAT_GLOBAL_DATA))
5816 			map->autocreate = false;
5817 
5818 		if (!map->autocreate) {
5819 			pr_debug("map '%s': skipped auto-creating...\n", map->name);
5820 			continue;
5821 		}
5822 
5823 		err = map_set_def_max_entries(map);
5824 		if (err)
5825 			goto err_out;
5826 
5827 		retried = false;
5828 retry:
5829 		if (map->pin_path) {
5830 			err = bpf_object__reuse_map(map);
5831 			if (err) {
5832 				pr_warn("map '%s': error reusing pinned map\n",
5833 					map->name);
5834 				goto err_out;
5835 			}
5836 			if (retried && map->fd < 0) {
5837 				pr_warn("map '%s': cannot find pinned map\n",
5838 					map->name);
5839 				err = -ENOENT;
5840 				goto err_out;
5841 			}
5842 		}
5843 
5844 		if (map->fd >= 0) {
5845 			pr_debug("map '%s': skipping creation (preset fd=%d)\n",
5846 				 map->name, map->fd);
5847 		} else {
5848 			err = bpf_object__create_map(obj, map, false);
5849 			if (err)
5850 				goto err_out;
5851 
5852 			pr_debug("map '%s': created successfully, fd=%d\n",
5853 				 map->name, map->fd);
5854 
5855 			if (bpf_map__is_internal(map)) {
5856 				err = bpf_object__populate_internal_map(obj, map);
5857 				if (err < 0) {
5858 					zclose(map->fd);
5859 					goto err_out;
5860 				}
5861 			}
5862 
5863 			if (map->init_slots_sz && map->def.type != BPF_MAP_TYPE_PROG_ARRAY) {
5864 				err = init_map_in_map_slots(obj, map);
5865 				if (err < 0) {
5866 					zclose(map->fd);
5867 					goto err_out;
5868 				}
5869 			}
5870 		}
5871 
5872 		if (map->pin_path && !map->pinned) {
5873 			err = bpf_map__pin(map, NULL);
5874 			if (err) {
5875 				zclose(map->fd);
5876 				if (!retried && err == -EEXIST) {
5877 					retried = true;
5878 					goto retry;
5879 				}
5880 				pr_warn("map '%s': failed to auto-pin at '%s': %d\n",
5881 					map->name, map->pin_path, err);
5882 				goto err_out;
5883 			}
5884 		}
5885 	}
5886 
5887 	return 0;
5888 
5889 err_out:
5890 	cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5891 	pr_warn("map '%s': failed to create: %s(%d)\n", map->name, cp, err);
5892 	pr_perm_msg(err);
5893 	for (j = 0; j < i; j++)
5894 		zclose(obj->maps[j].fd);
5895 	return err;
5896 }
5897 
5898 static bool bpf_core_is_flavor_sep(const char *s)
5899 {
5900 	/* check X___Y name pattern, where X and Y are not underscores */
5901 	return s[0] != '_' &&				      /* X */
5902 	       s[1] == '_' && s[2] == '_' && s[3] == '_' &&   /* ___ */
5903 	       s[4] != '_';				      /* Y */
5904 }
5905 
5906 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
5907  * before last triple underscore. Struct name part after last triple
5908  * underscore is ignored by BPF CO-RE relocation during relocation matching.
5909  */
5910 size_t bpf_core_essential_name_len(const char *name)
5911 {
5912 	size_t n = strlen(name);
5913 	int i;
5914 
5915 	for (i = n - 5; i >= 0; i--) {
5916 		if (bpf_core_is_flavor_sep(name + i))
5917 			return i + 1;
5918 	}
5919 	return n;
5920 }
5921 
5922 void bpf_core_free_cands(struct bpf_core_cand_list *cands)
5923 {
5924 	if (!cands)
5925 		return;
5926 
5927 	free(cands->cands);
5928 	free(cands);
5929 }
5930 
5931 int bpf_core_add_cands(struct bpf_core_cand *local_cand,
5932 		       size_t local_essent_len,
5933 		       const struct btf *targ_btf,
5934 		       const char *targ_btf_name,
5935 		       int targ_start_id,
5936 		       struct bpf_core_cand_list *cands)
5937 {
5938 	struct bpf_core_cand *new_cands, *cand;
5939 	const struct btf_type *t, *local_t;
5940 	const char *targ_name, *local_name;
5941 	size_t targ_essent_len;
5942 	int n, i;
5943 
5944 	local_t = btf__type_by_id(local_cand->btf, local_cand->id);
5945 	local_name = btf__str_by_offset(local_cand->btf, local_t->name_off);
5946 
5947 	n = btf__type_cnt(targ_btf);
5948 	for (i = targ_start_id; i < n; i++) {
5949 		t = btf__type_by_id(targ_btf, i);
5950 		if (!btf_kind_core_compat(t, local_t))
5951 			continue;
5952 
5953 		targ_name = btf__name_by_offset(targ_btf, t->name_off);
5954 		if (str_is_empty(targ_name))
5955 			continue;
5956 
5957 		targ_essent_len = bpf_core_essential_name_len(targ_name);
5958 		if (targ_essent_len != local_essent_len)
5959 			continue;
5960 
5961 		if (strncmp(local_name, targ_name, local_essent_len) != 0)
5962 			continue;
5963 
5964 		pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s in [%s]\n",
5965 			 local_cand->id, btf_kind_str(local_t),
5966 			 local_name, i, btf_kind_str(t), targ_name,
5967 			 targ_btf_name);
5968 		new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
5969 					      sizeof(*cands->cands));
5970 		if (!new_cands)
5971 			return -ENOMEM;
5972 
5973 		cand = &new_cands[cands->len];
5974 		cand->btf = targ_btf;
5975 		cand->id = i;
5976 
5977 		cands->cands = new_cands;
5978 		cands->len++;
5979 	}
5980 	return 0;
5981 }
5982 
5983 static int load_module_btfs(struct bpf_object *obj)
5984 {
5985 	struct bpf_btf_info info;
5986 	struct module_btf *mod_btf;
5987 	struct btf *btf;
5988 	char name[64];
5989 	__u32 id = 0, len;
5990 	int err, fd;
5991 
5992 	if (obj->btf_modules_loaded)
5993 		return 0;
5994 
5995 	if (obj->gen_loader)
5996 		return 0;
5997 
5998 	/* don't do this again, even if we find no module BTFs */
5999 	obj->btf_modules_loaded = true;
6000 
6001 	/* kernel too old to support module BTFs */
6002 	if (!kernel_supports(obj, FEAT_MODULE_BTF))
6003 		return 0;
6004 
6005 	while (true) {
6006 		err = bpf_btf_get_next_id(id, &id);
6007 		if (err && errno == ENOENT)
6008 			return 0;
6009 		if (err && errno == EPERM) {
6010 			pr_debug("skipping module BTFs loading, missing privileges\n");
6011 			return 0;
6012 		}
6013 		if (err) {
6014 			err = -errno;
6015 			pr_warn("failed to iterate BTF objects: %d\n", err);
6016 			return err;
6017 		}
6018 
6019 		fd = bpf_btf_get_fd_by_id(id);
6020 		if (fd < 0) {
6021 			if (errno == ENOENT)
6022 				continue; /* expected race: BTF was unloaded */
6023 			err = -errno;
6024 			pr_warn("failed to get BTF object #%d FD: %d\n", id, err);
6025 			return err;
6026 		}
6027 
6028 		len = sizeof(info);
6029 		memset(&info, 0, sizeof(info));
6030 		info.name = ptr_to_u64(name);
6031 		info.name_len = sizeof(name);
6032 
6033 		err = bpf_btf_get_info_by_fd(fd, &info, &len);
6034 		if (err) {
6035 			err = -errno;
6036 			pr_warn("failed to get BTF object #%d info: %d\n", id, err);
6037 			goto err_out;
6038 		}
6039 
6040 		/* ignore non-module BTFs */
6041 		if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
6042 			close(fd);
6043 			continue;
6044 		}
6045 
6046 		btf = btf_get_from_fd(fd, obj->btf_vmlinux);
6047 		err = libbpf_get_error(btf);
6048 		if (err) {
6049 			pr_warn("failed to load module [%s]'s BTF object #%d: %d\n",
6050 				name, id, err);
6051 			goto err_out;
6052 		}
6053 
6054 		err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
6055 					sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
6056 		if (err)
6057 			goto err_out;
6058 
6059 		mod_btf = &obj->btf_modules[obj->btf_module_cnt++];
6060 
6061 		mod_btf->btf = btf;
6062 		mod_btf->id = id;
6063 		mod_btf->fd = fd;
6064 		mod_btf->name = strdup(name);
6065 		if (!mod_btf->name) {
6066 			err = -ENOMEM;
6067 			goto err_out;
6068 		}
6069 		continue;
6070 
6071 err_out:
6072 		close(fd);
6073 		return err;
6074 	}
6075 
6076 	return 0;
6077 }
6078 
6079 static struct bpf_core_cand_list *
6080 bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
6081 {
6082 	struct bpf_core_cand local_cand = {};
6083 	struct bpf_core_cand_list *cands;
6084 	const struct btf *main_btf;
6085 	const struct btf_type *local_t;
6086 	const char *local_name;
6087 	size_t local_essent_len;
6088 	int err, i;
6089 
6090 	local_cand.btf = local_btf;
6091 	local_cand.id = local_type_id;
6092 	local_t = btf__type_by_id(local_btf, local_type_id);
6093 	if (!local_t)
6094 		return ERR_PTR(-EINVAL);
6095 
6096 	local_name = btf__name_by_offset(local_btf, local_t->name_off);
6097 	if (str_is_empty(local_name))
6098 		return ERR_PTR(-EINVAL);
6099 	local_essent_len = bpf_core_essential_name_len(local_name);
6100 
6101 	cands = calloc(1, sizeof(*cands));
6102 	if (!cands)
6103 		return ERR_PTR(-ENOMEM);
6104 
6105 	/* Attempt to find target candidates in vmlinux BTF first */
6106 	main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
6107 	err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
6108 	if (err)
6109 		goto err_out;
6110 
6111 	/* if vmlinux BTF has any candidate, don't got for module BTFs */
6112 	if (cands->len)
6113 		return cands;
6114 
6115 	/* if vmlinux BTF was overridden, don't attempt to load module BTFs */
6116 	if (obj->btf_vmlinux_override)
6117 		return cands;
6118 
6119 	/* now look through module BTFs, trying to still find candidates */
6120 	err = load_module_btfs(obj);
6121 	if (err)
6122 		goto err_out;
6123 
6124 	for (i = 0; i < obj->btf_module_cnt; i++) {
6125 		err = bpf_core_add_cands(&local_cand, local_essent_len,
6126 					 obj->btf_modules[i].btf,
6127 					 obj->btf_modules[i].name,
6128 					 btf__type_cnt(obj->btf_vmlinux),
6129 					 cands);
6130 		if (err)
6131 			goto err_out;
6132 	}
6133 
6134 	return cands;
6135 err_out:
6136 	bpf_core_free_cands(cands);
6137 	return ERR_PTR(err);
6138 }
6139 
6140 /* Check local and target types for compatibility. This check is used for
6141  * type-based CO-RE relocations and follow slightly different rules than
6142  * field-based relocations. This function assumes that root types were already
6143  * checked for name match. Beyond that initial root-level name check, names
6144  * are completely ignored. Compatibility rules are as follows:
6145  *   - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
6146  *     kind should match for local and target types (i.e., STRUCT is not
6147  *     compatible with UNION);
6148  *   - for ENUMs, the size is ignored;
6149  *   - for INT, size and signedness are ignored;
6150  *   - for ARRAY, dimensionality is ignored, element types are checked for
6151  *     compatibility recursively;
6152  *   - CONST/VOLATILE/RESTRICT modifiers are ignored;
6153  *   - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
6154  *   - FUNC_PROTOs are compatible if they have compatible signature: same
6155  *     number of input args and compatible return and argument types.
6156  * These rules are not set in stone and probably will be adjusted as we get
6157  * more experience with using BPF CO-RE relocations.
6158  */
6159 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
6160 			      const struct btf *targ_btf, __u32 targ_id)
6161 {
6162 	return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id, 32);
6163 }
6164 
6165 int bpf_core_types_match(const struct btf *local_btf, __u32 local_id,
6166 			 const struct btf *targ_btf, __u32 targ_id)
6167 {
6168 	return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false, 32);
6169 }
6170 
6171 static size_t bpf_core_hash_fn(const long key, void *ctx)
6172 {
6173 	return key;
6174 }
6175 
6176 static bool bpf_core_equal_fn(const long k1, const long k2, void *ctx)
6177 {
6178 	return k1 == k2;
6179 }
6180 
6181 static int record_relo_core(struct bpf_program *prog,
6182 			    const struct bpf_core_relo *core_relo, int insn_idx)
6183 {
6184 	struct reloc_desc *relos, *relo;
6185 
6186 	relos = libbpf_reallocarray(prog->reloc_desc,
6187 				    prog->nr_reloc + 1, sizeof(*relos));
6188 	if (!relos)
6189 		return -ENOMEM;
6190 	relo = &relos[prog->nr_reloc];
6191 	relo->type = RELO_CORE;
6192 	relo->insn_idx = insn_idx;
6193 	relo->core_relo = core_relo;
6194 	prog->reloc_desc = relos;
6195 	prog->nr_reloc++;
6196 	return 0;
6197 }
6198 
6199 static const struct bpf_core_relo *find_relo_core(struct bpf_program *prog, int insn_idx)
6200 {
6201 	struct reloc_desc *relo;
6202 	int i;
6203 
6204 	for (i = 0; i < prog->nr_reloc; i++) {
6205 		relo = &prog->reloc_desc[i];
6206 		if (relo->type != RELO_CORE || relo->insn_idx != insn_idx)
6207 			continue;
6208 
6209 		return relo->core_relo;
6210 	}
6211 
6212 	return NULL;
6213 }
6214 
6215 static int bpf_core_resolve_relo(struct bpf_program *prog,
6216 				 const struct bpf_core_relo *relo,
6217 				 int relo_idx,
6218 				 const struct btf *local_btf,
6219 				 struct hashmap *cand_cache,
6220 				 struct bpf_core_relo_res *targ_res)
6221 {
6222 	struct bpf_core_spec specs_scratch[3] = {};
6223 	struct bpf_core_cand_list *cands = NULL;
6224 	const char *prog_name = prog->name;
6225 	const struct btf_type *local_type;
6226 	const char *local_name;
6227 	__u32 local_id = relo->type_id;
6228 	int err;
6229 
6230 	local_type = btf__type_by_id(local_btf, local_id);
6231 	if (!local_type)
6232 		return -EINVAL;
6233 
6234 	local_name = btf__name_by_offset(local_btf, local_type->name_off);
6235 	if (!local_name)
6236 		return -EINVAL;
6237 
6238 	if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
6239 	    !hashmap__find(cand_cache, local_id, &cands)) {
6240 		cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
6241 		if (IS_ERR(cands)) {
6242 			pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n",
6243 				prog_name, relo_idx, local_id, btf_kind_str(local_type),
6244 				local_name, PTR_ERR(cands));
6245 			return PTR_ERR(cands);
6246 		}
6247 		err = hashmap__set(cand_cache, local_id, cands, NULL, NULL);
6248 		if (err) {
6249 			bpf_core_free_cands(cands);
6250 			return err;
6251 		}
6252 	}
6253 
6254 	return bpf_core_calc_relo_insn(prog_name, relo, relo_idx, local_btf, cands, specs_scratch,
6255 				       targ_res);
6256 }
6257 
6258 static int
6259 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
6260 {
6261 	const struct btf_ext_info_sec *sec;
6262 	struct bpf_core_relo_res targ_res;
6263 	const struct bpf_core_relo *rec;
6264 	const struct btf_ext_info *seg;
6265 	struct hashmap_entry *entry;
6266 	struct hashmap *cand_cache = NULL;
6267 	struct bpf_program *prog;
6268 	struct bpf_insn *insn;
6269 	const char *sec_name;
6270 	int i, err = 0, insn_idx, sec_idx, sec_num;
6271 
6272 	if (obj->btf_ext->core_relo_info.len == 0)
6273 		return 0;
6274 
6275 	if (targ_btf_path) {
6276 		obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
6277 		err = libbpf_get_error(obj->btf_vmlinux_override);
6278 		if (err) {
6279 			pr_warn("failed to parse target BTF: %d\n", err);
6280 			return err;
6281 		}
6282 	}
6283 
6284 	cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
6285 	if (IS_ERR(cand_cache)) {
6286 		err = PTR_ERR(cand_cache);
6287 		goto out;
6288 	}
6289 
6290 	seg = &obj->btf_ext->core_relo_info;
6291 	sec_num = 0;
6292 	for_each_btf_ext_sec(seg, sec) {
6293 		sec_idx = seg->sec_idxs[sec_num];
6294 		sec_num++;
6295 
6296 		sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
6297 		if (str_is_empty(sec_name)) {
6298 			err = -EINVAL;
6299 			goto out;
6300 		}
6301 
6302 		pr_debug("sec '%s': found %d CO-RE relocations\n", sec_name, sec->num_info);
6303 
6304 		for_each_btf_ext_rec(seg, sec, i, rec) {
6305 			if (rec->insn_off % BPF_INSN_SZ)
6306 				return -EINVAL;
6307 			insn_idx = rec->insn_off / BPF_INSN_SZ;
6308 			prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
6309 			if (!prog) {
6310 				/* When __weak subprog is "overridden" by another instance
6311 				 * of the subprog from a different object file, linker still
6312 				 * appends all the .BTF.ext info that used to belong to that
6313 				 * eliminated subprogram.
6314 				 * This is similar to what x86-64 linker does for relocations.
6315 				 * So just ignore such relocations just like we ignore
6316 				 * subprog instructions when discovering subprograms.
6317 				 */
6318 				pr_debug("sec '%s': skipping CO-RE relocation #%d for insn #%d belonging to eliminated weak subprogram\n",
6319 					 sec_name, i, insn_idx);
6320 				continue;
6321 			}
6322 			/* no need to apply CO-RE relocation if the program is
6323 			 * not going to be loaded
6324 			 */
6325 			if (!prog->autoload)
6326 				continue;
6327 
6328 			/* adjust insn_idx from section frame of reference to the local
6329 			 * program's frame of reference; (sub-)program code is not yet
6330 			 * relocated, so it's enough to just subtract in-section offset
6331 			 */
6332 			insn_idx = insn_idx - prog->sec_insn_off;
6333 			if (insn_idx >= prog->insns_cnt)
6334 				return -EINVAL;
6335 			insn = &prog->insns[insn_idx];
6336 
6337 			err = record_relo_core(prog, rec, insn_idx);
6338 			if (err) {
6339 				pr_warn("prog '%s': relo #%d: failed to record relocation: %d\n",
6340 					prog->name, i, err);
6341 				goto out;
6342 			}
6343 
6344 			if (prog->obj->gen_loader)
6345 				continue;
6346 
6347 			err = bpf_core_resolve_relo(prog, rec, i, obj->btf, cand_cache, &targ_res);
6348 			if (err) {
6349 				pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
6350 					prog->name, i, err);
6351 				goto out;
6352 			}
6353 
6354 			err = bpf_core_patch_insn(prog->name, insn, insn_idx, rec, i, &targ_res);
6355 			if (err) {
6356 				pr_warn("prog '%s': relo #%d: failed to patch insn #%u: %d\n",
6357 					prog->name, i, insn_idx, err);
6358 				goto out;
6359 			}
6360 		}
6361 	}
6362 
6363 out:
6364 	/* obj->btf_vmlinux and module BTFs are freed after object load */
6365 	btf__free(obj->btf_vmlinux_override);
6366 	obj->btf_vmlinux_override = NULL;
6367 
6368 	if (!IS_ERR_OR_NULL(cand_cache)) {
6369 		hashmap__for_each_entry(cand_cache, entry, i) {
6370 			bpf_core_free_cands(entry->pvalue);
6371 		}
6372 		hashmap__free(cand_cache);
6373 	}
6374 	return err;
6375 }
6376 
6377 /* base map load ldimm64 special constant, used also for log fixup logic */
6378 #define POISON_LDIMM64_MAP_BASE 2001000000
6379 #define POISON_LDIMM64_MAP_PFX "200100"
6380 
6381 static void poison_map_ldimm64(struct bpf_program *prog, int relo_idx,
6382 			       int insn_idx, struct bpf_insn *insn,
6383 			       int map_idx, const struct bpf_map *map)
6384 {
6385 	int i;
6386 
6387 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that loads map #%d '%s'\n",
6388 		 prog->name, relo_idx, insn_idx, map_idx, map->name);
6389 
6390 	/* we turn single ldimm64 into two identical invalid calls */
6391 	for (i = 0; i < 2; i++) {
6392 		insn->code = BPF_JMP | BPF_CALL;
6393 		insn->dst_reg = 0;
6394 		insn->src_reg = 0;
6395 		insn->off = 0;
6396 		/* if this instruction is reachable (not a dead code),
6397 		 * verifier will complain with something like:
6398 		 * invalid func unknown#2001000123
6399 		 * where lower 123 is map index into obj->maps[] array
6400 		 */
6401 		insn->imm = POISON_LDIMM64_MAP_BASE + map_idx;
6402 
6403 		insn++;
6404 	}
6405 }
6406 
6407 /* unresolved kfunc call special constant, used also for log fixup logic */
6408 #define POISON_CALL_KFUNC_BASE 2002000000
6409 #define POISON_CALL_KFUNC_PFX "2002"
6410 
6411 static void poison_kfunc_call(struct bpf_program *prog, int relo_idx,
6412 			      int insn_idx, struct bpf_insn *insn,
6413 			      int ext_idx, const struct extern_desc *ext)
6414 {
6415 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that calls kfunc '%s'\n",
6416 		 prog->name, relo_idx, insn_idx, ext->name);
6417 
6418 	/* we turn kfunc call into invalid helper call with identifiable constant */
6419 	insn->code = BPF_JMP | BPF_CALL;
6420 	insn->dst_reg = 0;
6421 	insn->src_reg = 0;
6422 	insn->off = 0;
6423 	/* if this instruction is reachable (not a dead code),
6424 	 * verifier will complain with something like:
6425 	 * invalid func unknown#2001000123
6426 	 * where lower 123 is extern index into obj->externs[] array
6427 	 */
6428 	insn->imm = POISON_CALL_KFUNC_BASE + ext_idx;
6429 }
6430 
6431 /* Relocate data references within program code:
6432  *  - map references;
6433  *  - global variable references;
6434  *  - extern references.
6435  */
6436 static int
6437 bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
6438 {
6439 	int i;
6440 
6441 	for (i = 0; i < prog->nr_reloc; i++) {
6442 		struct reloc_desc *relo = &prog->reloc_desc[i];
6443 		struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6444 		const struct bpf_map *map;
6445 		struct extern_desc *ext;
6446 
6447 		switch (relo->type) {
6448 		case RELO_LD64:
6449 			map = &obj->maps[relo->map_idx];
6450 			if (obj->gen_loader) {
6451 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
6452 				insn[0].imm = relo->map_idx;
6453 			} else if (map->autocreate) {
6454 				insn[0].src_reg = BPF_PSEUDO_MAP_FD;
6455 				insn[0].imm = map->fd;
6456 			} else {
6457 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6458 						   relo->map_idx, map);
6459 			}
6460 			break;
6461 		case RELO_DATA:
6462 			map = &obj->maps[relo->map_idx];
6463 			insn[1].imm = insn[0].imm + relo->sym_off;
6464 			if (obj->gen_loader) {
6465 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6466 				insn[0].imm = relo->map_idx;
6467 			} else if (map->autocreate) {
6468 				insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6469 				insn[0].imm = map->fd;
6470 			} else {
6471 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6472 						   relo->map_idx, map);
6473 			}
6474 			break;
6475 		case RELO_EXTERN_LD64:
6476 			ext = &obj->externs[relo->ext_idx];
6477 			if (ext->type == EXT_KCFG) {
6478 				if (obj->gen_loader) {
6479 					insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6480 					insn[0].imm = obj->kconfig_map_idx;
6481 				} else {
6482 					insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6483 					insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
6484 				}
6485 				insn[1].imm = ext->kcfg.data_off;
6486 			} else /* EXT_KSYM */ {
6487 				if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
6488 					insn[0].src_reg = BPF_PSEUDO_BTF_ID;
6489 					insn[0].imm = ext->ksym.kernel_btf_id;
6490 					insn[1].imm = ext->ksym.kernel_btf_obj_fd;
6491 				} else { /* typeless ksyms or unresolved typed ksyms */
6492 					insn[0].imm = (__u32)ext->ksym.addr;
6493 					insn[1].imm = ext->ksym.addr >> 32;
6494 				}
6495 			}
6496 			break;
6497 		case RELO_EXTERN_CALL:
6498 			ext = &obj->externs[relo->ext_idx];
6499 			insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
6500 			if (ext->is_set) {
6501 				insn[0].imm = ext->ksym.kernel_btf_id;
6502 				insn[0].off = ext->ksym.btf_fd_idx;
6503 			} else { /* unresolved weak kfunc call */
6504 				poison_kfunc_call(prog, i, relo->insn_idx, insn,
6505 						  relo->ext_idx, ext);
6506 			}
6507 			break;
6508 		case RELO_SUBPROG_ADDR:
6509 			if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
6510 				pr_warn("prog '%s': relo #%d: bad insn\n",
6511 					prog->name, i);
6512 				return -EINVAL;
6513 			}
6514 			/* handled already */
6515 			break;
6516 		case RELO_CALL:
6517 			/* handled already */
6518 			break;
6519 		case RELO_CORE:
6520 			/* will be handled by bpf_program_record_relos() */
6521 			break;
6522 		default:
6523 			pr_warn("prog '%s': relo #%d: bad relo type %d\n",
6524 				prog->name, i, relo->type);
6525 			return -EINVAL;
6526 		}
6527 	}
6528 
6529 	return 0;
6530 }
6531 
6532 static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
6533 				    const struct bpf_program *prog,
6534 				    const struct btf_ext_info *ext_info,
6535 				    void **prog_info, __u32 *prog_rec_cnt,
6536 				    __u32 *prog_rec_sz)
6537 {
6538 	void *copy_start = NULL, *copy_end = NULL;
6539 	void *rec, *rec_end, *new_prog_info;
6540 	const struct btf_ext_info_sec *sec;
6541 	size_t old_sz, new_sz;
6542 	int i, sec_num, sec_idx, off_adj;
6543 
6544 	sec_num = 0;
6545 	for_each_btf_ext_sec(ext_info, sec) {
6546 		sec_idx = ext_info->sec_idxs[sec_num];
6547 		sec_num++;
6548 		if (prog->sec_idx != sec_idx)
6549 			continue;
6550 
6551 		for_each_btf_ext_rec(ext_info, sec, i, rec) {
6552 			__u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
6553 
6554 			if (insn_off < prog->sec_insn_off)
6555 				continue;
6556 			if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
6557 				break;
6558 
6559 			if (!copy_start)
6560 				copy_start = rec;
6561 			copy_end = rec + ext_info->rec_size;
6562 		}
6563 
6564 		if (!copy_start)
6565 			return -ENOENT;
6566 
6567 		/* append func/line info of a given (sub-)program to the main
6568 		 * program func/line info
6569 		 */
6570 		old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
6571 		new_sz = old_sz + (copy_end - copy_start);
6572 		new_prog_info = realloc(*prog_info, new_sz);
6573 		if (!new_prog_info)
6574 			return -ENOMEM;
6575 		*prog_info = new_prog_info;
6576 		*prog_rec_cnt = new_sz / ext_info->rec_size;
6577 		memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
6578 
6579 		/* Kernel instruction offsets are in units of 8-byte
6580 		 * instructions, while .BTF.ext instruction offsets generated
6581 		 * by Clang are in units of bytes. So convert Clang offsets
6582 		 * into kernel offsets and adjust offset according to program
6583 		 * relocated position.
6584 		 */
6585 		off_adj = prog->sub_insn_off - prog->sec_insn_off;
6586 		rec = new_prog_info + old_sz;
6587 		rec_end = new_prog_info + new_sz;
6588 		for (; rec < rec_end; rec += ext_info->rec_size) {
6589 			__u32 *insn_off = rec;
6590 
6591 			*insn_off = *insn_off / BPF_INSN_SZ + off_adj;
6592 		}
6593 		*prog_rec_sz = ext_info->rec_size;
6594 		return 0;
6595 	}
6596 
6597 	return -ENOENT;
6598 }
6599 
6600 static int
6601 reloc_prog_func_and_line_info(const struct bpf_object *obj,
6602 			      struct bpf_program *main_prog,
6603 			      const struct bpf_program *prog)
6604 {
6605 	int err;
6606 
6607 	/* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
6608 	 * supprot func/line info
6609 	 */
6610 	if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
6611 		return 0;
6612 
6613 	/* only attempt func info relocation if main program's func_info
6614 	 * relocation was successful
6615 	 */
6616 	if (main_prog != prog && !main_prog->func_info)
6617 		goto line_info;
6618 
6619 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
6620 				       &main_prog->func_info,
6621 				       &main_prog->func_info_cnt,
6622 				       &main_prog->func_info_rec_size);
6623 	if (err) {
6624 		if (err != -ENOENT) {
6625 			pr_warn("prog '%s': error relocating .BTF.ext function info: %d\n",
6626 				prog->name, err);
6627 			return err;
6628 		}
6629 		if (main_prog->func_info) {
6630 			/*
6631 			 * Some info has already been found but has problem
6632 			 * in the last btf_ext reloc. Must have to error out.
6633 			 */
6634 			pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
6635 			return err;
6636 		}
6637 		/* Have problem loading the very first info. Ignore the rest. */
6638 		pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
6639 			prog->name);
6640 	}
6641 
6642 line_info:
6643 	/* don't relocate line info if main program's relocation failed */
6644 	if (main_prog != prog && !main_prog->line_info)
6645 		return 0;
6646 
6647 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
6648 				       &main_prog->line_info,
6649 				       &main_prog->line_info_cnt,
6650 				       &main_prog->line_info_rec_size);
6651 	if (err) {
6652 		if (err != -ENOENT) {
6653 			pr_warn("prog '%s': error relocating .BTF.ext line info: %d\n",
6654 				prog->name, err);
6655 			return err;
6656 		}
6657 		if (main_prog->line_info) {
6658 			/*
6659 			 * Some info has already been found but has problem
6660 			 * in the last btf_ext reloc. Must have to error out.
6661 			 */
6662 			pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
6663 			return err;
6664 		}
6665 		/* Have problem loading the very first info. Ignore the rest. */
6666 		pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
6667 			prog->name);
6668 	}
6669 	return 0;
6670 }
6671 
6672 static int cmp_relo_by_insn_idx(const void *key, const void *elem)
6673 {
6674 	size_t insn_idx = *(const size_t *)key;
6675 	const struct reloc_desc *relo = elem;
6676 
6677 	if (insn_idx == relo->insn_idx)
6678 		return 0;
6679 	return insn_idx < relo->insn_idx ? -1 : 1;
6680 }
6681 
6682 static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
6683 {
6684 	if (!prog->nr_reloc)
6685 		return NULL;
6686 	return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
6687 		       sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
6688 }
6689 
6690 static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
6691 {
6692 	int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
6693 	struct reloc_desc *relos;
6694 	int i;
6695 
6696 	if (main_prog == subprog)
6697 		return 0;
6698 	relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
6699 	/* if new count is zero, reallocarray can return a valid NULL result;
6700 	 * in this case the previous pointer will be freed, so we *have to*
6701 	 * reassign old pointer to the new value (even if it's NULL)
6702 	 */
6703 	if (!relos && new_cnt)
6704 		return -ENOMEM;
6705 	if (subprog->nr_reloc)
6706 		memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
6707 		       sizeof(*relos) * subprog->nr_reloc);
6708 
6709 	for (i = main_prog->nr_reloc; i < new_cnt; i++)
6710 		relos[i].insn_idx += subprog->sub_insn_off;
6711 	/* After insn_idx adjustment the 'relos' array is still sorted
6712 	 * by insn_idx and doesn't break bsearch.
6713 	 */
6714 	main_prog->reloc_desc = relos;
6715 	main_prog->nr_reloc = new_cnt;
6716 	return 0;
6717 }
6718 
6719 static int
6720 bpf_object__append_subprog_code(struct bpf_object *obj, struct bpf_program *main_prog,
6721 				struct bpf_program *subprog)
6722 {
6723        struct bpf_insn *insns;
6724        size_t new_cnt;
6725        int err;
6726 
6727        subprog->sub_insn_off = main_prog->insns_cnt;
6728 
6729        new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
6730        insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
6731        if (!insns) {
6732                pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
6733                return -ENOMEM;
6734        }
6735        main_prog->insns = insns;
6736        main_prog->insns_cnt = new_cnt;
6737 
6738        memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
6739               subprog->insns_cnt * sizeof(*insns));
6740 
6741        pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
6742                 main_prog->name, subprog->insns_cnt, subprog->name);
6743 
6744        /* The subprog insns are now appended. Append its relos too. */
6745        err = append_subprog_relos(main_prog, subprog);
6746        if (err)
6747                return err;
6748        return 0;
6749 }
6750 
6751 static int
6752 bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
6753 		       struct bpf_program *prog)
6754 {
6755 	size_t sub_insn_idx, insn_idx;
6756 	struct bpf_program *subprog;
6757 	struct reloc_desc *relo;
6758 	struct bpf_insn *insn;
6759 	int err;
6760 
6761 	err = reloc_prog_func_and_line_info(obj, main_prog, prog);
6762 	if (err)
6763 		return err;
6764 
6765 	for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
6766 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6767 		if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
6768 			continue;
6769 
6770 		relo = find_prog_insn_relo(prog, insn_idx);
6771 		if (relo && relo->type == RELO_EXTERN_CALL)
6772 			/* kfunc relocations will be handled later
6773 			 * in bpf_object__relocate_data()
6774 			 */
6775 			continue;
6776 		if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
6777 			pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
6778 				prog->name, insn_idx, relo->type);
6779 			return -LIBBPF_ERRNO__RELOC;
6780 		}
6781 		if (relo) {
6782 			/* sub-program instruction index is a combination of
6783 			 * an offset of a symbol pointed to by relocation and
6784 			 * call instruction's imm field; for global functions,
6785 			 * call always has imm = -1, but for static functions
6786 			 * relocation is against STT_SECTION and insn->imm
6787 			 * points to a start of a static function
6788 			 *
6789 			 * for subprog addr relocation, the relo->sym_off + insn->imm is
6790 			 * the byte offset in the corresponding section.
6791 			 */
6792 			if (relo->type == RELO_CALL)
6793 				sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
6794 			else
6795 				sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
6796 		} else if (insn_is_pseudo_func(insn)) {
6797 			/*
6798 			 * RELO_SUBPROG_ADDR relo is always emitted even if both
6799 			 * functions are in the same section, so it shouldn't reach here.
6800 			 */
6801 			pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
6802 				prog->name, insn_idx);
6803 			return -LIBBPF_ERRNO__RELOC;
6804 		} else {
6805 			/* if subprogram call is to a static function within
6806 			 * the same ELF section, there won't be any relocation
6807 			 * emitted, but it also means there is no additional
6808 			 * offset necessary, insns->imm is relative to
6809 			 * instruction's original position within the section
6810 			 */
6811 			sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
6812 		}
6813 
6814 		/* we enforce that sub-programs should be in .text section */
6815 		subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
6816 		if (!subprog) {
6817 			pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
6818 				prog->name);
6819 			return -LIBBPF_ERRNO__RELOC;
6820 		}
6821 
6822 		/* if it's the first call instruction calling into this
6823 		 * subprogram (meaning this subprog hasn't been processed
6824 		 * yet) within the context of current main program:
6825 		 *   - append it at the end of main program's instructions blog;
6826 		 *   - process is recursively, while current program is put on hold;
6827 		 *   - if that subprogram calls some other not yet processes
6828 		 *   subprogram, same thing will happen recursively until
6829 		 *   there are no more unprocesses subprograms left to append
6830 		 *   and relocate.
6831 		 */
6832 		if (subprog->sub_insn_off == 0) {
6833 			err = bpf_object__append_subprog_code(obj, main_prog, subprog);
6834 			if (err)
6835 				return err;
6836 			err = bpf_object__reloc_code(obj, main_prog, subprog);
6837 			if (err)
6838 				return err;
6839 		}
6840 
6841 		/* main_prog->insns memory could have been re-allocated, so
6842 		 * calculate pointer again
6843 		 */
6844 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6845 		/* calculate correct instruction position within current main
6846 		 * prog; each main prog can have a different set of
6847 		 * subprograms appended (potentially in different order as
6848 		 * well), so position of any subprog can be different for
6849 		 * different main programs
6850 		 */
6851 		insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
6852 
6853 		pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
6854 			 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
6855 	}
6856 
6857 	return 0;
6858 }
6859 
6860 /*
6861  * Relocate sub-program calls.
6862  *
6863  * Algorithm operates as follows. Each entry-point BPF program (referred to as
6864  * main prog) is processed separately. For each subprog (non-entry functions,
6865  * that can be called from either entry progs or other subprogs) gets their
6866  * sub_insn_off reset to zero. This serves as indicator that this subprogram
6867  * hasn't been yet appended and relocated within current main prog. Once its
6868  * relocated, sub_insn_off will point at the position within current main prog
6869  * where given subprog was appended. This will further be used to relocate all
6870  * the call instructions jumping into this subprog.
6871  *
6872  * We start with main program and process all call instructions. If the call
6873  * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
6874  * is zero), subprog instructions are appended at the end of main program's
6875  * instruction array. Then main program is "put on hold" while we recursively
6876  * process newly appended subprogram. If that subprogram calls into another
6877  * subprogram that hasn't been appended, new subprogram is appended again to
6878  * the *main* prog's instructions (subprog's instructions are always left
6879  * untouched, as they need to be in unmodified state for subsequent main progs
6880  * and subprog instructions are always sent only as part of a main prog) and
6881  * the process continues recursively. Once all the subprogs called from a main
6882  * prog or any of its subprogs are appended (and relocated), all their
6883  * positions within finalized instructions array are known, so it's easy to
6884  * rewrite call instructions with correct relative offsets, corresponding to
6885  * desired target subprog.
6886  *
6887  * Its important to realize that some subprogs might not be called from some
6888  * main prog and any of its called/used subprogs. Those will keep their
6889  * subprog->sub_insn_off as zero at all times and won't be appended to current
6890  * main prog and won't be relocated within the context of current main prog.
6891  * They might still be used from other main progs later.
6892  *
6893  * Visually this process can be shown as below. Suppose we have two main
6894  * programs mainA and mainB and BPF object contains three subprogs: subA,
6895  * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
6896  * subC both call subB:
6897  *
6898  *        +--------+ +-------+
6899  *        |        v v       |
6900  *     +--+---+ +--+-+-+ +---+--+
6901  *     | subA | | subB | | subC |
6902  *     +--+---+ +------+ +---+--+
6903  *        ^                  ^
6904  *        |                  |
6905  *    +---+-------+   +------+----+
6906  *    |   mainA   |   |   mainB   |
6907  *    +-----------+   +-----------+
6908  *
6909  * We'll start relocating mainA, will find subA, append it and start
6910  * processing sub A recursively:
6911  *
6912  *    +-----------+------+
6913  *    |   mainA   | subA |
6914  *    +-----------+------+
6915  *
6916  * At this point we notice that subB is used from subA, so we append it and
6917  * relocate (there are no further subcalls from subB):
6918  *
6919  *    +-----------+------+------+
6920  *    |   mainA   | subA | subB |
6921  *    +-----------+------+------+
6922  *
6923  * At this point, we relocate subA calls, then go one level up and finish with
6924  * relocatin mainA calls. mainA is done.
6925  *
6926  * For mainB process is similar but results in different order. We start with
6927  * mainB and skip subA and subB, as mainB never calls them (at least
6928  * directly), but we see subC is needed, so we append and start processing it:
6929  *
6930  *    +-----------+------+
6931  *    |   mainB   | subC |
6932  *    +-----------+------+
6933  * Now we see subC needs subB, so we go back to it, append and relocate it:
6934  *
6935  *    +-----------+------+------+
6936  *    |   mainB   | subC | subB |
6937  *    +-----------+------+------+
6938  *
6939  * At this point we unwind recursion, relocate calls in subC, then in mainB.
6940  */
6941 static int
6942 bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
6943 {
6944 	struct bpf_program *subprog;
6945 	int i, err;
6946 
6947 	/* mark all subprogs as not relocated (yet) within the context of
6948 	 * current main program
6949 	 */
6950 	for (i = 0; i < obj->nr_programs; i++) {
6951 		subprog = &obj->programs[i];
6952 		if (!prog_is_subprog(obj, subprog))
6953 			continue;
6954 
6955 		subprog->sub_insn_off = 0;
6956 	}
6957 
6958 	err = bpf_object__reloc_code(obj, prog, prog);
6959 	if (err)
6960 		return err;
6961 
6962 	return 0;
6963 }
6964 
6965 static void
6966 bpf_object__free_relocs(struct bpf_object *obj)
6967 {
6968 	struct bpf_program *prog;
6969 	int i;
6970 
6971 	/* free up relocation descriptors */
6972 	for (i = 0; i < obj->nr_programs; i++) {
6973 		prog = &obj->programs[i];
6974 		zfree(&prog->reloc_desc);
6975 		prog->nr_reloc = 0;
6976 	}
6977 }
6978 
6979 static int cmp_relocs(const void *_a, const void *_b)
6980 {
6981 	const struct reloc_desc *a = _a;
6982 	const struct reloc_desc *b = _b;
6983 
6984 	if (a->insn_idx != b->insn_idx)
6985 		return a->insn_idx < b->insn_idx ? -1 : 1;
6986 
6987 	/* no two relocations should have the same insn_idx, but ... */
6988 	if (a->type != b->type)
6989 		return a->type < b->type ? -1 : 1;
6990 
6991 	return 0;
6992 }
6993 
6994 static void bpf_object__sort_relos(struct bpf_object *obj)
6995 {
6996 	int i;
6997 
6998 	for (i = 0; i < obj->nr_programs; i++) {
6999 		struct bpf_program *p = &obj->programs[i];
7000 
7001 		if (!p->nr_reloc)
7002 			continue;
7003 
7004 		qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
7005 	}
7006 }
7007 
7008 static int
7009 bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
7010 {
7011 	struct bpf_program *prog;
7012 	size_t i, j;
7013 	int err;
7014 
7015 	if (obj->btf_ext) {
7016 		err = bpf_object__relocate_core(obj, targ_btf_path);
7017 		if (err) {
7018 			pr_warn("failed to perform CO-RE relocations: %d\n",
7019 				err);
7020 			return err;
7021 		}
7022 		bpf_object__sort_relos(obj);
7023 	}
7024 
7025 	/* Before relocating calls pre-process relocations and mark
7026 	 * few ld_imm64 instructions that points to subprogs.
7027 	 * Otherwise bpf_object__reloc_code() later would have to consider
7028 	 * all ld_imm64 insns as relocation candidates. That would
7029 	 * reduce relocation speed, since amount of find_prog_insn_relo()
7030 	 * would increase and most of them will fail to find a relo.
7031 	 */
7032 	for (i = 0; i < obj->nr_programs; i++) {
7033 		prog = &obj->programs[i];
7034 		for (j = 0; j < prog->nr_reloc; j++) {
7035 			struct reloc_desc *relo = &prog->reloc_desc[j];
7036 			struct bpf_insn *insn = &prog->insns[relo->insn_idx];
7037 
7038 			/* mark the insn, so it's recognized by insn_is_pseudo_func() */
7039 			if (relo->type == RELO_SUBPROG_ADDR)
7040 				insn[0].src_reg = BPF_PSEUDO_FUNC;
7041 		}
7042 	}
7043 
7044 	/* relocate subprogram calls and append used subprograms to main
7045 	 * programs; each copy of subprogram code needs to be relocated
7046 	 * differently for each main program, because its code location might
7047 	 * have changed.
7048 	 * Append subprog relos to main programs to allow data relos to be
7049 	 * processed after text is completely relocated.
7050 	 */
7051 	for (i = 0; i < obj->nr_programs; i++) {
7052 		prog = &obj->programs[i];
7053 		/* sub-program's sub-calls are relocated within the context of
7054 		 * its main program only
7055 		 */
7056 		if (prog_is_subprog(obj, prog))
7057 			continue;
7058 		if (!prog->autoload)
7059 			continue;
7060 
7061 		err = bpf_object__relocate_calls(obj, prog);
7062 		if (err) {
7063 			pr_warn("prog '%s': failed to relocate calls: %d\n",
7064 				prog->name, err);
7065 			return err;
7066 		}
7067 
7068 		/* Now, also append exception callback if it has not been done already. */
7069 		if (prog->exception_cb_idx >= 0) {
7070 			struct bpf_program *subprog = &obj->programs[prog->exception_cb_idx];
7071 
7072 			/* Calling exception callback directly is disallowed, which the
7073 			 * verifier will reject later. In case it was processed already,
7074 			 * we can skip this step, otherwise for all other valid cases we
7075 			 * have to append exception callback now.
7076 			 */
7077 			if (subprog->sub_insn_off == 0) {
7078 				err = bpf_object__append_subprog_code(obj, prog, subprog);
7079 				if (err)
7080 					return err;
7081 				err = bpf_object__reloc_code(obj, prog, subprog);
7082 				if (err)
7083 					return err;
7084 			}
7085 		}
7086 	}
7087 	/* Process data relos for main programs */
7088 	for (i = 0; i < obj->nr_programs; i++) {
7089 		prog = &obj->programs[i];
7090 		if (prog_is_subprog(obj, prog))
7091 			continue;
7092 		if (!prog->autoload)
7093 			continue;
7094 		err = bpf_object__relocate_data(obj, prog);
7095 		if (err) {
7096 			pr_warn("prog '%s': failed to relocate data references: %d\n",
7097 				prog->name, err);
7098 			return err;
7099 		}
7100 	}
7101 
7102 	return 0;
7103 }
7104 
7105 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
7106 					    Elf64_Shdr *shdr, Elf_Data *data);
7107 
7108 static int bpf_object__collect_map_relos(struct bpf_object *obj,
7109 					 Elf64_Shdr *shdr, Elf_Data *data)
7110 {
7111 	const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
7112 	int i, j, nrels, new_sz;
7113 	const struct btf_var_secinfo *vi = NULL;
7114 	const struct btf_type *sec, *var, *def;
7115 	struct bpf_map *map = NULL, *targ_map = NULL;
7116 	struct bpf_program *targ_prog = NULL;
7117 	bool is_prog_array, is_map_in_map;
7118 	const struct btf_member *member;
7119 	const char *name, *mname, *type;
7120 	unsigned int moff;
7121 	Elf64_Sym *sym;
7122 	Elf64_Rel *rel;
7123 	void *tmp;
7124 
7125 	if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
7126 		return -EINVAL;
7127 	sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
7128 	if (!sec)
7129 		return -EINVAL;
7130 
7131 	nrels = shdr->sh_size / shdr->sh_entsize;
7132 	for (i = 0; i < nrels; i++) {
7133 		rel = elf_rel_by_idx(data, i);
7134 		if (!rel) {
7135 			pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
7136 			return -LIBBPF_ERRNO__FORMAT;
7137 		}
7138 
7139 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
7140 		if (!sym) {
7141 			pr_warn(".maps relo #%d: symbol %zx not found\n",
7142 				i, (size_t)ELF64_R_SYM(rel->r_info));
7143 			return -LIBBPF_ERRNO__FORMAT;
7144 		}
7145 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
7146 
7147 		pr_debug(".maps relo #%d: for %zd value %zd rel->r_offset %zu name %d ('%s')\n",
7148 			 i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
7149 			 (size_t)rel->r_offset, sym->st_name, name);
7150 
7151 		for (j = 0; j < obj->nr_maps; j++) {
7152 			map = &obj->maps[j];
7153 			if (map->sec_idx != obj->efile.btf_maps_shndx)
7154 				continue;
7155 
7156 			vi = btf_var_secinfos(sec) + map->btf_var_idx;
7157 			if (vi->offset <= rel->r_offset &&
7158 			    rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size)
7159 				break;
7160 		}
7161 		if (j == obj->nr_maps) {
7162 			pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
7163 				i, name, (size_t)rel->r_offset);
7164 			return -EINVAL;
7165 		}
7166 
7167 		is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
7168 		is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
7169 		type = is_map_in_map ? "map" : "prog";
7170 		if (is_map_in_map) {
7171 			if (sym->st_shndx != obj->efile.btf_maps_shndx) {
7172 				pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
7173 					i, name);
7174 				return -LIBBPF_ERRNO__RELOC;
7175 			}
7176 			if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
7177 			    map->def.key_size != sizeof(int)) {
7178 				pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
7179 					i, map->name, sizeof(int));
7180 				return -EINVAL;
7181 			}
7182 			targ_map = bpf_object__find_map_by_name(obj, name);
7183 			if (!targ_map) {
7184 				pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
7185 					i, name);
7186 				return -ESRCH;
7187 			}
7188 		} else if (is_prog_array) {
7189 			targ_prog = bpf_object__find_program_by_name(obj, name);
7190 			if (!targ_prog) {
7191 				pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
7192 					i, name);
7193 				return -ESRCH;
7194 			}
7195 			if (targ_prog->sec_idx != sym->st_shndx ||
7196 			    targ_prog->sec_insn_off * 8 != sym->st_value ||
7197 			    prog_is_subprog(obj, targ_prog)) {
7198 				pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
7199 					i, name);
7200 				return -LIBBPF_ERRNO__RELOC;
7201 			}
7202 		} else {
7203 			return -EINVAL;
7204 		}
7205 
7206 		var = btf__type_by_id(obj->btf, vi->type);
7207 		def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
7208 		if (btf_vlen(def) == 0)
7209 			return -EINVAL;
7210 		member = btf_members(def) + btf_vlen(def) - 1;
7211 		mname = btf__name_by_offset(obj->btf, member->name_off);
7212 		if (strcmp(mname, "values"))
7213 			return -EINVAL;
7214 
7215 		moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
7216 		if (rel->r_offset - vi->offset < moff)
7217 			return -EINVAL;
7218 
7219 		moff = rel->r_offset - vi->offset - moff;
7220 		/* here we use BPF pointer size, which is always 64 bit, as we
7221 		 * are parsing ELF that was built for BPF target
7222 		 */
7223 		if (moff % bpf_ptr_sz)
7224 			return -EINVAL;
7225 		moff /= bpf_ptr_sz;
7226 		if (moff >= map->init_slots_sz) {
7227 			new_sz = moff + 1;
7228 			tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
7229 			if (!tmp)
7230 				return -ENOMEM;
7231 			map->init_slots = tmp;
7232 			memset(map->init_slots + map->init_slots_sz, 0,
7233 			       (new_sz - map->init_slots_sz) * host_ptr_sz);
7234 			map->init_slots_sz = new_sz;
7235 		}
7236 		map->init_slots[moff] = is_map_in_map ? (void *)targ_map : (void *)targ_prog;
7237 
7238 		pr_debug(".maps relo #%d: map '%s' slot [%d] points to %s '%s'\n",
7239 			 i, map->name, moff, type, name);
7240 	}
7241 
7242 	return 0;
7243 }
7244 
7245 static int bpf_object__collect_relos(struct bpf_object *obj)
7246 {
7247 	int i, err;
7248 
7249 	for (i = 0; i < obj->efile.sec_cnt; i++) {
7250 		struct elf_sec_desc *sec_desc = &obj->efile.secs[i];
7251 		Elf64_Shdr *shdr;
7252 		Elf_Data *data;
7253 		int idx;
7254 		Elf64_Shdr shdrelf;
7255 
7256 		if (sec_desc->sec_type != SEC_RELO)
7257 			continue;
7258 
7259 #if defined HAVE_LIBELF
7260 		shdr = sec_desc->shdr;
7261 #elif defined HAVE_ELFIO
7262 		shdr = elf_sec_hdr_by_idx(obj, i, &shdrelf);
7263 #endif
7264 		data = sec_desc->data;
7265 		idx = shdr->sh_info;
7266 
7267 		if (shdr->sh_type != SHT_REL) {
7268 			pr_warn("internal error at %d\n", __LINE__);
7269 			return -LIBBPF_ERRNO__INTERNAL;
7270 		}
7271 
7272 		if (idx == obj->efile.st_ops_shndx || idx == obj->efile.st_ops_link_shndx)
7273 			err = bpf_object__collect_st_ops_relos(obj, shdr, data);
7274 		else if (idx == obj->efile.btf_maps_shndx)
7275 			err = bpf_object__collect_map_relos(obj, shdr, data);
7276 		else
7277 			err = bpf_object__collect_prog_relos(obj, shdr, data);
7278 		if (err)
7279 			return err;
7280 	}
7281 
7282 	bpf_object__sort_relos(obj);
7283 	return 0;
7284 }
7285 
7286 static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
7287 {
7288 	if (BPF_CLASS(insn->code) == BPF_JMP &&
7289 	    BPF_OP(insn->code) == BPF_CALL &&
7290 	    BPF_SRC(insn->code) == BPF_K &&
7291 	    insn->src_reg == 0 &&
7292 	    insn->dst_reg == 0) {
7293 		    *func_id = insn->imm;
7294 		    return true;
7295 	}
7296 	return false;
7297 }
7298 
7299 static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
7300 {
7301 	struct bpf_insn *insn = prog->insns;
7302 	enum bpf_func_id func_id;
7303 	int i;
7304 
7305 	if (obj->gen_loader)
7306 		return 0;
7307 
7308 	for (i = 0; i < prog->insns_cnt; i++, insn++) {
7309 		if (!insn_is_helper_call(insn, &func_id))
7310 			continue;
7311 
7312 		/* on kernels that don't yet support
7313 		 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
7314 		 * to bpf_probe_read() which works well for old kernels
7315 		 */
7316 		switch (func_id) {
7317 		case BPF_FUNC_probe_read_kernel:
7318 		case BPF_FUNC_probe_read_user:
7319 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
7320 				insn->imm = BPF_FUNC_probe_read;
7321 			break;
7322 		case BPF_FUNC_probe_read_kernel_str:
7323 		case BPF_FUNC_probe_read_user_str:
7324 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
7325 				insn->imm = BPF_FUNC_probe_read_str;
7326 			break;
7327 		default:
7328 			break;
7329 		}
7330 	}
7331 	return 0;
7332 }
7333 
7334 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
7335 				     int *btf_obj_fd, int *btf_type_id);
7336 
7337 /* this is called as prog->sec_def->prog_prepare_load_fn for libbpf-supported sec_defs */
7338 static int libbpf_prepare_prog_load(struct bpf_program *prog,
7339 				    struct bpf_prog_load_opts *opts, long cookie)
7340 {
7341 	enum sec_def_flags def = cookie;
7342 
7343 	/* old kernels might not support specifying expected_attach_type */
7344 	if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
7345 		opts->expected_attach_type = 0;
7346 
7347 	if (def & SEC_SLEEPABLE)
7348 		opts->prog_flags |= BPF_F_SLEEPABLE;
7349 
7350 	if (prog->type == BPF_PROG_TYPE_XDP && (def & SEC_XDP_FRAGS))
7351 		opts->prog_flags |= BPF_F_XDP_HAS_FRAGS;
7352 
7353 	/* special check for usdt to use uprobe_multi link */
7354 	if ((def & SEC_USDT) && kernel_supports(prog->obj, FEAT_UPROBE_MULTI_LINK)) {
7355 		/* for BPF_TRACE_UPROBE_MULTI, user might want to query expected_attach_type
7356 		 * in prog, and expected_attach_type we set in kernel is from opts, so we
7357 		 * update both.
7358 		 */
7359 		prog->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
7360 		opts->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
7361 	}
7362 
7363 	if ((def & SEC_ATTACH_BTF) && !prog->attach_btf_id) {
7364 		int btf_obj_fd = 0, btf_type_id = 0, err;
7365 		const char *attach_name;
7366 
7367 		attach_name = strchr(prog->sec_name, '/');
7368 		if (!attach_name) {
7369 			/* if BPF program is annotated with just SEC("fentry")
7370 			 * (or similar) without declaratively specifying
7371 			 * target, then it is expected that target will be
7372 			 * specified with bpf_program__set_attach_target() at
7373 			 * runtime before BPF object load step. If not, then
7374 			 * there is nothing to load into the kernel as BPF
7375 			 * verifier won't be able to validate BPF program
7376 			 * correctness anyways.
7377 			 */
7378 			pr_warn("prog '%s': no BTF-based attach target is specified, use bpf_program__set_attach_target()\n",
7379 				prog->name);
7380 			return -EINVAL;
7381 		}
7382 		attach_name++; /* skip over / */
7383 
7384 		err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
7385 		if (err)
7386 			return err;
7387 
7388 		/* cache resolved BTF FD and BTF type ID in the prog */
7389 		prog->attach_btf_obj_fd = btf_obj_fd;
7390 		prog->attach_btf_id = btf_type_id;
7391 
7392 		/* but by now libbpf common logic is not utilizing
7393 		 * prog->atach_btf_obj_fd/prog->attach_btf_id anymore because
7394 		 * this callback is called after opts were populated by
7395 		 * libbpf, so this callback has to update opts explicitly here
7396 		 */
7397 		opts->attach_btf_obj_fd = btf_obj_fd;
7398 		opts->attach_btf_id = btf_type_id;
7399 	}
7400 	return 0;
7401 }
7402 
7403 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz);
7404 
7405 static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
7406 				struct bpf_insn *insns, int insns_cnt,
7407 				const char *license, __u32 kern_version, int *prog_fd)
7408 {
7409 	LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
7410 	const char *prog_name = NULL;
7411 	char *cp, errmsg[STRERR_BUFSIZE];
7412 	size_t log_buf_size = 0;
7413 	char *log_buf = NULL, *tmp;
7414 	int btf_fd, ret, err;
7415 	bool own_log_buf = true;
7416 	__u32 log_level = prog->log_level;
7417 
7418 	if (prog->type == BPF_PROG_TYPE_UNSPEC) {
7419 		/*
7420 		 * The program type must be set.  Most likely we couldn't find a proper
7421 		 * section definition at load time, and thus we didn't infer the type.
7422 		 */
7423 		pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
7424 			prog->name, prog->sec_name);
7425 		return -EINVAL;
7426 	}
7427 
7428 	if (!insns || !insns_cnt)
7429 		return -EINVAL;
7430 
7431 	if (kernel_supports(obj, FEAT_PROG_NAME))
7432 		prog_name = prog->name;
7433 	load_attr.attach_prog_fd = prog->attach_prog_fd;
7434 	load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
7435 	load_attr.attach_btf_id = prog->attach_btf_id;
7436 	load_attr.kern_version = kern_version;
7437 	load_attr.prog_ifindex = prog->prog_ifindex;
7438 	load_attr.expected_attach_type = prog->expected_attach_type;
7439 
7440 	/* specify func_info/line_info only if kernel supports them */
7441 	btf_fd = bpf_object__btf_fd(obj);
7442 	if (btf_fd >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
7443 		load_attr.prog_btf_fd = btf_fd;
7444 		load_attr.func_info = prog->func_info;
7445 		load_attr.func_info_rec_size = prog->func_info_rec_size;
7446 		load_attr.func_info_cnt = prog->func_info_cnt;
7447 		load_attr.line_info = prog->line_info;
7448 		load_attr.line_info_rec_size = prog->line_info_rec_size;
7449 		load_attr.line_info_cnt = prog->line_info_cnt;
7450 	}
7451 	load_attr.log_level = log_level;
7452 	load_attr.prog_flags = prog->prog_flags;
7453 	load_attr.fd_array = obj->fd_array;
7454 
7455 	/* adjust load_attr if sec_def provides custom preload callback */
7456 	if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
7457 		err = prog->sec_def->prog_prepare_load_fn(prog, &load_attr, prog->sec_def->cookie);
7458 		if (err < 0) {
7459 			pr_warn("prog '%s': failed to prepare load attributes: %d\n",
7460 				prog->name, err);
7461 			return err;
7462 		}
7463 		insns = prog->insns;
7464 		insns_cnt = prog->insns_cnt;
7465 	}
7466 
7467 	if (obj->gen_loader) {
7468 		bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
7469 				   license, insns, insns_cnt, &load_attr,
7470 				   prog - obj->programs);
7471 		*prog_fd = -1;
7472 		return 0;
7473 	}
7474 
7475 retry_load:
7476 	/* if log_level is zero, we don't request logs initially even if
7477 	 * custom log_buf is specified; if the program load fails, then we'll
7478 	 * bump log_level to 1 and use either custom log_buf or we'll allocate
7479 	 * our own and retry the load to get details on what failed
7480 	 */
7481 	if (log_level) {
7482 		if (prog->log_buf) {
7483 			log_buf = prog->log_buf;
7484 			log_buf_size = prog->log_size;
7485 			own_log_buf = false;
7486 		} else if (obj->log_buf) {
7487 			log_buf = obj->log_buf;
7488 			log_buf_size = obj->log_size;
7489 			own_log_buf = false;
7490 		} else {
7491 			log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
7492 			tmp = realloc(log_buf, log_buf_size);
7493 			if (!tmp) {
7494 				ret = -ENOMEM;
7495 				goto out;
7496 			}
7497 			log_buf = tmp;
7498 			log_buf[0] = '\0';
7499 			own_log_buf = true;
7500 		}
7501 	}
7502 
7503 	load_attr.log_buf = log_buf;
7504 	load_attr.log_size = log_buf_size;
7505 	load_attr.log_level = log_level;
7506 
7507 	ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
7508 	if (ret >= 0) {
7509 		if (log_level && own_log_buf) {
7510 			pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
7511 				 prog->name, log_buf);
7512 		}
7513 
7514 		if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
7515 			struct bpf_map *map;
7516 			int i;
7517 
7518 			for (i = 0; i < obj->nr_maps; i++) {
7519 				map = &prog->obj->maps[i];
7520 				if (map->libbpf_type != LIBBPF_MAP_RODATA)
7521 					continue;
7522 
7523 				if (bpf_prog_bind_map(ret, bpf_map__fd(map), NULL)) {
7524 					cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
7525 					pr_warn("prog '%s': failed to bind map '%s': %s\n",
7526 						prog->name, map->real_name, cp);
7527 					/* Don't fail hard if can't bind rodata. */
7528 				}
7529 			}
7530 		}
7531 
7532 		*prog_fd = ret;
7533 		ret = 0;
7534 		goto out;
7535 	}
7536 
7537 	if (log_level == 0) {
7538 		log_level = 1;
7539 		goto retry_load;
7540 	}
7541 	/* On ENOSPC, increase log buffer size and retry, unless custom
7542 	 * log_buf is specified.
7543 	 * Be careful to not overflow u32, though. Kernel's log buf size limit
7544 	 * isn't part of UAPI so it can always be bumped to full 4GB. So don't
7545 	 * multiply by 2 unless we are sure we'll fit within 32 bits.
7546 	 * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
7547 	 */
7548 	if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
7549 		goto retry_load;
7550 
7551 	ret = -errno;
7552 
7553 	/* post-process verifier log to improve error descriptions */
7554 	fixup_verifier_log(prog, log_buf, log_buf_size);
7555 
7556 	cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
7557 	pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, cp);
7558 	pr_perm_msg(ret);
7559 
7560 	if (own_log_buf && log_buf && log_buf[0] != '\0') {
7561 		pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
7562 			prog->name, log_buf);
7563 	}
7564 
7565 out:
7566 	if (own_log_buf)
7567 		free(log_buf);
7568 	return ret;
7569 }
7570 
7571 static char *find_prev_line(char *buf, char *cur)
7572 {
7573 	char *p;
7574 
7575 	if (cur == buf) /* end of a log buf */
7576 		return NULL;
7577 
7578 	p = cur - 1;
7579 	while (p - 1 >= buf && *(p - 1) != '\n')
7580 		p--;
7581 
7582 	return p;
7583 }
7584 
7585 static void patch_log(char *buf, size_t buf_sz, size_t log_sz,
7586 		      char *orig, size_t orig_sz, const char *patch)
7587 {
7588 	/* size of the remaining log content to the right from the to-be-replaced part */
7589 	size_t rem_sz = (buf + log_sz) - (orig + orig_sz);
7590 	size_t patch_sz = strlen(patch);
7591 
7592 	if (patch_sz != orig_sz) {
7593 		/* If patch line(s) are longer than original piece of verifier log,
7594 		 * shift log contents by (patch_sz - orig_sz) bytes to the right
7595 		 * starting from after to-be-replaced part of the log.
7596 		 *
7597 		 * If patch line(s) are shorter than original piece of verifier log,
7598 		 * shift log contents by (orig_sz - patch_sz) bytes to the left
7599 		 * starting from after to-be-replaced part of the log
7600 		 *
7601 		 * We need to be careful about not overflowing available
7602 		 * buf_sz capacity. If that's the case, we'll truncate the end
7603 		 * of the original log, as necessary.
7604 		 */
7605 		if (patch_sz > orig_sz) {
7606 			if (orig + patch_sz >= buf + buf_sz) {
7607 				/* patch is big enough to cover remaining space completely */
7608 				patch_sz -= (orig + patch_sz) - (buf + buf_sz) + 1;
7609 				rem_sz = 0;
7610 			} else if (patch_sz - orig_sz > buf_sz - log_sz) {
7611 				/* patch causes part of remaining log to be truncated */
7612 				rem_sz -= (patch_sz - orig_sz) - (buf_sz - log_sz);
7613 			}
7614 		}
7615 		/* shift remaining log to the right by calculated amount */
7616 		memmove(orig + patch_sz, orig + orig_sz, rem_sz);
7617 	}
7618 
7619 	memcpy(orig, patch, patch_sz);
7620 }
7621 
7622 static void fixup_log_failed_core_relo(struct bpf_program *prog,
7623 				       char *buf, size_t buf_sz, size_t log_sz,
7624 				       char *line1, char *line2, char *line3)
7625 {
7626 	/* Expected log for failed and not properly guarded CO-RE relocation:
7627 	 * line1 -> 123: (85) call unknown#195896080
7628 	 * line2 -> invalid func unknown#195896080
7629 	 * line3 -> <anything else or end of buffer>
7630 	 *
7631 	 * "123" is the index of the instruction that was poisoned. We extract
7632 	 * instruction index to find corresponding CO-RE relocation and
7633 	 * replace this part of the log with more relevant information about
7634 	 * failed CO-RE relocation.
7635 	 */
7636 	const struct bpf_core_relo *relo;
7637 	struct bpf_core_spec spec;
7638 	char patch[512], spec_buf[256];
7639 	int insn_idx, err, spec_len;
7640 
7641 	if (sscanf(line1, "%d: (%*d) call unknown#195896080\n", &insn_idx) != 1)
7642 		return;
7643 
7644 	relo = find_relo_core(prog, insn_idx);
7645 	if (!relo)
7646 		return;
7647 
7648 	err = bpf_core_parse_spec(prog->name, prog->obj->btf, relo, &spec);
7649 	if (err)
7650 		return;
7651 
7652 	spec_len = bpf_core_format_spec(spec_buf, sizeof(spec_buf), &spec);
7653 	snprintf(patch, sizeof(patch),
7654 		 "%d: <invalid CO-RE relocation>\n"
7655 		 "failed to resolve CO-RE relocation %s%s\n",
7656 		 insn_idx, spec_buf, spec_len >= sizeof(spec_buf) ? "..." : "");
7657 
7658 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7659 }
7660 
7661 static void fixup_log_missing_map_load(struct bpf_program *prog,
7662 				       char *buf, size_t buf_sz, size_t log_sz,
7663 				       char *line1, char *line2, char *line3)
7664 {
7665 	/* Expected log for failed and not properly guarded map reference:
7666 	 * line1 -> 123: (85) call unknown#2001000345
7667 	 * line2 -> invalid func unknown#2001000345
7668 	 * line3 -> <anything else or end of buffer>
7669 	 *
7670 	 * "123" is the index of the instruction that was poisoned.
7671 	 * "345" in "2001000345" is a map index in obj->maps to fetch map name.
7672 	 */
7673 	struct bpf_object *obj = prog->obj;
7674 	const struct bpf_map *map;
7675 	int insn_idx, map_idx;
7676 	char patch[128];
7677 
7678 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &map_idx) != 2)
7679 		return;
7680 
7681 	map_idx -= POISON_LDIMM64_MAP_BASE;
7682 	if (map_idx < 0 || map_idx >= obj->nr_maps)
7683 		return;
7684 	map = &obj->maps[map_idx];
7685 
7686 	snprintf(patch, sizeof(patch),
7687 		 "%d: <invalid BPF map reference>\n"
7688 		 "BPF map '%s' is referenced but wasn't created\n",
7689 		 insn_idx, map->name);
7690 
7691 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7692 }
7693 
7694 static void fixup_log_missing_kfunc_call(struct bpf_program *prog,
7695 					 char *buf, size_t buf_sz, size_t log_sz,
7696 					 char *line1, char *line2, char *line3)
7697 {
7698 	/* Expected log for failed and not properly guarded kfunc call:
7699 	 * line1 -> 123: (85) call unknown#2002000345
7700 	 * line2 -> invalid func unknown#2002000345
7701 	 * line3 -> <anything else or end of buffer>
7702 	 *
7703 	 * "123" is the index of the instruction that was poisoned.
7704 	 * "345" in "2002000345" is an extern index in obj->externs to fetch kfunc name.
7705 	 */
7706 	struct bpf_object *obj = prog->obj;
7707 	const struct extern_desc *ext;
7708 	int insn_idx, ext_idx;
7709 	char patch[128];
7710 
7711 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &ext_idx) != 2)
7712 		return;
7713 
7714 	ext_idx -= POISON_CALL_KFUNC_BASE;
7715 	if (ext_idx < 0 || ext_idx >= obj->nr_extern)
7716 		return;
7717 	ext = &obj->externs[ext_idx];
7718 
7719 	snprintf(patch, sizeof(patch),
7720 		 "%d: <invalid kfunc call>\n"
7721 		 "kfunc '%s' is referenced but wasn't resolved\n",
7722 		 insn_idx, ext->name);
7723 
7724 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7725 }
7726 
7727 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz)
7728 {
7729 	/* look for familiar error patterns in last N lines of the log */
7730 	const size_t max_last_line_cnt = 10;
7731 	char *prev_line, *cur_line, *next_line;
7732 	size_t log_sz;
7733 	int i;
7734 
7735 	if (!buf)
7736 		return;
7737 
7738 	log_sz = strlen(buf) + 1;
7739 	next_line = buf + log_sz - 1;
7740 
7741 	for (i = 0; i < max_last_line_cnt; i++, next_line = cur_line) {
7742 		cur_line = find_prev_line(buf, next_line);
7743 		if (!cur_line)
7744 			return;
7745 
7746 		if (str_has_pfx(cur_line, "invalid func unknown#195896080\n")) {
7747 			prev_line = find_prev_line(buf, cur_line);
7748 			if (!prev_line)
7749 				continue;
7750 
7751 			/* failed CO-RE relocation case */
7752 			fixup_log_failed_core_relo(prog, buf, buf_sz, log_sz,
7753 						   prev_line, cur_line, next_line);
7754 			return;
7755 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_LDIMM64_MAP_PFX)) {
7756 			prev_line = find_prev_line(buf, cur_line);
7757 			if (!prev_line)
7758 				continue;
7759 
7760 			/* reference to uncreated BPF map */
7761 			fixup_log_missing_map_load(prog, buf, buf_sz, log_sz,
7762 						   prev_line, cur_line, next_line);
7763 			return;
7764 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_CALL_KFUNC_PFX)) {
7765 			prev_line = find_prev_line(buf, cur_line);
7766 			if (!prev_line)
7767 				continue;
7768 
7769 			/* reference to unresolved kfunc */
7770 			fixup_log_missing_kfunc_call(prog, buf, buf_sz, log_sz,
7771 						     prev_line, cur_line, next_line);
7772 			return;
7773 		}
7774 	}
7775 }
7776 
7777 static int bpf_program_record_relos(struct bpf_program *prog)
7778 {
7779 	struct bpf_object *obj = prog->obj;
7780 	int i;
7781 
7782 	for (i = 0; i < prog->nr_reloc; i++) {
7783 		struct reloc_desc *relo = &prog->reloc_desc[i];
7784 		struct extern_desc *ext = &obj->externs[relo->ext_idx];
7785 		int kind;
7786 
7787 		switch (relo->type) {
7788 		case RELO_EXTERN_LD64:
7789 			if (ext->type != EXT_KSYM)
7790 				continue;
7791 			kind = btf_is_var(btf__type_by_id(obj->btf, ext->btf_id)) ?
7792 				BTF_KIND_VAR : BTF_KIND_FUNC;
7793 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7794 					       ext->is_weak, !ext->ksym.type_id,
7795 					       true, kind, relo->insn_idx);
7796 			break;
7797 		case RELO_EXTERN_CALL:
7798 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7799 					       ext->is_weak, false, false, BTF_KIND_FUNC,
7800 					       relo->insn_idx);
7801 			break;
7802 		case RELO_CORE: {
7803 			struct bpf_core_relo cr = {
7804 				.insn_off = relo->insn_idx * 8,
7805 				.type_id = relo->core_relo->type_id,
7806 				.access_str_off = relo->core_relo->access_str_off,
7807 				.kind = relo->core_relo->kind,
7808 			};
7809 
7810 			bpf_gen__record_relo_core(obj->gen_loader, &cr);
7811 			break;
7812 		}
7813 		default:
7814 			continue;
7815 		}
7816 	}
7817 	return 0;
7818 }
7819 
7820 static int
7821 bpf_object__load_progs(struct bpf_object *obj, int log_level)
7822 {
7823 	struct bpf_program *prog;
7824 	size_t i;
7825 	int err;
7826 
7827 	for (i = 0; i < obj->nr_programs; i++) {
7828 		prog = &obj->programs[i];
7829 		err = bpf_object__sanitize_prog(obj, prog);
7830 		if (err)
7831 			return err;
7832 	}
7833 
7834 	for (i = 0; i < obj->nr_programs; i++) {
7835 		prog = &obj->programs[i];
7836 		if (prog_is_subprog(obj, prog))
7837 			continue;
7838 		if (!prog->autoload) {
7839 			pr_debug("prog '%s': skipped loading\n", prog->name);
7840 			continue;
7841 		}
7842 		prog->log_level |= log_level;
7843 
7844 		if (obj->gen_loader)
7845 			bpf_program_record_relos(prog);
7846 
7847 		err = bpf_object_load_prog(obj, prog, prog->insns, prog->insns_cnt,
7848 					   obj->license, obj->kern_version, &prog->fd);
7849 		if (err) {
7850 			pr_warn("prog '%s': failed to load: %d\n", prog->name, err);
7851 			return err;
7852 		}
7853 	}
7854 
7855 	bpf_object__free_relocs(obj);
7856 	return 0;
7857 }
7858 
7859 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
7860 
7861 static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
7862 {
7863 	struct bpf_program *prog;
7864 	int err;
7865 
7866 	bpf_object__for_each_program(prog, obj) {
7867 		prog->sec_def = find_sec_def(prog->sec_name);
7868 		if (!prog->sec_def) {
7869 			/* couldn't guess, but user might manually specify */
7870 			pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
7871 				prog->name, prog->sec_name);
7872 			continue;
7873 		}
7874 
7875 		prog->type = prog->sec_def->prog_type;
7876 		prog->expected_attach_type = prog->sec_def->expected_attach_type;
7877 
7878 		/* sec_def can have custom callback which should be called
7879 		 * after bpf_program is initialized to adjust its properties
7880 		 */
7881 		if (prog->sec_def->prog_setup_fn) {
7882 			err = prog->sec_def->prog_setup_fn(prog, prog->sec_def->cookie);
7883 			if (err < 0) {
7884 				pr_warn("prog '%s': failed to initialize: %d\n",
7885 					prog->name, err);
7886 				return err;
7887 			}
7888 		}
7889 	}
7890 
7891 	return 0;
7892 }
7893 
7894 static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
7895 					  const char *obj_name,
7896 					  const struct bpf_object_open_opts *opts)
7897 {
7898 	const char *kconfig, *btf_tmp_path;
7899 	struct bpf_object *obj;
7900 	int err;
7901 	char *log_buf;
7902 	size_t log_size;
7903 	__u32 log_level;
7904 
7905 	if (obj_buf && !obj_name)
7906 		return ERR_PTR(-EINVAL);
7907 #ifdef HAVE_LIBELF
7908 	if (elf_version(EV_CURRENT) == EV_NONE) {
7909 		pr_warn("failed to init libelf for %s\n",
7910 			path ? : "(mem buf)");
7911 		return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
7912 	}
7913 #endif
7914 
7915 	if (!OPTS_VALID(opts, bpf_object_open_opts))
7916 		return ERR_PTR(-EINVAL);
7917 
7918 	obj_name = OPTS_GET(opts, object_name, NULL) ?: obj_name;
7919 	if (obj_buf) {
7920 		path = obj_name;
7921 		pr_debug("loading object '%s' from buffer\n", obj_name);
7922 	} else {
7923 		pr_debug("loading object from %s\n", path);
7924 	}
7925 
7926 	log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
7927 	log_size = OPTS_GET(opts, kernel_log_size, 0);
7928 	log_level = OPTS_GET(opts, kernel_log_level, 0);
7929 	if (log_size > UINT_MAX)
7930 		return ERR_PTR(-EINVAL);
7931 	if (log_size && !log_buf)
7932 		return ERR_PTR(-EINVAL);
7933 
7934 	obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
7935 	if (IS_ERR(obj))
7936 		return obj;
7937 
7938 	obj->log_buf = log_buf;
7939 	obj->log_size = log_size;
7940 	obj->log_level = log_level;
7941 
7942 	btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
7943 	if (btf_tmp_path) {
7944 		if (strlen(btf_tmp_path) >= PATH_MAX) {
7945 			err = -ENAMETOOLONG;
7946 			goto out;
7947 		}
7948 		obj->btf_custom_path = strdup(btf_tmp_path);
7949 		if (!obj->btf_custom_path) {
7950 			err = -ENOMEM;
7951 			goto out;
7952 		}
7953 	}
7954 
7955 	kconfig = OPTS_GET(opts, kconfig, NULL);
7956 	if (kconfig) {
7957 		obj->kconfig = strdup(kconfig);
7958 		if (!obj->kconfig) {
7959 			err = -ENOMEM;
7960 			goto out;
7961 		}
7962 	}
7963 
7964 	err = bpf_object__elf_init(obj);
7965 	err = err ? : bpf_object__check_endianness(obj);
7966 	err = err ? : bpf_object__elf_collect(obj);
7967 	err = err ? : bpf_object__collect_externs(obj);
7968 	err = err ? : bpf_object_fixup_btf(obj);
7969 	err = err ? : bpf_object__init_maps(obj, opts);
7970 	err = err ? : bpf_object_init_progs(obj, opts);
7971 	err = err ? : bpf_object__collect_relos(obj);
7972 	if (err)
7973 		goto out;
7974 
7975 	bpf_object__elf_finish(obj);
7976 
7977 	return obj;
7978 out:
7979 	bpf_object__close(obj);
7980 	return ERR_PTR(err);
7981 }
7982 
7983 struct bpf_object *
7984 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
7985 {
7986 	if (!path)
7987 		return libbpf_err_ptr(-EINVAL);
7988 
7989 	return libbpf_ptr(bpf_object_open(path, NULL, 0, NULL, opts));
7990 }
7991 
7992 struct bpf_object *bpf_object__open(const char *path)
7993 {
7994 	return bpf_object__open_file(path, NULL);
7995 }
7996 
7997 struct bpf_object *
7998 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
7999 		     const struct bpf_object_open_opts *opts)
8000 {
8001 	char tmp_name[64];
8002 
8003 	if (!obj_buf || obj_buf_sz == 0)
8004 		return libbpf_err_ptr(-EINVAL);
8005 
8006 	/* create a (quite useless) default "name" for this memory buffer object */
8007 	snprintf(tmp_name, sizeof(tmp_name), "%lx-%zx", (unsigned long)obj_buf, obj_buf_sz);
8008 
8009 	return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, tmp_name, opts));
8010 }
8011 
8012 static int bpf_object_unload(struct bpf_object *obj)
8013 {
8014 	size_t i;
8015 
8016 	if (!obj)
8017 		return libbpf_err(-EINVAL);
8018 
8019 	for (i = 0; i < obj->nr_maps; i++) {
8020 		zclose(obj->maps[i].fd);
8021 		if (obj->maps[i].st_ops)
8022 			zfree(&obj->maps[i].st_ops->kern_vdata);
8023 	}
8024 
8025 	for (i = 0; i < obj->nr_programs; i++)
8026 		bpf_program__unload(&obj->programs[i]);
8027 
8028 	return 0;
8029 }
8030 
8031 static int bpf_object__sanitize_maps(struct bpf_object *obj)
8032 {
8033 	struct bpf_map *m;
8034 
8035 	bpf_object__for_each_map(m, obj) {
8036 		if (!bpf_map__is_internal(m))
8037 			continue;
8038 		if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
8039 			m->def.map_flags &= ~BPF_F_MMAPABLE;
8040 	}
8041 
8042 	return 0;
8043 }
8044 
8045 int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
8046 {
8047 	char sym_type, sym_name[500];
8048 	unsigned long long sym_addr;
8049 	int ret, err = 0;
8050 	FILE *f;
8051 
8052 	f = fopen("/proc/kallsyms", "re");
8053 	if (!f) {
8054 		err = -errno;
8055 		pr_warn("failed to open /proc/kallsyms: %d\n", err);
8056 		return err;
8057 	}
8058 
8059 	while (true) {
8060 		ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
8061 			     &sym_addr, &sym_type, sym_name);
8062 		if (ret == EOF && feof(f))
8063 			break;
8064 		if (ret != 3) {
8065 			pr_warn("failed to read kallsyms entry: %d\n", ret);
8066 			err = -EINVAL;
8067 			break;
8068 		}
8069 
8070 		err = cb(sym_addr, sym_type, sym_name, ctx);
8071 		if (err)
8072 			break;
8073 	}
8074 
8075 	fclose(f);
8076 	return err;
8077 }
8078 
8079 static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
8080 		       const char *sym_name, void *ctx)
8081 {
8082 	struct bpf_object *obj = ctx;
8083 	const struct btf_type *t;
8084 	struct extern_desc *ext;
8085 
8086 	ext = find_extern_by_name(obj, sym_name);
8087 	if (!ext || ext->type != EXT_KSYM)
8088 		return 0;
8089 
8090 	t = btf__type_by_id(obj->btf, ext->btf_id);
8091 	if (!btf_is_var(t))
8092 		return 0;
8093 
8094 	if (ext->is_set && ext->ksym.addr != sym_addr) {
8095 		pr_warn("extern (ksym) '%s': resolution is ambiguous: 0x%llx or 0x%llx\n",
8096 			sym_name, ext->ksym.addr, sym_addr);
8097 		return -EINVAL;
8098 	}
8099 	if (!ext->is_set) {
8100 		ext->is_set = true;
8101 		ext->ksym.addr = sym_addr;
8102 		pr_debug("extern (ksym) '%s': set to 0x%llx\n", sym_name, sym_addr);
8103 	}
8104 	return 0;
8105 }
8106 
8107 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
8108 {
8109 	return libbpf_kallsyms_parse(kallsyms_cb, obj);
8110 }
8111 
8112 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
8113 			    __u16 kind, struct btf **res_btf,
8114 			    struct module_btf **res_mod_btf)
8115 {
8116 	struct module_btf *mod_btf;
8117 	struct btf *btf;
8118 	int i, id, err;
8119 
8120 	btf = obj->btf_vmlinux;
8121 	mod_btf = NULL;
8122 	id = btf__find_by_name_kind(btf, ksym_name, kind);
8123 
8124 	if (id == -ENOENT) {
8125 		err = load_module_btfs(obj);
8126 		if (err)
8127 			return err;
8128 
8129 		for (i = 0; i < obj->btf_module_cnt; i++) {
8130 			/* we assume module_btf's BTF FD is always >0 */
8131 			mod_btf = &obj->btf_modules[i];
8132 			btf = mod_btf->btf;
8133 			id = btf__find_by_name_kind_own(btf, ksym_name, kind);
8134 			if (id != -ENOENT)
8135 				break;
8136 		}
8137 	}
8138 	if (id <= 0)
8139 		return -ESRCH;
8140 
8141 	*res_btf = btf;
8142 	*res_mod_btf = mod_btf;
8143 	return id;
8144 }
8145 
8146 static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
8147 					       struct extern_desc *ext)
8148 {
8149 	const struct btf_type *targ_var, *targ_type;
8150 	__u32 targ_type_id, local_type_id;
8151 	struct module_btf *mod_btf = NULL;
8152 	const char *targ_var_name;
8153 	struct btf *btf = NULL;
8154 	int id, err;
8155 
8156 	id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
8157 	if (id < 0) {
8158 		if (id == -ESRCH && ext->is_weak)
8159 			return 0;
8160 		pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
8161 			ext->name);
8162 		return id;
8163 	}
8164 
8165 	/* find local type_id */
8166 	local_type_id = ext->ksym.type_id;
8167 
8168 	/* find target type_id */
8169 	targ_var = btf__type_by_id(btf, id);
8170 	targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
8171 	targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
8172 
8173 	err = bpf_core_types_are_compat(obj->btf, local_type_id,
8174 					btf, targ_type_id);
8175 	if (err <= 0) {
8176 		const struct btf_type *local_type;
8177 		const char *targ_name, *local_name;
8178 
8179 		local_type = btf__type_by_id(obj->btf, local_type_id);
8180 		local_name = btf__name_by_offset(obj->btf, local_type->name_off);
8181 		targ_name = btf__name_by_offset(btf, targ_type->name_off);
8182 
8183 		pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
8184 			ext->name, local_type_id,
8185 			btf_kind_str(local_type), local_name, targ_type_id,
8186 			btf_kind_str(targ_type), targ_name);
8187 		return -EINVAL;
8188 	}
8189 
8190 	ext->is_set = true;
8191 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
8192 	ext->ksym.kernel_btf_id = id;
8193 	pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
8194 		 ext->name, id, btf_kind_str(targ_var), targ_var_name);
8195 
8196 	return 0;
8197 }
8198 
8199 static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
8200 						struct extern_desc *ext)
8201 {
8202 	int local_func_proto_id, kfunc_proto_id, kfunc_id;
8203 	struct module_btf *mod_btf = NULL;
8204 	const struct btf_type *kern_func;
8205 	struct btf *kern_btf = NULL;
8206 	int ret;
8207 
8208 	local_func_proto_id = ext->ksym.type_id;
8209 
8210 	kfunc_id = find_ksym_btf_id(obj, ext->essent_name ?: ext->name, BTF_KIND_FUNC, &kern_btf,
8211 				    &mod_btf);
8212 	if (kfunc_id < 0) {
8213 		if (kfunc_id == -ESRCH && ext->is_weak)
8214 			return 0;
8215 		pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
8216 			ext->name);
8217 		return kfunc_id;
8218 	}
8219 
8220 	kern_func = btf__type_by_id(kern_btf, kfunc_id);
8221 	kfunc_proto_id = kern_func->type;
8222 
8223 	ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
8224 					kern_btf, kfunc_proto_id);
8225 	if (ret <= 0) {
8226 		if (ext->is_weak)
8227 			return 0;
8228 
8229 		pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with %s [%d]\n",
8230 			ext->name, local_func_proto_id,
8231 			mod_btf ? mod_btf->name : "vmlinux", kfunc_proto_id);
8232 		return -EINVAL;
8233 	}
8234 
8235 	/* set index for module BTF fd in fd_array, if unset */
8236 	if (mod_btf && !mod_btf->fd_array_idx) {
8237 		/* insn->off is s16 */
8238 		if (obj->fd_array_cnt == INT16_MAX) {
8239 			pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
8240 				ext->name, mod_btf->fd_array_idx);
8241 			return -E2BIG;
8242 		}
8243 		/* Cannot use index 0 for module BTF fd */
8244 		if (!obj->fd_array_cnt)
8245 			obj->fd_array_cnt = 1;
8246 
8247 		ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
8248 					obj->fd_array_cnt + 1);
8249 		if (ret)
8250 			return ret;
8251 		mod_btf->fd_array_idx = obj->fd_array_cnt;
8252 		/* we assume module BTF FD is always >0 */
8253 		obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
8254 	}
8255 
8256 	ext->is_set = true;
8257 	ext->ksym.kernel_btf_id = kfunc_id;
8258 	ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
8259 	/* Also set kernel_btf_obj_fd to make sure that bpf_object__relocate_data()
8260 	 * populates FD into ld_imm64 insn when it's used to point to kfunc.
8261 	 * {kernel_btf_id, btf_fd_idx} -> fixup bpf_call.
8262 	 * {kernel_btf_id, kernel_btf_obj_fd} -> fixup ld_imm64.
8263 	 */
8264 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
8265 	pr_debug("extern (func ksym) '%s': resolved to %s [%d]\n",
8266 		 ext->name, mod_btf ? mod_btf->name : "vmlinux", kfunc_id);
8267 
8268 	return 0;
8269 }
8270 
8271 static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
8272 {
8273 	const struct btf_type *t;
8274 	struct extern_desc *ext;
8275 	int i, err;
8276 
8277 	for (i = 0; i < obj->nr_extern; i++) {
8278 		ext = &obj->externs[i];
8279 		if (ext->type != EXT_KSYM || !ext->ksym.type_id)
8280 			continue;
8281 
8282 		if (obj->gen_loader) {
8283 			ext->is_set = true;
8284 			ext->ksym.kernel_btf_obj_fd = 0;
8285 			ext->ksym.kernel_btf_id = 0;
8286 			continue;
8287 		}
8288 		t = btf__type_by_id(obj->btf, ext->btf_id);
8289 		if (btf_is_var(t))
8290 			err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
8291 		else
8292 			err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
8293 		if (err)
8294 			return err;
8295 	}
8296 	return 0;
8297 }
8298 
8299 static int bpf_object__resolve_externs(struct bpf_object *obj,
8300 				       const char *extra_kconfig)
8301 {
8302 	bool need_config = false, need_kallsyms = false;
8303 	bool need_vmlinux_btf = false;
8304 	struct extern_desc *ext;
8305 	void *kcfg_data = NULL;
8306 	int err, i;
8307 
8308 	if (obj->nr_extern == 0)
8309 		return 0;
8310 
8311 	if (obj->kconfig_map_idx >= 0)
8312 		kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
8313 
8314 	for (i = 0; i < obj->nr_extern; i++) {
8315 		ext = &obj->externs[i];
8316 
8317 		if (ext->type == EXT_KSYM) {
8318 			if (ext->ksym.type_id)
8319 				need_vmlinux_btf = true;
8320 			else
8321 				need_kallsyms = true;
8322 			continue;
8323 		} else if (ext->type == EXT_KCFG) {
8324 			void *ext_ptr = kcfg_data + ext->kcfg.data_off;
8325 			__u64 value = 0;
8326 
8327 			/* Kconfig externs need actual /proc/config.gz */
8328 			if (str_has_pfx(ext->name, "CONFIG_")) {
8329 				need_config = true;
8330 				continue;
8331 			}
8332 
8333 			/* Virtual kcfg externs are customly handled by libbpf */
8334 			if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
8335 				value = get_kernel_version();
8336 				if (!value) {
8337 					pr_warn("extern (kcfg) '%s': failed to get kernel version\n", ext->name);
8338 					return -EINVAL;
8339 				}
8340 			} else if (strcmp(ext->name, "LINUX_HAS_BPF_COOKIE") == 0) {
8341 				value = kernel_supports(obj, FEAT_BPF_COOKIE);
8342 			} else if (strcmp(ext->name, "LINUX_HAS_SYSCALL_WRAPPER") == 0) {
8343 				value = kernel_supports(obj, FEAT_SYSCALL_WRAPPER);
8344 			} else if (!str_has_pfx(ext->name, "LINUX_") || !ext->is_weak) {
8345 				/* Currently libbpf supports only CONFIG_ and LINUX_ prefixed
8346 				 * __kconfig externs, where LINUX_ ones are virtual and filled out
8347 				 * customly by libbpf (their values don't come from Kconfig).
8348 				 * If LINUX_xxx variable is not recognized by libbpf, but is marked
8349 				 * __weak, it defaults to zero value, just like for CONFIG_xxx
8350 				 * externs.
8351 				 */
8352 				pr_warn("extern (kcfg) '%s': unrecognized virtual extern\n", ext->name);
8353 				return -EINVAL;
8354 			}
8355 
8356 			err = set_kcfg_value_num(ext, ext_ptr, value);
8357 			if (err)
8358 				return err;
8359 			pr_debug("extern (kcfg) '%s': set to 0x%llx\n",
8360 				 ext->name, (long long)value);
8361 		} else {
8362 			pr_warn("extern '%s': unrecognized extern kind\n", ext->name);
8363 			return -EINVAL;
8364 		}
8365 	}
8366 	if (need_config && extra_kconfig) {
8367 		err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
8368 		if (err)
8369 			return -EINVAL;
8370 		need_config = false;
8371 		for (i = 0; i < obj->nr_extern; i++) {
8372 			ext = &obj->externs[i];
8373 			if (ext->type == EXT_KCFG && !ext->is_set) {
8374 				need_config = true;
8375 				break;
8376 			}
8377 		}
8378 	}
8379 	if (need_config) {
8380 		err = bpf_object__read_kconfig_file(obj, kcfg_data);
8381 		if (err)
8382 			return -EINVAL;
8383 	}
8384 	if (need_kallsyms) {
8385 		err = bpf_object__read_kallsyms_file(obj);
8386 		if (err)
8387 			return -EINVAL;
8388 	}
8389 	if (need_vmlinux_btf) {
8390 		err = bpf_object__resolve_ksyms_btf_id(obj);
8391 		if (err)
8392 			return -EINVAL;
8393 	}
8394 	for (i = 0; i < obj->nr_extern; i++) {
8395 		ext = &obj->externs[i];
8396 
8397 		if (!ext->is_set && !ext->is_weak) {
8398 			pr_warn("extern '%s' (strong): not resolved\n", ext->name);
8399 			return -ESRCH;
8400 		} else if (!ext->is_set) {
8401 			pr_debug("extern '%s' (weak): not resolved, defaulting to zero\n",
8402 				 ext->name);
8403 		}
8404 	}
8405 
8406 	return 0;
8407 }
8408 
8409 static void bpf_map_prepare_vdata(const struct bpf_map *map)
8410 {
8411 	struct bpf_struct_ops *st_ops;
8412 	__u32 i;
8413 
8414 	st_ops = map->st_ops;
8415 	for (i = 0; i < btf_vlen(st_ops->type); i++) {
8416 		struct bpf_program *prog = st_ops->progs[i];
8417 		void *kern_data;
8418 		int prog_fd;
8419 
8420 		if (!prog)
8421 			continue;
8422 
8423 		prog_fd = bpf_program__fd(prog);
8424 		kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
8425 		*(unsigned long *)kern_data = prog_fd;
8426 	}
8427 }
8428 
8429 static int bpf_object_prepare_struct_ops(struct bpf_object *obj)
8430 {
8431 	int i;
8432 
8433 	for (i = 0; i < obj->nr_maps; i++)
8434 		if (bpf_map__is_struct_ops(&obj->maps[i]))
8435 			bpf_map_prepare_vdata(&obj->maps[i]);
8436 
8437 	return 0;
8438 }
8439 
8440 static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
8441 {
8442 	int err, i;
8443 
8444 	if (!obj)
8445 		return libbpf_err(-EINVAL);
8446 
8447 	if (obj->loaded) {
8448 		pr_warn("object '%s': load can't be attempted twice\n", obj->name);
8449 		return libbpf_err(-EINVAL);
8450 	}
8451 
8452 	if (obj->gen_loader)
8453 		bpf_gen__init(obj->gen_loader, extra_log_level, obj->nr_programs, obj->nr_maps);
8454 
8455 	err = bpf_object__probe_loading(obj);
8456 	err = err ? : bpf_object__load_vmlinux_btf(obj, false);
8457 	err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
8458 	err = err ? : bpf_object__sanitize_and_load_btf(obj);
8459 	err = err ? : bpf_object__sanitize_maps(obj);
8460 	err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
8461 	err = err ? : bpf_object__create_maps(obj);
8462 	err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
8463 	err = err ? : bpf_object__load_progs(obj, extra_log_level);
8464 	err = err ? : bpf_object_init_prog_arrays(obj);
8465 	err = err ? : bpf_object_prepare_struct_ops(obj);
8466 
8467 	if (obj->gen_loader) {
8468 		/* reset FDs */
8469 		if (obj->btf)
8470 			btf__set_fd(obj->btf, -1);
8471 		for (i = 0; i < obj->nr_maps; i++)
8472 			obj->maps[i].fd = -1;
8473 		if (!err)
8474 			err = bpf_gen__finish(obj->gen_loader, obj->nr_programs, obj->nr_maps);
8475 	}
8476 
8477 	/* clean up fd_array */
8478 	zfree(&obj->fd_array);
8479 
8480 	/* clean up module BTFs */
8481 	for (i = 0; i < obj->btf_module_cnt; i++) {
8482 		close(obj->btf_modules[i].fd);
8483 		btf__free(obj->btf_modules[i].btf);
8484 		free(obj->btf_modules[i].name);
8485 	}
8486 	free(obj->btf_modules);
8487 
8488 	/* clean up vmlinux BTF */
8489 	btf__free(obj->btf_vmlinux);
8490 	obj->btf_vmlinux = NULL;
8491 
8492 	obj->loaded = true; /* doesn't matter if successfully or not */
8493 
8494 	if (err)
8495 		goto out;
8496 
8497 	return 0;
8498 out:
8499 	/* unpin any maps that were auto-pinned during load */
8500 	for (i = 0; i < obj->nr_maps; i++)
8501 		if (obj->maps[i].pinned && !obj->maps[i].reused)
8502 			bpf_map__unpin(&obj->maps[i], NULL);
8503 
8504 	bpf_object_unload(obj);
8505 	pr_warn("failed to load object '%s'\n", obj->path);
8506 	return libbpf_err(err);
8507 }
8508 
8509 int bpf_object__load(struct bpf_object *obj)
8510 {
8511 	return bpf_object_load(obj, 0, NULL);
8512 }
8513 
8514 static int make_parent_dir(const char *path)
8515 {
8516 	char *cp, errmsg[STRERR_BUFSIZE];
8517 	char *dname, *dir;
8518 	int err = 0;
8519 
8520 	dname = strdup(path);
8521 	if (dname == NULL)
8522 		return -ENOMEM;
8523 
8524 	dir = dirname(dname);
8525 	if (mkdir(dir, 0700) && errno != EEXIST)
8526 		err = -errno;
8527 
8528 	free(dname);
8529 	if (err) {
8530 		cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
8531 		pr_warn("failed to mkdir %s: %s\n", path, cp);
8532 	}
8533 	return err;
8534 }
8535 
8536 static int check_path(const char *path)
8537 {
8538 	char *cp, errmsg[STRERR_BUFSIZE];
8539 	struct statfs st_fs;
8540 	char *dname, *dir;
8541 	int err = 0;
8542 
8543 	if (path == NULL)
8544 		return -EINVAL;
8545 
8546 	dname = strdup(path);
8547 	if (dname == NULL)
8548 		return -ENOMEM;
8549 
8550 	dir = dirname(dname);
8551 	if (statfs(dir, &st_fs)) {
8552 		cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
8553 		pr_warn("failed to statfs %s: %s\n", dir, cp);
8554 		err = -errno;
8555 	}
8556 	free(dname);
8557 
8558 	if (!err && st_fs.f_type != BPF_FS_MAGIC) {
8559 		pr_warn("specified path %s is not on BPF FS\n", path);
8560 		err = -EINVAL;
8561 	}
8562 
8563 	return err;
8564 }
8565 
8566 int bpf_program__pin(struct bpf_program *prog, const char *path)
8567 {
8568 	char *cp, errmsg[STRERR_BUFSIZE];
8569 	int err;
8570 
8571 	if (prog->fd < 0) {
8572 		pr_warn("prog '%s': can't pin program that wasn't loaded\n", prog->name);
8573 		return libbpf_err(-EINVAL);
8574 	}
8575 
8576 	err = make_parent_dir(path);
8577 	if (err)
8578 		return libbpf_err(err);
8579 
8580 	err = check_path(path);
8581 	if (err)
8582 		return libbpf_err(err);
8583 
8584 	if (bpf_obj_pin(prog->fd, path)) {
8585 		err = -errno;
8586 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
8587 		pr_warn("prog '%s': failed to pin at '%s': %s\n", prog->name, path, cp);
8588 		return libbpf_err(err);
8589 	}
8590 
8591 	pr_debug("prog '%s': pinned at '%s'\n", prog->name, path);
8592 	return 0;
8593 }
8594 
8595 int bpf_program__unpin(struct bpf_program *prog, const char *path)
8596 {
8597 	int err;
8598 
8599 	if (prog->fd < 0) {
8600 		pr_warn("prog '%s': can't unpin program that wasn't loaded\n", prog->name);
8601 		return libbpf_err(-EINVAL);
8602 	}
8603 
8604 	err = check_path(path);
8605 	if (err)
8606 		return libbpf_err(err);
8607 
8608 	err = unlink(path);
8609 	if (err)
8610 		return libbpf_err(-errno);
8611 
8612 	pr_debug("prog '%s': unpinned from '%s'\n", prog->name, path);
8613 	return 0;
8614 }
8615 
8616 int bpf_map__pin(struct bpf_map *map, const char *path)
8617 {
8618 	char *cp, errmsg[STRERR_BUFSIZE];
8619 	int err;
8620 
8621 	if (map == NULL) {
8622 		pr_warn("invalid map pointer\n");
8623 		return libbpf_err(-EINVAL);
8624 	}
8625 
8626 	if (map->pin_path) {
8627 		if (path && strcmp(path, map->pin_path)) {
8628 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8629 				bpf_map__name(map), map->pin_path, path);
8630 			return libbpf_err(-EINVAL);
8631 		} else if (map->pinned) {
8632 			pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
8633 				 bpf_map__name(map), map->pin_path);
8634 			return 0;
8635 		}
8636 	} else {
8637 		if (!path) {
8638 			pr_warn("missing a path to pin map '%s' at\n",
8639 				bpf_map__name(map));
8640 			return libbpf_err(-EINVAL);
8641 		} else if (map->pinned) {
8642 			pr_warn("map '%s' already pinned\n", bpf_map__name(map));
8643 			return libbpf_err(-EEXIST);
8644 		}
8645 
8646 		map->pin_path = strdup(path);
8647 		if (!map->pin_path) {
8648 			err = -errno;
8649 			goto out_err;
8650 		}
8651 	}
8652 
8653 	err = make_parent_dir(map->pin_path);
8654 	if (err)
8655 		return libbpf_err(err);
8656 
8657 	err = check_path(map->pin_path);
8658 	if (err)
8659 		return libbpf_err(err);
8660 
8661 	if (bpf_obj_pin(map->fd, map->pin_path)) {
8662 		err = -errno;
8663 		goto out_err;
8664 	}
8665 
8666 	map->pinned = true;
8667 	pr_debug("pinned map '%s'\n", map->pin_path);
8668 
8669 	return 0;
8670 
8671 out_err:
8672 	cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
8673 	pr_warn("failed to pin map: %s\n", cp);
8674 	return libbpf_err(err);
8675 }
8676 
8677 int bpf_map__unpin(struct bpf_map *map, const char *path)
8678 {
8679 	int err;
8680 
8681 	if (map == NULL) {
8682 		pr_warn("invalid map pointer\n");
8683 		return libbpf_err(-EINVAL);
8684 	}
8685 
8686 	if (map->pin_path) {
8687 		if (path && strcmp(path, map->pin_path)) {
8688 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8689 				bpf_map__name(map), map->pin_path, path);
8690 			return libbpf_err(-EINVAL);
8691 		}
8692 		path = map->pin_path;
8693 	} else if (!path) {
8694 		pr_warn("no path to unpin map '%s' from\n",
8695 			bpf_map__name(map));
8696 		return libbpf_err(-EINVAL);
8697 	}
8698 
8699 	err = check_path(path);
8700 	if (err)
8701 		return libbpf_err(err);
8702 
8703 	err = unlink(path);
8704 	if (err != 0)
8705 		return libbpf_err(-errno);
8706 
8707 	map->pinned = false;
8708 	pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
8709 
8710 	return 0;
8711 }
8712 
8713 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
8714 {
8715 	char *new = NULL;
8716 
8717 	if (path) {
8718 		new = strdup(path);
8719 		if (!new)
8720 			return libbpf_err(-errno);
8721 	}
8722 
8723 	free(map->pin_path);
8724 	map->pin_path = new;
8725 	return 0;
8726 }
8727 
8728 __alias(bpf_map__pin_path)
8729 const char *bpf_map__get_pin_path(const struct bpf_map *map);
8730 
8731 const char *bpf_map__pin_path(const struct bpf_map *map)
8732 {
8733 	return map->pin_path;
8734 }
8735 
8736 bool bpf_map__is_pinned(const struct bpf_map *map)
8737 {
8738 	return map->pinned;
8739 }
8740 
8741 static void sanitize_pin_path(char *s)
8742 {
8743 	/* bpffs disallows periods in path names */
8744 	while (*s) {
8745 		if (*s == '.')
8746 			*s = '_';
8747 		s++;
8748 	}
8749 }
8750 
8751 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
8752 {
8753 	struct bpf_map *map;
8754 	int err;
8755 
8756 	if (!obj)
8757 		return libbpf_err(-ENOENT);
8758 
8759 	if (!obj->loaded) {
8760 		pr_warn("object not yet loaded; load it first\n");
8761 		return libbpf_err(-ENOENT);
8762 	}
8763 
8764 	bpf_object__for_each_map(map, obj) {
8765 		char *pin_path = NULL;
8766 		char buf[PATH_MAX];
8767 
8768 		if (!map->autocreate)
8769 			continue;
8770 
8771 		if (path) {
8772 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8773 			if (err)
8774 				goto err_unpin_maps;
8775 			sanitize_pin_path(buf);
8776 			pin_path = buf;
8777 		} else if (!map->pin_path) {
8778 			continue;
8779 		}
8780 
8781 		err = bpf_map__pin(map, pin_path);
8782 		if (err)
8783 			goto err_unpin_maps;
8784 	}
8785 
8786 	return 0;
8787 
8788 err_unpin_maps:
8789 	while ((map = bpf_object__prev_map(obj, map))) {
8790 		if (!map->pin_path)
8791 			continue;
8792 
8793 		bpf_map__unpin(map, NULL);
8794 	}
8795 
8796 	return libbpf_err(err);
8797 }
8798 
8799 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
8800 {
8801 	struct bpf_map *map;
8802 	int err;
8803 
8804 	if (!obj)
8805 		return libbpf_err(-ENOENT);
8806 
8807 	bpf_object__for_each_map(map, obj) {
8808 		char *pin_path = NULL;
8809 		char buf[PATH_MAX];
8810 
8811 		if (path) {
8812 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8813 			if (err)
8814 				return libbpf_err(err);
8815 			sanitize_pin_path(buf);
8816 			pin_path = buf;
8817 		} else if (!map->pin_path) {
8818 			continue;
8819 		}
8820 
8821 		err = bpf_map__unpin(map, pin_path);
8822 		if (err)
8823 			return libbpf_err(err);
8824 	}
8825 
8826 	return 0;
8827 }
8828 
8829 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
8830 {
8831 	struct bpf_program *prog;
8832 	char buf[PATH_MAX];
8833 	int err;
8834 
8835 	if (!obj)
8836 		return libbpf_err(-ENOENT);
8837 
8838 	if (!obj->loaded) {
8839 		pr_warn("object not yet loaded; load it first\n");
8840 		return libbpf_err(-ENOENT);
8841 	}
8842 
8843 	bpf_object__for_each_program(prog, obj) {
8844 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
8845 		if (err)
8846 			goto err_unpin_programs;
8847 
8848 		err = bpf_program__pin(prog, buf);
8849 		if (err)
8850 			goto err_unpin_programs;
8851 	}
8852 
8853 	return 0;
8854 
8855 err_unpin_programs:
8856 	while ((prog = bpf_object__prev_program(obj, prog))) {
8857 		if (pathname_concat(buf, sizeof(buf), path, prog->name))
8858 			continue;
8859 
8860 		bpf_program__unpin(prog, buf);
8861 	}
8862 
8863 	return libbpf_err(err);
8864 }
8865 
8866 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
8867 {
8868 	struct bpf_program *prog;
8869 	int err;
8870 
8871 	if (!obj)
8872 		return libbpf_err(-ENOENT);
8873 
8874 	bpf_object__for_each_program(prog, obj) {
8875 		char buf[PATH_MAX];
8876 
8877 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
8878 		if (err)
8879 			return libbpf_err(err);
8880 
8881 		err = bpf_program__unpin(prog, buf);
8882 		if (err)
8883 			return libbpf_err(err);
8884 	}
8885 
8886 	return 0;
8887 }
8888 
8889 int bpf_object__pin(struct bpf_object *obj, const char *path)
8890 {
8891 	int err;
8892 
8893 	err = bpf_object__pin_maps(obj, path);
8894 	if (err)
8895 		return libbpf_err(err);
8896 
8897 	err = bpf_object__pin_programs(obj, path);
8898 	if (err) {
8899 		bpf_object__unpin_maps(obj, path);
8900 		return libbpf_err(err);
8901 	}
8902 
8903 	return 0;
8904 }
8905 
8906 int bpf_object__unpin(struct bpf_object *obj, const char *path)
8907 {
8908 	int err;
8909 
8910 	err = bpf_object__unpin_programs(obj, path);
8911 	if (err)
8912 		return libbpf_err(err);
8913 
8914 	err = bpf_object__unpin_maps(obj, path);
8915 	if (err)
8916 		return libbpf_err(err);
8917 
8918 	return 0;
8919 }
8920 
8921 static void bpf_map__destroy(struct bpf_map *map)
8922 {
8923 	if (map->inner_map) {
8924 		bpf_map__destroy(map->inner_map);
8925 		zfree(&map->inner_map);
8926 	}
8927 
8928 	zfree(&map->init_slots);
8929 	map->init_slots_sz = 0;
8930 
8931 	if (map->mmaped) {
8932 		size_t mmap_sz;
8933 
8934 		mmap_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
8935 		munmap(map->mmaped, mmap_sz);
8936 		map->mmaped = NULL;
8937 	}
8938 
8939 	if (map->st_ops) {
8940 		zfree(&map->st_ops->data);
8941 		zfree(&map->st_ops->progs);
8942 		zfree(&map->st_ops->kern_func_off);
8943 		zfree(&map->st_ops);
8944 	}
8945 
8946 	zfree(&map->name);
8947 	zfree(&map->real_name);
8948 	zfree(&map->pin_path);
8949 
8950 	if (map->fd >= 0)
8951 		zclose(map->fd);
8952 }
8953 
8954 void bpf_object__close(struct bpf_object *obj)
8955 {
8956 	size_t i;
8957 
8958 	if (IS_ERR_OR_NULL(obj))
8959 		return;
8960 #ifdef  HAVE_LIBELF
8961 	usdt_manager_free(obj->usdt_man);
8962 	obj->usdt_man = NULL;
8963 #endif  //HAVE_LIBELF
8964 	bpf_gen__free(obj->gen_loader);
8965 	bpf_object__elf_finish(obj);
8966 	bpf_object_unload(obj);
8967 	btf__free(obj->btf);
8968 	btf__free(obj->btf_vmlinux);
8969 	btf_ext__free(obj->btf_ext);
8970 
8971 	for (i = 0; i < obj->nr_maps; i++)
8972 		bpf_map__destroy(&obj->maps[i]);
8973 
8974 	zfree(&obj->btf_custom_path);
8975 	zfree(&obj->kconfig);
8976 
8977 	for (i = 0; i < obj->nr_extern; i++)
8978 		zfree(&obj->externs[i].essent_name);
8979 
8980 	zfree(&obj->externs);
8981 	obj->nr_extern = 0;
8982 
8983 	zfree(&obj->maps);
8984 	obj->nr_maps = 0;
8985 
8986 	if (obj->programs && obj->nr_programs) {
8987 		for (i = 0; i < obj->nr_programs; i++)
8988 			bpf_program__exit(&obj->programs[i]);
8989 	}
8990 	zfree(&obj->programs);
8991 
8992 	free(obj);
8993 }
8994 
8995 const char *bpf_object__name(const struct bpf_object *obj)
8996 {
8997 	return obj ? obj->name : libbpf_err_ptr(-EINVAL);
8998 }
8999 
9000 unsigned int bpf_object__kversion(const struct bpf_object *obj)
9001 {
9002 	return obj ? obj->kern_version : 0;
9003 }
9004 
9005 struct btf *bpf_object__btf(const struct bpf_object *obj)
9006 {
9007 	return obj ? obj->btf : NULL;
9008 }
9009 
9010 int bpf_object__btf_fd(const struct bpf_object *obj)
9011 {
9012 	return obj->btf ? btf__fd(obj->btf) : -1;
9013 }
9014 
9015 int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
9016 {
9017 	if (obj->loaded)
9018 		return libbpf_err(-EINVAL);
9019 
9020 	obj->kern_version = kern_version;
9021 
9022 	return 0;
9023 }
9024 
9025 int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
9026 {
9027 	struct bpf_gen *gen;
9028 
9029 	if (!opts)
9030 		return -EFAULT;
9031 	if (!OPTS_VALID(opts, gen_loader_opts))
9032 		return -EINVAL;
9033 	gen = calloc(sizeof(*gen), 1);
9034 	if (!gen)
9035 		return -ENOMEM;
9036 	gen->opts = opts;
9037 	obj->gen_loader = gen;
9038 	return 0;
9039 }
9040 
9041 static struct bpf_program *
9042 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
9043 		    bool forward)
9044 {
9045 	size_t nr_programs = obj->nr_programs;
9046 	ssize_t idx;
9047 
9048 	if (!nr_programs)
9049 		return NULL;
9050 
9051 	if (!p)
9052 		/* Iter from the beginning */
9053 		return forward ? &obj->programs[0] :
9054 			&obj->programs[nr_programs - 1];
9055 
9056 	if (p->obj != obj) {
9057 		pr_warn("error: program handler doesn't match object\n");
9058 		return errno = EINVAL, NULL;
9059 	}
9060 
9061 	idx = (p - obj->programs) + (forward ? 1 : -1);
9062 	if (idx >= obj->nr_programs || idx < 0)
9063 		return NULL;
9064 	return &obj->programs[idx];
9065 }
9066 
9067 struct bpf_program *
9068 bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
9069 {
9070 	struct bpf_program *prog = prev;
9071 
9072 	do {
9073 		prog = __bpf_program__iter(prog, obj, true);
9074 	} while (prog && prog_is_subprog(obj, prog));
9075 
9076 	return prog;
9077 }
9078 
9079 struct bpf_program *
9080 bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
9081 {
9082 	struct bpf_program *prog = next;
9083 
9084 	do {
9085 		prog = __bpf_program__iter(prog, obj, false);
9086 	} while (prog && prog_is_subprog(obj, prog));
9087 
9088 	return prog;
9089 }
9090 
9091 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
9092 {
9093 	prog->prog_ifindex = ifindex;
9094 }
9095 
9096 const char *bpf_program__name(const struct bpf_program *prog)
9097 {
9098 	return prog->name;
9099 }
9100 
9101 const char *bpf_program__section_name(const struct bpf_program *prog)
9102 {
9103 	return prog->sec_name;
9104 }
9105 
9106 bool bpf_program__autoload(const struct bpf_program *prog)
9107 {
9108 	return prog->autoload;
9109 }
9110 
9111 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
9112 {
9113 	if (prog->obj->loaded)
9114 		return libbpf_err(-EINVAL);
9115 
9116 	prog->autoload = autoload;
9117 	return 0;
9118 }
9119 
9120 bool bpf_program__autoattach(const struct bpf_program *prog)
9121 {
9122 	return prog->autoattach;
9123 }
9124 
9125 void bpf_program__set_autoattach(struct bpf_program *prog, bool autoattach)
9126 {
9127 	prog->autoattach = autoattach;
9128 }
9129 
9130 const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
9131 {
9132 	return prog->insns;
9133 }
9134 
9135 size_t bpf_program__insn_cnt(const struct bpf_program *prog)
9136 {
9137 	return prog->insns_cnt;
9138 }
9139 
9140 int bpf_program__set_insns(struct bpf_program *prog,
9141 			   struct bpf_insn *new_insns, size_t new_insn_cnt)
9142 {
9143 	struct bpf_insn *insns;
9144 
9145 	if (prog->obj->loaded)
9146 		return -EBUSY;
9147 
9148 	insns = libbpf_reallocarray(prog->insns, new_insn_cnt, sizeof(*insns));
9149 	/* NULL is a valid return from reallocarray if the new count is zero */
9150 	if (!insns && new_insn_cnt) {
9151 		pr_warn("prog '%s': failed to realloc prog code\n", prog->name);
9152 		return -ENOMEM;
9153 	}
9154 	memcpy(insns, new_insns, new_insn_cnt * sizeof(*insns));
9155 
9156 	prog->insns = insns;
9157 	prog->insns_cnt = new_insn_cnt;
9158 	return 0;
9159 }
9160 
9161 int bpf_program__fd(const struct bpf_program *prog)
9162 {
9163 	if (!prog)
9164 		return libbpf_err(-EINVAL);
9165 
9166 	if (prog->fd < 0)
9167 		return libbpf_err(-ENOENT);
9168 
9169 	return prog->fd;
9170 }
9171 
9172 __alias(bpf_program__type)
9173 enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog);
9174 
9175 enum bpf_prog_type bpf_program__type(const struct bpf_program *prog)
9176 {
9177 	return prog->type;
9178 }
9179 
9180 static size_t custom_sec_def_cnt;
9181 static struct bpf_sec_def *custom_sec_defs;
9182 static struct bpf_sec_def custom_fallback_def;
9183 static bool has_custom_fallback_def;
9184 static int last_custom_sec_def_handler_id;
9185 
9186 int bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
9187 {
9188 	if (prog->obj->loaded)
9189 		return libbpf_err(-EBUSY);
9190 
9191 	/* if type is not changed, do nothing */
9192 	if (prog->type == type)
9193 		return 0;
9194 
9195 	prog->type = type;
9196 
9197 	/* If a program type was changed, we need to reset associated SEC()
9198 	 * handler, as it will be invalid now. The only exception is a generic
9199 	 * fallback handler, which by definition is program type-agnostic and
9200 	 * is a catch-all custom handler, optionally set by the application,
9201 	 * so should be able to handle any type of BPF program.
9202 	 */
9203 	if (prog->sec_def != &custom_fallback_def)
9204 		prog->sec_def = NULL;
9205 	return 0;
9206 }
9207 
9208 __alias(bpf_program__expected_attach_type)
9209 enum bpf_attach_type bpf_program__get_expected_attach_type(const struct bpf_program *prog);
9210 
9211 enum bpf_attach_type bpf_program__expected_attach_type(const struct bpf_program *prog)
9212 {
9213 	return prog->expected_attach_type;
9214 }
9215 
9216 int bpf_program__set_expected_attach_type(struct bpf_program *prog,
9217 					   enum bpf_attach_type type)
9218 {
9219 	if (prog->obj->loaded)
9220 		return libbpf_err(-EBUSY);
9221 
9222 	prog->expected_attach_type = type;
9223 	return 0;
9224 }
9225 
9226 __u32 bpf_program__flags(const struct bpf_program *prog)
9227 {
9228 	return prog->prog_flags;
9229 }
9230 
9231 int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
9232 {
9233 	if (prog->obj->loaded)
9234 		return libbpf_err(-EBUSY);
9235 
9236 	prog->prog_flags = flags;
9237 	return 0;
9238 }
9239 
9240 __u32 bpf_program__log_level(const struct bpf_program *prog)
9241 {
9242 	return prog->log_level;
9243 }
9244 
9245 int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
9246 {
9247 	if (prog->obj->loaded)
9248 		return libbpf_err(-EBUSY);
9249 
9250 	prog->log_level = log_level;
9251 	return 0;
9252 }
9253 
9254 const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
9255 {
9256 	*log_size = prog->log_size;
9257 	return prog->log_buf;
9258 }
9259 
9260 int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
9261 {
9262 	if (log_size && !log_buf)
9263 		return -EINVAL;
9264 	if (prog->log_size > UINT_MAX)
9265 		return -EINVAL;
9266 	if (prog->obj->loaded)
9267 		return -EBUSY;
9268 
9269 	prog->log_buf = log_buf;
9270 	prog->log_size = log_size;
9271 	return 0;
9272 }
9273 
9274 #define SEC_DEF(sec_pfx, ptype, atype, flags, ...) {			    \
9275 	.sec = (char *)sec_pfx,						    \
9276 	.prog_type = BPF_PROG_TYPE_##ptype,				    \
9277 	.expected_attach_type = atype,					    \
9278 	.cookie = (long)(flags),					    \
9279 	.prog_prepare_load_fn = libbpf_prepare_prog_load,		    \
9280 	__VA_ARGS__							    \
9281 }
9282 
9283 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9284 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9285 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9286 #ifdef  HAVE_LIBELF
9287 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9288 #endif  //HAVE_LIBELF
9289 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9290 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9291 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9292 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9293 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9294 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9295 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9296 
9297 static const struct bpf_sec_def section_defs[] = {
9298 	SEC_DEF("socket",		SOCKET_FILTER, 0, SEC_NONE),
9299 	SEC_DEF("sk_reuseport/migrate",	SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE),
9300 	SEC_DEF("sk_reuseport",		SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE),
9301 	SEC_DEF("kprobe+",		KPROBE,	0, SEC_NONE, attach_kprobe),
9302 	SEC_DEF("uprobe+",		KPROBE,	0, SEC_NONE, attach_uprobe),
9303 	SEC_DEF("uprobe.s+",		KPROBE,	0, SEC_SLEEPABLE, attach_uprobe),
9304 	SEC_DEF("kretprobe+",		KPROBE, 0, SEC_NONE, attach_kprobe),
9305 	SEC_DEF("uretprobe+",		KPROBE, 0, SEC_NONE, attach_uprobe),
9306 	SEC_DEF("uretprobe.s+",		KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
9307 	SEC_DEF("kprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
9308 	SEC_DEF("kretprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
9309 	SEC_DEF("uprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
9310 	SEC_DEF("uretprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
9311 	SEC_DEF("uprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
9312 	SEC_DEF("uretprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
9313 	SEC_DEF("ksyscall+",		KPROBE,	0, SEC_NONE, attach_ksyscall),
9314 	SEC_DEF("kretsyscall+",		KPROBE, 0, SEC_NONE, attach_ksyscall),
9315 #ifdef  HAVE_LIBELF
9316 	SEC_DEF("usdt+",		KPROBE,	0, SEC_USDT, attach_usdt),
9317 	SEC_DEF("usdt.s+",		KPROBE,	0, SEC_USDT | SEC_SLEEPABLE, attach_usdt),
9318 #endif  //HAVE_LIBELF
9319 	SEC_DEF("tc/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE), /* alias for tcx */
9320 	SEC_DEF("tc/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),  /* alias for tcx */
9321 	SEC_DEF("tcx/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE),
9322 	SEC_DEF("tcx/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),
9323 	SEC_DEF("tc",			SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
9324 	SEC_DEF("classifier",		SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
9325 	SEC_DEF("action",		SCHED_ACT, 0, SEC_NONE), /* deprecated / legacy, use tcx */
9326 	SEC_DEF("netkit/primary",	SCHED_CLS, BPF_NETKIT_PRIMARY, SEC_NONE),
9327 	SEC_DEF("netkit/peer",		SCHED_CLS, BPF_NETKIT_PEER, SEC_NONE),
9328 	SEC_DEF("tracepoint+",		TRACEPOINT, 0, SEC_NONE, attach_tp),
9329 	SEC_DEF("tp+",			TRACEPOINT, 0, SEC_NONE, attach_tp),
9330 	SEC_DEF("raw_tracepoint+",	RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
9331 	SEC_DEF("raw_tp+",		RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
9332 	SEC_DEF("raw_tracepoint.w+",	RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
9333 	SEC_DEF("raw_tp.w+",		RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
9334 	SEC_DEF("tp_btf+",		TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
9335 	SEC_DEF("fentry+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
9336 	SEC_DEF("fmod_ret+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
9337 	SEC_DEF("fexit+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
9338 	SEC_DEF("fentry.s+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
9339 	SEC_DEF("fmod_ret.s+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
9340 	SEC_DEF("fexit.s+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
9341 	SEC_DEF("freplace+",		EXT, 0, SEC_ATTACH_BTF, attach_trace),
9342 	SEC_DEF("lsm+",			LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
9343 	SEC_DEF("lsm.s+",		LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
9344 	SEC_DEF("lsm_cgroup+",		LSM, BPF_LSM_CGROUP, SEC_ATTACH_BTF),
9345 	SEC_DEF("iter+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
9346 	SEC_DEF("iter.s+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_iter),
9347 	SEC_DEF("syscall",		SYSCALL, 0, SEC_SLEEPABLE),
9348 	SEC_DEF("xdp.frags/devmap",	XDP, BPF_XDP_DEVMAP, SEC_XDP_FRAGS),
9349 	SEC_DEF("xdp/devmap",		XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
9350 	SEC_DEF("xdp.frags/cpumap",	XDP, BPF_XDP_CPUMAP, SEC_XDP_FRAGS),
9351 	SEC_DEF("xdp/cpumap",		XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
9352 	SEC_DEF("xdp.frags",		XDP, BPF_XDP, SEC_XDP_FRAGS),
9353 	SEC_DEF("xdp",			XDP, BPF_XDP, SEC_ATTACHABLE_OPT),
9354 	SEC_DEF("perf_event",		PERF_EVENT, 0, SEC_NONE),
9355 	SEC_DEF("lwt_in",		LWT_IN, 0, SEC_NONE),
9356 	SEC_DEF("lwt_out",		LWT_OUT, 0, SEC_NONE),
9357 	SEC_DEF("lwt_xmit",		LWT_XMIT, 0, SEC_NONE),
9358 	SEC_DEF("lwt_seg6local",	LWT_SEG6LOCAL, 0, SEC_NONE),
9359 	SEC_DEF("sockops",		SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT),
9360 	SEC_DEF("sk_skb/stream_parser",	SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT),
9361 	SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT),
9362 	SEC_DEF("sk_skb",		SK_SKB, 0, SEC_NONE),
9363 	SEC_DEF("sk_msg",		SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT),
9364 	SEC_DEF("lirc_mode2",		LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT),
9365 	SEC_DEF("flow_dissector",	FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT),
9366 	SEC_DEF("cgroup_skb/ingress",	CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT),
9367 	SEC_DEF("cgroup_skb/egress",	CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT),
9368 	SEC_DEF("cgroup/skb",		CGROUP_SKB, 0, SEC_NONE),
9369 	SEC_DEF("cgroup/sock_create",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE),
9370 	SEC_DEF("cgroup/sock_release",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE),
9371 	SEC_DEF("cgroup/sock",		CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT),
9372 	SEC_DEF("cgroup/post_bind4",	CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE),
9373 	SEC_DEF("cgroup/post_bind6",	CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE),
9374 	SEC_DEF("cgroup/bind4",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE),
9375 	SEC_DEF("cgroup/bind6",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE),
9376 	SEC_DEF("cgroup/connect4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE),
9377 	SEC_DEF("cgroup/connect6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE),
9378 	SEC_DEF("cgroup/connect_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_CONNECT, SEC_ATTACHABLE),
9379 	SEC_DEF("cgroup/sendmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE),
9380 	SEC_DEF("cgroup/sendmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE),
9381 	SEC_DEF("cgroup/sendmsg_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_SENDMSG, SEC_ATTACHABLE),
9382 	SEC_DEF("cgroup/recvmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE),
9383 	SEC_DEF("cgroup/recvmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE),
9384 	SEC_DEF("cgroup/recvmsg_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_RECVMSG, SEC_ATTACHABLE),
9385 	SEC_DEF("cgroup/getpeername4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE),
9386 	SEC_DEF("cgroup/getpeername6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE),
9387 	SEC_DEF("cgroup/getpeername_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETPEERNAME, SEC_ATTACHABLE),
9388 	SEC_DEF("cgroup/getsockname4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE),
9389 	SEC_DEF("cgroup/getsockname6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE),
9390 	SEC_DEF("cgroup/getsockname_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETSOCKNAME, SEC_ATTACHABLE),
9391 	SEC_DEF("cgroup/sysctl",	CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE),
9392 	SEC_DEF("cgroup/getsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE),
9393 	SEC_DEF("cgroup/setsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE),
9394 	SEC_DEF("cgroup/dev",		CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT),
9395 	SEC_DEF("struct_ops+",		STRUCT_OPS, 0, SEC_NONE),
9396 	SEC_DEF("struct_ops.s+",	STRUCT_OPS, 0, SEC_SLEEPABLE),
9397 	SEC_DEF("sk_lookup",		SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE),
9398 	SEC_DEF("netfilter",		NETFILTER, BPF_NETFILTER, SEC_NONE),
9399 };
9400 
9401 int libbpf_register_prog_handler(const char *sec,
9402 				 enum bpf_prog_type prog_type,
9403 				 enum bpf_attach_type exp_attach_type,
9404 				 const struct libbpf_prog_handler_opts *opts)
9405 {
9406 	struct bpf_sec_def *sec_def;
9407 
9408 	if (!OPTS_VALID(opts, libbpf_prog_handler_opts))
9409 		return libbpf_err(-EINVAL);
9410 
9411 	if (last_custom_sec_def_handler_id == INT_MAX) /* prevent overflow */
9412 		return libbpf_err(-E2BIG);
9413 
9414 	if (sec) {
9415 		sec_def = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt + 1,
9416 					      sizeof(*sec_def));
9417 		if (!sec_def)
9418 			return libbpf_err(-ENOMEM);
9419 
9420 		custom_sec_defs = sec_def;
9421 		sec_def = &custom_sec_defs[custom_sec_def_cnt];
9422 	} else {
9423 		if (has_custom_fallback_def)
9424 			return libbpf_err(-EBUSY);
9425 
9426 		sec_def = &custom_fallback_def;
9427 	}
9428 
9429 	sec_def->sec = sec ? strdup(sec) : NULL;
9430 	if (sec && !sec_def->sec)
9431 		return libbpf_err(-ENOMEM);
9432 
9433 	sec_def->prog_type = prog_type;
9434 	sec_def->expected_attach_type = exp_attach_type;
9435 	sec_def->cookie = OPTS_GET(opts, cookie, 0);
9436 
9437 	sec_def->prog_setup_fn = OPTS_GET(opts, prog_setup_fn, NULL);
9438 	sec_def->prog_prepare_load_fn = OPTS_GET(opts, prog_prepare_load_fn, NULL);
9439 	sec_def->prog_attach_fn = OPTS_GET(opts, prog_attach_fn, NULL);
9440 
9441 	sec_def->handler_id = ++last_custom_sec_def_handler_id;
9442 
9443 	if (sec)
9444 		custom_sec_def_cnt++;
9445 	else
9446 		has_custom_fallback_def = true;
9447 
9448 	return sec_def->handler_id;
9449 }
9450 
9451 int libbpf_unregister_prog_handler(int handler_id)
9452 {
9453 	struct bpf_sec_def *sec_defs;
9454 	int i;
9455 
9456 	if (handler_id <= 0)
9457 		return libbpf_err(-EINVAL);
9458 
9459 	if (has_custom_fallback_def && custom_fallback_def.handler_id == handler_id) {
9460 		memset(&custom_fallback_def, 0, sizeof(custom_fallback_def));
9461 		has_custom_fallback_def = false;
9462 		return 0;
9463 	}
9464 
9465 	for (i = 0; i < custom_sec_def_cnt; i++) {
9466 		if (custom_sec_defs[i].handler_id == handler_id)
9467 			break;
9468 	}
9469 
9470 	if (i == custom_sec_def_cnt)
9471 		return libbpf_err(-ENOENT);
9472 
9473 	free(custom_sec_defs[i].sec);
9474 	for (i = i + 1; i < custom_sec_def_cnt; i++)
9475 		custom_sec_defs[i - 1] = custom_sec_defs[i];
9476 	custom_sec_def_cnt--;
9477 
9478 	/* try to shrink the array, but it's ok if we couldn't */
9479 	sec_defs = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt, sizeof(*sec_defs));
9480 	/* if new count is zero, reallocarray can return a valid NULL result;
9481 	 * in this case the previous pointer will be freed, so we *have to*
9482 	 * reassign old pointer to the new value (even if it's NULL)
9483 	 */
9484 	if (sec_defs || custom_sec_def_cnt == 0)
9485 		custom_sec_defs = sec_defs;
9486 
9487 	return 0;
9488 }
9489 
9490 static bool sec_def_matches(const struct bpf_sec_def *sec_def, const char *sec_name)
9491 {
9492 	size_t len = strlen(sec_def->sec);
9493 
9494 	/* "type/" always has to have proper SEC("type/extras") form */
9495 	if (sec_def->sec[len - 1] == '/') {
9496 		if (str_has_pfx(sec_name, sec_def->sec))
9497 			return true;
9498 		return false;
9499 	}
9500 
9501 	/* "type+" means it can be either exact SEC("type") or
9502 	 * well-formed SEC("type/extras") with proper '/' separator
9503 	 */
9504 	if (sec_def->sec[len - 1] == '+') {
9505 		len--;
9506 		/* not even a prefix */
9507 		if (strncmp(sec_name, sec_def->sec, len) != 0)
9508 			return false;
9509 		/* exact match or has '/' separator */
9510 		if (sec_name[len] == '\0' || sec_name[len] == '/')
9511 			return true;
9512 		return false;
9513 	}
9514 
9515 	return strcmp(sec_name, sec_def->sec) == 0;
9516 }
9517 
9518 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
9519 {
9520 	const struct bpf_sec_def *sec_def;
9521 	int i, n;
9522 
9523 	n = custom_sec_def_cnt;
9524 	for (i = 0; i < n; i++) {
9525 		sec_def = &custom_sec_defs[i];
9526 		if (sec_def_matches(sec_def, sec_name))
9527 			return sec_def;
9528 	}
9529 
9530 	n = ARRAY_SIZE(section_defs);
9531 	for (i = 0; i < n; i++) {
9532 		sec_def = &section_defs[i];
9533 		if (sec_def_matches(sec_def, sec_name))
9534 			return sec_def;
9535 	}
9536 
9537 	if (has_custom_fallback_def)
9538 		return &custom_fallback_def;
9539 
9540 	return NULL;
9541 }
9542 
9543 #define MAX_TYPE_NAME_SIZE 32
9544 
9545 static char *libbpf_get_type_names(bool attach_type)
9546 {
9547 	int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
9548 	char *buf;
9549 
9550 	buf = malloc(len);
9551 	if (!buf)
9552 		return NULL;
9553 
9554 	buf[0] = '\0';
9555 	/* Forge string buf with all available names */
9556 	for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
9557 		const struct bpf_sec_def *sec_def = &section_defs[i];
9558 
9559 		if (attach_type) {
9560 			if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
9561 				continue;
9562 
9563 			if (!(sec_def->cookie & SEC_ATTACHABLE))
9564 				continue;
9565 		}
9566 
9567 		if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
9568 			free(buf);
9569 			return NULL;
9570 		}
9571 		strcat(buf, " ");
9572 		strcat(buf, section_defs[i].sec);
9573 	}
9574 
9575 	return buf;
9576 }
9577 
9578 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
9579 			     enum bpf_attach_type *expected_attach_type)
9580 {
9581 	const struct bpf_sec_def *sec_def;
9582 	char *type_names;
9583 
9584 	if (!name)
9585 		return libbpf_err(-EINVAL);
9586 
9587 	sec_def = find_sec_def(name);
9588 	if (sec_def) {
9589 		*prog_type = sec_def->prog_type;
9590 		*expected_attach_type = sec_def->expected_attach_type;
9591 		return 0;
9592 	}
9593 
9594 	pr_debug("failed to guess program type from ELF section '%s'\n", name);
9595 	type_names = libbpf_get_type_names(false);
9596 	if (type_names != NULL) {
9597 		pr_debug("supported section(type) names are:%s\n", type_names);
9598 		free(type_names);
9599 	}
9600 
9601 	return libbpf_err(-ESRCH);
9602 }
9603 
9604 const char *libbpf_bpf_attach_type_str(enum bpf_attach_type t)
9605 {
9606 	if (t < 0 || t >= ARRAY_SIZE(attach_type_name))
9607 		return NULL;
9608 
9609 	return attach_type_name[t];
9610 }
9611 
9612 const char *libbpf_bpf_link_type_str(enum bpf_link_type t)
9613 {
9614 	if (t < 0 || t >= ARRAY_SIZE(link_type_name))
9615 		return NULL;
9616 
9617 	return link_type_name[t];
9618 }
9619 
9620 const char *libbpf_bpf_map_type_str(enum bpf_map_type t)
9621 {
9622 	if (t < 0 || t >= ARRAY_SIZE(map_type_name))
9623 		return NULL;
9624 
9625 	return map_type_name[t];
9626 }
9627 
9628 const char *libbpf_bpf_prog_type_str(enum bpf_prog_type t)
9629 {
9630 	if (t < 0 || t >= ARRAY_SIZE(prog_type_name))
9631 		return NULL;
9632 
9633 	return prog_type_name[t];
9634 }
9635 
9636 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
9637 						     int sec_idx,
9638 						     size_t offset)
9639 {
9640 	struct bpf_map *map;
9641 	size_t i;
9642 
9643 	for (i = 0; i < obj->nr_maps; i++) {
9644 		map = &obj->maps[i];
9645 		if (!bpf_map__is_struct_ops(map))
9646 			continue;
9647 		if (map->sec_idx == sec_idx &&
9648 		    map->sec_offset <= offset &&
9649 		    offset - map->sec_offset < map->def.value_size)
9650 			return map;
9651 	}
9652 
9653 	return NULL;
9654 }
9655 
9656 /* Collect the reloc from ELF and populate the st_ops->progs[] */
9657 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
9658 					    Elf64_Shdr *shdr, Elf_Data *data)
9659 {
9660 	const struct btf_member *member;
9661 	struct bpf_struct_ops *st_ops;
9662 	struct bpf_program *prog;
9663 	unsigned int shdr_idx;
9664 	const struct btf *btf;
9665 	struct bpf_map *map;
9666 	unsigned int moff, insn_idx;
9667 	const char *name;
9668 	__u32 member_idx;
9669 	Elf64_Sym *sym;
9670 	Elf64_Rel *rel;
9671 	int i, nrels;
9672 
9673 	btf = obj->btf;
9674 	nrels = shdr->sh_size / shdr->sh_entsize;
9675 	for (i = 0; i < nrels; i++) {
9676 		rel = elf_rel_by_idx(data, i);
9677 		if (!rel) {
9678 			pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
9679 			return -LIBBPF_ERRNO__FORMAT;
9680 		}
9681 
9682 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
9683 		if (!sym) {
9684 			pr_warn("struct_ops reloc: symbol %zx not found\n",
9685 				(size_t)ELF64_R_SYM(rel->r_info));
9686 			return -LIBBPF_ERRNO__FORMAT;
9687 		}
9688 
9689 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
9690 		map = find_struct_ops_map_by_offset(obj, shdr->sh_info, rel->r_offset);
9691 		if (!map) {
9692 			pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
9693 				(size_t)rel->r_offset);
9694 			return -EINVAL;
9695 		}
9696 
9697 		moff = rel->r_offset - map->sec_offset;
9698 		shdr_idx = sym->st_shndx;
9699 		st_ops = map->st_ops;
9700 		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",
9701 			 map->name,
9702 			 (long long)(rel->r_info >> 32),
9703 			 (long long)sym->st_value,
9704 			 shdr_idx, (size_t)rel->r_offset,
9705 			 map->sec_offset, sym->st_name, name);
9706 
9707 		if (shdr_idx >= SHN_LORESERVE) {
9708 			pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
9709 				map->name, (size_t)rel->r_offset, shdr_idx);
9710 			return -LIBBPF_ERRNO__RELOC;
9711 		}
9712 		if (sym->st_value % BPF_INSN_SZ) {
9713 			pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
9714 				map->name, (unsigned long long)sym->st_value);
9715 			return -LIBBPF_ERRNO__FORMAT;
9716 		}
9717 		insn_idx = sym->st_value / BPF_INSN_SZ;
9718 
9719 		member = find_member_by_offset(st_ops->type, moff * 8);
9720 		if (!member) {
9721 			pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
9722 				map->name, moff);
9723 			return -EINVAL;
9724 		}
9725 		member_idx = member - btf_members(st_ops->type);
9726 		name = btf__name_by_offset(btf, member->name_off);
9727 
9728 		if (!resolve_func_ptr(btf, member->type, NULL)) {
9729 			pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
9730 				map->name, name);
9731 			return -EINVAL;
9732 		}
9733 
9734 		prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
9735 		if (!prog) {
9736 			pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
9737 				map->name, shdr_idx, name);
9738 			return -EINVAL;
9739 		}
9740 
9741 		/* prevent the use of BPF prog with invalid type */
9742 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
9743 			pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
9744 				map->name, prog->name);
9745 			return -EINVAL;
9746 		}
9747 
9748 		/* if we haven't yet processed this BPF program, record proper
9749 		 * attach_btf_id and member_idx
9750 		 */
9751 		if (!prog->attach_btf_id) {
9752 			prog->attach_btf_id = st_ops->type_id;
9753 			prog->expected_attach_type = member_idx;
9754 		}
9755 
9756 		/* struct_ops BPF prog can be re-used between multiple
9757 		 * .struct_ops & .struct_ops.link as long as it's the
9758 		 * same struct_ops struct definition and the same
9759 		 * function pointer field
9760 		 */
9761 		if (prog->attach_btf_id != st_ops->type_id ||
9762 		    prog->expected_attach_type != member_idx) {
9763 			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",
9764 				map->name, prog->name, prog->sec_name, prog->type,
9765 				prog->attach_btf_id, prog->expected_attach_type, name);
9766 			return -EINVAL;
9767 		}
9768 
9769 		st_ops->progs[member_idx] = prog;
9770 	}
9771 
9772 	return 0;
9773 }
9774 
9775 #define BTF_TRACE_PREFIX "btf_trace_"
9776 #define BTF_LSM_PREFIX "bpf_lsm_"
9777 #define BTF_ITER_PREFIX "bpf_iter_"
9778 #define BTF_MAX_NAME_SIZE 128
9779 
9780 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
9781 				const char **prefix, int *kind)
9782 {
9783 	switch (attach_type) {
9784 	case BPF_TRACE_RAW_TP:
9785 		*prefix = BTF_TRACE_PREFIX;
9786 		*kind = BTF_KIND_TYPEDEF;
9787 		break;
9788 	case BPF_LSM_MAC:
9789 	case BPF_LSM_CGROUP:
9790 		*prefix = BTF_LSM_PREFIX;
9791 		*kind = BTF_KIND_FUNC;
9792 		break;
9793 	case BPF_TRACE_ITER:
9794 		*prefix = BTF_ITER_PREFIX;
9795 		*kind = BTF_KIND_FUNC;
9796 		break;
9797 	default:
9798 		*prefix = "";
9799 		*kind = BTF_KIND_FUNC;
9800 	}
9801 }
9802 
9803 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
9804 				   const char *name, __u32 kind)
9805 {
9806 	char btf_type_name[BTF_MAX_NAME_SIZE];
9807 	int ret;
9808 
9809 	ret = snprintf(btf_type_name, sizeof(btf_type_name),
9810 		       "%s%s", prefix, name);
9811 	/* snprintf returns the number of characters written excluding the
9812 	 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
9813 	 * indicates truncation.
9814 	 */
9815 	if (ret < 0 || ret >= sizeof(btf_type_name))
9816 		return -ENAMETOOLONG;
9817 	return btf__find_by_name_kind(btf, btf_type_name, kind);
9818 }
9819 
9820 static inline int find_attach_btf_id(struct btf *btf, const char *name,
9821 				     enum bpf_attach_type attach_type)
9822 {
9823 	const char *prefix;
9824 	int kind;
9825 
9826 	btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
9827 	return find_btf_by_prefix_kind(btf, prefix, name, kind);
9828 }
9829 
9830 int libbpf_find_vmlinux_btf_id(const char *name,
9831 			       enum bpf_attach_type attach_type)
9832 {
9833 	struct btf *btf;
9834 	int err;
9835 
9836 	btf = btf__load_vmlinux_btf();
9837 	err = libbpf_get_error(btf);
9838 	if (err) {
9839 		pr_warn("vmlinux BTF is not found\n");
9840 		return libbpf_err(err);
9841 	}
9842 
9843 	err = find_attach_btf_id(btf, name, attach_type);
9844 	if (err <= 0)
9845 		pr_warn("%s is not found in vmlinux BTF\n", name);
9846 
9847 	btf__free(btf);
9848 	return libbpf_err(err);
9849 }
9850 
9851 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
9852 {
9853 	struct bpf_prog_info info;
9854 	__u32 info_len = sizeof(info);
9855 	struct btf *btf;
9856 	int err;
9857 
9858 	memset(&info, 0, info_len);
9859 	err = bpf_prog_get_info_by_fd(attach_prog_fd, &info, &info_len);
9860 	if (err) {
9861 		pr_warn("failed bpf_prog_get_info_by_fd for FD %d: %d\n",
9862 			attach_prog_fd, err);
9863 		return err;
9864 	}
9865 
9866 	err = -EINVAL;
9867 	if (!info.btf_id) {
9868 		pr_warn("The target program doesn't have BTF\n");
9869 		goto out;
9870 	}
9871 	btf = btf__load_from_kernel_by_id(info.btf_id);
9872 	err = libbpf_get_error(btf);
9873 	if (err) {
9874 		pr_warn("Failed to get BTF %d of the program: %d\n", info.btf_id, err);
9875 		goto out;
9876 	}
9877 	err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
9878 	btf__free(btf);
9879 	if (err <= 0) {
9880 		pr_warn("%s is not found in prog's BTF\n", name);
9881 		goto out;
9882 	}
9883 out:
9884 	return err;
9885 }
9886 
9887 static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
9888 			      enum bpf_attach_type attach_type,
9889 			      int *btf_obj_fd, int *btf_type_id)
9890 {
9891 	int ret, i;
9892 
9893 	ret = find_attach_btf_id(obj->btf_vmlinux, attach_name, attach_type);
9894 	if (ret > 0) {
9895 		*btf_obj_fd = 0; /* vmlinux BTF */
9896 		*btf_type_id = ret;
9897 		return 0;
9898 	}
9899 	if (ret != -ENOENT)
9900 		return ret;
9901 
9902 	ret = load_module_btfs(obj);
9903 	if (ret)
9904 		return ret;
9905 
9906 	for (i = 0; i < obj->btf_module_cnt; i++) {
9907 		const struct module_btf *mod = &obj->btf_modules[i];
9908 
9909 		ret = find_attach_btf_id(mod->btf, attach_name, attach_type);
9910 		if (ret > 0) {
9911 			*btf_obj_fd = mod->fd;
9912 			*btf_type_id = ret;
9913 			return 0;
9914 		}
9915 		if (ret == -ENOENT)
9916 			continue;
9917 
9918 		return ret;
9919 	}
9920 
9921 	return -ESRCH;
9922 }
9923 
9924 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
9925 				     int *btf_obj_fd, int *btf_type_id)
9926 {
9927 	enum bpf_attach_type attach_type = prog->expected_attach_type;
9928 	__u32 attach_prog_fd = prog->attach_prog_fd;
9929 	int err = 0;
9930 
9931 	/* BPF program's BTF ID */
9932 	if (prog->type == BPF_PROG_TYPE_EXT || attach_prog_fd) {
9933 		if (!attach_prog_fd) {
9934 			pr_warn("prog '%s': attach program FD is not set\n", prog->name);
9935 			return -EINVAL;
9936 		}
9937 		err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd);
9938 		if (err < 0) {
9939 			pr_warn("prog '%s': failed to find BPF program (FD %d) BTF ID for '%s': %d\n",
9940 				 prog->name, attach_prog_fd, attach_name, err);
9941 			return err;
9942 		}
9943 		*btf_obj_fd = 0;
9944 		*btf_type_id = err;
9945 		return 0;
9946 	}
9947 
9948 	/* kernel/module BTF ID */
9949 	if (prog->obj->gen_loader) {
9950 		bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
9951 		*btf_obj_fd = 0;
9952 		*btf_type_id = 1;
9953 	} else {
9954 		err = find_kernel_btf_id(prog->obj, attach_name, attach_type, btf_obj_fd, btf_type_id);
9955 	}
9956 	if (err) {
9957 		pr_warn("prog '%s': failed to find kernel BTF type ID of '%s': %d\n",
9958 			prog->name, attach_name, err);
9959 		return err;
9960 	}
9961 	return 0;
9962 }
9963 
9964 int libbpf_attach_type_by_name(const char *name,
9965 			       enum bpf_attach_type *attach_type)
9966 {
9967 	char *type_names;
9968 	const struct bpf_sec_def *sec_def;
9969 
9970 	if (!name)
9971 		return libbpf_err(-EINVAL);
9972 
9973 	sec_def = find_sec_def(name);
9974 	if (!sec_def) {
9975 		pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
9976 		type_names = libbpf_get_type_names(true);
9977 		if (type_names != NULL) {
9978 			pr_debug("attachable section(type) names are:%s\n", type_names);
9979 			free(type_names);
9980 		}
9981 
9982 		return libbpf_err(-EINVAL);
9983 	}
9984 
9985 	if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
9986 		return libbpf_err(-EINVAL);
9987 	if (!(sec_def->cookie & SEC_ATTACHABLE))
9988 		return libbpf_err(-EINVAL);
9989 
9990 	*attach_type = sec_def->expected_attach_type;
9991 	return 0;
9992 }
9993 
9994 int bpf_map__fd(const struct bpf_map *map)
9995 {
9996 	return map ? map->fd : libbpf_err(-EINVAL);
9997 }
9998 
9999 static bool map_uses_real_name(const struct bpf_map *map)
10000 {
10001 	/* Since libbpf started to support custom .data.* and .rodata.* maps,
10002 	 * their user-visible name differs from kernel-visible name. Users see
10003 	 * such map's corresponding ELF section name as a map name.
10004 	 * This check distinguishes .data/.rodata from .data.* and .rodata.*
10005 	 * maps to know which name has to be returned to the user.
10006 	 */
10007 	if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
10008 		return true;
10009 	if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
10010 		return true;
10011 	return false;
10012 }
10013 
10014 const char *bpf_map__name(const struct bpf_map *map)
10015 {
10016 	if (!map)
10017 		return NULL;
10018 
10019 	if (map_uses_real_name(map))
10020 		return map->real_name;
10021 
10022 	return map->name;
10023 }
10024 
10025 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
10026 {
10027 	return map->def.type;
10028 }
10029 
10030 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
10031 {
10032 	if (map->fd >= 0)
10033 		return libbpf_err(-EBUSY);
10034 	map->def.type = type;
10035 	return 0;
10036 }
10037 
10038 __u32 bpf_map__map_flags(const struct bpf_map *map)
10039 {
10040 	return map->def.map_flags;
10041 }
10042 
10043 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
10044 {
10045 	if (map->fd >= 0)
10046 		return libbpf_err(-EBUSY);
10047 	map->def.map_flags = flags;
10048 	return 0;
10049 }
10050 
10051 __u64 bpf_map__map_extra(const struct bpf_map *map)
10052 {
10053 	return map->map_extra;
10054 }
10055 
10056 int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
10057 {
10058 	if (map->fd >= 0)
10059 		return libbpf_err(-EBUSY);
10060 	map->map_extra = map_extra;
10061 	return 0;
10062 }
10063 
10064 __u32 bpf_map__numa_node(const struct bpf_map *map)
10065 {
10066 	return map->numa_node;
10067 }
10068 
10069 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
10070 {
10071 	if (map->fd >= 0)
10072 		return libbpf_err(-EBUSY);
10073 	map->numa_node = numa_node;
10074 	return 0;
10075 }
10076 
10077 __u32 bpf_map__key_size(const struct bpf_map *map)
10078 {
10079 	return map->def.key_size;
10080 }
10081 
10082 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
10083 {
10084 	if (map->fd >= 0)
10085 		return libbpf_err(-EBUSY);
10086 	map->def.key_size = size;
10087 	return 0;
10088 }
10089 
10090 __u32 bpf_map__value_size(const struct bpf_map *map)
10091 {
10092 	return map->def.value_size;
10093 }
10094 
10095 static int map_btf_datasec_resize(struct bpf_map *map, __u32 size)
10096 {
10097 	struct btf *btf;
10098 	struct btf_type *datasec_type, *var_type;
10099 	struct btf_var_secinfo *var;
10100 	const struct btf_type *array_type;
10101 	const struct btf_array *array;
10102 	int vlen, element_sz, new_array_id;
10103 	__u32 nr_elements;
10104 
10105 	/* check btf existence */
10106 	btf = bpf_object__btf(map->obj);
10107 	if (!btf)
10108 		return -ENOENT;
10109 
10110 	/* verify map is datasec */
10111 	datasec_type = btf_type_by_id(btf, bpf_map__btf_value_type_id(map));
10112 	if (!btf_is_datasec(datasec_type)) {
10113 		pr_warn("map '%s': cannot be resized, map value type is not a datasec\n",
10114 			bpf_map__name(map));
10115 		return -EINVAL;
10116 	}
10117 
10118 	/* verify datasec has at least one var */
10119 	vlen = btf_vlen(datasec_type);
10120 	if (vlen == 0) {
10121 		pr_warn("map '%s': cannot be resized, map value datasec is empty\n",
10122 			bpf_map__name(map));
10123 		return -EINVAL;
10124 	}
10125 
10126 	/* verify last var in the datasec is an array */
10127 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
10128 	var_type = btf_type_by_id(btf, var->type);
10129 	array_type = skip_mods_and_typedefs(btf, var_type->type, NULL);
10130 	if (!btf_is_array(array_type)) {
10131 		pr_warn("map '%s': cannot be resized, last var must be an array\n",
10132 			bpf_map__name(map));
10133 		return -EINVAL;
10134 	}
10135 
10136 	/* verify request size aligns with array */
10137 	array = btf_array(array_type);
10138 	element_sz = btf__resolve_size(btf, array->type);
10139 	if (element_sz <= 0 || (size - var->offset) % element_sz != 0) {
10140 		pr_warn("map '%s': cannot be resized, element size (%d) doesn't align with new total size (%u)\n",
10141 			bpf_map__name(map), element_sz, size);
10142 		return -EINVAL;
10143 	}
10144 
10145 	/* create a new array based on the existing array, but with new length */
10146 	nr_elements = (size - var->offset) / element_sz;
10147 	new_array_id = btf__add_array(btf, array->index_type, array->type, nr_elements);
10148 	if (new_array_id < 0)
10149 		return new_array_id;
10150 
10151 	/* adding a new btf type invalidates existing pointers to btf objects,
10152 	 * so refresh pointers before proceeding
10153 	 */
10154 	datasec_type = btf_type_by_id(btf, map->btf_value_type_id);
10155 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
10156 	var_type = btf_type_by_id(btf, var->type);
10157 
10158 	/* finally update btf info */
10159 	datasec_type->size = size;
10160 	var->size = size - var->offset;
10161 	var_type->type = new_array_id;
10162 
10163 	return 0;
10164 }
10165 
10166 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
10167 {
10168 	if (map->fd >= 0)
10169 		return libbpf_err(-EBUSY);
10170 
10171 	if (map->mmaped) {
10172 		int err;
10173 		size_t mmap_old_sz, mmap_new_sz;
10174 
10175 		mmap_old_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
10176 		mmap_new_sz = bpf_map_mmap_sz(size, map->def.max_entries);
10177 		err = bpf_map_mmap_resize(map, mmap_old_sz, mmap_new_sz);
10178 		if (err) {
10179 			pr_warn("map '%s': failed to resize memory-mapped region: %d\n",
10180 				bpf_map__name(map), err);
10181 			return err;
10182 		}
10183 		err = map_btf_datasec_resize(map, size);
10184 		if (err && err != -ENOENT) {
10185 			pr_warn("map '%s': failed to adjust resized BTF, clearing BTF key/value info: %d\n",
10186 				bpf_map__name(map), err);
10187 			map->btf_value_type_id = 0;
10188 			map->btf_key_type_id = 0;
10189 		}
10190 	}
10191 
10192 	map->def.value_size = size;
10193 	return 0;
10194 }
10195 
10196 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
10197 {
10198 	return map ? map->btf_key_type_id : 0;
10199 }
10200 
10201 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
10202 {
10203 	return map ? map->btf_value_type_id : 0;
10204 }
10205 
10206 int bpf_map__set_initial_value(struct bpf_map *map,
10207 			       const void *data, size_t size)
10208 {
10209 	if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG ||
10210 	    size != map->def.value_size || map->fd >= 0)
10211 		return libbpf_err(-EINVAL);
10212 
10213 	memcpy(map->mmaped, data, size);
10214 	return 0;
10215 }
10216 
10217 void *bpf_map__initial_value(struct bpf_map *map, size_t *psize)
10218 {
10219 	if (!map->mmaped)
10220 		return NULL;
10221 	*psize = map->def.value_size;
10222 	return map->mmaped;
10223 }
10224 
10225 bool bpf_map__is_internal(const struct bpf_map *map)
10226 {
10227 	return map->libbpf_type != LIBBPF_MAP_UNSPEC;
10228 }
10229 
10230 __u32 bpf_map__ifindex(const struct bpf_map *map)
10231 {
10232 	return map->map_ifindex;
10233 }
10234 
10235 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
10236 {
10237 	if (map->fd >= 0)
10238 		return libbpf_err(-EBUSY);
10239 	map->map_ifindex = ifindex;
10240 	return 0;
10241 }
10242 
10243 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
10244 {
10245 	if (!bpf_map_type__is_map_in_map(map->def.type)) {
10246 		pr_warn("error: unsupported map type\n");
10247 		return libbpf_err(-EINVAL);
10248 	}
10249 	if (map->inner_map_fd != -1) {
10250 		pr_warn("error: inner_map_fd already specified\n");
10251 		return libbpf_err(-EINVAL);
10252 	}
10253 	if (map->inner_map) {
10254 		bpf_map__destroy(map->inner_map);
10255 		zfree(&map->inner_map);
10256 	}
10257 	map->inner_map_fd = fd;
10258 	return 0;
10259 }
10260 
10261 static struct bpf_map *
10262 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
10263 {
10264 	ssize_t idx;
10265 	struct bpf_map *s, *e;
10266 
10267 	if (!obj || !obj->maps)
10268 		return errno = EINVAL, NULL;
10269 
10270 	s = obj->maps;
10271 	e = obj->maps + obj->nr_maps;
10272 
10273 	if ((m < s) || (m >= e)) {
10274 		pr_warn("error in %s: map handler doesn't belong to object\n",
10275 			 __func__);
10276 		return errno = EINVAL, NULL;
10277 	}
10278 
10279 	idx = (m - obj->maps) + i;
10280 	if (idx >= obj->nr_maps || idx < 0)
10281 		return NULL;
10282 	return &obj->maps[idx];
10283 }
10284 
10285 struct bpf_map *
10286 bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
10287 {
10288 	if (prev == NULL)
10289 		return obj->maps;
10290 
10291 	return __bpf_map__iter(prev, obj, 1);
10292 }
10293 
10294 struct bpf_map *
10295 bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
10296 {
10297 	if (next == NULL) {
10298 		if (!obj->nr_maps)
10299 			return NULL;
10300 		return obj->maps + obj->nr_maps - 1;
10301 	}
10302 
10303 	return __bpf_map__iter(next, obj, -1);
10304 }
10305 
10306 struct bpf_map *
10307 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
10308 {
10309 	struct bpf_map *pos;
10310 
10311 	bpf_object__for_each_map(pos, obj) {
10312 		/* if it's a special internal map name (which always starts
10313 		 * with dot) then check if that special name matches the
10314 		 * real map name (ELF section name)
10315 		 */
10316 		if (name[0] == '.') {
10317 			if (pos->real_name && strcmp(pos->real_name, name) == 0)
10318 				return pos;
10319 			continue;
10320 		}
10321 		/* otherwise map name has to be an exact match */
10322 		if (map_uses_real_name(pos)) {
10323 			if (strcmp(pos->real_name, name) == 0)
10324 				return pos;
10325 			continue;
10326 		}
10327 		if (strcmp(pos->name, name) == 0)
10328 			return pos;
10329 	}
10330 	return errno = ENOENT, NULL;
10331 }
10332 
10333 int
10334 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
10335 {
10336 	return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
10337 }
10338 
10339 static int validate_map_op(const struct bpf_map *map, size_t key_sz,
10340 			   size_t value_sz, bool check_value_sz)
10341 {
10342 	if (map->fd <= 0)
10343 		return -ENOENT;
10344 
10345 	if (map->def.key_size != key_sz) {
10346 		pr_warn("map '%s': unexpected key size %zu provided, expected %u\n",
10347 			map->name, key_sz, map->def.key_size);
10348 		return -EINVAL;
10349 	}
10350 
10351 	if (!check_value_sz)
10352 		return 0;
10353 
10354 	switch (map->def.type) {
10355 	case BPF_MAP_TYPE_PERCPU_ARRAY:
10356 	case BPF_MAP_TYPE_PERCPU_HASH:
10357 	case BPF_MAP_TYPE_LRU_PERCPU_HASH:
10358 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: {
10359 		int num_cpu = libbpf_num_possible_cpus();
10360 		size_t elem_sz = roundup(map->def.value_size, 8);
10361 
10362 		if (value_sz != num_cpu * elem_sz) {
10363 			pr_warn("map '%s': unexpected value size %zu provided for per-CPU map, expected %d * %zu = %zd\n",
10364 				map->name, value_sz, num_cpu, elem_sz, num_cpu * elem_sz);
10365 			return -EINVAL;
10366 		}
10367 		break;
10368 	}
10369 	default:
10370 		if (map->def.value_size != value_sz) {
10371 			pr_warn("map '%s': unexpected value size %zu provided, expected %u\n",
10372 				map->name, value_sz, map->def.value_size);
10373 			return -EINVAL;
10374 		}
10375 		break;
10376 	}
10377 	return 0;
10378 }
10379 
10380 int bpf_map__lookup_elem(const struct bpf_map *map,
10381 			 const void *key, size_t key_sz,
10382 			 void *value, size_t value_sz, __u64 flags)
10383 {
10384 	int err;
10385 
10386 	err = validate_map_op(map, key_sz, value_sz, true);
10387 	if (err)
10388 		return libbpf_err(err);
10389 
10390 	return bpf_map_lookup_elem_flags(map->fd, key, value, flags);
10391 }
10392 
10393 int bpf_map__update_elem(const struct bpf_map *map,
10394 			 const void *key, size_t key_sz,
10395 			 const void *value, size_t value_sz, __u64 flags)
10396 {
10397 	int err;
10398 
10399 	err = validate_map_op(map, key_sz, value_sz, true);
10400 	if (err)
10401 		return libbpf_err(err);
10402 
10403 	return bpf_map_update_elem(map->fd, key, value, flags);
10404 }
10405 
10406 int bpf_map__delete_elem(const struct bpf_map *map,
10407 			 const void *key, size_t key_sz, __u64 flags)
10408 {
10409 	int err;
10410 
10411 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
10412 	if (err)
10413 		return libbpf_err(err);
10414 
10415 	return bpf_map_delete_elem_flags(map->fd, key, flags);
10416 }
10417 
10418 int bpf_map__lookup_and_delete_elem(const struct bpf_map *map,
10419 				    const void *key, size_t key_sz,
10420 				    void *value, size_t value_sz, __u64 flags)
10421 {
10422 	int err;
10423 
10424 	err = validate_map_op(map, key_sz, value_sz, true);
10425 	if (err)
10426 		return libbpf_err(err);
10427 
10428 	return bpf_map_lookup_and_delete_elem_flags(map->fd, key, value, flags);
10429 }
10430 
10431 int bpf_map__get_next_key(const struct bpf_map *map,
10432 			  const void *cur_key, void *next_key, size_t key_sz)
10433 {
10434 	int err;
10435 
10436 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
10437 	if (err)
10438 		return libbpf_err(err);
10439 
10440 	return bpf_map_get_next_key(map->fd, cur_key, next_key);
10441 }
10442 
10443 long libbpf_get_error(const void *ptr)
10444 {
10445 	if (!IS_ERR_OR_NULL(ptr))
10446 		return 0;
10447 
10448 	if (IS_ERR(ptr))
10449 		errno = -PTR_ERR(ptr);
10450 
10451 	/* If ptr == NULL, then errno should be already set by the failing
10452 	 * API, because libbpf never returns NULL on success and it now always
10453 	 * sets errno on error. So no extra errno handling for ptr == NULL
10454 	 * case.
10455 	 */
10456 	return -errno;
10457 }
10458 
10459 /* Replace link's underlying BPF program with the new one */
10460 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
10461 {
10462 	int ret;
10463 
10464 	ret = bpf_link_update(bpf_link__fd(link), bpf_program__fd(prog), NULL);
10465 	return libbpf_err_errno(ret);
10466 }
10467 
10468 /* Release "ownership" of underlying BPF resource (typically, BPF program
10469  * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
10470  * link, when destructed through bpf_link__destroy() call won't attempt to
10471  * detach/unregisted that BPF resource. This is useful in situations where,
10472  * say, attached BPF program has to outlive userspace program that attached it
10473  * in the system. Depending on type of BPF program, though, there might be
10474  * additional steps (like pinning BPF program in BPF FS) necessary to ensure
10475  * exit of userspace program doesn't trigger automatic detachment and clean up
10476  * inside the kernel.
10477  */
10478 void bpf_link__disconnect(struct bpf_link *link)
10479 {
10480 	link->disconnected = true;
10481 }
10482 
10483 int bpf_link__destroy(struct bpf_link *link)
10484 {
10485 	int err = 0;
10486 
10487 	if (IS_ERR_OR_NULL(link))
10488 		return 0;
10489 
10490 	if (!link->disconnected && link->detach)
10491 		err = link->detach(link);
10492 	if (link->pin_path)
10493 		free(link->pin_path);
10494 	if (link->dealloc)
10495 		link->dealloc(link);
10496 	else
10497 		free(link);
10498 
10499 	return libbpf_err(err);
10500 }
10501 
10502 int bpf_link__fd(const struct bpf_link *link)
10503 {
10504 	return link->fd;
10505 }
10506 
10507 const char *bpf_link__pin_path(const struct bpf_link *link)
10508 {
10509 	return link->pin_path;
10510 }
10511 
10512 static int bpf_link__detach_fd(struct bpf_link *link)
10513 {
10514 	return libbpf_err_errno(close(link->fd));
10515 }
10516 
10517 struct bpf_link *bpf_link__open(const char *path)
10518 {
10519 	struct bpf_link *link;
10520 	int fd;
10521 
10522 	fd = bpf_obj_get(path);
10523 	if (fd < 0) {
10524 		fd = -errno;
10525 		pr_warn("failed to open link at %s: %d\n", path, fd);
10526 		return libbpf_err_ptr(fd);
10527 	}
10528 
10529 	link = calloc(1, sizeof(*link));
10530 	if (!link) {
10531 		close(fd);
10532 		return libbpf_err_ptr(-ENOMEM);
10533 	}
10534 	link->detach = &bpf_link__detach_fd;
10535 	link->fd = fd;
10536 
10537 	link->pin_path = strdup(path);
10538 	if (!link->pin_path) {
10539 		bpf_link__destroy(link);
10540 		return libbpf_err_ptr(-ENOMEM);
10541 	}
10542 
10543 	return link;
10544 }
10545 
10546 int bpf_link__detach(struct bpf_link *link)
10547 {
10548 	return bpf_link_detach(link->fd) ? -errno : 0;
10549 }
10550 
10551 int bpf_link__pin(struct bpf_link *link, const char *path)
10552 {
10553 	int err;
10554 
10555 	if (link->pin_path)
10556 		return libbpf_err(-EBUSY);
10557 	err = make_parent_dir(path);
10558 	if (err)
10559 		return libbpf_err(err);
10560 	err = check_path(path);
10561 	if (err)
10562 		return libbpf_err(err);
10563 
10564 	link->pin_path = strdup(path);
10565 	if (!link->pin_path)
10566 		return libbpf_err(-ENOMEM);
10567 
10568 	if (bpf_obj_pin(link->fd, link->pin_path)) {
10569 		err = -errno;
10570 		zfree(&link->pin_path);
10571 		return libbpf_err(err);
10572 	}
10573 
10574 	pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
10575 	return 0;
10576 }
10577 
10578 int bpf_link__unpin(struct bpf_link *link)
10579 {
10580 	int err;
10581 
10582 	if (!link->pin_path)
10583 		return libbpf_err(-EINVAL);
10584 
10585 	err = unlink(link->pin_path);
10586 	if (err != 0)
10587 		return -errno;
10588 
10589 	pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
10590 	zfree(&link->pin_path);
10591 	return 0;
10592 }
10593 
10594 struct bpf_link_perf {
10595 	struct bpf_link link;
10596 	int perf_event_fd;
10597 	/* legacy kprobe support: keep track of probe identifier and type */
10598 	char *legacy_probe_name;
10599 	bool legacy_is_kprobe;
10600 	bool legacy_is_retprobe;
10601 };
10602 
10603 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
10604 static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
10605 
10606 static int bpf_link_perf_detach(struct bpf_link *link)
10607 {
10608 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10609 	int err = 0;
10610 
10611 	if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
10612 		err = -errno;
10613 
10614 	if (perf_link->perf_event_fd != link->fd)
10615 		close(perf_link->perf_event_fd);
10616 	close(link->fd);
10617 
10618 	/* legacy uprobe/kprobe needs to be removed after perf event fd closure */
10619 	if (perf_link->legacy_probe_name) {
10620 		if (perf_link->legacy_is_kprobe) {
10621 			err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
10622 							 perf_link->legacy_is_retprobe);
10623 		} else {
10624 			err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
10625 							 perf_link->legacy_is_retprobe);
10626 		}
10627 	}
10628 
10629 	return err;
10630 }
10631 
10632 static void bpf_link_perf_dealloc(struct bpf_link *link)
10633 {
10634 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10635 
10636 	free(perf_link->legacy_probe_name);
10637 	free(perf_link);
10638 }
10639 
10640 struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
10641 						     const struct bpf_perf_event_opts *opts)
10642 {
10643 	char errmsg[STRERR_BUFSIZE];
10644 	struct bpf_link_perf *link;
10645 	int prog_fd, link_fd = -1, err;
10646 	bool force_ioctl_attach;
10647 
10648 	if (!OPTS_VALID(opts, bpf_perf_event_opts))
10649 		return libbpf_err_ptr(-EINVAL);
10650 
10651 	if (pfd < 0) {
10652 		pr_warn("prog '%s': invalid perf event FD %d\n",
10653 			prog->name, pfd);
10654 		return libbpf_err_ptr(-EINVAL);
10655 	}
10656 	prog_fd = bpf_program__fd(prog);
10657 	if (prog_fd < 0) {
10658 		pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
10659 			prog->name);
10660 		return libbpf_err_ptr(-EINVAL);
10661 	}
10662 
10663 	link = calloc(1, sizeof(*link));
10664 	if (!link)
10665 		return libbpf_err_ptr(-ENOMEM);
10666 	link->link.detach = &bpf_link_perf_detach;
10667 	link->link.dealloc = &bpf_link_perf_dealloc;
10668 	link->perf_event_fd = pfd;
10669 
10670 	force_ioctl_attach = OPTS_GET(opts, force_ioctl_attach, false);
10671 	if (kernel_supports(prog->obj, FEAT_PERF_LINK) && !force_ioctl_attach) {
10672 		DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
10673 			.perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
10674 
10675 		link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
10676 		if (link_fd < 0) {
10677 			err = -errno;
10678 			pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %d (%s)\n",
10679 				prog->name, pfd,
10680 				err, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10681 			goto err_out;
10682 		}
10683 		link->link.fd = link_fd;
10684 	} else {
10685 		if (OPTS_GET(opts, bpf_cookie, 0)) {
10686 			pr_warn("prog '%s': user context value is not supported\n", prog->name);
10687 			err = -EOPNOTSUPP;
10688 			goto err_out;
10689 		}
10690 
10691 		if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
10692 			err = -errno;
10693 			pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
10694 				prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10695 			if (err == -EPROTO)
10696 				pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
10697 					prog->name, pfd);
10698 			goto err_out;
10699 		}
10700 		link->link.fd = pfd;
10701 	}
10702 	if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
10703 		err = -errno;
10704 		pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
10705 			prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10706 		goto err_out;
10707 	}
10708 
10709 	return &link->link;
10710 err_out:
10711 	if (link_fd >= 0)
10712 		close(link_fd);
10713 	free(link);
10714 	return libbpf_err_ptr(err);
10715 }
10716 
10717 struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
10718 {
10719 	return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
10720 }
10721 
10722 /*
10723  * this function is expected to parse integer in the range of [0, 2^31-1] from
10724  * given file using scanf format string fmt. If actual parsed value is
10725  * negative, the result might be indistinguishable from error
10726  */
10727 static int parse_uint_from_file(const char *file, const char *fmt)
10728 {
10729 	char buf[STRERR_BUFSIZE];
10730 	int err, ret;
10731 	FILE *f;
10732 
10733 	f = fopen(file, "re");
10734 	if (!f) {
10735 		err = -errno;
10736 		pr_debug("failed to open '%s': %s\n", file,
10737 			 libbpf_strerror_r(err, buf, sizeof(buf)));
10738 		return err;
10739 	}
10740 	err = fscanf(f, fmt, &ret);
10741 	if (err != 1) {
10742 		err = err == EOF ? -EIO : -errno;
10743 		pr_debug("failed to parse '%s': %s\n", file,
10744 			libbpf_strerror_r(err, buf, sizeof(buf)));
10745 		fclose(f);
10746 		return err;
10747 	}
10748 	fclose(f);
10749 	return ret;
10750 }
10751 
10752 static int determine_kprobe_perf_type(void)
10753 {
10754 	const char *file = "/sys/bus/event_source/devices/kprobe/type";
10755 
10756 	return parse_uint_from_file(file, "%d\n");
10757 }
10758 
10759 static int determine_uprobe_perf_type(void)
10760 {
10761 	const char *file = "/sys/bus/event_source/devices/uprobe/type";
10762 
10763 	return parse_uint_from_file(file, "%d\n");
10764 }
10765 
10766 static int determine_kprobe_retprobe_bit(void)
10767 {
10768 	const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
10769 
10770 	return parse_uint_from_file(file, "config:%d\n");
10771 }
10772 
10773 static int determine_uprobe_retprobe_bit(void)
10774 {
10775 	const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
10776 
10777 	return parse_uint_from_file(file, "config:%d\n");
10778 }
10779 
10780 #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
10781 #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
10782 
10783 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
10784 				 uint64_t offset, int pid, size_t ref_ctr_off)
10785 {
10786 	const size_t attr_sz = sizeof(struct perf_event_attr);
10787 	struct perf_event_attr attr;
10788 	char errmsg[STRERR_BUFSIZE];
10789 	int type, pfd;
10790 
10791 	if ((__u64)ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
10792 		return -EINVAL;
10793 
10794 	memset(&attr, 0, attr_sz);
10795 
10796 	type = uprobe ? determine_uprobe_perf_type()
10797 		      : determine_kprobe_perf_type();
10798 	if (type < 0) {
10799 		pr_warn("failed to determine %s perf type: %s\n",
10800 			uprobe ? "uprobe" : "kprobe",
10801 			libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
10802 		return type;
10803 	}
10804 	if (retprobe) {
10805 		int bit = uprobe ? determine_uprobe_retprobe_bit()
10806 				 : determine_kprobe_retprobe_bit();
10807 
10808 		if (bit < 0) {
10809 			pr_warn("failed to determine %s retprobe bit: %s\n",
10810 				uprobe ? "uprobe" : "kprobe",
10811 				libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
10812 			return bit;
10813 		}
10814 		attr.config |= 1 << bit;
10815 	}
10816 	attr.size = attr_sz;
10817 	attr.type = type;
10818 	attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
10819 	attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
10820 	attr.config2 = offset;		 /* kprobe_addr or probe_offset */
10821 
10822 	/* pid filter is meaningful only for uprobes */
10823 	pfd = syscall(__NR_perf_event_open, &attr,
10824 		      pid < 0 ? -1 : pid /* pid */,
10825 		      pid == -1 ? 0 : -1 /* cpu */,
10826 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
10827 	return pfd >= 0 ? pfd : -errno;
10828 }
10829 
10830 static int append_to_file(const char *file, const char *fmt, ...)
10831 {
10832 	int fd, n, err = 0;
10833 	va_list ap;
10834 	char buf[1024];
10835 
10836 	va_start(ap, fmt);
10837 	n = vsnprintf(buf, sizeof(buf), fmt, ap);
10838 	va_end(ap);
10839 
10840 	if (n < 0 || n >= sizeof(buf))
10841 		return -EINVAL;
10842 
10843 	fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
10844 	if (fd < 0)
10845 		return -errno;
10846 
10847 	if (write(fd, buf, n) < 0)
10848 		err = -errno;
10849 
10850 	close(fd);
10851 	return err;
10852 }
10853 
10854 #define DEBUGFS "/sys/kernel/debug/tracing"
10855 #define TRACEFS "/sys/kernel/tracing"
10856 
10857 static bool use_debugfs(void)
10858 {
10859 	static int has_debugfs = -1;
10860 
10861 	if (has_debugfs < 0)
10862 		has_debugfs = faccessat(AT_FDCWD, DEBUGFS, F_OK, AT_EACCESS) == 0;
10863 
10864 	return has_debugfs == 1;
10865 }
10866 
10867 static const char *tracefs_path(void)
10868 {
10869 	return use_debugfs() ? DEBUGFS : TRACEFS;
10870 }
10871 
10872 static const char *tracefs_kprobe_events(void)
10873 {
10874 	return use_debugfs() ? DEBUGFS"/kprobe_events" : TRACEFS"/kprobe_events";
10875 }
10876 
10877 static const char *tracefs_uprobe_events(void)
10878 {
10879 	return use_debugfs() ? DEBUGFS"/uprobe_events" : TRACEFS"/uprobe_events";
10880 }
10881 
10882 static const char *tracefs_available_filter_functions(void)
10883 {
10884 	return use_debugfs() ? DEBUGFS"/available_filter_functions"
10885 			     : TRACEFS"/available_filter_functions";
10886 }
10887 
10888 static const char *tracefs_available_filter_functions_addrs(void)
10889 {
10890 	return use_debugfs() ? DEBUGFS"/available_filter_functions_addrs"
10891 			     : TRACEFS"/available_filter_functions_addrs";
10892 }
10893 
10894 static void gen_kprobe_legacy_event_name(char *buf, size_t buf_sz,
10895 					 const char *kfunc_name, size_t offset)
10896 {
10897 	static int index = 0;
10898 	int i;
10899 
10900 	snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx_%d", getpid(), kfunc_name, offset,
10901 		 __sync_fetch_and_add(&index, 1));
10902 
10903 	/* sanitize binary_path in the probe name */
10904 	for (i = 0; buf[i]; i++) {
10905 		if (!isalnum(buf[i]))
10906 			buf[i] = '_';
10907 	}
10908 }
10909 
10910 static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
10911 				   const char *kfunc_name, size_t offset)
10912 {
10913 	return append_to_file(tracefs_kprobe_events(), "%c:%s/%s %s+0x%zx",
10914 			      retprobe ? 'r' : 'p',
10915 			      retprobe ? "kretprobes" : "kprobes",
10916 			      probe_name, kfunc_name, offset);
10917 }
10918 
10919 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
10920 {
10921 	return append_to_file(tracefs_kprobe_events(), "-:%s/%s",
10922 			      retprobe ? "kretprobes" : "kprobes", probe_name);
10923 }
10924 
10925 static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
10926 {
10927 	char file[256];
10928 
10929 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
10930 		 tracefs_path(), retprobe ? "kretprobes" : "kprobes", probe_name);
10931 
10932 	return parse_uint_from_file(file, "%d\n");
10933 }
10934 
10935 static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
10936 					 const char *kfunc_name, size_t offset, int pid)
10937 {
10938 	const size_t attr_sz = sizeof(struct perf_event_attr);
10939 	struct perf_event_attr attr;
10940 	char errmsg[STRERR_BUFSIZE];
10941 	int type, pfd, err;
10942 
10943 	err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
10944 	if (err < 0) {
10945 		pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
10946 			kfunc_name, offset,
10947 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10948 		return err;
10949 	}
10950 	type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
10951 	if (type < 0) {
10952 		err = type;
10953 		pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
10954 			kfunc_name, offset,
10955 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10956 		goto err_clean_legacy;
10957 	}
10958 
10959 	memset(&attr, 0, attr_sz);
10960 	attr.size = attr_sz;
10961 	attr.config = type;
10962 	attr.type = PERF_TYPE_TRACEPOINT;
10963 
10964 	pfd = syscall(__NR_perf_event_open, &attr,
10965 		      pid < 0 ? -1 : pid, /* pid */
10966 		      pid == -1 ? 0 : -1, /* cpu */
10967 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
10968 	if (pfd < 0) {
10969 		err = -errno;
10970 		pr_warn("legacy kprobe perf_event_open() failed: %s\n",
10971 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10972 		goto err_clean_legacy;
10973 	}
10974 	return pfd;
10975 
10976 err_clean_legacy:
10977 	/* Clear the newly added legacy kprobe_event */
10978 	remove_kprobe_event_legacy(probe_name, retprobe);
10979 	return err;
10980 }
10981 
10982 static const char *arch_specific_syscall_pfx(void)
10983 {
10984 #if defined(__x86_64__)
10985 	return "x64";
10986 #elif defined(__i386__)
10987 	return "ia32";
10988 #elif defined(__s390x__)
10989 	return "s390x";
10990 #elif defined(__s390__)
10991 	return "s390";
10992 #elif defined(__arm__)
10993 	return "arm";
10994 #elif defined(__aarch64__)
10995 	return "arm64";
10996 #elif defined(__mips__)
10997 	return "mips";
10998 #elif defined(__riscv)
10999 	return "riscv";
11000 #elif defined(__powerpc__)
11001 	return "powerpc";
11002 #elif defined(__powerpc64__)
11003 	return "powerpc64";
11004 #else
11005 	return NULL;
11006 #endif
11007 }
11008 
11009 static int probe_kern_syscall_wrapper(void)
11010 {
11011 	char syscall_name[64];
11012 	const char *ksys_pfx;
11013 
11014 	ksys_pfx = arch_specific_syscall_pfx();
11015 	if (!ksys_pfx)
11016 		return 0;
11017 
11018 	snprintf(syscall_name, sizeof(syscall_name), "__%s_sys_bpf", ksys_pfx);
11019 
11020 	if (determine_kprobe_perf_type() >= 0) {
11021 		int pfd;
11022 
11023 		pfd = perf_event_open_probe(false, false, syscall_name, 0, getpid(), 0);
11024 		if (pfd >= 0)
11025 			close(pfd);
11026 
11027 		return pfd >= 0 ? 1 : 0;
11028 	} else { /* legacy mode */
11029 		char probe_name[128];
11030 
11031 		gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name), syscall_name, 0);
11032 		if (add_kprobe_event_legacy(probe_name, false, syscall_name, 0) < 0)
11033 			return 0;
11034 
11035 		(void)remove_kprobe_event_legacy(probe_name, false);
11036 		return 1;
11037 	}
11038 }
11039 
11040 struct bpf_link *
11041 bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
11042 				const char *func_name,
11043 				const struct bpf_kprobe_opts *opts)
11044 {
11045 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11046 	enum probe_attach_mode attach_mode;
11047 	char errmsg[STRERR_BUFSIZE];
11048 	char *legacy_probe = NULL;
11049 	struct bpf_link *link;
11050 	size_t offset;
11051 	bool retprobe, legacy;
11052 	int pfd, err;
11053 
11054 	if (!OPTS_VALID(opts, bpf_kprobe_opts))
11055 		return libbpf_err_ptr(-EINVAL);
11056 
11057 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
11058 	retprobe = OPTS_GET(opts, retprobe, false);
11059 	offset = OPTS_GET(opts, offset, 0);
11060 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11061 
11062 	legacy = determine_kprobe_perf_type() < 0;
11063 	switch (attach_mode) {
11064 	case PROBE_ATTACH_MODE_LEGACY:
11065 		legacy = true;
11066 		pe_opts.force_ioctl_attach = true;
11067 		break;
11068 	case PROBE_ATTACH_MODE_PERF:
11069 		if (legacy)
11070 			return libbpf_err_ptr(-ENOTSUP);
11071 		pe_opts.force_ioctl_attach = true;
11072 		break;
11073 	case PROBE_ATTACH_MODE_LINK:
11074 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
11075 			return libbpf_err_ptr(-ENOTSUP);
11076 		break;
11077 	case PROBE_ATTACH_MODE_DEFAULT:
11078 		break;
11079 	default:
11080 		return libbpf_err_ptr(-EINVAL);
11081 	}
11082 
11083 	if (!legacy) {
11084 		pfd = perf_event_open_probe(false /* uprobe */, retprobe,
11085 					    func_name, offset,
11086 					    -1 /* pid */, 0 /* ref_ctr_off */);
11087 	} else {
11088 		char probe_name[256];
11089 
11090 		gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name),
11091 					     func_name, offset);
11092 
11093 		legacy_probe = strdup(probe_name);
11094 		if (!legacy_probe)
11095 			return libbpf_err_ptr(-ENOMEM);
11096 
11097 		pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
11098 						    offset, -1 /* pid */);
11099 	}
11100 	if (pfd < 0) {
11101 		err = -errno;
11102 		pr_warn("prog '%s': failed to create %s '%s+0x%zx' perf event: %s\n",
11103 			prog->name, retprobe ? "kretprobe" : "kprobe",
11104 			func_name, offset,
11105 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11106 		goto err_out;
11107 	}
11108 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11109 	err = libbpf_get_error(link);
11110 	if (err) {
11111 		close(pfd);
11112 		pr_warn("prog '%s': failed to attach to %s '%s+0x%zx': %s\n",
11113 			prog->name, retprobe ? "kretprobe" : "kprobe",
11114 			func_name, offset,
11115 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11116 		goto err_clean_legacy;
11117 	}
11118 	if (legacy) {
11119 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
11120 
11121 		perf_link->legacy_probe_name = legacy_probe;
11122 		perf_link->legacy_is_kprobe = true;
11123 		perf_link->legacy_is_retprobe = retprobe;
11124 	}
11125 
11126 	return link;
11127 
11128 err_clean_legacy:
11129 	if (legacy)
11130 		remove_kprobe_event_legacy(legacy_probe, retprobe);
11131 err_out:
11132 	free(legacy_probe);
11133 	return libbpf_err_ptr(err);
11134 }
11135 
11136 struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
11137 					    bool retprobe,
11138 					    const char *func_name)
11139 {
11140 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
11141 		.retprobe = retprobe,
11142 	);
11143 
11144 	return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
11145 }
11146 
11147 struct bpf_link *bpf_program__attach_ksyscall(const struct bpf_program *prog,
11148 					      const char *syscall_name,
11149 					      const struct bpf_ksyscall_opts *opts)
11150 {
11151 	LIBBPF_OPTS(bpf_kprobe_opts, kprobe_opts);
11152 	char func_name[128];
11153 
11154 	if (!OPTS_VALID(opts, bpf_ksyscall_opts))
11155 		return libbpf_err_ptr(-EINVAL);
11156 
11157 	if (kernel_supports(prog->obj, FEAT_SYSCALL_WRAPPER)) {
11158 		/* arch_specific_syscall_pfx() should never return NULL here
11159 		 * because it is guarded by kernel_supports(). However, since
11160 		 * compiler does not know that we have an explicit conditional
11161 		 * as well.
11162 		 */
11163 		snprintf(func_name, sizeof(func_name), "__%s_sys_%s",
11164 			 arch_specific_syscall_pfx() ? : "", syscall_name);
11165 	} else {
11166 		snprintf(func_name, sizeof(func_name), "__se_sys_%s", syscall_name);
11167 	}
11168 
11169 	kprobe_opts.retprobe = OPTS_GET(opts, retprobe, false);
11170 	kprobe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11171 
11172 	return bpf_program__attach_kprobe_opts(prog, func_name, &kprobe_opts);
11173 }
11174 
11175 /* Adapted from perf/util/string.c */
11176 bool glob_match(const char *str, const char *pat)
11177 {
11178 	while (*str && *pat && *pat != '*') {
11179 		if (*pat == '?') {      /* Matches any single character */
11180 			str++;
11181 			pat++;
11182 			continue;
11183 		}
11184 		if (*str != *pat)
11185 			return false;
11186 		str++;
11187 		pat++;
11188 	}
11189 	/* Check wild card */
11190 	if (*pat == '*') {
11191 		while (*pat == '*')
11192 			pat++;
11193 		if (!*pat) /* Tail wild card matches all */
11194 			return true;
11195 		while (*str)
11196 			if (glob_match(str++, pat))
11197 				return true;
11198 	}
11199 	return !*str && !*pat;
11200 }
11201 
11202 struct kprobe_multi_resolve {
11203 	const char *pattern;
11204 	unsigned long *addrs;
11205 	size_t cap;
11206 	size_t cnt;
11207 };
11208 
11209 struct avail_kallsyms_data {
11210 	char **syms;
11211 	size_t cnt;
11212 	struct kprobe_multi_resolve *res;
11213 };
11214 
11215 static int avail_func_cmp(const void *a, const void *b)
11216 {
11217 	return strcmp(*(const char **)a, *(const char **)b);
11218 }
11219 
11220 static int avail_kallsyms_cb(unsigned long long sym_addr, char sym_type,
11221 			     const char *sym_name, void *ctx)
11222 {
11223 	struct avail_kallsyms_data *data = ctx;
11224 	struct kprobe_multi_resolve *res = data->res;
11225 	int err;
11226 
11227 	if (!bsearch(&sym_name, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp))
11228 		return 0;
11229 
11230 	err = libbpf_ensure_mem((void **)&res->addrs, &res->cap, sizeof(*res->addrs), res->cnt + 1);
11231 	if (err)
11232 		return err;
11233 
11234 	res->addrs[res->cnt++] = (unsigned long)sym_addr;
11235 	return 0;
11236 }
11237 
11238 static int libbpf_available_kallsyms_parse(struct kprobe_multi_resolve *res)
11239 {
11240 	const char *available_functions_file = tracefs_available_filter_functions();
11241 	struct avail_kallsyms_data data;
11242 	char sym_name[500];
11243 	FILE *f;
11244 	int err = 0, ret, i;
11245 	char **syms = NULL;
11246 	size_t cap = 0, cnt = 0;
11247 
11248 	f = fopen(available_functions_file, "re");
11249 	if (!f) {
11250 		err = -errno;
11251 		pr_warn("failed to open %s: %d\n", available_functions_file, err);
11252 		return err;
11253 	}
11254 
11255 	while (true) {
11256 		char *name;
11257 
11258 		ret = fscanf(f, "%499s%*[^\n]\n", sym_name);
11259 		if (ret == EOF && feof(f))
11260 			break;
11261 
11262 		if (ret != 1) {
11263 			pr_warn("failed to parse available_filter_functions entry: %d\n", ret);
11264 			err = -EINVAL;
11265 			goto cleanup;
11266 		}
11267 
11268 		if (!glob_match(sym_name, res->pattern))
11269 			continue;
11270 
11271 		err = libbpf_ensure_mem((void **)&syms, &cap, sizeof(*syms), cnt + 1);
11272 		if (err)
11273 			goto cleanup;
11274 
11275 		name = strdup(sym_name);
11276 		if (!name) {
11277 			err = -errno;
11278 			goto cleanup;
11279 		}
11280 
11281 		syms[cnt++] = name;
11282 	}
11283 
11284 	/* no entries found, bail out */
11285 	if (cnt == 0) {
11286 		err = -ENOENT;
11287 		goto cleanup;
11288 	}
11289 
11290 	/* sort available functions */
11291 	qsort(syms, cnt, sizeof(*syms), avail_func_cmp);
11292 
11293 	data.syms = syms;
11294 	data.res = res;
11295 	data.cnt = cnt;
11296 	libbpf_kallsyms_parse(avail_kallsyms_cb, &data);
11297 
11298 	if (res->cnt == 0)
11299 		err = -ENOENT;
11300 
11301 cleanup:
11302 	for (i = 0; i < cnt; i++)
11303 		free((char *)syms[i]);
11304 	free(syms);
11305 
11306 	fclose(f);
11307 	return err;
11308 }
11309 
11310 static bool has_available_filter_functions_addrs(void)
11311 {
11312 	return access(tracefs_available_filter_functions_addrs(), R_OK) != -1;
11313 }
11314 
11315 static int libbpf_available_kprobes_parse(struct kprobe_multi_resolve *res)
11316 {
11317 	const char *available_path = tracefs_available_filter_functions_addrs();
11318 	char sym_name[500];
11319 	FILE *f;
11320 	int ret, err = 0;
11321 	unsigned long long sym_addr;
11322 
11323 	f = fopen(available_path, "re");
11324 	if (!f) {
11325 		err = -errno;
11326 		pr_warn("failed to open %s: %d\n", available_path, err);
11327 		return err;
11328 	}
11329 
11330 	while (true) {
11331 		ret = fscanf(f, "%llx %499s%*[^\n]\n", &sym_addr, sym_name);
11332 		if (ret == EOF && feof(f))
11333 			break;
11334 
11335 		if (ret != 2) {
11336 			pr_warn("failed to parse available_filter_functions_addrs entry: %d\n",
11337 				ret);
11338 			err = -EINVAL;
11339 			goto cleanup;
11340 		}
11341 
11342 		if (!glob_match(sym_name, res->pattern))
11343 			continue;
11344 
11345 		err = libbpf_ensure_mem((void **)&res->addrs, &res->cap,
11346 					sizeof(*res->addrs), res->cnt + 1);
11347 		if (err)
11348 			goto cleanup;
11349 
11350 		res->addrs[res->cnt++] = (unsigned long)sym_addr;
11351 	}
11352 
11353 	if (res->cnt == 0)
11354 		err = -ENOENT;
11355 
11356 cleanup:
11357 	fclose(f);
11358 	return err;
11359 }
11360 
11361 struct bpf_link *
11362 bpf_program__attach_kprobe_multi_opts(const struct bpf_program *prog,
11363 				      const char *pattern,
11364 				      const struct bpf_kprobe_multi_opts *opts)
11365 {
11366 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
11367 	struct kprobe_multi_resolve res = {
11368 		.pattern = pattern,
11369 	};
11370 	struct bpf_link *link = NULL;
11371 	char errmsg[STRERR_BUFSIZE];
11372 	const unsigned long *addrs;
11373 	int err, link_fd, prog_fd;
11374 	const __u64 *cookies;
11375 	const char **syms;
11376 	bool retprobe;
11377 	size_t cnt;
11378 
11379 	if (!OPTS_VALID(opts, bpf_kprobe_multi_opts))
11380 		return libbpf_err_ptr(-EINVAL);
11381 
11382 	syms    = OPTS_GET(opts, syms, false);
11383 	addrs   = OPTS_GET(opts, addrs, false);
11384 	cnt     = OPTS_GET(opts, cnt, false);
11385 	cookies = OPTS_GET(opts, cookies, false);
11386 
11387 	if (!pattern && !addrs && !syms)
11388 		return libbpf_err_ptr(-EINVAL);
11389 	if (pattern && (addrs || syms || cookies || cnt))
11390 		return libbpf_err_ptr(-EINVAL);
11391 	if (!pattern && !cnt)
11392 		return libbpf_err_ptr(-EINVAL);
11393 	if (addrs && syms)
11394 		return libbpf_err_ptr(-EINVAL);
11395 
11396 	if (pattern) {
11397 		if (has_available_filter_functions_addrs())
11398 			err = libbpf_available_kprobes_parse(&res);
11399 		else
11400 			err = libbpf_available_kallsyms_parse(&res);
11401 		if (err)
11402 			goto error;
11403 		addrs = res.addrs;
11404 		cnt = res.cnt;
11405 	}
11406 
11407 	retprobe = OPTS_GET(opts, retprobe, false);
11408 
11409 	lopts.kprobe_multi.syms = syms;
11410 	lopts.kprobe_multi.addrs = addrs;
11411 	lopts.kprobe_multi.cookies = cookies;
11412 	lopts.kprobe_multi.cnt = cnt;
11413 	lopts.kprobe_multi.flags = retprobe ? BPF_F_KPROBE_MULTI_RETURN : 0;
11414 
11415 	link = calloc(1, sizeof(*link));
11416 	if (!link) {
11417 		err = -ENOMEM;
11418 		goto error;
11419 	}
11420 	link->detach = &bpf_link__detach_fd;
11421 
11422 	prog_fd = bpf_program__fd(prog);
11423 	link_fd = bpf_link_create(prog_fd, 0, BPF_TRACE_KPROBE_MULTI, &lopts);
11424 	if (link_fd < 0) {
11425 		err = -errno;
11426 		pr_warn("prog '%s': failed to attach: %s\n",
11427 			prog->name, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11428 		goto error;
11429 	}
11430 	link->fd = link_fd;
11431 	free(res.addrs);
11432 	return link;
11433 
11434 error:
11435 	free(link);
11436 	free(res.addrs);
11437 	return libbpf_err_ptr(err);
11438 }
11439 
11440 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11441 {
11442 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
11443 	unsigned long offset = 0;
11444 	const char *func_name;
11445 	char *func;
11446 	int n;
11447 
11448 	*link = NULL;
11449 
11450 	/* no auto-attach for SEC("kprobe") and SEC("kretprobe") */
11451 	if (strcmp(prog->sec_name, "kprobe") == 0 || strcmp(prog->sec_name, "kretprobe") == 0)
11452 		return 0;
11453 
11454 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
11455 	if (opts.retprobe)
11456 		func_name = prog->sec_name + sizeof("kretprobe/") - 1;
11457 	else
11458 		func_name = prog->sec_name + sizeof("kprobe/") - 1;
11459 
11460 	n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
11461 	if (n < 1) {
11462 		pr_warn("kprobe name is invalid: %s\n", func_name);
11463 		return -EINVAL;
11464 	}
11465 	if (opts.retprobe && offset != 0) {
11466 		free(func);
11467 		pr_warn("kretprobes do not support offset specification\n");
11468 		return -EINVAL;
11469 	}
11470 
11471 	opts.offset = offset;
11472 	*link = bpf_program__attach_kprobe_opts(prog, func, &opts);
11473 	free(func);
11474 	return libbpf_get_error(*link);
11475 }
11476 
11477 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11478 {
11479 	LIBBPF_OPTS(bpf_ksyscall_opts, opts);
11480 	const char *syscall_name;
11481 
11482 	*link = NULL;
11483 
11484 	/* no auto-attach for SEC("ksyscall") and SEC("kretsyscall") */
11485 	if (strcmp(prog->sec_name, "ksyscall") == 0 || strcmp(prog->sec_name, "kretsyscall") == 0)
11486 		return 0;
11487 
11488 	opts.retprobe = str_has_pfx(prog->sec_name, "kretsyscall/");
11489 	if (opts.retprobe)
11490 		syscall_name = prog->sec_name + sizeof("kretsyscall/") - 1;
11491 	else
11492 		syscall_name = prog->sec_name + sizeof("ksyscall/") - 1;
11493 
11494 	*link = bpf_program__attach_ksyscall(prog, syscall_name, &opts);
11495 	return *link ? 0 : -errno;
11496 }
11497 
11498 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11499 {
11500 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts);
11501 	const char *spec;
11502 	char *pattern;
11503 	int n;
11504 
11505 	*link = NULL;
11506 
11507 	/* no auto-attach for SEC("kprobe.multi") and SEC("kretprobe.multi") */
11508 	if (strcmp(prog->sec_name, "kprobe.multi") == 0 ||
11509 	    strcmp(prog->sec_name, "kretprobe.multi") == 0)
11510 		return 0;
11511 
11512 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe.multi/");
11513 	if (opts.retprobe)
11514 		spec = prog->sec_name + sizeof("kretprobe.multi/") - 1;
11515 	else
11516 		spec = prog->sec_name + sizeof("kprobe.multi/") - 1;
11517 
11518 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
11519 	if (n < 1) {
11520 		pr_warn("kprobe multi pattern is invalid: %s\n", pattern);
11521 		return -EINVAL;
11522 	}
11523 
11524 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
11525 	free(pattern);
11526 	return libbpf_get_error(*link);
11527 }
11528 
11529 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11530 {
11531 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
11532 	LIBBPF_OPTS(bpf_uprobe_multi_opts, opts);
11533 	int n, ret = -EINVAL;
11534 
11535 	*link = NULL;
11536 
11537 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
11538 		   &probe_type, &binary_path, &func_name);
11539 	switch (n) {
11540 	case 1:
11541 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
11542 		ret = 0;
11543 		break;
11544 	case 3:
11545 		opts.retprobe = str_has_pfx(probe_type, "uretprobe.multi");
11546 		*link = bpf_program__attach_uprobe_multi(prog, -1, binary_path, func_name, &opts);
11547 		ret = libbpf_get_error(*link);
11548 		break;
11549 	default:
11550 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
11551 			prog->sec_name);
11552 		break;
11553 	}
11554 	free(probe_type);
11555 	free(binary_path);
11556 	free(func_name);
11557 	return ret;
11558 }
11559 
11560 static void gen_uprobe_legacy_event_name(char *buf, size_t buf_sz,
11561 					 const char *binary_path, uint64_t offset)
11562 {
11563 	int i;
11564 
11565 	snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx", getpid(), binary_path, (size_t)offset);
11566 
11567 	/* sanitize binary_path in the probe name */
11568 	for (i = 0; buf[i]; i++) {
11569 		if (!isalnum(buf[i]))
11570 			buf[i] = '_';
11571 	}
11572 }
11573 
11574 static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
11575 					  const char *binary_path, size_t offset)
11576 {
11577 	return append_to_file(tracefs_uprobe_events(), "%c:%s/%s %s:0x%zx",
11578 			      retprobe ? 'r' : 'p',
11579 			      retprobe ? "uretprobes" : "uprobes",
11580 			      probe_name, binary_path, offset);
11581 }
11582 
11583 static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
11584 {
11585 	return append_to_file(tracefs_uprobe_events(), "-:%s/%s",
11586 			      retprobe ? "uretprobes" : "uprobes", probe_name);
11587 }
11588 
11589 static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
11590 {
11591 	char file[512];
11592 
11593 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11594 		 tracefs_path(), retprobe ? "uretprobes" : "uprobes", probe_name);
11595 
11596 	return parse_uint_from_file(file, "%d\n");
11597 }
11598 
11599 static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
11600 					 const char *binary_path, size_t offset, int pid)
11601 {
11602 	const size_t attr_sz = sizeof(struct perf_event_attr);
11603 	struct perf_event_attr attr;
11604 	int type, pfd, err;
11605 
11606 	err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
11607 	if (err < 0) {
11608 		pr_warn("failed to add legacy uprobe event for %s:0x%zx: %d\n",
11609 			binary_path, (size_t)offset, err);
11610 		return err;
11611 	}
11612 	type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
11613 	if (type < 0) {
11614 		err = type;
11615 		pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %d\n",
11616 			binary_path, offset, err);
11617 		goto err_clean_legacy;
11618 	}
11619 
11620 	memset(&attr, 0, attr_sz);
11621 	attr.size = attr_sz;
11622 	attr.config = type;
11623 	attr.type = PERF_TYPE_TRACEPOINT;
11624 
11625 	pfd = syscall(__NR_perf_event_open, &attr,
11626 		      pid < 0 ? -1 : pid, /* pid */
11627 		      pid == -1 ? 0 : -1, /* cpu */
11628 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
11629 	if (pfd < 0) {
11630 		err = -errno;
11631 		pr_warn("legacy uprobe perf_event_open() failed: %d\n", err);
11632 		goto err_clean_legacy;
11633 	}
11634 	return pfd;
11635 
11636 err_clean_legacy:
11637 	/* Clear the newly added legacy uprobe_event */
11638 	remove_uprobe_event_legacy(probe_name, retprobe);
11639 	return err;
11640 }
11641 
11642 /* Find offset of function name in archive specified by path. Currently
11643  * supported are .zip files that do not compress their contents, as used on
11644  * Android in the form of APKs, for example. "file_name" is the name of the ELF
11645  * file inside the archive. "func_name" matches symbol name or name@@LIB for
11646  * library functions.
11647  *
11648  * An overview of the APK format specifically provided here:
11649  * https://en.wikipedia.org/w/index.php?title=Apk_(file_format)&oldid=1139099120#Package_contents
11650  */
11651 static long elf_find_func_offset_from_archive(const char *archive_path, const char *file_name,
11652 					      const char *func_name)
11653 {
11654 	struct zip_archive *archive;
11655 	struct zip_entry entry;
11656 	long ret;
11657 #ifdef HAVE_LIBELF
11658 	Elf *elf;
11659 #elif defined HAVE_ELFIO
11660 	pelfio_t elf;
11661 #endif
11662 
11663 	archive = zip_archive_open(archive_path);
11664 	if (IS_ERR(archive)) {
11665 		ret = PTR_ERR(archive);
11666 		pr_warn("zip: failed to open %s: %ld\n", archive_path, ret);
11667 		return ret;
11668 	}
11669 
11670 	ret = zip_archive_find_entry(archive, file_name, &entry);
11671 	if (ret) {
11672 		pr_warn("zip: could not find archive member %s in %s: %ld\n", file_name,
11673 			archive_path, ret);
11674 		goto out;
11675 	}
11676 	pr_debug("zip: found entry for %s in %s at 0x%lx\n", file_name, archive_path,
11677 		 (unsigned long)entry.data_offset);
11678 
11679 	if (entry.compression) {
11680 		pr_warn("zip: entry %s of %s is compressed and cannot be handled\n", file_name,
11681 			archive_path);
11682 		ret = -LIBBPF_ERRNO__FORMAT;
11683 		goto out;
11684 	}
11685 #ifdef HAVE_LIBELF
11686 		elf = elf_memory((void *)entry.data, entry.data_length);
11687 #elif defined HAVE_ELFIO
11688 		char  memfd_path[PATH_MAX] = {0};
11689 		elf = elfio_new();
11690 		int fdm = syscall(__NR_memfd_create, "bpfelf", MFD_CLOEXEC);
11691 		ftruncate(fdm, entry.data_length);
11692 		write(fdm, (char *)entry.data, entry.data_length);
11693 		snprintf(memfd_path, PATH_MAX, "/proc/self/fd/%d", fdm);
11694 		elfio_load(elf, memfd_path);
11695 #endif
11696 	if (!elf) {
11697 		pr_warn("elf: could not read elf file %s from %s: %s\n", file_name, archive_path,
11698 			elf_errmsg(-1));
11699 		ret = -LIBBPF_ERRNO__LIBELF;
11700 		goto out;
11701 	}
11702 
11703 	ret = elf_find_func_offset(elf, file_name, func_name);
11704 	if (ret > 0) {
11705 		pr_debug("elf: symbol address match for %s of %s in %s: 0x%x + 0x%lx = 0x%lx\n",
11706 			 func_name, file_name, archive_path, entry.data_offset, ret,
11707 			 ret + entry.data_offset);
11708 		ret += entry.data_offset;
11709 	}
11710 #ifdef  HAVE_LIBELF
11711 	elf_end(elf);
11712 #elif HAVE_ELFIO
11713 	 elfio_delete(elf);
11714 #endif
11715 out:
11716 	zip_archive_close(archive);
11717 	return ret;
11718 }
11719 
11720 static const char *arch_specific_lib_paths(void)
11721 {
11722 	/*
11723 	 * Based on https://packages.debian.org/sid/libc6.
11724 	 *
11725 	 * Assume that the traced program is built for the same architecture
11726 	 * as libbpf, which should cover the vast majority of cases.
11727 	 */
11728 #if defined(__x86_64__)
11729 	return "/lib/x86_64-linux-gnu";
11730 #elif defined(__i386__)
11731 	return "/lib/i386-linux-gnu";
11732 #elif defined(__s390x__)
11733 	return "/lib/s390x-linux-gnu";
11734 #elif defined(__s390__)
11735 	return "/lib/s390-linux-gnu";
11736 #elif defined(__arm__) && defined(__SOFTFP__)
11737 	return "/lib/arm-linux-gnueabi";
11738 #elif defined(__arm__) && !defined(__SOFTFP__)
11739 	return "/lib/arm-linux-gnueabihf";
11740 #elif defined(__aarch64__)
11741 	return "/lib/aarch64-linux-gnu";
11742 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 64
11743 	return "/lib/mips64el-linux-gnuabi64";
11744 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 32
11745 	return "/lib/mipsel-linux-gnu";
11746 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
11747 	return "/lib/powerpc64le-linux-gnu";
11748 #elif defined(__sparc__) && defined(__arch64__)
11749 	return "/lib/sparc64-linux-gnu";
11750 #elif defined(__riscv) && __riscv_xlen == 64
11751 	return "/lib/riscv64-linux-gnu";
11752 #else
11753 	return NULL;
11754 #endif
11755 }
11756 
11757 /* Get full path to program/shared library. */
11758 static int resolve_full_path(const char *file, char *result, size_t result_sz)
11759 {
11760 	const char *search_paths[3] = {};
11761 	int i, perm;
11762 
11763 	if (str_has_sfx(file, ".so") || strstr(file, ".so.")) {
11764 		search_paths[0] = getenv("LD_LIBRARY_PATH");
11765 		search_paths[1] = "/usr/lib64:/usr/lib";
11766 		search_paths[2] = arch_specific_lib_paths();
11767 		perm = R_OK;
11768 	} else {
11769 		search_paths[0] = getenv("PATH");
11770 		search_paths[1] = "/usr/bin:/usr/sbin";
11771 		perm = R_OK | X_OK;
11772 	}
11773 
11774 	for (i = 0; i < ARRAY_SIZE(search_paths); i++) {
11775 		const char *s;
11776 
11777 		if (!search_paths[i])
11778 			continue;
11779 		for (s = search_paths[i]; s != NULL; s = strchr(s, ':')) {
11780 			char *next_path;
11781 			int seg_len;
11782 
11783 			if (s[0] == ':')
11784 				s++;
11785 			next_path = strchr(s, ':');
11786 			seg_len = next_path ? next_path - s : strlen(s);
11787 			if (!seg_len)
11788 				continue;
11789 			snprintf(result, result_sz, "%.*s/%s", seg_len, s, file);
11790 			/* ensure it has required permissions */
11791 			if (faccessat(AT_FDCWD, result, perm, AT_EACCESS) < 0)
11792 				continue;
11793 			pr_debug("resolved '%s' to '%s'\n", file, result);
11794 			return 0;
11795 		}
11796 	}
11797 	return -ENOENT;
11798 }
11799 
11800 struct bpf_link *
11801 bpf_program__attach_uprobe_multi(const struct bpf_program *prog,
11802 				 pid_t pid,
11803 				 const char *path,
11804 				 const char *func_pattern,
11805 				 const struct bpf_uprobe_multi_opts *opts)
11806 {
11807 	const unsigned long *ref_ctr_offsets = NULL, *offsets = NULL;
11808 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
11809 	unsigned long *resolved_offsets = NULL;
11810 	int err = 0, link_fd, prog_fd;
11811 	struct bpf_link *link = NULL;
11812 	char errmsg[STRERR_BUFSIZE];
11813 	char full_path[PATH_MAX];
11814 	const __u64 *cookies;
11815 	const char **syms;
11816 	size_t cnt;
11817 
11818 	if (!OPTS_VALID(opts, bpf_uprobe_multi_opts))
11819 		return libbpf_err_ptr(-EINVAL);
11820 
11821 	syms = OPTS_GET(opts, syms, NULL);
11822 	offsets = OPTS_GET(opts, offsets, NULL);
11823 	ref_ctr_offsets = OPTS_GET(opts, ref_ctr_offsets, NULL);
11824 	cookies = OPTS_GET(opts, cookies, NULL);
11825 	cnt = OPTS_GET(opts, cnt, 0);
11826 
11827 	/*
11828 	 * User can specify 2 mutually exclusive set of inputs:
11829 	 *
11830 	 * 1) use only path/func_pattern/pid arguments
11831 	 *
11832 	 * 2) use path/pid with allowed combinations of:
11833 	 *    syms/offsets/ref_ctr_offsets/cookies/cnt
11834 	 *
11835 	 *    - syms and offsets are mutually exclusive
11836 	 *    - ref_ctr_offsets and cookies are optional
11837 	 *
11838 	 * Any other usage results in error.
11839 	 */
11840 
11841 	if (!path)
11842 		return libbpf_err_ptr(-EINVAL);
11843 	if (!func_pattern && cnt == 0)
11844 		return libbpf_err_ptr(-EINVAL);
11845 
11846 	if (func_pattern) {
11847 		if (syms || offsets || ref_ctr_offsets || cookies || cnt)
11848 			return libbpf_err_ptr(-EINVAL);
11849 	} else {
11850 		if (!!syms == !!offsets)
11851 			return libbpf_err_ptr(-EINVAL);
11852 	}
11853 
11854 	if (func_pattern) {
11855 		if (!strchr(path, '/')) {
11856 			err = resolve_full_path(path, full_path, sizeof(full_path));
11857 			if (err) {
11858 				pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11859 					prog->name, path, err);
11860 				return libbpf_err_ptr(err);
11861 			}
11862 			path = full_path;
11863 		}
11864 
11865 		err = elf_resolve_pattern_offsets(path, func_pattern,
11866 						  &resolved_offsets, &cnt);
11867 		if (err < 0)
11868 			return libbpf_err_ptr(err);
11869 		offsets = resolved_offsets;
11870 	} else if (syms) {
11871 		err = elf_resolve_syms_offsets(path, cnt, syms, &resolved_offsets);
11872 		if (err < 0)
11873 			return libbpf_err_ptr(err);
11874 		offsets = resolved_offsets;
11875 	}
11876 
11877 	lopts.uprobe_multi.path = path;
11878 	lopts.uprobe_multi.offsets = offsets;
11879 	lopts.uprobe_multi.ref_ctr_offsets = ref_ctr_offsets;
11880 	lopts.uprobe_multi.cookies = cookies;
11881 	lopts.uprobe_multi.cnt = cnt;
11882 	lopts.uprobe_multi.flags = OPTS_GET(opts, retprobe, false) ? BPF_F_UPROBE_MULTI_RETURN : 0;
11883 
11884 	if (pid == 0)
11885 		pid = getpid();
11886 	if (pid > 0)
11887 		lopts.uprobe_multi.pid = pid;
11888 
11889 	link = calloc(1, sizeof(*link));
11890 	if (!link) {
11891 		err = -ENOMEM;
11892 		goto error;
11893 	}
11894 	link->detach = &bpf_link__detach_fd;
11895 
11896 	prog_fd = bpf_program__fd(prog);
11897 	link_fd = bpf_link_create(prog_fd, 0, BPF_TRACE_UPROBE_MULTI, &lopts);
11898 	if (link_fd < 0) {
11899 		err = -errno;
11900 		pr_warn("prog '%s': failed to attach multi-uprobe: %s\n",
11901 			prog->name, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11902 		goto error;
11903 	}
11904 	link->fd = link_fd;
11905 	free(resolved_offsets);
11906 	return link;
11907 
11908 error:
11909 	free(resolved_offsets);
11910 	free(link);
11911 	return libbpf_err_ptr(err);
11912 }
11913 
11914 LIBBPF_API struct bpf_link *
11915 bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
11916 				const char *binary_path, size_t func_offset,
11917 				const struct bpf_uprobe_opts *opts)
11918 {
11919 	const char *archive_path = NULL, *archive_sep = NULL;
11920 	char errmsg[STRERR_BUFSIZE], *legacy_probe = NULL;
11921 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11922 	enum probe_attach_mode attach_mode;
11923 	char full_path[PATH_MAX];
11924 	struct bpf_link *link;
11925 	size_t ref_ctr_off;
11926 	int pfd, err;
11927 	bool retprobe, legacy;
11928 	const char *func_name;
11929 
11930 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
11931 		return libbpf_err_ptr(-EINVAL);
11932 
11933 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
11934 	retprobe = OPTS_GET(opts, retprobe, false);
11935 	ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
11936 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11937 
11938 	if (!binary_path)
11939 		return libbpf_err_ptr(-EINVAL);
11940 
11941 	/* Check if "binary_path" refers to an archive. */
11942 	archive_sep = strstr(binary_path, "!/");
11943 	if (archive_sep) {
11944 		full_path[0] = '\0';
11945 		libbpf_strlcpy(full_path, binary_path,
11946 			       min(sizeof(full_path), (size_t)(archive_sep - binary_path + 1)));
11947 		archive_path = full_path;
11948 		binary_path = archive_sep + 2;
11949 	} else if (!strchr(binary_path, '/')) {
11950 		err = resolve_full_path(binary_path, full_path, sizeof(full_path));
11951 		if (err) {
11952 			pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11953 				prog->name, binary_path, err);
11954 			return libbpf_err_ptr(err);
11955 		}
11956 		binary_path = full_path;
11957 	}
11958 	func_name = OPTS_GET(opts, func_name, NULL);
11959 	if (func_name) {
11960 		long sym_off;
11961 
11962 		if (archive_path) {
11963 			sym_off = elf_find_func_offset_from_archive(archive_path, binary_path,
11964 								    func_name);
11965 			binary_path = archive_path;
11966 		} else {
11967 			sym_off = elf_find_func_offset_from_file(binary_path, func_name);
11968 		}
11969 		if (sym_off < 0)
11970 			return libbpf_err_ptr(sym_off);
11971 		func_offset += sym_off;
11972 	}
11973 
11974 	legacy = determine_uprobe_perf_type() < 0;
11975 	switch (attach_mode) {
11976 	case PROBE_ATTACH_MODE_LEGACY:
11977 		legacy = true;
11978 		pe_opts.force_ioctl_attach = true;
11979 		break;
11980 	case PROBE_ATTACH_MODE_PERF:
11981 		if (legacy)
11982 			return libbpf_err_ptr(-ENOTSUP);
11983 		pe_opts.force_ioctl_attach = true;
11984 		break;
11985 	case PROBE_ATTACH_MODE_LINK:
11986 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
11987 			return libbpf_err_ptr(-ENOTSUP);
11988 		break;
11989 	case PROBE_ATTACH_MODE_DEFAULT:
11990 		break;
11991 	default:
11992 		return libbpf_err_ptr(-EINVAL);
11993 	}
11994 
11995 	if (!legacy) {
11996 		pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
11997 					    func_offset, pid, ref_ctr_off);
11998 	} else {
11999 		char probe_name[PATH_MAX + 64];
12000 
12001 		if (ref_ctr_off)
12002 			return libbpf_err_ptr(-EINVAL);
12003 
12004 		gen_uprobe_legacy_event_name(probe_name, sizeof(probe_name),
12005 					     binary_path, func_offset);
12006 
12007 		legacy_probe = strdup(probe_name);
12008 		if (!legacy_probe)
12009 			return libbpf_err_ptr(-ENOMEM);
12010 
12011 		pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
12012 						    binary_path, func_offset, pid);
12013 	}
12014 	if (pfd < 0) {
12015 		err = -errno;
12016 		pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
12017 			prog->name, retprobe ? "uretprobe" : "uprobe",
12018 			binary_path, func_offset,
12019 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
12020 		goto err_out;
12021 	}
12022 
12023 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
12024 	err = libbpf_get_error(link);
12025 	if (err) {
12026 		close(pfd);
12027 		pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
12028 			prog->name, retprobe ? "uretprobe" : "uprobe",
12029 			binary_path, func_offset,
12030 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
12031 		goto err_clean_legacy;
12032 	}
12033 	if (legacy) {
12034 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
12035 
12036 		perf_link->legacy_probe_name = legacy_probe;
12037 		perf_link->legacy_is_kprobe = false;
12038 		perf_link->legacy_is_retprobe = retprobe;
12039 	}
12040 	return link;
12041 
12042 err_clean_legacy:
12043 	if (legacy)
12044 		remove_uprobe_event_legacy(legacy_probe, retprobe);
12045 err_out:
12046 	free(legacy_probe);
12047 	return libbpf_err_ptr(err);
12048 }
12049 
12050 /* Format of u[ret]probe section definition supporting auto-attach:
12051  * u[ret]probe/binary:function[+offset]
12052  *
12053  * binary can be an absolute/relative path or a filename; the latter is resolved to a
12054  * full binary path via bpf_program__attach_uprobe_opts.
12055  *
12056  * Specifying uprobe+ ensures we carry out strict matching; either "uprobe" must be
12057  * specified (and auto-attach is not possible) or the above format is specified for
12058  * auto-attach.
12059  */
12060 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12061 {
12062 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts);
12063 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL, *func_off;
12064 	int n, c, ret = -EINVAL;
12065 	long offset = 0;
12066 
12067 	*link = NULL;
12068 
12069 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
12070 		   &probe_type, &binary_path, &func_name);
12071 	switch (n) {
12072 	case 1:
12073 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
12074 		ret = 0;
12075 		break;
12076 	case 2:
12077 		pr_warn("prog '%s': section '%s' missing ':function[+offset]' specification\n",
12078 			prog->name, prog->sec_name);
12079 		break;
12080 	case 3:
12081 		/* check if user specifies `+offset`, if yes, this should be
12082 		 * the last part of the string, make sure sscanf read to EOL
12083 		 */
12084 		func_off = strrchr(func_name, '+');
12085 		if (func_off) {
12086 			n = sscanf(func_off, "+%li%n", &offset, &c);
12087 			if (n == 1 && *(func_off + c) == '\0')
12088 				func_off[0] = '\0';
12089 			else
12090 				offset = 0;
12091 		}
12092 		opts.retprobe = strcmp(probe_type, "uretprobe") == 0 ||
12093 				strcmp(probe_type, "uretprobe.s") == 0;
12094 		if (opts.retprobe && offset != 0) {
12095 			pr_warn("prog '%s': uretprobes do not support offset specification\n",
12096 				prog->name);
12097 			break;
12098 		}
12099 		opts.func_name = func_name;
12100 		*link = bpf_program__attach_uprobe_opts(prog, -1, binary_path, offset, &opts);
12101 		ret = libbpf_get_error(*link);
12102 		break;
12103 	default:
12104 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
12105 			prog->sec_name);
12106 		break;
12107 	}
12108 	free(probe_type);
12109 	free(binary_path);
12110 	free(func_name);
12111 
12112 	return ret;
12113 }
12114 
12115 struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
12116 					    bool retprobe, pid_t pid,
12117 					    const char *binary_path,
12118 					    size_t func_offset)
12119 {
12120 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
12121 
12122 	return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
12123 }
12124 
12125 #ifdef  HAVE_LIBELF
12126 struct bpf_link *bpf_program__attach_usdt(const struct bpf_program *prog,
12127 					  pid_t pid, const char *binary_path,
12128 					  const char *usdt_provider, const char *usdt_name,
12129 					  const struct bpf_usdt_opts *opts)
12130 {
12131 	char resolved_path[512];
12132 	struct bpf_object *obj = prog->obj;
12133 	struct bpf_link *link;
12134 	__u64 usdt_cookie;
12135 	int err;
12136 
12137 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
12138 		return libbpf_err_ptr(-EINVAL);
12139 
12140 	if (bpf_program__fd(prog) < 0) {
12141 		pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
12142 			prog->name);
12143 		return libbpf_err_ptr(-EINVAL);
12144 	}
12145 
12146 	if (!binary_path)
12147 		return libbpf_err_ptr(-EINVAL);
12148 
12149 	if (!strchr(binary_path, '/')) {
12150 		err = resolve_full_path(binary_path, resolved_path, sizeof(resolved_path));
12151 		if (err) {
12152 			pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
12153 				prog->name, binary_path, err);
12154 			return libbpf_err_ptr(err);
12155 		}
12156 		binary_path = resolved_path;
12157 	}
12158 
12159 	/* USDT manager is instantiated lazily on first USDT attach. It will
12160 	 * be destroyed together with BPF object in bpf_object__close().
12161 	 */
12162 	if (IS_ERR(obj->usdt_man))
12163 		return libbpf_ptr(obj->usdt_man);
12164 	if (!obj->usdt_man) {
12165 		obj->usdt_man = usdt_manager_new(obj);
12166 		if (IS_ERR(obj->usdt_man))
12167 			return libbpf_ptr(obj->usdt_man);
12168 	}
12169 
12170 	usdt_cookie = OPTS_GET(opts, usdt_cookie, 0);
12171 	link = usdt_manager_attach_usdt(obj->usdt_man, prog, pid, binary_path,
12172 					usdt_provider, usdt_name, usdt_cookie);
12173 	err = libbpf_get_error(link);
12174 	if (err)
12175 		return libbpf_err_ptr(err);
12176 	return link;
12177 }
12178 #endif  //HAVE_LIBELF
12179 
12180 #ifdef  HAVE_LIBELF
12181 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12182 {
12183 	char *path = NULL, *provider = NULL, *name = NULL;
12184 	const char *sec_name;
12185 	int n, err;
12186 
12187 	sec_name = bpf_program__section_name(prog);
12188 	if (strcmp(sec_name, "usdt") == 0) {
12189 		/* no auto-attach for just SEC("usdt") */
12190 		*link = NULL;
12191 		return 0;
12192 	}
12193 
12194 	n = sscanf(sec_name, "usdt/%m[^:]:%m[^:]:%m[^:]", &path, &provider, &name);
12195 	if (n != 3) {
12196 		pr_warn("invalid section '%s', expected SEC(\"usdt/<path>:<provider>:<name>\")\n",
12197 			sec_name);
12198 		err = -EINVAL;
12199 	} else {
12200 		*link = bpf_program__attach_usdt(prog, -1 /* any process */, path,
12201 						 provider, name, NULL);
12202 		err = libbpf_get_error(*link);
12203 	}
12204 	free(path);
12205 	free(provider);
12206 	free(name);
12207 	return err;
12208 }
12209 #endif  //HAVE_LIBELF
12210 
12211 static int determine_tracepoint_id(const char *tp_category,
12212 				   const char *tp_name)
12213 {
12214 	char file[PATH_MAX];
12215 	int ret;
12216 
12217 	ret = snprintf(file, sizeof(file), "%s/events/%s/%s/id",
12218 		       tracefs_path(), tp_category, tp_name);
12219 	if (ret < 0)
12220 		return -errno;
12221 	if (ret >= sizeof(file)) {
12222 		pr_debug("tracepoint %s/%s path is too long\n",
12223 			 tp_category, tp_name);
12224 		return -E2BIG;
12225 	}
12226 	return parse_uint_from_file(file, "%d\n");
12227 }
12228 
12229 static int perf_event_open_tracepoint(const char *tp_category,
12230 				      const char *tp_name)
12231 {
12232 	const size_t attr_sz = sizeof(struct perf_event_attr);
12233 	struct perf_event_attr attr;
12234 	char errmsg[STRERR_BUFSIZE];
12235 	int tp_id, pfd, err;
12236 
12237 	tp_id = determine_tracepoint_id(tp_category, tp_name);
12238 	if (tp_id < 0) {
12239 		pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
12240 			tp_category, tp_name,
12241 			libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
12242 		return tp_id;
12243 	}
12244 
12245 	memset(&attr, 0, attr_sz);
12246 	attr.type = PERF_TYPE_TRACEPOINT;
12247 	attr.size = attr_sz;
12248 	attr.config = tp_id;
12249 
12250 	pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
12251 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
12252 	if (pfd < 0) {
12253 		err = -errno;
12254 		pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
12255 			tp_category, tp_name,
12256 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
12257 		return err;
12258 	}
12259 	return pfd;
12260 }
12261 
12262 struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
12263 						     const char *tp_category,
12264 						     const char *tp_name,
12265 						     const struct bpf_tracepoint_opts *opts)
12266 {
12267 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
12268 	char errmsg[STRERR_BUFSIZE];
12269 	struct bpf_link *link;
12270 	int pfd, err;
12271 
12272 	if (!OPTS_VALID(opts, bpf_tracepoint_opts))
12273 		return libbpf_err_ptr(-EINVAL);
12274 
12275 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
12276 
12277 	pfd = perf_event_open_tracepoint(tp_category, tp_name);
12278 	if (pfd < 0) {
12279 		pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
12280 			prog->name, tp_category, tp_name,
12281 			libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
12282 		return libbpf_err_ptr(pfd);
12283 	}
12284 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
12285 	err = libbpf_get_error(link);
12286 	if (err) {
12287 		close(pfd);
12288 		pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
12289 			prog->name, tp_category, tp_name,
12290 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
12291 		return libbpf_err_ptr(err);
12292 	}
12293 	return link;
12294 }
12295 
12296 struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
12297 						const char *tp_category,
12298 						const char *tp_name)
12299 {
12300 	return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
12301 }
12302 
12303 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12304 {
12305 	char *sec_name, *tp_cat, *tp_name;
12306 
12307 	*link = NULL;
12308 
12309 	/* no auto-attach for SEC("tp") or SEC("tracepoint") */
12310 	if (strcmp(prog->sec_name, "tp") == 0 || strcmp(prog->sec_name, "tracepoint") == 0)
12311 		return 0;
12312 
12313 	sec_name = strdup(prog->sec_name);
12314 	if (!sec_name)
12315 		return -ENOMEM;
12316 
12317 	/* extract "tp/<category>/<name>" or "tracepoint/<category>/<name>" */
12318 	if (str_has_pfx(prog->sec_name, "tp/"))
12319 		tp_cat = sec_name + sizeof("tp/") - 1;
12320 	else
12321 		tp_cat = sec_name + sizeof("tracepoint/") - 1;
12322 	tp_name = strchr(tp_cat, '/');
12323 	if (!tp_name) {
12324 		free(sec_name);
12325 		return -EINVAL;
12326 	}
12327 	*tp_name = '\0';
12328 	tp_name++;
12329 
12330 	*link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
12331 	free(sec_name);
12332 	return libbpf_get_error(*link);
12333 }
12334 
12335 struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
12336 						    const char *tp_name)
12337 {
12338 	char errmsg[STRERR_BUFSIZE];
12339 	struct bpf_link *link;
12340 	int prog_fd, pfd;
12341 
12342 	prog_fd = bpf_program__fd(prog);
12343 	if (prog_fd < 0) {
12344 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12345 		return libbpf_err_ptr(-EINVAL);
12346 	}
12347 
12348 	link = calloc(1, sizeof(*link));
12349 	if (!link)
12350 		return libbpf_err_ptr(-ENOMEM);
12351 	link->detach = &bpf_link__detach_fd;
12352 
12353 	pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
12354 	if (pfd < 0) {
12355 		pfd = -errno;
12356 		free(link);
12357 		pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
12358 			prog->name, tp_name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
12359 		return libbpf_err_ptr(pfd);
12360 	}
12361 	link->fd = pfd;
12362 	return link;
12363 }
12364 
12365 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12366 {
12367 	static const char *const prefixes[] = {
12368 		"raw_tp",
12369 		"raw_tracepoint",
12370 		"raw_tp.w",
12371 		"raw_tracepoint.w",
12372 	};
12373 	size_t i;
12374 	const char *tp_name = NULL;
12375 
12376 	*link = NULL;
12377 
12378 	for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
12379 		size_t pfx_len;
12380 
12381 		if (!str_has_pfx(prog->sec_name, prefixes[i]))
12382 			continue;
12383 
12384 		pfx_len = strlen(prefixes[i]);
12385 		/* no auto-attach case of, e.g., SEC("raw_tp") */
12386 		if (prog->sec_name[pfx_len] == '\0')
12387 			return 0;
12388 
12389 		if (prog->sec_name[pfx_len] != '/')
12390 			continue;
12391 
12392 		tp_name = prog->sec_name + pfx_len + 1;
12393 		break;
12394 	}
12395 
12396 	if (!tp_name) {
12397 		pr_warn("prog '%s': invalid section name '%s'\n",
12398 			prog->name, prog->sec_name);
12399 		return -EINVAL;
12400 	}
12401 
12402 	*link = bpf_program__attach_raw_tracepoint(prog, tp_name);
12403 	return libbpf_get_error(*link);
12404 }
12405 
12406 /* Common logic for all BPF program types that attach to a btf_id */
12407 static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog,
12408 						   const struct bpf_trace_opts *opts)
12409 {
12410 	LIBBPF_OPTS(bpf_link_create_opts, link_opts);
12411 	char errmsg[STRERR_BUFSIZE];
12412 	struct bpf_link *link;
12413 	int prog_fd, pfd;
12414 
12415 	if (!OPTS_VALID(opts, bpf_trace_opts))
12416 		return libbpf_err_ptr(-EINVAL);
12417 
12418 	prog_fd = bpf_program__fd(prog);
12419 	if (prog_fd < 0) {
12420 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12421 		return libbpf_err_ptr(-EINVAL);
12422 	}
12423 
12424 	link = calloc(1, sizeof(*link));
12425 	if (!link)
12426 		return libbpf_err_ptr(-ENOMEM);
12427 	link->detach = &bpf_link__detach_fd;
12428 
12429 	/* libbpf is smart enough to redirect to BPF_RAW_TRACEPOINT_OPEN on old kernels */
12430 	link_opts.tracing.cookie = OPTS_GET(opts, cookie, 0);
12431 	pfd = bpf_link_create(prog_fd, 0, bpf_program__expected_attach_type(prog), &link_opts);
12432 	if (pfd < 0) {
12433 		pfd = -errno;
12434 		free(link);
12435 		pr_warn("prog '%s': failed to attach: %s\n",
12436 			prog->name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
12437 		return libbpf_err_ptr(pfd);
12438 	}
12439 	link->fd = pfd;
12440 	return link;
12441 }
12442 
12443 struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
12444 {
12445 	return bpf_program__attach_btf_id(prog, NULL);
12446 }
12447 
12448 struct bpf_link *bpf_program__attach_trace_opts(const struct bpf_program *prog,
12449 						const struct bpf_trace_opts *opts)
12450 {
12451 	return bpf_program__attach_btf_id(prog, opts);
12452 }
12453 
12454 struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
12455 {
12456 	return bpf_program__attach_btf_id(prog, NULL);
12457 }
12458 
12459 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12460 {
12461 	*link = bpf_program__attach_trace(prog);
12462 	return libbpf_get_error(*link);
12463 }
12464 
12465 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12466 {
12467 	*link = bpf_program__attach_lsm(prog);
12468 	return libbpf_get_error(*link);
12469 }
12470 
12471 static struct bpf_link *
12472 bpf_program_attach_fd(const struct bpf_program *prog,
12473 		      int target_fd, const char *target_name,
12474 		      const struct bpf_link_create_opts *opts)
12475 {
12476 	enum bpf_attach_type attach_type;
12477 	char errmsg[STRERR_BUFSIZE];
12478 	struct bpf_link *link;
12479 	int prog_fd, link_fd;
12480 
12481 	prog_fd = bpf_program__fd(prog);
12482 	if (prog_fd < 0) {
12483 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12484 		return libbpf_err_ptr(-EINVAL);
12485 	}
12486 
12487 	link = calloc(1, sizeof(*link));
12488 	if (!link)
12489 		return libbpf_err_ptr(-ENOMEM);
12490 	link->detach = &bpf_link__detach_fd;
12491 
12492 	attach_type = bpf_program__expected_attach_type(prog);
12493 	link_fd = bpf_link_create(prog_fd, target_fd, attach_type, opts);
12494 	if (link_fd < 0) {
12495 		link_fd = -errno;
12496 		free(link);
12497 		pr_warn("prog '%s': failed to attach to %s: %s\n",
12498 			prog->name, target_name,
12499 			libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
12500 		return libbpf_err_ptr(link_fd);
12501 	}
12502 	link->fd = link_fd;
12503 	return link;
12504 }
12505 
12506 struct bpf_link *
12507 bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
12508 {
12509 	return bpf_program_attach_fd(prog, cgroup_fd, "cgroup", NULL);
12510 }
12511 
12512 struct bpf_link *
12513 bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
12514 {
12515 	return bpf_program_attach_fd(prog, netns_fd, "netns", NULL);
12516 }
12517 
12518 struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
12519 {
12520 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
12521 	return bpf_program_attach_fd(prog, ifindex, "xdp", NULL);
12522 }
12523 
12524 struct bpf_link *
12525 bpf_program__attach_tcx(const struct bpf_program *prog, int ifindex,
12526 			const struct bpf_tcx_opts *opts)
12527 {
12528 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12529 	__u32 relative_id;
12530 	int relative_fd;
12531 
12532 	if (!OPTS_VALID(opts, bpf_tcx_opts))
12533 		return libbpf_err_ptr(-EINVAL);
12534 
12535 	relative_id = OPTS_GET(opts, relative_id, 0);
12536 	relative_fd = OPTS_GET(opts, relative_fd, 0);
12537 
12538 	/* validate we don't have unexpected combinations of non-zero fields */
12539 	if (!ifindex) {
12540 		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
12541 			prog->name);
12542 		return libbpf_err_ptr(-EINVAL);
12543 	}
12544 	if (relative_fd && relative_id) {
12545 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
12546 			prog->name);
12547 		return libbpf_err_ptr(-EINVAL);
12548 	}
12549 
12550 	link_create_opts.tcx.expected_revision = OPTS_GET(opts, expected_revision, 0);
12551 	link_create_opts.tcx.relative_fd = relative_fd;
12552 	link_create_opts.tcx.relative_id = relative_id;
12553 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
12554 
12555 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
12556 	return bpf_program_attach_fd(prog, ifindex, "tcx", &link_create_opts);
12557 }
12558 
12559 struct bpf_link *
12560 bpf_program__attach_netkit(const struct bpf_program *prog, int ifindex,
12561 			   const struct bpf_netkit_opts *opts)
12562 {
12563 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12564 	__u32 relative_id;
12565 	int relative_fd;
12566 
12567 	if (!OPTS_VALID(opts, bpf_netkit_opts))
12568 		return libbpf_err_ptr(-EINVAL);
12569 
12570 	relative_id = OPTS_GET(opts, relative_id, 0);
12571 	relative_fd = OPTS_GET(opts, relative_fd, 0);
12572 
12573 	/* validate we don't have unexpected combinations of non-zero fields */
12574 	if (!ifindex) {
12575 		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
12576 			prog->name);
12577 		return libbpf_err_ptr(-EINVAL);
12578 	}
12579 	if (relative_fd && relative_id) {
12580 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
12581 			prog->name);
12582 		return libbpf_err_ptr(-EINVAL);
12583 	}
12584 
12585 	link_create_opts.netkit.expected_revision = OPTS_GET(opts, expected_revision, 0);
12586 	link_create_opts.netkit.relative_fd = relative_fd;
12587 	link_create_opts.netkit.relative_id = relative_id;
12588 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
12589 
12590 	return bpf_program_attach_fd(prog, ifindex, "netkit", &link_create_opts);
12591 }
12592 
12593 struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
12594 					      int target_fd,
12595 					      const char *attach_func_name)
12596 {
12597 	int btf_id;
12598 
12599 	if (!!target_fd != !!attach_func_name) {
12600 		pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
12601 			prog->name);
12602 		return libbpf_err_ptr(-EINVAL);
12603 	}
12604 
12605 	if (prog->type != BPF_PROG_TYPE_EXT) {
12606 		pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace",
12607 			prog->name);
12608 		return libbpf_err_ptr(-EINVAL);
12609 	}
12610 
12611 	if (target_fd) {
12612 		LIBBPF_OPTS(bpf_link_create_opts, target_opts);
12613 
12614 		btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd);
12615 		if (btf_id < 0)
12616 			return libbpf_err_ptr(btf_id);
12617 
12618 		target_opts.target_btf_id = btf_id;
12619 
12620 		return bpf_program_attach_fd(prog, target_fd, "freplace",
12621 					     &target_opts);
12622 	} else {
12623 		/* no target, so use raw_tracepoint_open for compatibility
12624 		 * with old kernels
12625 		 */
12626 		return bpf_program__attach_trace(prog);
12627 	}
12628 }
12629 
12630 struct bpf_link *
12631 bpf_program__attach_iter(const struct bpf_program *prog,
12632 			 const struct bpf_iter_attach_opts *opts)
12633 {
12634 	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12635 	char errmsg[STRERR_BUFSIZE];
12636 	struct bpf_link *link;
12637 	int prog_fd, link_fd;
12638 	__u32 target_fd = 0;
12639 
12640 	if (!OPTS_VALID(opts, bpf_iter_attach_opts))
12641 		return libbpf_err_ptr(-EINVAL);
12642 
12643 	link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
12644 	link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
12645 
12646 	prog_fd = bpf_program__fd(prog);
12647 	if (prog_fd < 0) {
12648 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12649 		return libbpf_err_ptr(-EINVAL);
12650 	}
12651 
12652 	link = calloc(1, sizeof(*link));
12653 	if (!link)
12654 		return libbpf_err_ptr(-ENOMEM);
12655 	link->detach = &bpf_link__detach_fd;
12656 
12657 	link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
12658 				  &link_create_opts);
12659 	if (link_fd < 0) {
12660 		link_fd = -errno;
12661 		free(link);
12662 		pr_warn("prog '%s': failed to attach to iterator: %s\n",
12663 			prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
12664 		return libbpf_err_ptr(link_fd);
12665 	}
12666 	link->fd = link_fd;
12667 	return link;
12668 }
12669 
12670 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12671 {
12672 	*link = bpf_program__attach_iter(prog, NULL);
12673 	return libbpf_get_error(*link);
12674 }
12675 
12676 struct bpf_link *bpf_program__attach_netfilter(const struct bpf_program *prog,
12677 					       const struct bpf_netfilter_opts *opts)
12678 {
12679 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
12680 	struct bpf_link *link;
12681 	int prog_fd, link_fd;
12682 
12683 	if (!OPTS_VALID(opts, bpf_netfilter_opts))
12684 		return libbpf_err_ptr(-EINVAL);
12685 
12686 	prog_fd = bpf_program__fd(prog);
12687 	if (prog_fd < 0) {
12688 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12689 		return libbpf_err_ptr(-EINVAL);
12690 	}
12691 
12692 	link = calloc(1, sizeof(*link));
12693 	if (!link)
12694 		return libbpf_err_ptr(-ENOMEM);
12695 
12696 	link->detach = &bpf_link__detach_fd;
12697 
12698 	lopts.netfilter.pf = OPTS_GET(opts, pf, 0);
12699 	lopts.netfilter.hooknum = OPTS_GET(opts, hooknum, 0);
12700 	lopts.netfilter.priority = OPTS_GET(opts, priority, 0);
12701 	lopts.netfilter.flags = OPTS_GET(opts, flags, 0);
12702 
12703 	link_fd = bpf_link_create(prog_fd, 0, BPF_NETFILTER, &lopts);
12704 	if (link_fd < 0) {
12705 		char errmsg[STRERR_BUFSIZE];
12706 
12707 		link_fd = -errno;
12708 		free(link);
12709 		pr_warn("prog '%s': failed to attach to netfilter: %s\n",
12710 			prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
12711 		return libbpf_err_ptr(link_fd);
12712 	}
12713 	link->fd = link_fd;
12714 
12715 	return link;
12716 }
12717 
12718 struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
12719 {
12720 	struct bpf_link *link = NULL;
12721 	int err;
12722 
12723 	if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
12724 		return libbpf_err_ptr(-EOPNOTSUPP);
12725 
12726 	err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, &link);
12727 	if (err)
12728 		return libbpf_err_ptr(err);
12729 
12730 	/* When calling bpf_program__attach() explicitly, auto-attach support
12731 	 * is expected to work, so NULL returned link is considered an error.
12732 	 * This is different for skeleton's attach, see comment in
12733 	 * bpf_object__attach_skeleton().
12734 	 */
12735 	if (!link)
12736 		return libbpf_err_ptr(-EOPNOTSUPP);
12737 
12738 	return link;
12739 }
12740 
12741 struct bpf_link_struct_ops {
12742 	struct bpf_link link;
12743 	int map_fd;
12744 };
12745 
12746 static int bpf_link__detach_struct_ops(struct bpf_link *link)
12747 {
12748 	struct bpf_link_struct_ops *st_link;
12749 	__u32 zero = 0;
12750 
12751 	st_link = container_of(link, struct bpf_link_struct_ops, link);
12752 
12753 	if (st_link->map_fd < 0)
12754 		/* w/o a real link */
12755 		return bpf_map_delete_elem(link->fd, &zero);
12756 
12757 	return close(link->fd);
12758 }
12759 
12760 struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
12761 {
12762 	struct bpf_link_struct_ops *link;
12763 	__u32 zero = 0;
12764 	int err, fd;
12765 
12766 	if (!bpf_map__is_struct_ops(map) || map->fd == -1)
12767 		return libbpf_err_ptr(-EINVAL);
12768 
12769 	link = calloc(1, sizeof(*link));
12770 	if (!link)
12771 		return libbpf_err_ptr(-EINVAL);
12772 
12773 	/* kern_vdata should be prepared during the loading phase. */
12774 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
12775 	/* It can be EBUSY if the map has been used to create or
12776 	 * update a link before.  We don't allow updating the value of
12777 	 * a struct_ops once it is set.  That ensures that the value
12778 	 * never changed.  So, it is safe to skip EBUSY.
12779 	 */
12780 	if (err && (!(map->def.map_flags & BPF_F_LINK) || err != -EBUSY)) {
12781 		free(link);
12782 		return libbpf_err_ptr(err);
12783 	}
12784 
12785 	link->link.detach = bpf_link__detach_struct_ops;
12786 
12787 	if (!(map->def.map_flags & BPF_F_LINK)) {
12788 		/* w/o a real link */
12789 		link->link.fd = map->fd;
12790 		link->map_fd = -1;
12791 		return &link->link;
12792 	}
12793 
12794 	fd = bpf_link_create(map->fd, 0, BPF_STRUCT_OPS, NULL);
12795 	if (fd < 0) {
12796 		free(link);
12797 		return libbpf_err_ptr(fd);
12798 	}
12799 
12800 	link->link.fd = fd;
12801 	link->map_fd = map->fd;
12802 
12803 	return &link->link;
12804 }
12805 
12806 /*
12807  * Swap the back struct_ops of a link with a new struct_ops map.
12808  */
12809 int bpf_link__update_map(struct bpf_link *link, const struct bpf_map *map)
12810 {
12811 	struct bpf_link_struct_ops *st_ops_link;
12812 	__u32 zero = 0;
12813 	int err;
12814 
12815 	if (!bpf_map__is_struct_ops(map) || map->fd < 0)
12816 		return -EINVAL;
12817 
12818 	st_ops_link = container_of(link, struct bpf_link_struct_ops, link);
12819 	/* Ensure the type of a link is correct */
12820 	if (st_ops_link->map_fd < 0)
12821 		return -EINVAL;
12822 
12823 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
12824 	/* It can be EBUSY if the map has been used to create or
12825 	 * update a link before.  We don't allow updating the value of
12826 	 * a struct_ops once it is set.  That ensures that the value
12827 	 * never changed.  So, it is safe to skip EBUSY.
12828 	 */
12829 	if (err && err != -EBUSY)
12830 		return err;
12831 
12832 	err = bpf_link_update(link->fd, map->fd, NULL);
12833 	if (err < 0)
12834 		return err;
12835 
12836 	st_ops_link->map_fd = map->fd;
12837 
12838 	return 0;
12839 }
12840 
12841 typedef enum bpf_perf_event_ret (*bpf_perf_event_print_t)(struct perf_event_header *hdr,
12842 							  void *private_data);
12843 
12844 static enum bpf_perf_event_ret
12845 perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
12846 		       void **copy_mem, size_t *copy_size,
12847 		       bpf_perf_event_print_t fn, void *private_data)
12848 {
12849 	struct perf_event_mmap_page *header = mmap_mem;
12850 	__u64 data_head = ring_buffer_read_head(header);
12851 	__u64 data_tail = header->data_tail;
12852 	void *base = ((__u8 *)header) + page_size;
12853 	int ret = LIBBPF_PERF_EVENT_CONT;
12854 	struct perf_event_header *ehdr;
12855 	size_t ehdr_size;
12856 
12857 	while (data_head != data_tail) {
12858 		ehdr = base + (data_tail & (mmap_size - 1));
12859 		ehdr_size = ehdr->size;
12860 
12861 		if (((void *)ehdr) + ehdr_size > base + mmap_size) {
12862 			void *copy_start = ehdr;
12863 			size_t len_first = base + mmap_size - copy_start;
12864 			size_t len_secnd = ehdr_size - len_first;
12865 
12866 			if (*copy_size < ehdr_size) {
12867 				free(*copy_mem);
12868 				*copy_mem = malloc(ehdr_size);
12869 				if (!*copy_mem) {
12870 					*copy_size = 0;
12871 					ret = LIBBPF_PERF_EVENT_ERROR;
12872 					break;
12873 				}
12874 				*copy_size = ehdr_size;
12875 			}
12876 
12877 			memcpy(*copy_mem, copy_start, len_first);
12878 			memcpy(*copy_mem + len_first, base, len_secnd);
12879 			ehdr = *copy_mem;
12880 		}
12881 
12882 		ret = fn(ehdr, private_data);
12883 		data_tail += ehdr_size;
12884 		if (ret != LIBBPF_PERF_EVENT_CONT)
12885 			break;
12886 	}
12887 
12888 	ring_buffer_write_tail(header, data_tail);
12889 	return libbpf_err(ret);
12890 }
12891 
12892 struct perf_buffer;
12893 
12894 struct perf_buffer_params {
12895 	struct perf_event_attr *attr;
12896 	/* if event_cb is specified, it takes precendence */
12897 	perf_buffer_event_fn event_cb;
12898 	/* sample_cb and lost_cb are higher-level common-case callbacks */
12899 	perf_buffer_sample_fn sample_cb;
12900 	perf_buffer_lost_fn lost_cb;
12901 	void *ctx;
12902 	int cpu_cnt;
12903 	int *cpus;
12904 	int *map_keys;
12905 };
12906 
12907 struct perf_cpu_buf {
12908 	struct perf_buffer *pb;
12909 	void *base; /* mmap()'ed memory */
12910 	void *buf; /* for reconstructing segmented data */
12911 	size_t buf_size;
12912 	int fd;
12913 	int cpu;
12914 	int map_key;
12915 };
12916 
12917 struct perf_buffer {
12918 	perf_buffer_event_fn event_cb;
12919 	perf_buffer_sample_fn sample_cb;
12920 	perf_buffer_lost_fn lost_cb;
12921 	void *ctx; /* passed into callbacks */
12922 
12923 	size_t page_size;
12924 	size_t mmap_size;
12925 	struct perf_cpu_buf **cpu_bufs;
12926 	struct epoll_event *events;
12927 	int cpu_cnt; /* number of allocated CPU buffers */
12928 	int epoll_fd; /* perf event FD */
12929 	int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
12930 };
12931 
12932 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
12933 				      struct perf_cpu_buf *cpu_buf)
12934 {
12935 	if (!cpu_buf)
12936 		return;
12937 	if (cpu_buf->base &&
12938 	    munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
12939 		pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
12940 	if (cpu_buf->fd >= 0) {
12941 		ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
12942 		close(cpu_buf->fd);
12943 	}
12944 	free(cpu_buf->buf);
12945 	free(cpu_buf);
12946 }
12947 
12948 void perf_buffer__free(struct perf_buffer *pb)
12949 {
12950 	int i;
12951 
12952 	if (IS_ERR_OR_NULL(pb))
12953 		return;
12954 	if (pb->cpu_bufs) {
12955 		for (i = 0; i < pb->cpu_cnt; i++) {
12956 			struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
12957 
12958 			if (!cpu_buf)
12959 				continue;
12960 
12961 			bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
12962 			perf_buffer__free_cpu_buf(pb, cpu_buf);
12963 		}
12964 		free(pb->cpu_bufs);
12965 	}
12966 	if (pb->epoll_fd >= 0)
12967 		close(pb->epoll_fd);
12968 	free(pb->events);
12969 	free(pb);
12970 }
12971 
12972 static struct perf_cpu_buf *
12973 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
12974 			  int cpu, int map_key)
12975 {
12976 	struct perf_cpu_buf *cpu_buf;
12977 	char msg[STRERR_BUFSIZE];
12978 	int err;
12979 
12980 	cpu_buf = calloc(1, sizeof(*cpu_buf));
12981 	if (!cpu_buf)
12982 		return ERR_PTR(-ENOMEM);
12983 
12984 	cpu_buf->pb = pb;
12985 	cpu_buf->cpu = cpu;
12986 	cpu_buf->map_key = map_key;
12987 
12988 	cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
12989 			      -1, PERF_FLAG_FD_CLOEXEC);
12990 	if (cpu_buf->fd < 0) {
12991 		err = -errno;
12992 		pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
12993 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
12994 		goto error;
12995 	}
12996 
12997 	cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
12998 			     PROT_READ | PROT_WRITE, MAP_SHARED,
12999 			     cpu_buf->fd, 0);
13000 	if (cpu_buf->base == MAP_FAILED) {
13001 		cpu_buf->base = NULL;
13002 		err = -errno;
13003 		pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
13004 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
13005 		goto error;
13006 	}
13007 
13008 	if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
13009 		err = -errno;
13010 		pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
13011 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
13012 		goto error;
13013 	}
13014 
13015 	return cpu_buf;
13016 
13017 error:
13018 	perf_buffer__free_cpu_buf(pb, cpu_buf);
13019 	return (struct perf_cpu_buf *)ERR_PTR(err);
13020 }
13021 
13022 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
13023 					      struct perf_buffer_params *p);
13024 
13025 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
13026 				     perf_buffer_sample_fn sample_cb,
13027 				     perf_buffer_lost_fn lost_cb,
13028 				     void *ctx,
13029 				     const struct perf_buffer_opts *opts)
13030 {
13031 	const size_t attr_sz = sizeof(struct perf_event_attr);
13032 	struct perf_buffer_params p = {};
13033 	struct perf_event_attr attr;
13034 	__u32 sample_period;
13035 
13036 	if (!OPTS_VALID(opts, perf_buffer_opts))
13037 		return libbpf_err_ptr(-EINVAL);
13038 
13039 	sample_period = OPTS_GET(opts, sample_period, 1);
13040 	if (!sample_period)
13041 		sample_period = 1;
13042 
13043 	memset(&attr, 0, attr_sz);
13044 	attr.size = attr_sz;
13045 	attr.config = PERF_COUNT_SW_BPF_OUTPUT;
13046 	attr.type = PERF_TYPE_SOFTWARE;
13047 	attr.sample_type = PERF_SAMPLE_RAW;
13048 	attr.sample_period = sample_period;
13049 	attr.wakeup_events = sample_period;
13050 
13051 	p.attr = &attr;
13052 	p.sample_cb = sample_cb;
13053 	p.lost_cb = lost_cb;
13054 	p.ctx = ctx;
13055 
13056 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
13057 }
13058 
13059 struct perf_buffer *perf_buffer__new_raw(int map_fd, size_t page_cnt,
13060 					 struct perf_event_attr *attr,
13061 					 perf_buffer_event_fn event_cb, void *ctx,
13062 					 const struct perf_buffer_raw_opts *opts)
13063 {
13064 	struct perf_buffer_params p = {};
13065 
13066 	if (!attr)
13067 		return libbpf_err_ptr(-EINVAL);
13068 
13069 	if (!OPTS_VALID(opts, perf_buffer_raw_opts))
13070 		return libbpf_err_ptr(-EINVAL);
13071 
13072 	p.attr = attr;
13073 	p.event_cb = event_cb;
13074 	p.ctx = ctx;
13075 	p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
13076 	p.cpus = OPTS_GET(opts, cpus, NULL);
13077 	p.map_keys = OPTS_GET(opts, map_keys, NULL);
13078 
13079 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
13080 }
13081 
13082 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
13083 					      struct perf_buffer_params *p)
13084 {
13085 	const char *online_cpus_file = "/sys/devices/system/cpu/online";
13086 	struct bpf_map_info map;
13087 	char msg[STRERR_BUFSIZE];
13088 	struct perf_buffer *pb;
13089 	bool *online = NULL;
13090 	__u32 map_info_len;
13091 	int err, i, j, n;
13092 
13093 	if (page_cnt == 0 || (page_cnt & (page_cnt - 1))) {
13094 		pr_warn("page count should be power of two, but is %zu\n",
13095 			page_cnt);
13096 		return ERR_PTR(-EINVAL);
13097 	}
13098 
13099 	/* best-effort sanity checks */
13100 	memset(&map, 0, sizeof(map));
13101 	map_info_len = sizeof(map);
13102 	err = bpf_map_get_info_by_fd(map_fd, &map, &map_info_len);
13103 	if (err) {
13104 		err = -errno;
13105 		/* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
13106 		 * -EBADFD, -EFAULT, or -E2BIG on real error
13107 		 */
13108 		if (err != -EINVAL) {
13109 			pr_warn("failed to get map info for map FD %d: %s\n",
13110 				map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
13111 			return ERR_PTR(err);
13112 		}
13113 		pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
13114 			 map_fd);
13115 	} else {
13116 		if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
13117 			pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
13118 				map.name);
13119 			return ERR_PTR(-EINVAL);
13120 		}
13121 	}
13122 
13123 	pb = calloc(1, sizeof(*pb));
13124 	if (!pb)
13125 		return ERR_PTR(-ENOMEM);
13126 
13127 	pb->event_cb = p->event_cb;
13128 	pb->sample_cb = p->sample_cb;
13129 	pb->lost_cb = p->lost_cb;
13130 	pb->ctx = p->ctx;
13131 
13132 	pb->page_size = getpagesize();
13133 	pb->mmap_size = pb->page_size * page_cnt;
13134 	pb->map_fd = map_fd;
13135 
13136 	pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
13137 	if (pb->epoll_fd < 0) {
13138 		err = -errno;
13139 		pr_warn("failed to create epoll instance: %s\n",
13140 			libbpf_strerror_r(err, msg, sizeof(msg)));
13141 		goto error;
13142 	}
13143 
13144 	if (p->cpu_cnt > 0) {
13145 		pb->cpu_cnt = p->cpu_cnt;
13146 	} else {
13147 		pb->cpu_cnt = libbpf_num_possible_cpus();
13148 		if (pb->cpu_cnt < 0) {
13149 			err = pb->cpu_cnt;
13150 			goto error;
13151 		}
13152 		if (map.max_entries && map.max_entries < pb->cpu_cnt)
13153 			pb->cpu_cnt = map.max_entries;
13154 	}
13155 
13156 	pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
13157 	if (!pb->events) {
13158 		err = -ENOMEM;
13159 		pr_warn("failed to allocate events: out of memory\n");
13160 		goto error;
13161 	}
13162 	pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
13163 	if (!pb->cpu_bufs) {
13164 		err = -ENOMEM;
13165 		pr_warn("failed to allocate buffers: out of memory\n");
13166 		goto error;
13167 	}
13168 
13169 	err = parse_cpu_mask_file(online_cpus_file, &online, &n);
13170 	if (err) {
13171 		pr_warn("failed to get online CPU mask: %d\n", err);
13172 		goto error;
13173 	}
13174 
13175 	for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
13176 		struct perf_cpu_buf *cpu_buf;
13177 		int cpu, map_key;
13178 
13179 		cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
13180 		map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
13181 
13182 		/* in case user didn't explicitly requested particular CPUs to
13183 		 * be attached to, skip offline/not present CPUs
13184 		 */
13185 		if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
13186 			continue;
13187 
13188 		cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
13189 		if (IS_ERR(cpu_buf)) {
13190 			err = PTR_ERR(cpu_buf);
13191 			goto error;
13192 		}
13193 
13194 		pb->cpu_bufs[j] = cpu_buf;
13195 
13196 		err = bpf_map_update_elem(pb->map_fd, &map_key,
13197 					  &cpu_buf->fd, 0);
13198 		if (err) {
13199 			err = -errno;
13200 			pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
13201 				cpu, map_key, cpu_buf->fd,
13202 				libbpf_strerror_r(err, msg, sizeof(msg)));
13203 			goto error;
13204 		}
13205 
13206 		pb->events[j].events = EPOLLIN;
13207 		pb->events[j].data.ptr = cpu_buf;
13208 		if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
13209 			      &pb->events[j]) < 0) {
13210 			err = -errno;
13211 			pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
13212 				cpu, cpu_buf->fd,
13213 				libbpf_strerror_r(err, msg, sizeof(msg)));
13214 			goto error;
13215 		}
13216 		j++;
13217 	}
13218 	pb->cpu_cnt = j;
13219 	free(online);
13220 
13221 	return pb;
13222 
13223 error:
13224 	free(online);
13225 	if (pb)
13226 		perf_buffer__free(pb);
13227 	return ERR_PTR(err);
13228 }
13229 
13230 struct perf_sample_raw {
13231 	struct perf_event_header header;
13232 	uint32_t size;
13233 	char data[];
13234 };
13235 
13236 struct perf_sample_lost {
13237 	struct perf_event_header header;
13238 	uint64_t id;
13239 	uint64_t lost;
13240 	uint64_t sample_id;
13241 };
13242 
13243 static enum bpf_perf_event_ret
13244 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
13245 {
13246 	struct perf_cpu_buf *cpu_buf = ctx;
13247 	struct perf_buffer *pb = cpu_buf->pb;
13248 	void *data = e;
13249 
13250 	/* user wants full control over parsing perf event */
13251 	if (pb->event_cb)
13252 		return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
13253 
13254 	switch (e->type) {
13255 	case PERF_RECORD_SAMPLE: {
13256 		struct perf_sample_raw *s = data;
13257 
13258 		if (pb->sample_cb)
13259 			pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
13260 		break;
13261 	}
13262 	case PERF_RECORD_LOST: {
13263 		struct perf_sample_lost *s = data;
13264 
13265 		if (pb->lost_cb)
13266 			pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
13267 		break;
13268 	}
13269 	default:
13270 		pr_warn("unknown perf sample type %d\n", e->type);
13271 		return LIBBPF_PERF_EVENT_ERROR;
13272 	}
13273 	return LIBBPF_PERF_EVENT_CONT;
13274 }
13275 
13276 static int perf_buffer__process_records(struct perf_buffer *pb,
13277 					struct perf_cpu_buf *cpu_buf)
13278 {
13279 	enum bpf_perf_event_ret ret;
13280 
13281 	ret = perf_event_read_simple(cpu_buf->base, pb->mmap_size,
13282 				     pb->page_size, &cpu_buf->buf,
13283 				     &cpu_buf->buf_size,
13284 				     perf_buffer__process_record, cpu_buf);
13285 	if (ret != LIBBPF_PERF_EVENT_CONT)
13286 		return ret;
13287 	return 0;
13288 }
13289 
13290 int perf_buffer__epoll_fd(const struct perf_buffer *pb)
13291 {
13292 	return pb->epoll_fd;
13293 }
13294 
13295 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
13296 {
13297 	int i, cnt, err;
13298 
13299 	cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
13300 	if (cnt < 0)
13301 		return -errno;
13302 
13303 	for (i = 0; i < cnt; i++) {
13304 		struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
13305 
13306 		err = perf_buffer__process_records(pb, cpu_buf);
13307 		if (err) {
13308 			pr_warn("error while processing records: %d\n", err);
13309 			return libbpf_err(err);
13310 		}
13311 	}
13312 	return cnt;
13313 }
13314 
13315 /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
13316  * manager.
13317  */
13318 size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
13319 {
13320 	return pb->cpu_cnt;
13321 }
13322 
13323 /*
13324  * Return perf_event FD of a ring buffer in *buf_idx* slot of
13325  * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
13326  * select()/poll()/epoll() Linux syscalls.
13327  */
13328 int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
13329 {
13330 	struct perf_cpu_buf *cpu_buf;
13331 
13332 	if (buf_idx >= pb->cpu_cnt)
13333 		return libbpf_err(-EINVAL);
13334 
13335 	cpu_buf = pb->cpu_bufs[buf_idx];
13336 	if (!cpu_buf)
13337 		return libbpf_err(-ENOENT);
13338 
13339 	return cpu_buf->fd;
13340 }
13341 
13342 int perf_buffer__buffer(struct perf_buffer *pb, int buf_idx, void **buf, size_t *buf_size)
13343 {
13344 	struct perf_cpu_buf *cpu_buf;
13345 
13346 	if (buf_idx >= pb->cpu_cnt)
13347 		return libbpf_err(-EINVAL);
13348 
13349 	cpu_buf = pb->cpu_bufs[buf_idx];
13350 	if (!cpu_buf)
13351 		return libbpf_err(-ENOENT);
13352 
13353 	*buf = cpu_buf->base;
13354 	*buf_size = pb->mmap_size;
13355 	return 0;
13356 }
13357 
13358 /*
13359  * Consume data from perf ring buffer corresponding to slot *buf_idx* in
13360  * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
13361  * consume, do nothing and return success.
13362  * Returns:
13363  *   - 0 on success;
13364  *   - <0 on failure.
13365  */
13366 int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
13367 {
13368 	struct perf_cpu_buf *cpu_buf;
13369 
13370 	if (buf_idx >= pb->cpu_cnt)
13371 		return libbpf_err(-EINVAL);
13372 
13373 	cpu_buf = pb->cpu_bufs[buf_idx];
13374 	if (!cpu_buf)
13375 		return libbpf_err(-ENOENT);
13376 
13377 	return perf_buffer__process_records(pb, cpu_buf);
13378 }
13379 
13380 int perf_buffer__consume(struct perf_buffer *pb)
13381 {
13382 	int i, err;
13383 
13384 	for (i = 0; i < pb->cpu_cnt; i++) {
13385 		struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
13386 
13387 		if (!cpu_buf)
13388 			continue;
13389 
13390 		err = perf_buffer__process_records(pb, cpu_buf);
13391 		if (err) {
13392 			pr_warn("perf_buffer: failed to process records in buffer #%d: %d\n", i, err);
13393 			return libbpf_err(err);
13394 		}
13395 	}
13396 	return 0;
13397 }
13398 
13399 int bpf_program__set_attach_target(struct bpf_program *prog,
13400 				   int attach_prog_fd,
13401 				   const char *attach_func_name)
13402 {
13403 	int btf_obj_fd = 0, btf_id = 0, err;
13404 
13405 	if (!prog || attach_prog_fd < 0)
13406 		return libbpf_err(-EINVAL);
13407 
13408 	if (prog->obj->loaded)
13409 		return libbpf_err(-EINVAL);
13410 
13411 	if (attach_prog_fd && !attach_func_name) {
13412 		/* remember attach_prog_fd and let bpf_program__load() find
13413 		 * BTF ID during the program load
13414 		 */
13415 		prog->attach_prog_fd = attach_prog_fd;
13416 		return 0;
13417 	}
13418 
13419 	if (attach_prog_fd) {
13420 		btf_id = libbpf_find_prog_btf_id(attach_func_name,
13421 						 attach_prog_fd);
13422 		if (btf_id < 0)
13423 			return libbpf_err(btf_id);
13424 	} else {
13425 		if (!attach_func_name)
13426 			return libbpf_err(-EINVAL);
13427 
13428 		/* load btf_vmlinux, if not yet */
13429 		err = bpf_object__load_vmlinux_btf(prog->obj, true);
13430 		if (err)
13431 			return libbpf_err(err);
13432 		err = find_kernel_btf_id(prog->obj, attach_func_name,
13433 					 prog->expected_attach_type,
13434 					 &btf_obj_fd, &btf_id);
13435 		if (err)
13436 			return libbpf_err(err);
13437 	}
13438 
13439 	prog->attach_btf_id = btf_id;
13440 	prog->attach_btf_obj_fd = btf_obj_fd;
13441 	prog->attach_prog_fd = attach_prog_fd;
13442 	return 0;
13443 }
13444 
13445 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
13446 {
13447 	int err = 0, n, len, start, end = -1;
13448 	bool *tmp;
13449 
13450 	*mask = NULL;
13451 	*mask_sz = 0;
13452 
13453 	/* Each sub string separated by ',' has format \d+-\d+ or \d+ */
13454 	while (*s) {
13455 		if (*s == ',' || *s == '\n') {
13456 			s++;
13457 			continue;
13458 		}
13459 		n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
13460 		if (n <= 0 || n > 2) {
13461 			pr_warn("Failed to get CPU range %s: %d\n", s, n);
13462 			err = -EINVAL;
13463 			goto cleanup;
13464 		} else if (n == 1) {
13465 			end = start;
13466 		}
13467 		if (start < 0 || start > end) {
13468 			pr_warn("Invalid CPU range [%d,%d] in %s\n",
13469 				start, end, s);
13470 			err = -EINVAL;
13471 			goto cleanup;
13472 		}
13473 		tmp = realloc(*mask, end + 1);
13474 		if (!tmp) {
13475 			err = -ENOMEM;
13476 			goto cleanup;
13477 		}
13478 		*mask = tmp;
13479 		memset(tmp + *mask_sz, 0, start - *mask_sz);
13480 		memset(tmp + start, 1, end - start + 1);
13481 		*mask_sz = end + 1;
13482 		s += len;
13483 	}
13484 	if (!*mask_sz) {
13485 		pr_warn("Empty CPU range\n");
13486 		return -EINVAL;
13487 	}
13488 	return 0;
13489 cleanup:
13490 	free(*mask);
13491 	*mask = NULL;
13492 	return err;
13493 }
13494 
13495 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
13496 {
13497 	int fd, err = 0, len;
13498 	char buf[128];
13499 
13500 	fd = open(fcpu, O_RDONLY | O_CLOEXEC);
13501 	if (fd < 0) {
13502 		err = -errno;
13503 		pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
13504 		return err;
13505 	}
13506 	len = read(fd, buf, sizeof(buf));
13507 	close(fd);
13508 	if (len <= 0) {
13509 		err = len ? -errno : -EINVAL;
13510 		pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
13511 		return err;
13512 	}
13513 	if (len >= sizeof(buf)) {
13514 		pr_warn("CPU mask is too big in file %s\n", fcpu);
13515 		return -E2BIG;
13516 	}
13517 	buf[len] = '\0';
13518 
13519 	return parse_cpu_mask_str(buf, mask, mask_sz);
13520 }
13521 
13522 int libbpf_num_possible_cpus(void)
13523 {
13524 	static const char *fcpu = "/sys/devices/system/cpu/possible";
13525 	static int cpus;
13526 	int err, n, i, tmp_cpus;
13527 	bool *mask;
13528 
13529 	tmp_cpus = READ_ONCE(cpus);
13530 	if (tmp_cpus > 0)
13531 		return tmp_cpus;
13532 
13533 	err = parse_cpu_mask_file(fcpu, &mask, &n);
13534 	if (err)
13535 		return libbpf_err(err);
13536 
13537 	tmp_cpus = 0;
13538 	for (i = 0; i < n; i++) {
13539 		if (mask[i])
13540 			tmp_cpus++;
13541 	}
13542 	free(mask);
13543 
13544 	WRITE_ONCE(cpus, tmp_cpus);
13545 	return tmp_cpus;
13546 }
13547 
13548 static int populate_skeleton_maps(const struct bpf_object *obj,
13549 				  struct bpf_map_skeleton *maps,
13550 				  size_t map_cnt, size_t map_skel_sz)
13551 {
13552 	int i;
13553 
13554 	for (i = 0; i < map_cnt; i++) {
13555 		struct bpf_map_skeleton *map_skel = (void *)maps + i * map_skel_sz;
13556 		struct bpf_map **map = map_skel->map;
13557 		const char *name = map_skel->name;
13558 		void **mmaped = map_skel->mmaped;
13559 
13560 		*map = bpf_object__find_map_by_name(obj, name);
13561 		if (!*map) {
13562 			pr_warn("failed to find skeleton map '%s'\n", name);
13563 			return -ESRCH;
13564 		}
13565 
13566 		/* externs shouldn't be pre-setup from user code */
13567 		if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
13568 			*mmaped = (*map)->mmaped;
13569 	}
13570 	return 0;
13571 }
13572 
13573 static int populate_skeleton_progs(const struct bpf_object *obj,
13574 				   struct bpf_prog_skeleton *progs,
13575 				   size_t prog_cnt, size_t prog_skel_sz)
13576 {
13577 	int i;
13578 
13579 	for (i = 0; i < prog_cnt; i++) {
13580 		struct bpf_prog_skeleton *prog_skel = (void *)progs + i * prog_skel_sz;
13581 		struct bpf_program **prog = prog_skel->prog;
13582 		const char *name = prog_skel->name;
13583 
13584 		*prog = bpf_object__find_program_by_name(obj, name);
13585 		if (!*prog) {
13586 			pr_warn("failed to find skeleton program '%s'\n", name);
13587 			return -ESRCH;
13588 		}
13589 	}
13590 	return 0;
13591 }
13592 
13593 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
13594 			      const struct bpf_object_open_opts *opts)
13595 {
13596 	struct bpf_object *obj;
13597 	int err;
13598 
13599 	obj = bpf_object_open(NULL, s->data, s->data_sz, s->name, opts);
13600 	if (IS_ERR(obj)) {
13601 		err = PTR_ERR(obj);
13602 		pr_warn("failed to initialize skeleton BPF object '%s': %d\n", s->name, err);
13603 		return libbpf_err(err);
13604 	}
13605 
13606 	*s->obj = obj;
13607 	err = populate_skeleton_maps(obj, s->maps, s->map_cnt, s->map_skel_sz);
13608 	if (err) {
13609 		pr_warn("failed to populate skeleton maps for '%s': %d\n", s->name, err);
13610 		return libbpf_err(err);
13611 	}
13612 
13613 	err = populate_skeleton_progs(obj, s->progs, s->prog_cnt, s->prog_skel_sz);
13614 	if (err) {
13615 		pr_warn("failed to populate skeleton progs for '%s': %d\n", s->name, err);
13616 		return libbpf_err(err);
13617 	}
13618 
13619 	return 0;
13620 }
13621 
13622 int bpf_object__open_subskeleton(struct bpf_object_subskeleton *s)
13623 {
13624 	int err, len, var_idx, i;
13625 	const char *var_name;
13626 	const struct bpf_map *map;
13627 	struct btf *btf;
13628 	__u32 map_type_id;
13629 	const struct btf_type *map_type, *var_type;
13630 	const struct bpf_var_skeleton *var_skel;
13631 	struct btf_var_secinfo *var;
13632 
13633 	if (!s->obj)
13634 		return libbpf_err(-EINVAL);
13635 
13636 	btf = bpf_object__btf(s->obj);
13637 	if (!btf) {
13638 		pr_warn("subskeletons require BTF at runtime (object %s)\n",
13639 			bpf_object__name(s->obj));
13640 		return libbpf_err(-errno);
13641 	}
13642 
13643 	err = populate_skeleton_maps(s->obj, s->maps, s->map_cnt, s->map_skel_sz);
13644 	if (err) {
13645 		pr_warn("failed to populate subskeleton maps: %d\n", err);
13646 		return libbpf_err(err);
13647 	}
13648 
13649 	err = populate_skeleton_progs(s->obj, s->progs, s->prog_cnt, s->prog_skel_sz);
13650 	if (err) {
13651 		pr_warn("failed to populate subskeleton maps: %d\n", err);
13652 		return libbpf_err(err);
13653 	}
13654 
13655 	for (var_idx = 0; var_idx < s->var_cnt; var_idx++) {
13656 		var_skel = (void *)s->vars + var_idx * s->var_skel_sz;
13657 		map = *var_skel->map;
13658 		map_type_id = bpf_map__btf_value_type_id(map);
13659 		map_type = btf__type_by_id(btf, map_type_id);
13660 
13661 		if (!btf_is_datasec(map_type)) {
13662 			pr_warn("type for map '%1$s' is not a datasec: %2$s",
13663 				bpf_map__name(map),
13664 				__btf_kind_str(btf_kind(map_type)));
13665 			return libbpf_err(-EINVAL);
13666 		}
13667 
13668 		len = btf_vlen(map_type);
13669 		var = btf_var_secinfos(map_type);
13670 		for (i = 0; i < len; i++, var++) {
13671 			var_type = btf__type_by_id(btf, var->type);
13672 			var_name = btf__name_by_offset(btf, var_type->name_off);
13673 			if (strcmp(var_name, var_skel->name) == 0) {
13674 				*var_skel->addr = map->mmaped + var->offset;
13675 				break;
13676 			}
13677 		}
13678 	}
13679 	return 0;
13680 }
13681 
13682 void bpf_object__destroy_subskeleton(struct bpf_object_subskeleton *s)
13683 {
13684 	if (!s)
13685 		return;
13686 	free(s->maps);
13687 	free(s->progs);
13688 	free(s->vars);
13689 	free(s);
13690 }
13691 
13692 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
13693 {
13694 	int i, err;
13695 
13696 	err = bpf_object__load(*s->obj);
13697 	if (err) {
13698 		pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
13699 		return libbpf_err(err);
13700 	}
13701 
13702 	for (i = 0; i < s->map_cnt; i++) {
13703 		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
13704 		struct bpf_map *map = *map_skel->map;
13705 
13706 		if (!map_skel->mmaped)
13707 			continue;
13708 
13709 		*map_skel->mmaped = map->mmaped;
13710 	}
13711 
13712 	return 0;
13713 }
13714 
13715 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
13716 {
13717 	int i, err;
13718 
13719 	for (i = 0; i < s->prog_cnt; i++) {
13720 		struct bpf_prog_skeleton *prog_skel = (void *)s->progs + i * s->prog_skel_sz;
13721 		struct bpf_program *prog = *prog_skel->prog;
13722 		struct bpf_link **link = prog_skel->link;
13723 
13724 		if (!prog->autoload || !prog->autoattach)
13725 			continue;
13726 
13727 		/* auto-attaching not supported for this program */
13728 		if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
13729 			continue;
13730 
13731 		/* if user already set the link manually, don't attempt auto-attach */
13732 		if (*link)
13733 			continue;
13734 
13735 		err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, link);
13736 		if (err) {
13737 			pr_warn("prog '%s': failed to auto-attach: %d\n",
13738 				bpf_program__name(prog), err);
13739 			return libbpf_err(err);
13740 		}
13741 
13742 		/* It's possible that for some SEC() definitions auto-attach
13743 		 * is supported in some cases (e.g., if definition completely
13744 		 * specifies target information), but is not in other cases.
13745 		 * SEC("uprobe") is one such case. If user specified target
13746 		 * binary and function name, such BPF program can be
13747 		 * auto-attached. But if not, it shouldn't trigger skeleton's
13748 		 * attach to fail. It should just be skipped.
13749 		 * attach_fn signals such case with returning 0 (no error) and
13750 		 * setting link to NULL.
13751 		 */
13752 	}
13753 
13754 	return 0;
13755 }
13756 
13757 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
13758 {
13759 	int i;
13760 
13761 	for (i = 0; i < s->prog_cnt; i++) {
13762 		struct bpf_prog_skeleton *prog_skel = (void *)s->progs + i * s->prog_skel_sz;
13763 		struct bpf_link **link = prog_skel->link;
13764 
13765 		bpf_link__destroy(*link);
13766 		*link = NULL;
13767 	}
13768 }
13769 
13770 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
13771 {
13772 	if (!s)
13773 		return;
13774 
13775 	if (s->progs)
13776 		bpf_object__detach_skeleton(s);
13777 	if (s->obj)
13778 		bpf_object__close(*s->obj);
13779 	free(s->maps);
13780 	free(s->progs);
13781 	free(s);
13782 }
13783