xref: /linux/tools/lib/bpf/libbpf.c (revision e958da0ddbe831197a0023251880a4a09d5ba268)
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/bpf_perf_event.h>
37 #include <linux/ring_buffer.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 #include <libelf.h>
47 #include <gelf.h>
48 #include <zlib.h>
49 
50 #include "libbpf.h"
51 #include "bpf.h"
52 #include "btf.h"
53 #include "str_error.h"
54 #include "libbpf_internal.h"
55 #include "hashmap.h"
56 #include "bpf_gen_internal.h"
57 #include "zip.h"
58 
59 #ifndef BPF_FS_MAGIC
60 #define BPF_FS_MAGIC		0xcafe4a11
61 #endif
62 
63 #define BPF_FS_DEFAULT_PATH "/sys/fs/bpf"
64 
65 #define BPF_INSN_SZ (sizeof(struct bpf_insn))
66 
67 /* vsprintf() in __base_pr() uses nonliteral format string. It may break
68  * compilation if user enables corresponding warning. Disable it explicitly.
69  */
70 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
71 
72 #define __printf(a, b)	__attribute__((format(printf, a, b)))
73 
74 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj);
75 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog);
76 static int map_set_def_max_entries(struct bpf_map *map);
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 	[BPF_LINK_TYPE_SOCKMAP]			= "sockmap",
153 };
154 
155 static const char * const map_type_name[] = {
156 	[BPF_MAP_TYPE_UNSPEC]			= "unspec",
157 	[BPF_MAP_TYPE_HASH]			= "hash",
158 	[BPF_MAP_TYPE_ARRAY]			= "array",
159 	[BPF_MAP_TYPE_PROG_ARRAY]		= "prog_array",
160 	[BPF_MAP_TYPE_PERF_EVENT_ARRAY]		= "perf_event_array",
161 	[BPF_MAP_TYPE_PERCPU_HASH]		= "percpu_hash",
162 	[BPF_MAP_TYPE_PERCPU_ARRAY]		= "percpu_array",
163 	[BPF_MAP_TYPE_STACK_TRACE]		= "stack_trace",
164 	[BPF_MAP_TYPE_CGROUP_ARRAY]		= "cgroup_array",
165 	[BPF_MAP_TYPE_LRU_HASH]			= "lru_hash",
166 	[BPF_MAP_TYPE_LRU_PERCPU_HASH]		= "lru_percpu_hash",
167 	[BPF_MAP_TYPE_LPM_TRIE]			= "lpm_trie",
168 	[BPF_MAP_TYPE_ARRAY_OF_MAPS]		= "array_of_maps",
169 	[BPF_MAP_TYPE_HASH_OF_MAPS]		= "hash_of_maps",
170 	[BPF_MAP_TYPE_DEVMAP]			= "devmap",
171 	[BPF_MAP_TYPE_DEVMAP_HASH]		= "devmap_hash",
172 	[BPF_MAP_TYPE_SOCKMAP]			= "sockmap",
173 	[BPF_MAP_TYPE_CPUMAP]			= "cpumap",
174 	[BPF_MAP_TYPE_XSKMAP]			= "xskmap",
175 	[BPF_MAP_TYPE_SOCKHASH]			= "sockhash",
176 	[BPF_MAP_TYPE_CGROUP_STORAGE]		= "cgroup_storage",
177 	[BPF_MAP_TYPE_REUSEPORT_SOCKARRAY]	= "reuseport_sockarray",
178 	[BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE]	= "percpu_cgroup_storage",
179 	[BPF_MAP_TYPE_QUEUE]			= "queue",
180 	[BPF_MAP_TYPE_STACK]			= "stack",
181 	[BPF_MAP_TYPE_SK_STORAGE]		= "sk_storage",
182 	[BPF_MAP_TYPE_STRUCT_OPS]		= "struct_ops",
183 	[BPF_MAP_TYPE_RINGBUF]			= "ringbuf",
184 	[BPF_MAP_TYPE_INODE_STORAGE]		= "inode_storage",
185 	[BPF_MAP_TYPE_TASK_STORAGE]		= "task_storage",
186 	[BPF_MAP_TYPE_BLOOM_FILTER]		= "bloom_filter",
187 	[BPF_MAP_TYPE_USER_RINGBUF]             = "user_ringbuf",
188 	[BPF_MAP_TYPE_CGRP_STORAGE]		= "cgrp_storage",
189 	[BPF_MAP_TYPE_ARENA]			= "arena",
190 };
191 
192 static const char * const prog_type_name[] = {
193 	[BPF_PROG_TYPE_UNSPEC]			= "unspec",
194 	[BPF_PROG_TYPE_SOCKET_FILTER]		= "socket_filter",
195 	[BPF_PROG_TYPE_KPROBE]			= "kprobe",
196 	[BPF_PROG_TYPE_SCHED_CLS]		= "sched_cls",
197 	[BPF_PROG_TYPE_SCHED_ACT]		= "sched_act",
198 	[BPF_PROG_TYPE_TRACEPOINT]		= "tracepoint",
199 	[BPF_PROG_TYPE_XDP]			= "xdp",
200 	[BPF_PROG_TYPE_PERF_EVENT]		= "perf_event",
201 	[BPF_PROG_TYPE_CGROUP_SKB]		= "cgroup_skb",
202 	[BPF_PROG_TYPE_CGROUP_SOCK]		= "cgroup_sock",
203 	[BPF_PROG_TYPE_LWT_IN]			= "lwt_in",
204 	[BPF_PROG_TYPE_LWT_OUT]			= "lwt_out",
205 	[BPF_PROG_TYPE_LWT_XMIT]		= "lwt_xmit",
206 	[BPF_PROG_TYPE_SOCK_OPS]		= "sock_ops",
207 	[BPF_PROG_TYPE_SK_SKB]			= "sk_skb",
208 	[BPF_PROG_TYPE_CGROUP_DEVICE]		= "cgroup_device",
209 	[BPF_PROG_TYPE_SK_MSG]			= "sk_msg",
210 	[BPF_PROG_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
211 	[BPF_PROG_TYPE_CGROUP_SOCK_ADDR]	= "cgroup_sock_addr",
212 	[BPF_PROG_TYPE_LWT_SEG6LOCAL]		= "lwt_seg6local",
213 	[BPF_PROG_TYPE_LIRC_MODE2]		= "lirc_mode2",
214 	[BPF_PROG_TYPE_SK_REUSEPORT]		= "sk_reuseport",
215 	[BPF_PROG_TYPE_FLOW_DISSECTOR]		= "flow_dissector",
216 	[BPF_PROG_TYPE_CGROUP_SYSCTL]		= "cgroup_sysctl",
217 	[BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE]	= "raw_tracepoint_writable",
218 	[BPF_PROG_TYPE_CGROUP_SOCKOPT]		= "cgroup_sockopt",
219 	[BPF_PROG_TYPE_TRACING]			= "tracing",
220 	[BPF_PROG_TYPE_STRUCT_OPS]		= "struct_ops",
221 	[BPF_PROG_TYPE_EXT]			= "ext",
222 	[BPF_PROG_TYPE_LSM]			= "lsm",
223 	[BPF_PROG_TYPE_SK_LOOKUP]		= "sk_lookup",
224 	[BPF_PROG_TYPE_SYSCALL]			= "syscall",
225 	[BPF_PROG_TYPE_NETFILTER]		= "netfilter",
226 };
227 
228 static int __base_pr(enum libbpf_print_level level, const char *format,
229 		     va_list args)
230 {
231 	if (level == LIBBPF_DEBUG)
232 		return 0;
233 
234 	return vfprintf(stderr, format, args);
235 }
236 
237 static libbpf_print_fn_t __libbpf_pr = __base_pr;
238 
239 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
240 {
241 	libbpf_print_fn_t old_print_fn;
242 
243 	old_print_fn = __atomic_exchange_n(&__libbpf_pr, fn, __ATOMIC_RELAXED);
244 
245 	return old_print_fn;
246 }
247 
248 __printf(2, 3)
249 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
250 {
251 	va_list args;
252 	int old_errno;
253 	libbpf_print_fn_t print_fn;
254 
255 	print_fn = __atomic_load_n(&__libbpf_pr, __ATOMIC_RELAXED);
256 	if (!print_fn)
257 		return;
258 
259 	old_errno = errno;
260 
261 	va_start(args, format);
262 	__libbpf_pr(level, format, args);
263 	va_end(args);
264 
265 	errno = old_errno;
266 }
267 
268 static void pr_perm_msg(int err)
269 {
270 	struct rlimit limit;
271 	char buf[100];
272 
273 	if (err != -EPERM || geteuid() != 0)
274 		return;
275 
276 	err = getrlimit(RLIMIT_MEMLOCK, &limit);
277 	if (err)
278 		return;
279 
280 	if (limit.rlim_cur == RLIM_INFINITY)
281 		return;
282 
283 	if (limit.rlim_cur < 1024)
284 		snprintf(buf, sizeof(buf), "%zu bytes", (size_t)limit.rlim_cur);
285 	else if (limit.rlim_cur < 1024*1024)
286 		snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
287 	else
288 		snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
289 
290 	pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
291 		buf);
292 }
293 
294 #define STRERR_BUFSIZE  128
295 
296 /* Copied from tools/perf/util/util.h */
297 #ifndef zfree
298 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
299 #endif
300 
301 #ifndef zclose
302 # define zclose(fd) ({			\
303 	int ___err = 0;			\
304 	if ((fd) >= 0)			\
305 		___err = close((fd));	\
306 	fd = -1;			\
307 	___err; })
308 #endif
309 
310 static inline __u64 ptr_to_u64(const void *ptr)
311 {
312 	return (__u64) (unsigned long) ptr;
313 }
314 
315 int libbpf_set_strict_mode(enum libbpf_strict_mode mode)
316 {
317 	/* as of v1.0 libbpf_set_strict_mode() is a no-op */
318 	return 0;
319 }
320 
321 __u32 libbpf_major_version(void)
322 {
323 	return LIBBPF_MAJOR_VERSION;
324 }
325 
326 __u32 libbpf_minor_version(void)
327 {
328 	return LIBBPF_MINOR_VERSION;
329 }
330 
331 const char *libbpf_version_string(void)
332 {
333 #define __S(X) #X
334 #define _S(X) __S(X)
335 	return  "v" _S(LIBBPF_MAJOR_VERSION) "." _S(LIBBPF_MINOR_VERSION);
336 #undef _S
337 #undef __S
338 }
339 
340 enum reloc_type {
341 	RELO_LD64,
342 	RELO_CALL,
343 	RELO_DATA,
344 	RELO_EXTERN_LD64,
345 	RELO_EXTERN_CALL,
346 	RELO_SUBPROG_ADDR,
347 	RELO_CORE,
348 };
349 
350 struct reloc_desc {
351 	enum reloc_type type;
352 	int insn_idx;
353 	union {
354 		const struct bpf_core_relo *core_relo; /* used when type == RELO_CORE */
355 		struct {
356 			int map_idx;
357 			int sym_off;
358 			int ext_idx;
359 		};
360 	};
361 };
362 
363 /* stored as sec_def->cookie for all libbpf-supported SEC()s */
364 enum sec_def_flags {
365 	SEC_NONE = 0,
366 	/* expected_attach_type is optional, if kernel doesn't support that */
367 	SEC_EXP_ATTACH_OPT = 1,
368 	/* legacy, only used by libbpf_get_type_names() and
369 	 * libbpf_attach_type_by_name(), not used by libbpf itself at all.
370 	 * This used to be associated with cgroup (and few other) BPF programs
371 	 * that were attachable through BPF_PROG_ATTACH command. Pretty
372 	 * meaningless nowadays, though.
373 	 */
374 	SEC_ATTACHABLE = 2,
375 	SEC_ATTACHABLE_OPT = SEC_ATTACHABLE | SEC_EXP_ATTACH_OPT,
376 	/* attachment target is specified through BTF ID in either kernel or
377 	 * other BPF program's BTF object
378 	 */
379 	SEC_ATTACH_BTF = 4,
380 	/* BPF program type allows sleeping/blocking in kernel */
381 	SEC_SLEEPABLE = 8,
382 	/* BPF program support non-linear XDP buffer */
383 	SEC_XDP_FRAGS = 16,
384 	/* Setup proper attach type for usdt probes. */
385 	SEC_USDT = 32,
386 };
387 
388 struct bpf_sec_def {
389 	char *sec;
390 	enum bpf_prog_type prog_type;
391 	enum bpf_attach_type expected_attach_type;
392 	long cookie;
393 	int handler_id;
394 
395 	libbpf_prog_setup_fn_t prog_setup_fn;
396 	libbpf_prog_prepare_load_fn_t prog_prepare_load_fn;
397 	libbpf_prog_attach_fn_t prog_attach_fn;
398 };
399 
400 /*
401  * bpf_prog should be a better name but it has been used in
402  * linux/filter.h.
403  */
404 struct bpf_program {
405 	char *name;
406 	char *sec_name;
407 	size_t sec_idx;
408 	const struct bpf_sec_def *sec_def;
409 	/* this program's instruction offset (in number of instructions)
410 	 * within its containing ELF section
411 	 */
412 	size_t sec_insn_off;
413 	/* number of original instructions in ELF section belonging to this
414 	 * program, not taking into account subprogram instructions possible
415 	 * appended later during relocation
416 	 */
417 	size_t sec_insn_cnt;
418 	/* Offset (in number of instructions) of the start of instruction
419 	 * belonging to this BPF program  within its containing main BPF
420 	 * program. For the entry-point (main) BPF program, this is always
421 	 * zero. For a sub-program, this gets reset before each of main BPF
422 	 * programs are processed and relocated and is used to determined
423 	 * whether sub-program was already appended to the main program, and
424 	 * if yes, at which instruction offset.
425 	 */
426 	size_t sub_insn_off;
427 
428 	/* instructions that belong to BPF program; insns[0] is located at
429 	 * sec_insn_off instruction within its ELF section in ELF file, so
430 	 * when mapping ELF file instruction index to the local instruction,
431 	 * one needs to subtract sec_insn_off; and vice versa.
432 	 */
433 	struct bpf_insn *insns;
434 	/* actual number of instruction in this BPF program's image; for
435 	 * entry-point BPF programs this includes the size of main program
436 	 * itself plus all the used sub-programs, appended at the end
437 	 */
438 	size_t insns_cnt;
439 
440 	struct reloc_desc *reloc_desc;
441 	int nr_reloc;
442 
443 	/* BPF verifier log settings */
444 	char *log_buf;
445 	size_t log_size;
446 	__u32 log_level;
447 
448 	struct bpf_object *obj;
449 
450 	int fd;
451 	bool autoload;
452 	bool autoattach;
453 	bool sym_global;
454 	bool mark_btf_static;
455 	enum bpf_prog_type type;
456 	enum bpf_attach_type expected_attach_type;
457 	int exception_cb_idx;
458 
459 	int prog_ifindex;
460 	__u32 attach_btf_obj_fd;
461 	__u32 attach_btf_id;
462 	__u32 attach_prog_fd;
463 
464 	void *func_info;
465 	__u32 func_info_rec_size;
466 	__u32 func_info_cnt;
467 
468 	void *line_info;
469 	__u32 line_info_rec_size;
470 	__u32 line_info_cnt;
471 	__u32 prog_flags;
472 };
473 
474 struct bpf_struct_ops {
475 	const char *tname;
476 	const struct btf_type *type;
477 	struct bpf_program **progs;
478 	__u32 *kern_func_off;
479 	/* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
480 	void *data;
481 	/* e.g. struct bpf_struct_ops_tcp_congestion_ops in
482 	 *      btf_vmlinux's format.
483 	 * struct bpf_struct_ops_tcp_congestion_ops {
484 	 *	[... some other kernel fields ...]
485 	 *	struct tcp_congestion_ops data;
486 	 * }
487 	 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
488 	 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
489 	 * from "data".
490 	 */
491 	void *kern_vdata;
492 	__u32 type_id;
493 };
494 
495 #define DATA_SEC ".data"
496 #define BSS_SEC ".bss"
497 #define RODATA_SEC ".rodata"
498 #define KCONFIG_SEC ".kconfig"
499 #define KSYMS_SEC ".ksyms"
500 #define STRUCT_OPS_SEC ".struct_ops"
501 #define STRUCT_OPS_LINK_SEC ".struct_ops.link"
502 #define ARENA_SEC ".addr_space.1"
503 
504 enum libbpf_map_type {
505 	LIBBPF_MAP_UNSPEC,
506 	LIBBPF_MAP_DATA,
507 	LIBBPF_MAP_BSS,
508 	LIBBPF_MAP_RODATA,
509 	LIBBPF_MAP_KCONFIG,
510 };
511 
512 struct bpf_map_def {
513 	unsigned int type;
514 	unsigned int key_size;
515 	unsigned int value_size;
516 	unsigned int max_entries;
517 	unsigned int map_flags;
518 };
519 
520 struct bpf_map {
521 	struct bpf_object *obj;
522 	char *name;
523 	/* real_name is defined for special internal maps (.rodata*,
524 	 * .data*, .bss, .kconfig) and preserves their original ELF section
525 	 * name. This is important to be able to find corresponding BTF
526 	 * DATASEC information.
527 	 */
528 	char *real_name;
529 	int fd;
530 	int sec_idx;
531 	size_t sec_offset;
532 	int map_ifindex;
533 	int inner_map_fd;
534 	struct bpf_map_def def;
535 	__u32 numa_node;
536 	__u32 btf_var_idx;
537 	int mod_btf_fd;
538 	__u32 btf_key_type_id;
539 	__u32 btf_value_type_id;
540 	__u32 btf_vmlinux_value_type_id;
541 	enum libbpf_map_type libbpf_type;
542 	void *mmaped;
543 	struct bpf_struct_ops *st_ops;
544 	struct bpf_map *inner_map;
545 	void **init_slots;
546 	int init_slots_sz;
547 	char *pin_path;
548 	bool pinned;
549 	bool reused;
550 	bool autocreate;
551 	__u64 map_extra;
552 };
553 
554 enum extern_type {
555 	EXT_UNKNOWN,
556 	EXT_KCFG,
557 	EXT_KSYM,
558 };
559 
560 enum kcfg_type {
561 	KCFG_UNKNOWN,
562 	KCFG_CHAR,
563 	KCFG_BOOL,
564 	KCFG_INT,
565 	KCFG_TRISTATE,
566 	KCFG_CHAR_ARR,
567 };
568 
569 struct extern_desc {
570 	enum extern_type type;
571 	int sym_idx;
572 	int btf_id;
573 	int sec_btf_id;
574 	const char *name;
575 	char *essent_name;
576 	bool is_set;
577 	bool is_weak;
578 	union {
579 		struct {
580 			enum kcfg_type type;
581 			int sz;
582 			int align;
583 			int data_off;
584 			bool is_signed;
585 		} kcfg;
586 		struct {
587 			unsigned long long addr;
588 
589 			/* target btf_id of the corresponding kernel var. */
590 			int kernel_btf_obj_fd;
591 			int kernel_btf_id;
592 
593 			/* local btf_id of the ksym extern's type. */
594 			__u32 type_id;
595 			/* BTF fd index to be patched in for insn->off, this is
596 			 * 0 for vmlinux BTF, index in obj->fd_array for module
597 			 * BTF
598 			 */
599 			__s16 btf_fd_idx;
600 		} ksym;
601 	};
602 };
603 
604 struct module_btf {
605 	struct btf *btf;
606 	char *name;
607 	__u32 id;
608 	int fd;
609 	int fd_array_idx;
610 };
611 
612 enum sec_type {
613 	SEC_UNUSED = 0,
614 	SEC_RELO,
615 	SEC_BSS,
616 	SEC_DATA,
617 	SEC_RODATA,
618 	SEC_ST_OPS,
619 };
620 
621 struct elf_sec_desc {
622 	enum sec_type sec_type;
623 	Elf64_Shdr *shdr;
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 	Elf *elf;
632 	Elf64_Ehdr *ehdr;
633 	Elf_Data *symbols;
634 	Elf_Data *arena_data;
635 	size_t shstrndx; /* section index for section name strings */
636 	size_t strtabidx;
637 	struct elf_sec_desc *secs;
638 	size_t sec_cnt;
639 	int btf_maps_shndx;
640 	__u32 btf_maps_sec_btf_id;
641 	int text_shndx;
642 	int symbols_shndx;
643 	bool has_st_ops;
644 	int arena_data_shndx;
645 };
646 
647 struct usdt_manager;
648 
649 struct bpf_object {
650 	char name[BPF_OBJ_NAME_LEN];
651 	char license[64];
652 	__u32 kern_version;
653 
654 	struct bpf_program *programs;
655 	size_t nr_programs;
656 	struct bpf_map *maps;
657 	size_t nr_maps;
658 	size_t maps_cap;
659 
660 	char *kconfig;
661 	struct extern_desc *externs;
662 	int nr_extern;
663 	int kconfig_map_idx;
664 
665 	bool loaded;
666 	bool has_subcalls;
667 	bool has_rodata;
668 
669 	struct bpf_gen *gen_loader;
670 
671 	/* Information when doing ELF related work. Only valid if efile.elf is not NULL */
672 	struct elf_state efile;
673 
674 	struct btf *btf;
675 	struct btf_ext *btf_ext;
676 
677 	/* Parse and load BTF vmlinux if any of the programs in the object need
678 	 * it at load time.
679 	 */
680 	struct btf *btf_vmlinux;
681 	/* Path to the custom BTF to be used for BPF CO-RE relocations as an
682 	 * override for vmlinux BTF.
683 	 */
684 	char *btf_custom_path;
685 	/* vmlinux BTF override for CO-RE relocations */
686 	struct btf *btf_vmlinux_override;
687 	/* Lazily initialized kernel module BTFs */
688 	struct module_btf *btf_modules;
689 	bool btf_modules_loaded;
690 	size_t btf_module_cnt;
691 	size_t btf_module_cap;
692 
693 	/* optional log settings passed to BPF_BTF_LOAD and BPF_PROG_LOAD commands */
694 	char *log_buf;
695 	size_t log_size;
696 	__u32 log_level;
697 
698 	int *fd_array;
699 	size_t fd_array_cap;
700 	size_t fd_array_cnt;
701 
702 	struct usdt_manager *usdt_man;
703 
704 	struct bpf_map *arena_map;
705 	void *arena_data;
706 	size_t arena_data_sz;
707 
708 	struct kern_feature_cache *feat_cache;
709 	char *token_path;
710 	int token_fd;
711 
712 	char path[];
713 };
714 
715 static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
716 static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
717 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
718 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
719 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn);
720 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
721 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
722 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx);
723 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx);
724 
725 void bpf_program__unload(struct bpf_program *prog)
726 {
727 	if (!prog)
728 		return;
729 
730 	zclose(prog->fd);
731 
732 	zfree(&prog->func_info);
733 	zfree(&prog->line_info);
734 }
735 
736 static void bpf_program__exit(struct bpf_program *prog)
737 {
738 	if (!prog)
739 		return;
740 
741 	bpf_program__unload(prog);
742 	zfree(&prog->name);
743 	zfree(&prog->sec_name);
744 	zfree(&prog->insns);
745 	zfree(&prog->reloc_desc);
746 
747 	prog->nr_reloc = 0;
748 	prog->insns_cnt = 0;
749 	prog->sec_idx = -1;
750 }
751 
752 static bool insn_is_subprog_call(const struct bpf_insn *insn)
753 {
754 	return BPF_CLASS(insn->code) == BPF_JMP &&
755 	       BPF_OP(insn->code) == BPF_CALL &&
756 	       BPF_SRC(insn->code) == BPF_K &&
757 	       insn->src_reg == BPF_PSEUDO_CALL &&
758 	       insn->dst_reg == 0 &&
759 	       insn->off == 0;
760 }
761 
762 static bool is_call_insn(const struct bpf_insn *insn)
763 {
764 	return insn->code == (BPF_JMP | BPF_CALL);
765 }
766 
767 static bool insn_is_pseudo_func(struct bpf_insn *insn)
768 {
769 	return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
770 }
771 
772 static int
773 bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
774 		      const char *name, size_t sec_idx, const char *sec_name,
775 		      size_t sec_off, void *insn_data, size_t insn_data_sz)
776 {
777 	if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
778 		pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
779 			sec_name, name, sec_off, insn_data_sz);
780 		return -EINVAL;
781 	}
782 
783 	memset(prog, 0, sizeof(*prog));
784 	prog->obj = obj;
785 
786 	prog->sec_idx = sec_idx;
787 	prog->sec_insn_off = sec_off / BPF_INSN_SZ;
788 	prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
789 	/* insns_cnt can later be increased by appending used subprograms */
790 	prog->insns_cnt = prog->sec_insn_cnt;
791 
792 	prog->type = BPF_PROG_TYPE_UNSPEC;
793 	prog->fd = -1;
794 	prog->exception_cb_idx = -1;
795 
796 	/* libbpf's convention for SEC("?abc...") is that it's just like
797 	 * SEC("abc...") but the corresponding bpf_program starts out with
798 	 * autoload set to false.
799 	 */
800 	if (sec_name[0] == '?') {
801 		prog->autoload = false;
802 		/* from now on forget there was ? in section name */
803 		sec_name++;
804 	} else {
805 		prog->autoload = true;
806 	}
807 
808 	prog->autoattach = true;
809 
810 	/* inherit object's log_level */
811 	prog->log_level = obj->log_level;
812 
813 	prog->sec_name = strdup(sec_name);
814 	if (!prog->sec_name)
815 		goto errout;
816 
817 	prog->name = strdup(name);
818 	if (!prog->name)
819 		goto errout;
820 
821 	prog->insns = malloc(insn_data_sz);
822 	if (!prog->insns)
823 		goto errout;
824 	memcpy(prog->insns, insn_data, insn_data_sz);
825 
826 	return 0;
827 errout:
828 	pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
829 	bpf_program__exit(prog);
830 	return -ENOMEM;
831 }
832 
833 static int
834 bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
835 			 const char *sec_name, int sec_idx)
836 {
837 	Elf_Data *symbols = obj->efile.symbols;
838 	struct bpf_program *prog, *progs;
839 	void *data = sec_data->d_buf;
840 	size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
841 	int nr_progs, err, i;
842 	const char *name;
843 	Elf64_Sym *sym;
844 
845 	progs = obj->programs;
846 	nr_progs = obj->nr_programs;
847 	nr_syms = symbols->d_size / sizeof(Elf64_Sym);
848 
849 	for (i = 0; i < nr_syms; i++) {
850 		sym = elf_sym_by_idx(obj, i);
851 
852 		if (sym->st_shndx != sec_idx)
853 			continue;
854 		if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC)
855 			continue;
856 
857 		prog_sz = sym->st_size;
858 		sec_off = sym->st_value;
859 
860 		name = elf_sym_str(obj, sym->st_name);
861 		if (!name) {
862 			pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
863 				sec_name, sec_off);
864 			return -LIBBPF_ERRNO__FORMAT;
865 		}
866 
867 		if (sec_off + prog_sz > sec_sz) {
868 			pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
869 				sec_name, sec_off);
870 			return -LIBBPF_ERRNO__FORMAT;
871 		}
872 
873 		if (sec_idx != obj->efile.text_shndx && ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
874 			pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
875 			return -ENOTSUP;
876 		}
877 
878 		pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
879 			 sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
880 
881 		progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
882 		if (!progs) {
883 			/*
884 			 * In this case the original obj->programs
885 			 * is still valid, so don't need special treat for
886 			 * bpf_close_object().
887 			 */
888 			pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
889 				sec_name, name);
890 			return -ENOMEM;
891 		}
892 		obj->programs = progs;
893 
894 		prog = &progs[nr_progs];
895 
896 		err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
897 					    sec_off, data + sec_off, prog_sz);
898 		if (err)
899 			return err;
900 
901 		if (ELF64_ST_BIND(sym->st_info) != STB_LOCAL)
902 			prog->sym_global = true;
903 
904 		/* if function is a global/weak symbol, but has restricted
905 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
906 		 * as static to enable more permissive BPF verification mode
907 		 * with more outside context available to BPF verifier
908 		 */
909 		if (prog->sym_global && (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
910 		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL))
911 			prog->mark_btf_static = true;
912 
913 		nr_progs++;
914 		obj->nr_programs = nr_progs;
915 	}
916 
917 	return 0;
918 }
919 
920 static const struct btf_member *
921 find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
922 {
923 	struct btf_member *m;
924 	int i;
925 
926 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
927 		if (btf_member_bit_offset(t, i) == bit_offset)
928 			return m;
929 	}
930 
931 	return NULL;
932 }
933 
934 static const struct btf_member *
935 find_member_by_name(const struct btf *btf, const struct btf_type *t,
936 		    const char *name)
937 {
938 	struct btf_member *m;
939 	int i;
940 
941 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
942 		if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
943 			return m;
944 	}
945 
946 	return NULL;
947 }
948 
949 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
950 			    __u16 kind, struct btf **res_btf,
951 			    struct module_btf **res_mod_btf);
952 
953 #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
954 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
955 				   const char *name, __u32 kind);
956 
957 static int
958 find_struct_ops_kern_types(struct bpf_object *obj, const char *tname_raw,
959 			   struct module_btf **mod_btf,
960 			   const struct btf_type **type, __u32 *type_id,
961 			   const struct btf_type **vtype, __u32 *vtype_id,
962 			   const struct btf_member **data_member)
963 {
964 	const struct btf_type *kern_type, *kern_vtype;
965 	const struct btf_member *kern_data_member;
966 	struct btf *btf;
967 	__s32 kern_vtype_id, kern_type_id;
968 	char tname[256];
969 	__u32 i;
970 
971 	snprintf(tname, sizeof(tname), "%.*s",
972 		 (int)bpf_core_essential_name_len(tname_raw), tname_raw);
973 
974 	kern_type_id = find_ksym_btf_id(obj, tname, BTF_KIND_STRUCT,
975 					&btf, mod_btf);
976 	if (kern_type_id < 0) {
977 		pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n",
978 			tname);
979 		return kern_type_id;
980 	}
981 	kern_type = btf__type_by_id(btf, kern_type_id);
982 
983 	/* Find the corresponding "map_value" type that will be used
984 	 * in map_update(BPF_MAP_TYPE_STRUCT_OPS).  For example,
985 	 * find "struct bpf_struct_ops_tcp_congestion_ops" from the
986 	 * btf_vmlinux.
987 	 */
988 	kern_vtype_id = find_btf_by_prefix_kind(btf, STRUCT_OPS_VALUE_PREFIX,
989 						tname, BTF_KIND_STRUCT);
990 	if (kern_vtype_id < 0) {
991 		pr_warn("struct_ops init_kern: struct %s%s is not found in kernel BTF\n",
992 			STRUCT_OPS_VALUE_PREFIX, tname);
993 		return kern_vtype_id;
994 	}
995 	kern_vtype = btf__type_by_id(btf, kern_vtype_id);
996 
997 	/* Find "struct tcp_congestion_ops" from
998 	 * struct bpf_struct_ops_tcp_congestion_ops {
999 	 *	[ ... ]
1000 	 *	struct tcp_congestion_ops data;
1001 	 * }
1002 	 */
1003 	kern_data_member = btf_members(kern_vtype);
1004 	for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
1005 		if (kern_data_member->type == kern_type_id)
1006 			break;
1007 	}
1008 	if (i == btf_vlen(kern_vtype)) {
1009 		pr_warn("struct_ops init_kern: struct %s data is not found in struct %s%s\n",
1010 			tname, STRUCT_OPS_VALUE_PREFIX, tname);
1011 		return -EINVAL;
1012 	}
1013 
1014 	*type = kern_type;
1015 	*type_id = kern_type_id;
1016 	*vtype = kern_vtype;
1017 	*vtype_id = kern_vtype_id;
1018 	*data_member = kern_data_member;
1019 
1020 	return 0;
1021 }
1022 
1023 static bool bpf_map__is_struct_ops(const struct bpf_map *map)
1024 {
1025 	return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
1026 }
1027 
1028 static bool is_valid_st_ops_program(struct bpf_object *obj,
1029 				    const struct bpf_program *prog)
1030 {
1031 	int i;
1032 
1033 	for (i = 0; i < obj->nr_programs; i++) {
1034 		if (&obj->programs[i] == prog)
1035 			return prog->type == BPF_PROG_TYPE_STRUCT_OPS;
1036 	}
1037 
1038 	return false;
1039 }
1040 
1041 /* For each struct_ops program P, referenced from some struct_ops map M,
1042  * enable P.autoload if there are Ms for which M.autocreate is true,
1043  * disable P.autoload if for all Ms M.autocreate is false.
1044  * Don't change P.autoload for programs that are not referenced from any maps.
1045  */
1046 static int bpf_object_adjust_struct_ops_autoload(struct bpf_object *obj)
1047 {
1048 	struct bpf_program *prog, *slot_prog;
1049 	struct bpf_map *map;
1050 	int i, j, k, vlen;
1051 
1052 	for (i = 0; i < obj->nr_programs; ++i) {
1053 		int should_load = false;
1054 		int use_cnt = 0;
1055 
1056 		prog = &obj->programs[i];
1057 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS)
1058 			continue;
1059 
1060 		for (j = 0; j < obj->nr_maps; ++j) {
1061 			map = &obj->maps[j];
1062 			if (!bpf_map__is_struct_ops(map))
1063 				continue;
1064 
1065 			vlen = btf_vlen(map->st_ops->type);
1066 			for (k = 0; k < vlen; ++k) {
1067 				slot_prog = map->st_ops->progs[k];
1068 				if (prog != slot_prog)
1069 					continue;
1070 
1071 				use_cnt++;
1072 				if (map->autocreate)
1073 					should_load = true;
1074 			}
1075 		}
1076 		if (use_cnt)
1077 			prog->autoload = should_load;
1078 	}
1079 
1080 	return 0;
1081 }
1082 
1083 /* Init the map's fields that depend on kern_btf */
1084 static int bpf_map__init_kern_struct_ops(struct bpf_map *map)
1085 {
1086 	const struct btf_member *member, *kern_member, *kern_data_member;
1087 	const struct btf_type *type, *kern_type, *kern_vtype;
1088 	__u32 i, kern_type_id, kern_vtype_id, kern_data_off;
1089 	struct bpf_object *obj = map->obj;
1090 	const struct btf *btf = obj->btf;
1091 	struct bpf_struct_ops *st_ops;
1092 	const struct btf *kern_btf;
1093 	struct module_btf *mod_btf;
1094 	void *data, *kern_data;
1095 	const char *tname;
1096 	int err;
1097 
1098 	st_ops = map->st_ops;
1099 	type = st_ops->type;
1100 	tname = st_ops->tname;
1101 	err = find_struct_ops_kern_types(obj, tname, &mod_btf,
1102 					 &kern_type, &kern_type_id,
1103 					 &kern_vtype, &kern_vtype_id,
1104 					 &kern_data_member);
1105 	if (err)
1106 		return err;
1107 
1108 	kern_btf = mod_btf ? mod_btf->btf : obj->btf_vmlinux;
1109 
1110 	pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
1111 		 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
1112 
1113 	map->mod_btf_fd = mod_btf ? mod_btf->fd : -1;
1114 	map->def.value_size = kern_vtype->size;
1115 	map->btf_vmlinux_value_type_id = kern_vtype_id;
1116 
1117 	st_ops->kern_vdata = calloc(1, kern_vtype->size);
1118 	if (!st_ops->kern_vdata)
1119 		return -ENOMEM;
1120 
1121 	data = st_ops->data;
1122 	kern_data_off = kern_data_member->offset / 8;
1123 	kern_data = st_ops->kern_vdata + kern_data_off;
1124 
1125 	member = btf_members(type);
1126 	for (i = 0; i < btf_vlen(type); i++, member++) {
1127 		const struct btf_type *mtype, *kern_mtype;
1128 		__u32 mtype_id, kern_mtype_id;
1129 		void *mdata, *kern_mdata;
1130 		__s64 msize, kern_msize;
1131 		__u32 moff, kern_moff;
1132 		__u32 kern_member_idx;
1133 		const char *mname;
1134 
1135 		mname = btf__name_by_offset(btf, member->name_off);
1136 		moff = member->offset / 8;
1137 		mdata = data + moff;
1138 		msize = btf__resolve_size(btf, member->type);
1139 		if (msize < 0) {
1140 			pr_warn("struct_ops init_kern %s: failed to resolve the size of member %s\n",
1141 				map->name, mname);
1142 			return msize;
1143 		}
1144 
1145 		kern_member = find_member_by_name(kern_btf, kern_type, mname);
1146 		if (!kern_member) {
1147 			/* Skip all zeros or null fields if they are not
1148 			 * presented in the kernel BTF.
1149 			 */
1150 			if (libbpf_is_mem_zeroed(mdata, msize)) {
1151 				pr_info("struct_ops %s: member %s not found in kernel, skipping it as it's set to zero\n",
1152 					map->name, mname);
1153 				continue;
1154 			}
1155 
1156 			pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
1157 				map->name, mname);
1158 			return -ENOTSUP;
1159 		}
1160 
1161 		kern_member_idx = kern_member - btf_members(kern_type);
1162 		if (btf_member_bitfield_size(type, i) ||
1163 		    btf_member_bitfield_size(kern_type, kern_member_idx)) {
1164 			pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
1165 				map->name, mname);
1166 			return -ENOTSUP;
1167 		}
1168 
1169 		kern_moff = kern_member->offset / 8;
1170 		kern_mdata = kern_data + kern_moff;
1171 
1172 		mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
1173 		kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
1174 						    &kern_mtype_id);
1175 		if (BTF_INFO_KIND(mtype->info) !=
1176 		    BTF_INFO_KIND(kern_mtype->info)) {
1177 			pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
1178 				map->name, mname, BTF_INFO_KIND(mtype->info),
1179 				BTF_INFO_KIND(kern_mtype->info));
1180 			return -ENOTSUP;
1181 		}
1182 
1183 		if (btf_is_ptr(mtype)) {
1184 			struct bpf_program *prog;
1185 
1186 			/* Update the value from the shadow type */
1187 			prog = *(void **)mdata;
1188 			st_ops->progs[i] = prog;
1189 			if (!prog)
1190 				continue;
1191 			if (!is_valid_st_ops_program(obj, prog)) {
1192 				pr_warn("struct_ops init_kern %s: member %s is not a struct_ops program\n",
1193 					map->name, mname);
1194 				return -ENOTSUP;
1195 			}
1196 
1197 			kern_mtype = skip_mods_and_typedefs(kern_btf,
1198 							    kern_mtype->type,
1199 							    &kern_mtype_id);
1200 
1201 			/* mtype->type must be a func_proto which was
1202 			 * guaranteed in bpf_object__collect_st_ops_relos(),
1203 			 * so only check kern_mtype for func_proto here.
1204 			 */
1205 			if (!btf_is_func_proto(kern_mtype)) {
1206 				pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
1207 					map->name, mname);
1208 				return -ENOTSUP;
1209 			}
1210 
1211 			if (mod_btf)
1212 				prog->attach_btf_obj_fd = mod_btf->fd;
1213 
1214 			/* if we haven't yet processed this BPF program, record proper
1215 			 * attach_btf_id and member_idx
1216 			 */
1217 			if (!prog->attach_btf_id) {
1218 				prog->attach_btf_id = kern_type_id;
1219 				prog->expected_attach_type = kern_member_idx;
1220 			}
1221 
1222 			/* struct_ops BPF prog can be re-used between multiple
1223 			 * .struct_ops & .struct_ops.link as long as it's the
1224 			 * same struct_ops struct definition and the same
1225 			 * function pointer field
1226 			 */
1227 			if (prog->attach_btf_id != kern_type_id) {
1228 				pr_warn("struct_ops init_kern %s func ptr %s: invalid reuse of prog %s in sec %s with type %u: attach_btf_id %u != kern_type_id %u\n",
1229 					map->name, mname, prog->name, prog->sec_name, prog->type,
1230 					prog->attach_btf_id, kern_type_id);
1231 				return -EINVAL;
1232 			}
1233 			if (prog->expected_attach_type != kern_member_idx) {
1234 				pr_warn("struct_ops init_kern %s func ptr %s: invalid reuse of prog %s in sec %s with type %u: expected_attach_type %u != kern_member_idx %u\n",
1235 					map->name, mname, prog->name, prog->sec_name, prog->type,
1236 					prog->expected_attach_type, kern_member_idx);
1237 				return -EINVAL;
1238 			}
1239 
1240 			st_ops->kern_func_off[i] = kern_data_off + kern_moff;
1241 
1242 			pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
1243 				 map->name, mname, prog->name, moff,
1244 				 kern_moff);
1245 
1246 			continue;
1247 		}
1248 
1249 		kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
1250 		if (kern_msize < 0 || msize != kern_msize) {
1251 			pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
1252 				map->name, mname, (ssize_t)msize,
1253 				(ssize_t)kern_msize);
1254 			return -ENOTSUP;
1255 		}
1256 
1257 		pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
1258 			 map->name, mname, (unsigned int)msize,
1259 			 moff, kern_moff);
1260 		memcpy(kern_mdata, mdata, msize);
1261 	}
1262 
1263 	return 0;
1264 }
1265 
1266 static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
1267 {
1268 	struct bpf_map *map;
1269 	size_t i;
1270 	int err;
1271 
1272 	for (i = 0; i < obj->nr_maps; i++) {
1273 		map = &obj->maps[i];
1274 
1275 		if (!bpf_map__is_struct_ops(map))
1276 			continue;
1277 
1278 		if (!map->autocreate)
1279 			continue;
1280 
1281 		err = bpf_map__init_kern_struct_ops(map);
1282 		if (err)
1283 			return err;
1284 	}
1285 
1286 	return 0;
1287 }
1288 
1289 static int init_struct_ops_maps(struct bpf_object *obj, const char *sec_name,
1290 				int shndx, Elf_Data *data)
1291 {
1292 	const struct btf_type *type, *datasec;
1293 	const struct btf_var_secinfo *vsi;
1294 	struct bpf_struct_ops *st_ops;
1295 	const char *tname, *var_name;
1296 	__s32 type_id, datasec_id;
1297 	const struct btf *btf;
1298 	struct bpf_map *map;
1299 	__u32 i;
1300 
1301 	if (shndx == -1)
1302 		return 0;
1303 
1304 	btf = obj->btf;
1305 	datasec_id = btf__find_by_name_kind(btf, sec_name,
1306 					    BTF_KIND_DATASEC);
1307 	if (datasec_id < 0) {
1308 		pr_warn("struct_ops init: DATASEC %s not found\n",
1309 			sec_name);
1310 		return -EINVAL;
1311 	}
1312 
1313 	datasec = btf__type_by_id(btf, datasec_id);
1314 	vsi = btf_var_secinfos(datasec);
1315 	for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
1316 		type = btf__type_by_id(obj->btf, vsi->type);
1317 		var_name = btf__name_by_offset(obj->btf, type->name_off);
1318 
1319 		type_id = btf__resolve_type(obj->btf, vsi->type);
1320 		if (type_id < 0) {
1321 			pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
1322 				vsi->type, sec_name);
1323 			return -EINVAL;
1324 		}
1325 
1326 		type = btf__type_by_id(obj->btf, type_id);
1327 		tname = btf__name_by_offset(obj->btf, type->name_off);
1328 		if (!tname[0]) {
1329 			pr_warn("struct_ops init: anonymous type is not supported\n");
1330 			return -ENOTSUP;
1331 		}
1332 		if (!btf_is_struct(type)) {
1333 			pr_warn("struct_ops init: %s is not a struct\n", tname);
1334 			return -EINVAL;
1335 		}
1336 
1337 		map = bpf_object__add_map(obj);
1338 		if (IS_ERR(map))
1339 			return PTR_ERR(map);
1340 
1341 		map->sec_idx = shndx;
1342 		map->sec_offset = vsi->offset;
1343 		map->name = strdup(var_name);
1344 		if (!map->name)
1345 			return -ENOMEM;
1346 		map->btf_value_type_id = type_id;
1347 
1348 		/* Follow same convention as for programs autoload:
1349 		 * SEC("?.struct_ops") means map is not created by default.
1350 		 */
1351 		if (sec_name[0] == '?') {
1352 			map->autocreate = false;
1353 			/* from now on forget there was ? in section name */
1354 			sec_name++;
1355 		}
1356 
1357 		map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
1358 		map->def.key_size = sizeof(int);
1359 		map->def.value_size = type->size;
1360 		map->def.max_entries = 1;
1361 		map->def.map_flags = strcmp(sec_name, STRUCT_OPS_LINK_SEC) == 0 ? BPF_F_LINK : 0;
1362 
1363 		map->st_ops = calloc(1, sizeof(*map->st_ops));
1364 		if (!map->st_ops)
1365 			return -ENOMEM;
1366 		st_ops = map->st_ops;
1367 		st_ops->data = malloc(type->size);
1368 		st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1369 		st_ops->kern_func_off = malloc(btf_vlen(type) *
1370 					       sizeof(*st_ops->kern_func_off));
1371 		if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1372 			return -ENOMEM;
1373 
1374 		if (vsi->offset + type->size > data->d_size) {
1375 			pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1376 				var_name, sec_name);
1377 			return -EINVAL;
1378 		}
1379 
1380 		memcpy(st_ops->data,
1381 		       data->d_buf + vsi->offset,
1382 		       type->size);
1383 		st_ops->tname = tname;
1384 		st_ops->type = type;
1385 		st_ops->type_id = type_id;
1386 
1387 		pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
1388 			 tname, type_id, var_name, vsi->offset);
1389 	}
1390 
1391 	return 0;
1392 }
1393 
1394 static int bpf_object_init_struct_ops(struct bpf_object *obj)
1395 {
1396 	const char *sec_name;
1397 	int sec_idx, err;
1398 
1399 	for (sec_idx = 0; sec_idx < obj->efile.sec_cnt; ++sec_idx) {
1400 		struct elf_sec_desc *desc = &obj->efile.secs[sec_idx];
1401 
1402 		if (desc->sec_type != SEC_ST_OPS)
1403 			continue;
1404 
1405 		sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1406 		if (!sec_name)
1407 			return -LIBBPF_ERRNO__FORMAT;
1408 
1409 		err = init_struct_ops_maps(obj, sec_name, sec_idx, desc->data);
1410 		if (err)
1411 			return err;
1412 	}
1413 
1414 	return 0;
1415 }
1416 
1417 static struct bpf_object *bpf_object__new(const char *path,
1418 					  const void *obj_buf,
1419 					  size_t obj_buf_sz,
1420 					  const char *obj_name)
1421 {
1422 	struct bpf_object *obj;
1423 	char *end;
1424 
1425 	obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1426 	if (!obj) {
1427 		pr_warn("alloc memory failed for %s\n", path);
1428 		return ERR_PTR(-ENOMEM);
1429 	}
1430 
1431 	strcpy(obj->path, path);
1432 	if (obj_name) {
1433 		libbpf_strlcpy(obj->name, obj_name, sizeof(obj->name));
1434 	} else {
1435 		/* Using basename() GNU version which doesn't modify arg. */
1436 		libbpf_strlcpy(obj->name, basename((void *)path), sizeof(obj->name));
1437 		end = strchr(obj->name, '.');
1438 		if (end)
1439 			*end = 0;
1440 	}
1441 
1442 	obj->efile.fd = -1;
1443 	/*
1444 	 * Caller of this function should also call
1445 	 * bpf_object__elf_finish() after data collection to return
1446 	 * obj_buf to user. If not, we should duplicate the buffer to
1447 	 * avoid user freeing them before elf finish.
1448 	 */
1449 	obj->efile.obj_buf = obj_buf;
1450 	obj->efile.obj_buf_sz = obj_buf_sz;
1451 	obj->efile.btf_maps_shndx = -1;
1452 	obj->kconfig_map_idx = -1;
1453 
1454 	obj->kern_version = get_kernel_version();
1455 	obj->loaded = false;
1456 
1457 	return obj;
1458 }
1459 
1460 static void bpf_object__elf_finish(struct bpf_object *obj)
1461 {
1462 	if (!obj->efile.elf)
1463 		return;
1464 
1465 	elf_end(obj->efile.elf);
1466 	obj->efile.elf = NULL;
1467 	obj->efile.symbols = NULL;
1468 	obj->efile.arena_data = NULL;
1469 
1470 	zfree(&obj->efile.secs);
1471 	obj->efile.sec_cnt = 0;
1472 	zclose(obj->efile.fd);
1473 	obj->efile.obj_buf = NULL;
1474 	obj->efile.obj_buf_sz = 0;
1475 }
1476 
1477 static int bpf_object__elf_init(struct bpf_object *obj)
1478 {
1479 	Elf64_Ehdr *ehdr;
1480 	int err = 0;
1481 	Elf *elf;
1482 
1483 	if (obj->efile.elf) {
1484 		pr_warn("elf: init internal error\n");
1485 		return -LIBBPF_ERRNO__LIBELF;
1486 	}
1487 
1488 	if (obj->efile.obj_buf_sz > 0) {
1489 		/* obj_buf should have been validated by bpf_object__open_mem(). */
1490 		elf = elf_memory((char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
1491 	} else {
1492 		obj->efile.fd = open(obj->path, O_RDONLY | O_CLOEXEC);
1493 		if (obj->efile.fd < 0) {
1494 			char errmsg[STRERR_BUFSIZE], *cp;
1495 
1496 			err = -errno;
1497 			cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
1498 			pr_warn("elf: failed to open %s: %s\n", obj->path, cp);
1499 			return err;
1500 		}
1501 
1502 		elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1503 	}
1504 
1505 	if (!elf) {
1506 		pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
1507 		err = -LIBBPF_ERRNO__LIBELF;
1508 		goto errout;
1509 	}
1510 
1511 	obj->efile.elf = elf;
1512 
1513 	if (elf_kind(elf) != ELF_K_ELF) {
1514 		err = -LIBBPF_ERRNO__FORMAT;
1515 		pr_warn("elf: '%s' is not a proper ELF object\n", obj->path);
1516 		goto errout;
1517 	}
1518 
1519 	if (gelf_getclass(elf) != ELFCLASS64) {
1520 		err = -LIBBPF_ERRNO__FORMAT;
1521 		pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path);
1522 		goto errout;
1523 	}
1524 
1525 	obj->efile.ehdr = ehdr = elf64_getehdr(elf);
1526 	if (!obj->efile.ehdr) {
1527 		pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
1528 		err = -LIBBPF_ERRNO__FORMAT;
1529 		goto errout;
1530 	}
1531 
1532 	if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
1533 		pr_warn("elf: failed to get section names section index for %s: %s\n",
1534 			obj->path, elf_errmsg(-1));
1535 		err = -LIBBPF_ERRNO__FORMAT;
1536 		goto errout;
1537 	}
1538 
1539 	/* ELF is corrupted/truncated, avoid calling elf_strptr. */
1540 	if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
1541 		pr_warn("elf: failed to get section names strings from %s: %s\n",
1542 			obj->path, elf_errmsg(-1));
1543 		err = -LIBBPF_ERRNO__FORMAT;
1544 		goto errout;
1545 	}
1546 
1547 	/* Old LLVM set e_machine to EM_NONE */
1548 	if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
1549 		pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
1550 		err = -LIBBPF_ERRNO__FORMAT;
1551 		goto errout;
1552 	}
1553 
1554 	return 0;
1555 errout:
1556 	bpf_object__elf_finish(obj);
1557 	return err;
1558 }
1559 
1560 static int bpf_object__check_endianness(struct bpf_object *obj)
1561 {
1562 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1563 	if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2LSB)
1564 		return 0;
1565 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1566 	if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2MSB)
1567 		return 0;
1568 #else
1569 # error "Unrecognized __BYTE_ORDER__"
1570 #endif
1571 	pr_warn("elf: endianness mismatch in %s.\n", obj->path);
1572 	return -LIBBPF_ERRNO__ENDIAN;
1573 }
1574 
1575 static int
1576 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1577 {
1578 	if (!data) {
1579 		pr_warn("invalid license section in %s\n", obj->path);
1580 		return -LIBBPF_ERRNO__FORMAT;
1581 	}
1582 	/* libbpf_strlcpy() only copies first N - 1 bytes, so size + 1 won't
1583 	 * go over allowed ELF data section buffer
1584 	 */
1585 	libbpf_strlcpy(obj->license, data, min(size + 1, sizeof(obj->license)));
1586 	pr_debug("license of %s is %s\n", obj->path, obj->license);
1587 	return 0;
1588 }
1589 
1590 static int
1591 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1592 {
1593 	__u32 kver;
1594 
1595 	if (!data || size != sizeof(kver)) {
1596 		pr_warn("invalid kver section in %s\n", obj->path);
1597 		return -LIBBPF_ERRNO__FORMAT;
1598 	}
1599 	memcpy(&kver, data, sizeof(kver));
1600 	obj->kern_version = kver;
1601 	pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1602 	return 0;
1603 }
1604 
1605 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1606 {
1607 	if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1608 	    type == BPF_MAP_TYPE_HASH_OF_MAPS)
1609 		return true;
1610 	return false;
1611 }
1612 
1613 static int find_elf_sec_sz(const struct bpf_object *obj, const char *name, __u32 *size)
1614 {
1615 	Elf_Data *data;
1616 	Elf_Scn *scn;
1617 
1618 	if (!name)
1619 		return -EINVAL;
1620 
1621 	scn = elf_sec_by_name(obj, name);
1622 	data = elf_sec_data(obj, scn);
1623 	if (data) {
1624 		*size = data->d_size;
1625 		return 0; /* found it */
1626 	}
1627 
1628 	return -ENOENT;
1629 }
1630 
1631 static Elf64_Sym *find_elf_var_sym(const struct bpf_object *obj, const char *name)
1632 {
1633 	Elf_Data *symbols = obj->efile.symbols;
1634 	const char *sname;
1635 	size_t si;
1636 
1637 	for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
1638 		Elf64_Sym *sym = elf_sym_by_idx(obj, si);
1639 
1640 		if (ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)
1641 			continue;
1642 
1643 		if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL &&
1644 		    ELF64_ST_BIND(sym->st_info) != STB_WEAK)
1645 			continue;
1646 
1647 		sname = elf_sym_str(obj, sym->st_name);
1648 		if (!sname) {
1649 			pr_warn("failed to get sym name string for var %s\n", name);
1650 			return ERR_PTR(-EIO);
1651 		}
1652 		if (strcmp(name, sname) == 0)
1653 			return sym;
1654 	}
1655 
1656 	return ERR_PTR(-ENOENT);
1657 }
1658 
1659 /* Some versions of Android don't provide memfd_create() in their libc
1660  * implementation, so avoid complications and just go straight to Linux
1661  * syscall.
1662  */
1663 static int sys_memfd_create(const char *name, unsigned flags)
1664 {
1665 	return syscall(__NR_memfd_create, name, flags);
1666 }
1667 
1668 #ifndef MFD_CLOEXEC
1669 #define MFD_CLOEXEC 0x0001U
1670 #endif
1671 
1672 static int create_placeholder_fd(void)
1673 {
1674 	int fd;
1675 
1676 	fd = ensure_good_fd(sys_memfd_create("libbpf-placeholder-fd", MFD_CLOEXEC));
1677 	if (fd < 0)
1678 		return -errno;
1679 	return fd;
1680 }
1681 
1682 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1683 {
1684 	struct bpf_map *map;
1685 	int err;
1686 
1687 	err = libbpf_ensure_mem((void **)&obj->maps, &obj->maps_cap,
1688 				sizeof(*obj->maps), obj->nr_maps + 1);
1689 	if (err)
1690 		return ERR_PTR(err);
1691 
1692 	map = &obj->maps[obj->nr_maps++];
1693 	map->obj = obj;
1694 	/* Preallocate map FD without actually creating BPF map just yet.
1695 	 * These map FD "placeholders" will be reused later without changing
1696 	 * FD value when map is actually created in the kernel.
1697 	 *
1698 	 * This is useful to be able to perform BPF program relocations
1699 	 * without having to create BPF maps before that step. This allows us
1700 	 * to finalize and load BTF very late in BPF object's loading phase,
1701 	 * right before BPF maps have to be created and BPF programs have to
1702 	 * be loaded. By having these map FD placeholders we can perform all
1703 	 * the sanitizations, relocations, and any other adjustments before we
1704 	 * start creating actual BPF kernel objects (BTF, maps, progs).
1705 	 */
1706 	map->fd = create_placeholder_fd();
1707 	if (map->fd < 0)
1708 		return ERR_PTR(map->fd);
1709 	map->inner_map_fd = -1;
1710 	map->autocreate = true;
1711 
1712 	return map;
1713 }
1714 
1715 static size_t array_map_mmap_sz(unsigned int value_sz, unsigned int max_entries)
1716 {
1717 	const long page_sz = sysconf(_SC_PAGE_SIZE);
1718 	size_t map_sz;
1719 
1720 	map_sz = (size_t)roundup(value_sz, 8) * max_entries;
1721 	map_sz = roundup(map_sz, page_sz);
1722 	return map_sz;
1723 }
1724 
1725 static size_t bpf_map_mmap_sz(const struct bpf_map *map)
1726 {
1727 	const long page_sz = sysconf(_SC_PAGE_SIZE);
1728 
1729 	switch (map->def.type) {
1730 	case BPF_MAP_TYPE_ARRAY:
1731 		return array_map_mmap_sz(map->def.value_size, map->def.max_entries);
1732 	case BPF_MAP_TYPE_ARENA:
1733 		return page_sz * map->def.max_entries;
1734 	default:
1735 		return 0; /* not supported */
1736 	}
1737 }
1738 
1739 static int bpf_map_mmap_resize(struct bpf_map *map, size_t old_sz, size_t new_sz)
1740 {
1741 	void *mmaped;
1742 
1743 	if (!map->mmaped)
1744 		return -EINVAL;
1745 
1746 	if (old_sz == new_sz)
1747 		return 0;
1748 
1749 	mmaped = mmap(NULL, new_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1750 	if (mmaped == MAP_FAILED)
1751 		return -errno;
1752 
1753 	memcpy(mmaped, map->mmaped, min(old_sz, new_sz));
1754 	munmap(map->mmaped, old_sz);
1755 	map->mmaped = mmaped;
1756 	return 0;
1757 }
1758 
1759 static char *internal_map_name(struct bpf_object *obj, const char *real_name)
1760 {
1761 	char map_name[BPF_OBJ_NAME_LEN], *p;
1762 	int pfx_len, sfx_len = max((size_t)7, strlen(real_name));
1763 
1764 	/* This is one of the more confusing parts of libbpf for various
1765 	 * reasons, some of which are historical. The original idea for naming
1766 	 * internal names was to include as much of BPF object name prefix as
1767 	 * possible, so that it can be distinguished from similar internal
1768 	 * maps of a different BPF object.
1769 	 * As an example, let's say we have bpf_object named 'my_object_name'
1770 	 * and internal map corresponding to '.rodata' ELF section. The final
1771 	 * map name advertised to user and to the kernel will be
1772 	 * 'my_objec.rodata', taking first 8 characters of object name and
1773 	 * entire 7 characters of '.rodata'.
1774 	 * Somewhat confusingly, if internal map ELF section name is shorter
1775 	 * than 7 characters, e.g., '.bss', we still reserve 7 characters
1776 	 * for the suffix, even though we only have 4 actual characters, and
1777 	 * resulting map will be called 'my_objec.bss', not even using all 15
1778 	 * characters allowed by the kernel. Oh well, at least the truncated
1779 	 * object name is somewhat consistent in this case. But if the map
1780 	 * name is '.kconfig', we'll still have entirety of '.kconfig' added
1781 	 * (8 chars) and thus will be left with only first 7 characters of the
1782 	 * object name ('my_obje'). Happy guessing, user, that the final map
1783 	 * name will be "my_obje.kconfig".
1784 	 * Now, with libbpf starting to support arbitrarily named .rodata.*
1785 	 * and .data.* data sections, it's possible that ELF section name is
1786 	 * longer than allowed 15 chars, so we now need to be careful to take
1787 	 * only up to 15 first characters of ELF name, taking no BPF object
1788 	 * name characters at all. So '.rodata.abracadabra' will result in
1789 	 * '.rodata.abracad' kernel and user-visible name.
1790 	 * We need to keep this convoluted logic intact for .data, .bss and
1791 	 * .rodata maps, but for new custom .data.custom and .rodata.custom
1792 	 * maps we use their ELF names as is, not prepending bpf_object name
1793 	 * in front. We still need to truncate them to 15 characters for the
1794 	 * kernel. Full name can be recovered for such maps by using DATASEC
1795 	 * BTF type associated with such map's value type, though.
1796 	 */
1797 	if (sfx_len >= BPF_OBJ_NAME_LEN)
1798 		sfx_len = BPF_OBJ_NAME_LEN - 1;
1799 
1800 	/* if there are two or more dots in map name, it's a custom dot map */
1801 	if (strchr(real_name + 1, '.') != NULL)
1802 		pfx_len = 0;
1803 	else
1804 		pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
1805 
1806 	snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1807 		 sfx_len, real_name);
1808 
1809 	/* sanitise map name to characters allowed by kernel */
1810 	for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1811 		if (!isalnum(*p) && *p != '_' && *p != '.')
1812 			*p = '_';
1813 
1814 	return strdup(map_name);
1815 }
1816 
1817 static int
1818 map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map);
1819 
1820 /* Internal BPF map is mmap()'able only if at least one of corresponding
1821  * DATASEC's VARs are to be exposed through BPF skeleton. I.e., it's a GLOBAL
1822  * variable and it's not marked as __hidden (which turns it into, effectively,
1823  * a STATIC variable).
1824  */
1825 static bool map_is_mmapable(struct bpf_object *obj, struct bpf_map *map)
1826 {
1827 	const struct btf_type *t, *vt;
1828 	struct btf_var_secinfo *vsi;
1829 	int i, n;
1830 
1831 	if (!map->btf_value_type_id)
1832 		return false;
1833 
1834 	t = btf__type_by_id(obj->btf, map->btf_value_type_id);
1835 	if (!btf_is_datasec(t))
1836 		return false;
1837 
1838 	vsi = btf_var_secinfos(t);
1839 	for (i = 0, n = btf_vlen(t); i < n; i++, vsi++) {
1840 		vt = btf__type_by_id(obj->btf, vsi->type);
1841 		if (!btf_is_var(vt))
1842 			continue;
1843 
1844 		if (btf_var(vt)->linkage != BTF_VAR_STATIC)
1845 			return true;
1846 	}
1847 
1848 	return false;
1849 }
1850 
1851 static int
1852 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
1853 			      const char *real_name, int sec_idx, void *data, size_t data_sz)
1854 {
1855 	struct bpf_map_def *def;
1856 	struct bpf_map *map;
1857 	size_t mmap_sz;
1858 	int err;
1859 
1860 	map = bpf_object__add_map(obj);
1861 	if (IS_ERR(map))
1862 		return PTR_ERR(map);
1863 
1864 	map->libbpf_type = type;
1865 	map->sec_idx = sec_idx;
1866 	map->sec_offset = 0;
1867 	map->real_name = strdup(real_name);
1868 	map->name = internal_map_name(obj, real_name);
1869 	if (!map->real_name || !map->name) {
1870 		zfree(&map->real_name);
1871 		zfree(&map->name);
1872 		return -ENOMEM;
1873 	}
1874 
1875 	def = &map->def;
1876 	def->type = BPF_MAP_TYPE_ARRAY;
1877 	def->key_size = sizeof(int);
1878 	def->value_size = data_sz;
1879 	def->max_entries = 1;
1880 	def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
1881 		? BPF_F_RDONLY_PROG : 0;
1882 
1883 	/* failures are fine because of maps like .rodata.str1.1 */
1884 	(void) map_fill_btf_type_info(obj, map);
1885 
1886 	if (map_is_mmapable(obj, map))
1887 		def->map_flags |= BPF_F_MMAPABLE;
1888 
1889 	pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
1890 		 map->name, map->sec_idx, map->sec_offset, def->map_flags);
1891 
1892 	mmap_sz = bpf_map_mmap_sz(map);
1893 	map->mmaped = mmap(NULL, mmap_sz, PROT_READ | PROT_WRITE,
1894 			   MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1895 	if (map->mmaped == MAP_FAILED) {
1896 		err = -errno;
1897 		map->mmaped = NULL;
1898 		pr_warn("failed to alloc map '%s' content buffer: %d\n",
1899 			map->name, err);
1900 		zfree(&map->real_name);
1901 		zfree(&map->name);
1902 		return err;
1903 	}
1904 
1905 	if (data)
1906 		memcpy(map->mmaped, data, data_sz);
1907 
1908 	pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
1909 	return 0;
1910 }
1911 
1912 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
1913 {
1914 	struct elf_sec_desc *sec_desc;
1915 	const char *sec_name;
1916 	int err = 0, sec_idx;
1917 
1918 	/*
1919 	 * Populate obj->maps with libbpf internal maps.
1920 	 */
1921 	for (sec_idx = 1; sec_idx < obj->efile.sec_cnt; sec_idx++) {
1922 		sec_desc = &obj->efile.secs[sec_idx];
1923 
1924 		/* Skip recognized sections with size 0. */
1925 		if (!sec_desc->data || sec_desc->data->d_size == 0)
1926 			continue;
1927 
1928 		switch (sec_desc->sec_type) {
1929 		case SEC_DATA:
1930 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1931 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
1932 							    sec_name, sec_idx,
1933 							    sec_desc->data->d_buf,
1934 							    sec_desc->data->d_size);
1935 			break;
1936 		case SEC_RODATA:
1937 			obj->has_rodata = true;
1938 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1939 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
1940 							    sec_name, sec_idx,
1941 							    sec_desc->data->d_buf,
1942 							    sec_desc->data->d_size);
1943 			break;
1944 		case SEC_BSS:
1945 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1946 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
1947 							    sec_name, sec_idx,
1948 							    NULL,
1949 							    sec_desc->data->d_size);
1950 			break;
1951 		default:
1952 			/* skip */
1953 			break;
1954 		}
1955 		if (err)
1956 			return err;
1957 	}
1958 	return 0;
1959 }
1960 
1961 
1962 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
1963 					       const void *name)
1964 {
1965 	int i;
1966 
1967 	for (i = 0; i < obj->nr_extern; i++) {
1968 		if (strcmp(obj->externs[i].name, name) == 0)
1969 			return &obj->externs[i];
1970 	}
1971 	return NULL;
1972 }
1973 
1974 static struct extern_desc *find_extern_by_name_with_len(const struct bpf_object *obj,
1975 							const void *name, int len)
1976 {
1977 	const char *ext_name;
1978 	int i;
1979 
1980 	for (i = 0; i < obj->nr_extern; i++) {
1981 		ext_name = obj->externs[i].name;
1982 		if (strlen(ext_name) == len && strncmp(ext_name, name, len) == 0)
1983 			return &obj->externs[i];
1984 	}
1985 	return NULL;
1986 }
1987 
1988 static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
1989 			      char value)
1990 {
1991 	switch (ext->kcfg.type) {
1992 	case KCFG_BOOL:
1993 		if (value == 'm') {
1994 			pr_warn("extern (kcfg) '%s': value '%c' implies tristate or char type\n",
1995 				ext->name, value);
1996 			return -EINVAL;
1997 		}
1998 		*(bool *)ext_val = value == 'y' ? true : false;
1999 		break;
2000 	case KCFG_TRISTATE:
2001 		if (value == 'y')
2002 			*(enum libbpf_tristate *)ext_val = TRI_YES;
2003 		else if (value == 'm')
2004 			*(enum libbpf_tristate *)ext_val = TRI_MODULE;
2005 		else /* value == 'n' */
2006 			*(enum libbpf_tristate *)ext_val = TRI_NO;
2007 		break;
2008 	case KCFG_CHAR:
2009 		*(char *)ext_val = value;
2010 		break;
2011 	case KCFG_UNKNOWN:
2012 	case KCFG_INT:
2013 	case KCFG_CHAR_ARR:
2014 	default:
2015 		pr_warn("extern (kcfg) '%s': value '%c' implies bool, tristate, or char type\n",
2016 			ext->name, value);
2017 		return -EINVAL;
2018 	}
2019 	ext->is_set = true;
2020 	return 0;
2021 }
2022 
2023 static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
2024 			      const char *value)
2025 {
2026 	size_t len;
2027 
2028 	if (ext->kcfg.type != KCFG_CHAR_ARR) {
2029 		pr_warn("extern (kcfg) '%s': value '%s' implies char array type\n",
2030 			ext->name, value);
2031 		return -EINVAL;
2032 	}
2033 
2034 	len = strlen(value);
2035 	if (value[len - 1] != '"') {
2036 		pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
2037 			ext->name, value);
2038 		return -EINVAL;
2039 	}
2040 
2041 	/* strip quotes */
2042 	len -= 2;
2043 	if (len >= ext->kcfg.sz) {
2044 		pr_warn("extern (kcfg) '%s': long string '%s' of (%zu bytes) truncated to %d bytes\n",
2045 			ext->name, value, len, ext->kcfg.sz - 1);
2046 		len = ext->kcfg.sz - 1;
2047 	}
2048 	memcpy(ext_val, value + 1, len);
2049 	ext_val[len] = '\0';
2050 	ext->is_set = true;
2051 	return 0;
2052 }
2053 
2054 static int parse_u64(const char *value, __u64 *res)
2055 {
2056 	char *value_end;
2057 	int err;
2058 
2059 	errno = 0;
2060 	*res = strtoull(value, &value_end, 0);
2061 	if (errno) {
2062 		err = -errno;
2063 		pr_warn("failed to parse '%s' as integer: %d\n", value, err);
2064 		return err;
2065 	}
2066 	if (*value_end) {
2067 		pr_warn("failed to parse '%s' as integer completely\n", value);
2068 		return -EINVAL;
2069 	}
2070 	return 0;
2071 }
2072 
2073 static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
2074 {
2075 	int bit_sz = ext->kcfg.sz * 8;
2076 
2077 	if (ext->kcfg.sz == 8)
2078 		return true;
2079 
2080 	/* Validate that value stored in u64 fits in integer of `ext->sz`
2081 	 * bytes size without any loss of information. If the target integer
2082 	 * is signed, we rely on the following limits of integer type of
2083 	 * Y bits and subsequent transformation:
2084 	 *
2085 	 *     -2^(Y-1) <= X           <= 2^(Y-1) - 1
2086 	 *            0 <= X + 2^(Y-1) <= 2^Y - 1
2087 	 *            0 <= X + 2^(Y-1) <  2^Y
2088 	 *
2089 	 *  For unsigned target integer, check that all the (64 - Y) bits are
2090 	 *  zero.
2091 	 */
2092 	if (ext->kcfg.is_signed)
2093 		return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
2094 	else
2095 		return (v >> bit_sz) == 0;
2096 }
2097 
2098 static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
2099 			      __u64 value)
2100 {
2101 	if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR &&
2102 	    ext->kcfg.type != KCFG_BOOL) {
2103 		pr_warn("extern (kcfg) '%s': value '%llu' implies integer, char, or boolean type\n",
2104 			ext->name, (unsigned long long)value);
2105 		return -EINVAL;
2106 	}
2107 	if (ext->kcfg.type == KCFG_BOOL && value > 1) {
2108 		pr_warn("extern (kcfg) '%s': value '%llu' isn't boolean compatible\n",
2109 			ext->name, (unsigned long long)value);
2110 		return -EINVAL;
2111 
2112 	}
2113 	if (!is_kcfg_value_in_range(ext, value)) {
2114 		pr_warn("extern (kcfg) '%s': value '%llu' doesn't fit in %d bytes\n",
2115 			ext->name, (unsigned long long)value, ext->kcfg.sz);
2116 		return -ERANGE;
2117 	}
2118 	switch (ext->kcfg.sz) {
2119 	case 1:
2120 		*(__u8 *)ext_val = value;
2121 		break;
2122 	case 2:
2123 		*(__u16 *)ext_val = value;
2124 		break;
2125 	case 4:
2126 		*(__u32 *)ext_val = value;
2127 		break;
2128 	case 8:
2129 		*(__u64 *)ext_val = value;
2130 		break;
2131 	default:
2132 		return -EINVAL;
2133 	}
2134 	ext->is_set = true;
2135 	return 0;
2136 }
2137 
2138 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
2139 					    char *buf, void *data)
2140 {
2141 	struct extern_desc *ext;
2142 	char *sep, *value;
2143 	int len, err = 0;
2144 	void *ext_val;
2145 	__u64 num;
2146 
2147 	if (!str_has_pfx(buf, "CONFIG_"))
2148 		return 0;
2149 
2150 	sep = strchr(buf, '=');
2151 	if (!sep) {
2152 		pr_warn("failed to parse '%s': no separator\n", buf);
2153 		return -EINVAL;
2154 	}
2155 
2156 	/* Trim ending '\n' */
2157 	len = strlen(buf);
2158 	if (buf[len - 1] == '\n')
2159 		buf[len - 1] = '\0';
2160 	/* Split on '=' and ensure that a value is present. */
2161 	*sep = '\0';
2162 	if (!sep[1]) {
2163 		*sep = '=';
2164 		pr_warn("failed to parse '%s': no value\n", buf);
2165 		return -EINVAL;
2166 	}
2167 
2168 	ext = find_extern_by_name(obj, buf);
2169 	if (!ext || ext->is_set)
2170 		return 0;
2171 
2172 	ext_val = data + ext->kcfg.data_off;
2173 	value = sep + 1;
2174 
2175 	switch (*value) {
2176 	case 'y': case 'n': case 'm':
2177 		err = set_kcfg_value_tri(ext, ext_val, *value);
2178 		break;
2179 	case '"':
2180 		err = set_kcfg_value_str(ext, ext_val, value);
2181 		break;
2182 	default:
2183 		/* assume integer */
2184 		err = parse_u64(value, &num);
2185 		if (err) {
2186 			pr_warn("extern (kcfg) '%s': value '%s' isn't a valid integer\n", ext->name, value);
2187 			return err;
2188 		}
2189 		if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
2190 			pr_warn("extern (kcfg) '%s': value '%s' implies integer type\n", ext->name, value);
2191 			return -EINVAL;
2192 		}
2193 		err = set_kcfg_value_num(ext, ext_val, num);
2194 		break;
2195 	}
2196 	if (err)
2197 		return err;
2198 	pr_debug("extern (kcfg) '%s': set to %s\n", ext->name, value);
2199 	return 0;
2200 }
2201 
2202 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
2203 {
2204 	char buf[PATH_MAX];
2205 	struct utsname uts;
2206 	int len, err = 0;
2207 	gzFile file;
2208 
2209 	uname(&uts);
2210 	len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
2211 	if (len < 0)
2212 		return -EINVAL;
2213 	else if (len >= PATH_MAX)
2214 		return -ENAMETOOLONG;
2215 
2216 	/* gzopen also accepts uncompressed files. */
2217 	file = gzopen(buf, "re");
2218 	if (!file)
2219 		file = gzopen("/proc/config.gz", "re");
2220 
2221 	if (!file) {
2222 		pr_warn("failed to open system Kconfig\n");
2223 		return -ENOENT;
2224 	}
2225 
2226 	while (gzgets(file, buf, sizeof(buf))) {
2227 		err = bpf_object__process_kconfig_line(obj, buf, data);
2228 		if (err) {
2229 			pr_warn("error parsing system Kconfig line '%s': %d\n",
2230 				buf, err);
2231 			goto out;
2232 		}
2233 	}
2234 
2235 out:
2236 	gzclose(file);
2237 	return err;
2238 }
2239 
2240 static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
2241 					const char *config, void *data)
2242 {
2243 	char buf[PATH_MAX];
2244 	int err = 0;
2245 	FILE *file;
2246 
2247 	file = fmemopen((void *)config, strlen(config), "r");
2248 	if (!file) {
2249 		err = -errno;
2250 		pr_warn("failed to open in-memory Kconfig: %d\n", err);
2251 		return err;
2252 	}
2253 
2254 	while (fgets(buf, sizeof(buf), file)) {
2255 		err = bpf_object__process_kconfig_line(obj, buf, data);
2256 		if (err) {
2257 			pr_warn("error parsing in-memory Kconfig line '%s': %d\n",
2258 				buf, err);
2259 			break;
2260 		}
2261 	}
2262 
2263 	fclose(file);
2264 	return err;
2265 }
2266 
2267 static int bpf_object__init_kconfig_map(struct bpf_object *obj)
2268 {
2269 	struct extern_desc *last_ext = NULL, *ext;
2270 	size_t map_sz;
2271 	int i, err;
2272 
2273 	for (i = 0; i < obj->nr_extern; i++) {
2274 		ext = &obj->externs[i];
2275 		if (ext->type == EXT_KCFG)
2276 			last_ext = ext;
2277 	}
2278 
2279 	if (!last_ext)
2280 		return 0;
2281 
2282 	map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
2283 	err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
2284 					    ".kconfig", obj->efile.symbols_shndx,
2285 					    NULL, map_sz);
2286 	if (err)
2287 		return err;
2288 
2289 	obj->kconfig_map_idx = obj->nr_maps - 1;
2290 
2291 	return 0;
2292 }
2293 
2294 const struct btf_type *
2295 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
2296 {
2297 	const struct btf_type *t = btf__type_by_id(btf, id);
2298 
2299 	if (res_id)
2300 		*res_id = id;
2301 
2302 	while (btf_is_mod(t) || btf_is_typedef(t)) {
2303 		if (res_id)
2304 			*res_id = t->type;
2305 		t = btf__type_by_id(btf, t->type);
2306 	}
2307 
2308 	return t;
2309 }
2310 
2311 static const struct btf_type *
2312 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
2313 {
2314 	const struct btf_type *t;
2315 
2316 	t = skip_mods_and_typedefs(btf, id, NULL);
2317 	if (!btf_is_ptr(t))
2318 		return NULL;
2319 
2320 	t = skip_mods_and_typedefs(btf, t->type, res_id);
2321 
2322 	return btf_is_func_proto(t) ? t : NULL;
2323 }
2324 
2325 static const char *__btf_kind_str(__u16 kind)
2326 {
2327 	switch (kind) {
2328 	case BTF_KIND_UNKN: return "void";
2329 	case BTF_KIND_INT: return "int";
2330 	case BTF_KIND_PTR: return "ptr";
2331 	case BTF_KIND_ARRAY: return "array";
2332 	case BTF_KIND_STRUCT: return "struct";
2333 	case BTF_KIND_UNION: return "union";
2334 	case BTF_KIND_ENUM: return "enum";
2335 	case BTF_KIND_FWD: return "fwd";
2336 	case BTF_KIND_TYPEDEF: return "typedef";
2337 	case BTF_KIND_VOLATILE: return "volatile";
2338 	case BTF_KIND_CONST: return "const";
2339 	case BTF_KIND_RESTRICT: return "restrict";
2340 	case BTF_KIND_FUNC: return "func";
2341 	case BTF_KIND_FUNC_PROTO: return "func_proto";
2342 	case BTF_KIND_VAR: return "var";
2343 	case BTF_KIND_DATASEC: return "datasec";
2344 	case BTF_KIND_FLOAT: return "float";
2345 	case BTF_KIND_DECL_TAG: return "decl_tag";
2346 	case BTF_KIND_TYPE_TAG: return "type_tag";
2347 	case BTF_KIND_ENUM64: return "enum64";
2348 	default: return "unknown";
2349 	}
2350 }
2351 
2352 const char *btf_kind_str(const struct btf_type *t)
2353 {
2354 	return __btf_kind_str(btf_kind(t));
2355 }
2356 
2357 /*
2358  * Fetch integer attribute of BTF map definition. Such attributes are
2359  * represented using a pointer to an array, in which dimensionality of array
2360  * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2361  * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2362  * type definition, while using only sizeof(void *) space in ELF data section.
2363  */
2364 static bool get_map_field_int(const char *map_name, const struct btf *btf,
2365 			      const struct btf_member *m, __u32 *res)
2366 {
2367 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2368 	const char *name = btf__name_by_offset(btf, m->name_off);
2369 	const struct btf_array *arr_info;
2370 	const struct btf_type *arr_t;
2371 
2372 	if (!btf_is_ptr(t)) {
2373 		pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2374 			map_name, name, btf_kind_str(t));
2375 		return false;
2376 	}
2377 
2378 	arr_t = btf__type_by_id(btf, t->type);
2379 	if (!arr_t) {
2380 		pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2381 			map_name, name, t->type);
2382 		return false;
2383 	}
2384 	if (!btf_is_array(arr_t)) {
2385 		pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2386 			map_name, name, btf_kind_str(arr_t));
2387 		return false;
2388 	}
2389 	arr_info = btf_array(arr_t);
2390 	*res = arr_info->nelems;
2391 	return true;
2392 }
2393 
2394 static bool get_map_field_long(const char *map_name, const struct btf *btf,
2395 			       const struct btf_member *m, __u64 *res)
2396 {
2397 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2398 	const char *name = btf__name_by_offset(btf, m->name_off);
2399 
2400 	if (btf_is_ptr(t)) {
2401 		__u32 res32;
2402 		bool ret;
2403 
2404 		ret = get_map_field_int(map_name, btf, m, &res32);
2405 		if (ret)
2406 			*res = (__u64)res32;
2407 		return ret;
2408 	}
2409 
2410 	if (!btf_is_enum(t) && !btf_is_enum64(t)) {
2411 		pr_warn("map '%s': attr '%s': expected ENUM or ENUM64, got %s.\n",
2412 			map_name, name, btf_kind_str(t));
2413 		return false;
2414 	}
2415 
2416 	if (btf_vlen(t) != 1) {
2417 		pr_warn("map '%s': attr '%s': invalid __ulong\n",
2418 			map_name, name);
2419 		return false;
2420 	}
2421 
2422 	if (btf_is_enum(t)) {
2423 		const struct btf_enum *e = btf_enum(t);
2424 
2425 		*res = e->val;
2426 	} else {
2427 		const struct btf_enum64 *e = btf_enum64(t);
2428 
2429 		*res = btf_enum64_value(e);
2430 	}
2431 	return true;
2432 }
2433 
2434 static int pathname_concat(char *buf, size_t buf_sz, const char *path, const char *name)
2435 {
2436 	int len;
2437 
2438 	len = snprintf(buf, buf_sz, "%s/%s", path, name);
2439 	if (len < 0)
2440 		return -EINVAL;
2441 	if (len >= buf_sz)
2442 		return -ENAMETOOLONG;
2443 
2444 	return 0;
2445 }
2446 
2447 static int build_map_pin_path(struct bpf_map *map, const char *path)
2448 {
2449 	char buf[PATH_MAX];
2450 	int err;
2451 
2452 	if (!path)
2453 		path = BPF_FS_DEFAULT_PATH;
2454 
2455 	err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
2456 	if (err)
2457 		return err;
2458 
2459 	return bpf_map__set_pin_path(map, buf);
2460 }
2461 
2462 /* should match definition in bpf_helpers.h */
2463 enum libbpf_pin_type {
2464 	LIBBPF_PIN_NONE,
2465 	/* PIN_BY_NAME: pin maps by name (in /sys/fs/bpf by default) */
2466 	LIBBPF_PIN_BY_NAME,
2467 };
2468 
2469 int parse_btf_map_def(const char *map_name, struct btf *btf,
2470 		      const struct btf_type *def_t, bool strict,
2471 		      struct btf_map_def *map_def, struct btf_map_def *inner_def)
2472 {
2473 	const struct btf_type *t;
2474 	const struct btf_member *m;
2475 	bool is_inner = inner_def == NULL;
2476 	int vlen, i;
2477 
2478 	vlen = btf_vlen(def_t);
2479 	m = btf_members(def_t);
2480 	for (i = 0; i < vlen; i++, m++) {
2481 		const char *name = btf__name_by_offset(btf, m->name_off);
2482 
2483 		if (!name) {
2484 			pr_warn("map '%s': invalid field #%d.\n", map_name, i);
2485 			return -EINVAL;
2486 		}
2487 		if (strcmp(name, "type") == 0) {
2488 			if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
2489 				return -EINVAL;
2490 			map_def->parts |= MAP_DEF_MAP_TYPE;
2491 		} else if (strcmp(name, "max_entries") == 0) {
2492 			if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
2493 				return -EINVAL;
2494 			map_def->parts |= MAP_DEF_MAX_ENTRIES;
2495 		} else if (strcmp(name, "map_flags") == 0) {
2496 			if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
2497 				return -EINVAL;
2498 			map_def->parts |= MAP_DEF_MAP_FLAGS;
2499 		} else if (strcmp(name, "numa_node") == 0) {
2500 			if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
2501 				return -EINVAL;
2502 			map_def->parts |= MAP_DEF_NUMA_NODE;
2503 		} else if (strcmp(name, "key_size") == 0) {
2504 			__u32 sz;
2505 
2506 			if (!get_map_field_int(map_name, btf, m, &sz))
2507 				return -EINVAL;
2508 			if (map_def->key_size && map_def->key_size != sz) {
2509 				pr_warn("map '%s': conflicting key size %u != %u.\n",
2510 					map_name, map_def->key_size, sz);
2511 				return -EINVAL;
2512 			}
2513 			map_def->key_size = sz;
2514 			map_def->parts |= MAP_DEF_KEY_SIZE;
2515 		} else if (strcmp(name, "key") == 0) {
2516 			__s64 sz;
2517 
2518 			t = btf__type_by_id(btf, m->type);
2519 			if (!t) {
2520 				pr_warn("map '%s': key type [%d] not found.\n",
2521 					map_name, m->type);
2522 				return -EINVAL;
2523 			}
2524 			if (!btf_is_ptr(t)) {
2525 				pr_warn("map '%s': key spec is not PTR: %s.\n",
2526 					map_name, btf_kind_str(t));
2527 				return -EINVAL;
2528 			}
2529 			sz = btf__resolve_size(btf, t->type);
2530 			if (sz < 0) {
2531 				pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2532 					map_name, t->type, (ssize_t)sz);
2533 				return sz;
2534 			}
2535 			if (map_def->key_size && map_def->key_size != sz) {
2536 				pr_warn("map '%s': conflicting key size %u != %zd.\n",
2537 					map_name, map_def->key_size, (ssize_t)sz);
2538 				return -EINVAL;
2539 			}
2540 			map_def->key_size = sz;
2541 			map_def->key_type_id = t->type;
2542 			map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
2543 		} else if (strcmp(name, "value_size") == 0) {
2544 			__u32 sz;
2545 
2546 			if (!get_map_field_int(map_name, btf, m, &sz))
2547 				return -EINVAL;
2548 			if (map_def->value_size && map_def->value_size != sz) {
2549 				pr_warn("map '%s': conflicting value size %u != %u.\n",
2550 					map_name, map_def->value_size, sz);
2551 				return -EINVAL;
2552 			}
2553 			map_def->value_size = sz;
2554 			map_def->parts |= MAP_DEF_VALUE_SIZE;
2555 		} else if (strcmp(name, "value") == 0) {
2556 			__s64 sz;
2557 
2558 			t = btf__type_by_id(btf, m->type);
2559 			if (!t) {
2560 				pr_warn("map '%s': value type [%d] not found.\n",
2561 					map_name, m->type);
2562 				return -EINVAL;
2563 			}
2564 			if (!btf_is_ptr(t)) {
2565 				pr_warn("map '%s': value spec is not PTR: %s.\n",
2566 					map_name, btf_kind_str(t));
2567 				return -EINVAL;
2568 			}
2569 			sz = btf__resolve_size(btf, t->type);
2570 			if (sz < 0) {
2571 				pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2572 					map_name, t->type, (ssize_t)sz);
2573 				return sz;
2574 			}
2575 			if (map_def->value_size && map_def->value_size != sz) {
2576 				pr_warn("map '%s': conflicting value size %u != %zd.\n",
2577 					map_name, map_def->value_size, (ssize_t)sz);
2578 				return -EINVAL;
2579 			}
2580 			map_def->value_size = sz;
2581 			map_def->value_type_id = t->type;
2582 			map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
2583 		}
2584 		else if (strcmp(name, "values") == 0) {
2585 			bool is_map_in_map = bpf_map_type__is_map_in_map(map_def->map_type);
2586 			bool is_prog_array = map_def->map_type == BPF_MAP_TYPE_PROG_ARRAY;
2587 			const char *desc = is_map_in_map ? "map-in-map inner" : "prog-array value";
2588 			char inner_map_name[128];
2589 			int err;
2590 
2591 			if (is_inner) {
2592 				pr_warn("map '%s': multi-level inner maps not supported.\n",
2593 					map_name);
2594 				return -ENOTSUP;
2595 			}
2596 			if (i != vlen - 1) {
2597 				pr_warn("map '%s': '%s' member should be last.\n",
2598 					map_name, name);
2599 				return -EINVAL;
2600 			}
2601 			if (!is_map_in_map && !is_prog_array) {
2602 				pr_warn("map '%s': should be map-in-map or prog-array.\n",
2603 					map_name);
2604 				return -ENOTSUP;
2605 			}
2606 			if (map_def->value_size && map_def->value_size != 4) {
2607 				pr_warn("map '%s': conflicting value size %u != 4.\n",
2608 					map_name, map_def->value_size);
2609 				return -EINVAL;
2610 			}
2611 			map_def->value_size = 4;
2612 			t = btf__type_by_id(btf, m->type);
2613 			if (!t) {
2614 				pr_warn("map '%s': %s type [%d] not found.\n",
2615 					map_name, desc, m->type);
2616 				return -EINVAL;
2617 			}
2618 			if (!btf_is_array(t) || btf_array(t)->nelems) {
2619 				pr_warn("map '%s': %s spec is not a zero-sized array.\n",
2620 					map_name, desc);
2621 				return -EINVAL;
2622 			}
2623 			t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
2624 			if (!btf_is_ptr(t)) {
2625 				pr_warn("map '%s': %s def is of unexpected kind %s.\n",
2626 					map_name, desc, btf_kind_str(t));
2627 				return -EINVAL;
2628 			}
2629 			t = skip_mods_and_typedefs(btf, t->type, NULL);
2630 			if (is_prog_array) {
2631 				if (!btf_is_func_proto(t)) {
2632 					pr_warn("map '%s': prog-array value def is of unexpected kind %s.\n",
2633 						map_name, btf_kind_str(t));
2634 					return -EINVAL;
2635 				}
2636 				continue;
2637 			}
2638 			if (!btf_is_struct(t)) {
2639 				pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2640 					map_name, btf_kind_str(t));
2641 				return -EINVAL;
2642 			}
2643 
2644 			snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2645 			err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
2646 			if (err)
2647 				return err;
2648 
2649 			map_def->parts |= MAP_DEF_INNER_MAP;
2650 		} else if (strcmp(name, "pinning") == 0) {
2651 			__u32 val;
2652 
2653 			if (is_inner) {
2654 				pr_warn("map '%s': inner def can't be pinned.\n", map_name);
2655 				return -EINVAL;
2656 			}
2657 			if (!get_map_field_int(map_name, btf, m, &val))
2658 				return -EINVAL;
2659 			if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
2660 				pr_warn("map '%s': invalid pinning value %u.\n",
2661 					map_name, val);
2662 				return -EINVAL;
2663 			}
2664 			map_def->pinning = val;
2665 			map_def->parts |= MAP_DEF_PINNING;
2666 		} else if (strcmp(name, "map_extra") == 0) {
2667 			__u64 map_extra;
2668 
2669 			if (!get_map_field_long(map_name, btf, m, &map_extra))
2670 				return -EINVAL;
2671 			map_def->map_extra = map_extra;
2672 			map_def->parts |= MAP_DEF_MAP_EXTRA;
2673 		} else {
2674 			if (strict) {
2675 				pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
2676 				return -ENOTSUP;
2677 			}
2678 			pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
2679 		}
2680 	}
2681 
2682 	if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2683 		pr_warn("map '%s': map type isn't specified.\n", map_name);
2684 		return -EINVAL;
2685 	}
2686 
2687 	return 0;
2688 }
2689 
2690 static size_t adjust_ringbuf_sz(size_t sz)
2691 {
2692 	__u32 page_sz = sysconf(_SC_PAGE_SIZE);
2693 	__u32 mul;
2694 
2695 	/* if user forgot to set any size, make sure they see error */
2696 	if (sz == 0)
2697 		return 0;
2698 	/* Kernel expects BPF_MAP_TYPE_RINGBUF's max_entries to be
2699 	 * a power-of-2 multiple of kernel's page size. If user diligently
2700 	 * satisified these conditions, pass the size through.
2701 	 */
2702 	if ((sz % page_sz) == 0 && is_pow_of_2(sz / page_sz))
2703 		return sz;
2704 
2705 	/* Otherwise find closest (page_sz * power_of_2) product bigger than
2706 	 * user-set size to satisfy both user size request and kernel
2707 	 * requirements and substitute correct max_entries for map creation.
2708 	 */
2709 	for (mul = 1; mul <= UINT_MAX / page_sz; mul <<= 1) {
2710 		if (mul * page_sz > sz)
2711 			return mul * page_sz;
2712 	}
2713 
2714 	/* if it's impossible to satisfy the conditions (i.e., user size is
2715 	 * very close to UINT_MAX but is not a power-of-2 multiple of
2716 	 * page_size) then just return original size and let kernel reject it
2717 	 */
2718 	return sz;
2719 }
2720 
2721 static bool map_is_ringbuf(const struct bpf_map *map)
2722 {
2723 	return map->def.type == BPF_MAP_TYPE_RINGBUF ||
2724 	       map->def.type == BPF_MAP_TYPE_USER_RINGBUF;
2725 }
2726 
2727 static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2728 {
2729 	map->def.type = def->map_type;
2730 	map->def.key_size = def->key_size;
2731 	map->def.value_size = def->value_size;
2732 	map->def.max_entries = def->max_entries;
2733 	map->def.map_flags = def->map_flags;
2734 	map->map_extra = def->map_extra;
2735 
2736 	map->numa_node = def->numa_node;
2737 	map->btf_key_type_id = def->key_type_id;
2738 	map->btf_value_type_id = def->value_type_id;
2739 
2740 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
2741 	if (map_is_ringbuf(map))
2742 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
2743 
2744 	if (def->parts & MAP_DEF_MAP_TYPE)
2745 		pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2746 
2747 	if (def->parts & MAP_DEF_KEY_TYPE)
2748 		pr_debug("map '%s': found key [%u], sz = %u.\n",
2749 			 map->name, def->key_type_id, def->key_size);
2750 	else if (def->parts & MAP_DEF_KEY_SIZE)
2751 		pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2752 
2753 	if (def->parts & MAP_DEF_VALUE_TYPE)
2754 		pr_debug("map '%s': found value [%u], sz = %u.\n",
2755 			 map->name, def->value_type_id, def->value_size);
2756 	else if (def->parts & MAP_DEF_VALUE_SIZE)
2757 		pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2758 
2759 	if (def->parts & MAP_DEF_MAX_ENTRIES)
2760 		pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2761 	if (def->parts & MAP_DEF_MAP_FLAGS)
2762 		pr_debug("map '%s': found map_flags = 0x%x.\n", map->name, def->map_flags);
2763 	if (def->parts & MAP_DEF_MAP_EXTRA)
2764 		pr_debug("map '%s': found map_extra = 0x%llx.\n", map->name,
2765 			 (unsigned long long)def->map_extra);
2766 	if (def->parts & MAP_DEF_PINNING)
2767 		pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2768 	if (def->parts & MAP_DEF_NUMA_NODE)
2769 		pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2770 
2771 	if (def->parts & MAP_DEF_INNER_MAP)
2772 		pr_debug("map '%s': found inner map definition.\n", map->name);
2773 }
2774 
2775 static const char *btf_var_linkage_str(__u32 linkage)
2776 {
2777 	switch (linkage) {
2778 	case BTF_VAR_STATIC: return "static";
2779 	case BTF_VAR_GLOBAL_ALLOCATED: return "global";
2780 	case BTF_VAR_GLOBAL_EXTERN: return "extern";
2781 	default: return "unknown";
2782 	}
2783 }
2784 
2785 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2786 					 const struct btf_type *sec,
2787 					 int var_idx, int sec_idx,
2788 					 const Elf_Data *data, bool strict,
2789 					 const char *pin_root_path)
2790 {
2791 	struct btf_map_def map_def = {}, inner_def = {};
2792 	const struct btf_type *var, *def;
2793 	const struct btf_var_secinfo *vi;
2794 	const struct btf_var *var_extra;
2795 	const char *map_name;
2796 	struct bpf_map *map;
2797 	int err;
2798 
2799 	vi = btf_var_secinfos(sec) + var_idx;
2800 	var = btf__type_by_id(obj->btf, vi->type);
2801 	var_extra = btf_var(var);
2802 	map_name = btf__name_by_offset(obj->btf, var->name_off);
2803 
2804 	if (map_name == NULL || map_name[0] == '\0') {
2805 		pr_warn("map #%d: empty name.\n", var_idx);
2806 		return -EINVAL;
2807 	}
2808 	if ((__u64)vi->offset + vi->size > data->d_size) {
2809 		pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2810 		return -EINVAL;
2811 	}
2812 	if (!btf_is_var(var)) {
2813 		pr_warn("map '%s': unexpected var kind %s.\n",
2814 			map_name, btf_kind_str(var));
2815 		return -EINVAL;
2816 	}
2817 	if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
2818 		pr_warn("map '%s': unsupported map linkage %s.\n",
2819 			map_name, btf_var_linkage_str(var_extra->linkage));
2820 		return -EOPNOTSUPP;
2821 	}
2822 
2823 	def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2824 	if (!btf_is_struct(def)) {
2825 		pr_warn("map '%s': unexpected def kind %s.\n",
2826 			map_name, btf_kind_str(var));
2827 		return -EINVAL;
2828 	}
2829 	if (def->size > vi->size) {
2830 		pr_warn("map '%s': invalid def size.\n", map_name);
2831 		return -EINVAL;
2832 	}
2833 
2834 	map = bpf_object__add_map(obj);
2835 	if (IS_ERR(map))
2836 		return PTR_ERR(map);
2837 	map->name = strdup(map_name);
2838 	if (!map->name) {
2839 		pr_warn("map '%s': failed to alloc map name.\n", map_name);
2840 		return -ENOMEM;
2841 	}
2842 	map->libbpf_type = LIBBPF_MAP_UNSPEC;
2843 	map->def.type = BPF_MAP_TYPE_UNSPEC;
2844 	map->sec_idx = sec_idx;
2845 	map->sec_offset = vi->offset;
2846 	map->btf_var_idx = var_idx;
2847 	pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2848 		 map_name, map->sec_idx, map->sec_offset);
2849 
2850 	err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
2851 	if (err)
2852 		return err;
2853 
2854 	fill_map_from_def(map, &map_def);
2855 
2856 	if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
2857 		err = build_map_pin_path(map, pin_root_path);
2858 		if (err) {
2859 			pr_warn("map '%s': couldn't build pin path.\n", map->name);
2860 			return err;
2861 		}
2862 	}
2863 
2864 	if (map_def.parts & MAP_DEF_INNER_MAP) {
2865 		map->inner_map = calloc(1, sizeof(*map->inner_map));
2866 		if (!map->inner_map)
2867 			return -ENOMEM;
2868 		map->inner_map->fd = create_placeholder_fd();
2869 		if (map->inner_map->fd < 0)
2870 			return map->inner_map->fd;
2871 		map->inner_map->sec_idx = sec_idx;
2872 		map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
2873 		if (!map->inner_map->name)
2874 			return -ENOMEM;
2875 		sprintf(map->inner_map->name, "%s.inner", map_name);
2876 
2877 		fill_map_from_def(map->inner_map, &inner_def);
2878 	}
2879 
2880 	err = map_fill_btf_type_info(obj, map);
2881 	if (err)
2882 		return err;
2883 
2884 	return 0;
2885 }
2886 
2887 static int init_arena_map_data(struct bpf_object *obj, struct bpf_map *map,
2888 			       const char *sec_name, int sec_idx,
2889 			       void *data, size_t data_sz)
2890 {
2891 	const long page_sz = sysconf(_SC_PAGE_SIZE);
2892 	size_t mmap_sz;
2893 
2894 	mmap_sz = bpf_map_mmap_sz(obj->arena_map);
2895 	if (roundup(data_sz, page_sz) > mmap_sz) {
2896 		pr_warn("elf: sec '%s': declared ARENA map size (%zu) is too small to hold global __arena variables of size %zu\n",
2897 			sec_name, mmap_sz, data_sz);
2898 		return -E2BIG;
2899 	}
2900 
2901 	obj->arena_data = malloc(data_sz);
2902 	if (!obj->arena_data)
2903 		return -ENOMEM;
2904 	memcpy(obj->arena_data, data, data_sz);
2905 	obj->arena_data_sz = data_sz;
2906 
2907 	/* make bpf_map__init_value() work for ARENA maps */
2908 	map->mmaped = obj->arena_data;
2909 
2910 	return 0;
2911 }
2912 
2913 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
2914 					  const char *pin_root_path)
2915 {
2916 	const struct btf_type *sec = NULL;
2917 	int nr_types, i, vlen, err;
2918 	const struct btf_type *t;
2919 	const char *name;
2920 	Elf_Data *data;
2921 	Elf_Scn *scn;
2922 
2923 	if (obj->efile.btf_maps_shndx < 0)
2924 		return 0;
2925 
2926 	scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
2927 	data = elf_sec_data(obj, scn);
2928 	if (!scn || !data) {
2929 		pr_warn("elf: failed to get %s map definitions for %s\n",
2930 			MAPS_ELF_SEC, obj->path);
2931 		return -EINVAL;
2932 	}
2933 
2934 	nr_types = btf__type_cnt(obj->btf);
2935 	for (i = 1; i < nr_types; i++) {
2936 		t = btf__type_by_id(obj->btf, i);
2937 		if (!btf_is_datasec(t))
2938 			continue;
2939 		name = btf__name_by_offset(obj->btf, t->name_off);
2940 		if (strcmp(name, MAPS_ELF_SEC) == 0) {
2941 			sec = t;
2942 			obj->efile.btf_maps_sec_btf_id = i;
2943 			break;
2944 		}
2945 	}
2946 
2947 	if (!sec) {
2948 		pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
2949 		return -ENOENT;
2950 	}
2951 
2952 	vlen = btf_vlen(sec);
2953 	for (i = 0; i < vlen; i++) {
2954 		err = bpf_object__init_user_btf_map(obj, sec, i,
2955 						    obj->efile.btf_maps_shndx,
2956 						    data, strict,
2957 						    pin_root_path);
2958 		if (err)
2959 			return err;
2960 	}
2961 
2962 	for (i = 0; i < obj->nr_maps; i++) {
2963 		struct bpf_map *map = &obj->maps[i];
2964 
2965 		if (map->def.type != BPF_MAP_TYPE_ARENA)
2966 			continue;
2967 
2968 		if (obj->arena_map) {
2969 			pr_warn("map '%s': only single ARENA map is supported (map '%s' is also ARENA)\n",
2970 				map->name, obj->arena_map->name);
2971 			return -EINVAL;
2972 		}
2973 		obj->arena_map = map;
2974 
2975 		if (obj->efile.arena_data) {
2976 			err = init_arena_map_data(obj, map, ARENA_SEC, obj->efile.arena_data_shndx,
2977 						  obj->efile.arena_data->d_buf,
2978 						  obj->efile.arena_data->d_size);
2979 			if (err)
2980 				return err;
2981 		}
2982 	}
2983 	if (obj->efile.arena_data && !obj->arena_map) {
2984 		pr_warn("elf: sec '%s': to use global __arena variables the ARENA map should be explicitly declared in SEC(\".maps\")\n",
2985 			ARENA_SEC);
2986 		return -ENOENT;
2987 	}
2988 
2989 	return 0;
2990 }
2991 
2992 static int bpf_object__init_maps(struct bpf_object *obj,
2993 				 const struct bpf_object_open_opts *opts)
2994 {
2995 	const char *pin_root_path;
2996 	bool strict;
2997 	int err = 0;
2998 
2999 	strict = !OPTS_GET(opts, relaxed_maps, false);
3000 	pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
3001 
3002 	err = bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
3003 	err = err ?: bpf_object__init_global_data_maps(obj);
3004 	err = err ?: bpf_object__init_kconfig_map(obj);
3005 	err = err ?: bpf_object_init_struct_ops(obj);
3006 
3007 	return err;
3008 }
3009 
3010 static bool section_have_execinstr(struct bpf_object *obj, int idx)
3011 {
3012 	Elf64_Shdr *sh;
3013 
3014 	sh = elf_sec_hdr(obj, elf_sec_by_idx(obj, idx));
3015 	if (!sh)
3016 		return false;
3017 
3018 	return sh->sh_flags & SHF_EXECINSTR;
3019 }
3020 
3021 static bool starts_with_qmark(const char *s)
3022 {
3023 	return s && s[0] == '?';
3024 }
3025 
3026 static bool btf_needs_sanitization(struct bpf_object *obj)
3027 {
3028 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
3029 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
3030 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
3031 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
3032 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
3033 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
3034 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
3035 	bool has_qmark_datasec = kernel_supports(obj, FEAT_BTF_QMARK_DATASEC);
3036 
3037 	return !has_func || !has_datasec || !has_func_global || !has_float ||
3038 	       !has_decl_tag || !has_type_tag || !has_enum64 || !has_qmark_datasec;
3039 }
3040 
3041 static int bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *btf)
3042 {
3043 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
3044 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
3045 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
3046 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
3047 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
3048 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
3049 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
3050 	bool has_qmark_datasec = kernel_supports(obj, FEAT_BTF_QMARK_DATASEC);
3051 	int enum64_placeholder_id = 0;
3052 	struct btf_type *t;
3053 	int i, j, vlen;
3054 
3055 	for (i = 1; i < btf__type_cnt(btf); i++) {
3056 		t = (struct btf_type *)btf__type_by_id(btf, i);
3057 
3058 		if ((!has_datasec && btf_is_var(t)) || (!has_decl_tag && btf_is_decl_tag(t))) {
3059 			/* replace VAR/DECL_TAG with INT */
3060 			t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
3061 			/*
3062 			 * using size = 1 is the safest choice, 4 will be too
3063 			 * big and cause kernel BTF validation failure if
3064 			 * original variable took less than 4 bytes
3065 			 */
3066 			t->size = 1;
3067 			*(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
3068 		} else if (!has_datasec && btf_is_datasec(t)) {
3069 			/* replace DATASEC with STRUCT */
3070 			const struct btf_var_secinfo *v = btf_var_secinfos(t);
3071 			struct btf_member *m = btf_members(t);
3072 			struct btf_type *vt;
3073 			char *name;
3074 
3075 			name = (char *)btf__name_by_offset(btf, t->name_off);
3076 			while (*name) {
3077 				if (*name == '.' || *name == '?')
3078 					*name = '_';
3079 				name++;
3080 			}
3081 
3082 			vlen = btf_vlen(t);
3083 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
3084 			for (j = 0; j < vlen; j++, v++, m++) {
3085 				/* order of field assignments is important */
3086 				m->offset = v->offset * 8;
3087 				m->type = v->type;
3088 				/* preserve variable name as member name */
3089 				vt = (void *)btf__type_by_id(btf, v->type);
3090 				m->name_off = vt->name_off;
3091 			}
3092 		} else if (!has_qmark_datasec && btf_is_datasec(t) &&
3093 			   starts_with_qmark(btf__name_by_offset(btf, t->name_off))) {
3094 			/* replace '?' prefix with '_' for DATASEC names */
3095 			char *name;
3096 
3097 			name = (char *)btf__name_by_offset(btf, t->name_off);
3098 			if (name[0] == '?')
3099 				name[0] = '_';
3100 		} else if (!has_func && btf_is_func_proto(t)) {
3101 			/* replace FUNC_PROTO with ENUM */
3102 			vlen = btf_vlen(t);
3103 			t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
3104 			t->size = sizeof(__u32); /* kernel enforced */
3105 		} else if (!has_func && btf_is_func(t)) {
3106 			/* replace FUNC with TYPEDEF */
3107 			t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
3108 		} else if (!has_func_global && btf_is_func(t)) {
3109 			/* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
3110 			t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
3111 		} else if (!has_float && btf_is_float(t)) {
3112 			/* replace FLOAT with an equally-sized empty STRUCT;
3113 			 * since C compilers do not accept e.g. "float" as a
3114 			 * valid struct name, make it anonymous
3115 			 */
3116 			t->name_off = 0;
3117 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
3118 		} else if (!has_type_tag && btf_is_type_tag(t)) {
3119 			/* replace TYPE_TAG with a CONST */
3120 			t->name_off = 0;
3121 			t->info = BTF_INFO_ENC(BTF_KIND_CONST, 0, 0);
3122 		} else if (!has_enum64 && btf_is_enum(t)) {
3123 			/* clear the kflag */
3124 			t->info = btf_type_info(btf_kind(t), btf_vlen(t), false);
3125 		} else if (!has_enum64 && btf_is_enum64(t)) {
3126 			/* replace ENUM64 with a union */
3127 			struct btf_member *m;
3128 
3129 			if (enum64_placeholder_id == 0) {
3130 				enum64_placeholder_id = btf__add_int(btf, "enum64_placeholder", 1, 0);
3131 				if (enum64_placeholder_id < 0)
3132 					return enum64_placeholder_id;
3133 
3134 				t = (struct btf_type *)btf__type_by_id(btf, i);
3135 			}
3136 
3137 			m = btf_members(t);
3138 			vlen = btf_vlen(t);
3139 			t->info = BTF_INFO_ENC(BTF_KIND_UNION, 0, vlen);
3140 			for (j = 0; j < vlen; j++, m++) {
3141 				m->type = enum64_placeholder_id;
3142 				m->offset = 0;
3143 			}
3144 		}
3145 	}
3146 
3147 	return 0;
3148 }
3149 
3150 static bool libbpf_needs_btf(const struct bpf_object *obj)
3151 {
3152 	return obj->efile.btf_maps_shndx >= 0 ||
3153 	       obj->efile.has_st_ops ||
3154 	       obj->nr_extern > 0;
3155 }
3156 
3157 static bool kernel_needs_btf(const struct bpf_object *obj)
3158 {
3159 	return obj->efile.has_st_ops;
3160 }
3161 
3162 static int bpf_object__init_btf(struct bpf_object *obj,
3163 				Elf_Data *btf_data,
3164 				Elf_Data *btf_ext_data)
3165 {
3166 	int err = -ENOENT;
3167 
3168 	if (btf_data) {
3169 		obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
3170 		err = libbpf_get_error(obj->btf);
3171 		if (err) {
3172 			obj->btf = NULL;
3173 			pr_warn("Error loading ELF section %s: %d.\n", BTF_ELF_SEC, err);
3174 			goto out;
3175 		}
3176 		/* enforce 8-byte pointers for BPF-targeted BTFs */
3177 		btf__set_pointer_size(obj->btf, 8);
3178 	}
3179 	if (btf_ext_data) {
3180 		struct btf_ext_info *ext_segs[3];
3181 		int seg_num, sec_num;
3182 
3183 		if (!obj->btf) {
3184 			pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
3185 				 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
3186 			goto out;
3187 		}
3188 		obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
3189 		err = libbpf_get_error(obj->btf_ext);
3190 		if (err) {
3191 			pr_warn("Error loading ELF section %s: %d. Ignored and continue.\n",
3192 				BTF_EXT_ELF_SEC, err);
3193 			obj->btf_ext = NULL;
3194 			goto out;
3195 		}
3196 
3197 		/* setup .BTF.ext to ELF section mapping */
3198 		ext_segs[0] = &obj->btf_ext->func_info;
3199 		ext_segs[1] = &obj->btf_ext->line_info;
3200 		ext_segs[2] = &obj->btf_ext->core_relo_info;
3201 		for (seg_num = 0; seg_num < ARRAY_SIZE(ext_segs); seg_num++) {
3202 			struct btf_ext_info *seg = ext_segs[seg_num];
3203 			const struct btf_ext_info_sec *sec;
3204 			const char *sec_name;
3205 			Elf_Scn *scn;
3206 
3207 			if (seg->sec_cnt == 0)
3208 				continue;
3209 
3210 			seg->sec_idxs = calloc(seg->sec_cnt, sizeof(*seg->sec_idxs));
3211 			if (!seg->sec_idxs) {
3212 				err = -ENOMEM;
3213 				goto out;
3214 			}
3215 
3216 			sec_num = 0;
3217 			for_each_btf_ext_sec(seg, sec) {
3218 				/* preventively increment index to avoid doing
3219 				 * this before every continue below
3220 				 */
3221 				sec_num++;
3222 
3223 				sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
3224 				if (str_is_empty(sec_name))
3225 					continue;
3226 				scn = elf_sec_by_name(obj, sec_name);
3227 				if (!scn)
3228 					continue;
3229 
3230 				seg->sec_idxs[sec_num - 1] = elf_ndxscn(scn);
3231 			}
3232 		}
3233 	}
3234 out:
3235 	if (err && libbpf_needs_btf(obj)) {
3236 		pr_warn("BTF is required, but is missing or corrupted.\n");
3237 		return err;
3238 	}
3239 	return 0;
3240 }
3241 
3242 static int compare_vsi_off(const void *_a, const void *_b)
3243 {
3244 	const struct btf_var_secinfo *a = _a;
3245 	const struct btf_var_secinfo *b = _b;
3246 
3247 	return a->offset - b->offset;
3248 }
3249 
3250 static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
3251 			     struct btf_type *t)
3252 {
3253 	__u32 size = 0, i, vars = btf_vlen(t);
3254 	const char *sec_name = btf__name_by_offset(btf, t->name_off);
3255 	struct btf_var_secinfo *vsi;
3256 	bool fixup_offsets = false;
3257 	int err;
3258 
3259 	if (!sec_name) {
3260 		pr_debug("No name found in string section for DATASEC kind.\n");
3261 		return -ENOENT;
3262 	}
3263 
3264 	/* Extern-backing datasecs (.ksyms, .kconfig) have their size and
3265 	 * variable offsets set at the previous step. Further, not every
3266 	 * extern BTF VAR has corresponding ELF symbol preserved, so we skip
3267 	 * all fixups altogether for such sections and go straight to sorting
3268 	 * VARs within their DATASEC.
3269 	 */
3270 	if (strcmp(sec_name, KCONFIG_SEC) == 0 || strcmp(sec_name, KSYMS_SEC) == 0)
3271 		goto sort_vars;
3272 
3273 	/* Clang leaves DATASEC size and VAR offsets as zeroes, so we need to
3274 	 * fix this up. But BPF static linker already fixes this up and fills
3275 	 * all the sizes and offsets during static linking. So this step has
3276 	 * to be optional. But the STV_HIDDEN handling is non-optional for any
3277 	 * non-extern DATASEC, so the variable fixup loop below handles both
3278 	 * functions at the same time, paying the cost of BTF VAR <-> ELF
3279 	 * symbol matching just once.
3280 	 */
3281 	if (t->size == 0) {
3282 		err = find_elf_sec_sz(obj, sec_name, &size);
3283 		if (err || !size) {
3284 			pr_debug("sec '%s': failed to determine size from ELF: size %u, err %d\n",
3285 				 sec_name, size, err);
3286 			return -ENOENT;
3287 		}
3288 
3289 		t->size = size;
3290 		fixup_offsets = true;
3291 	}
3292 
3293 	for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
3294 		const struct btf_type *t_var;
3295 		struct btf_var *var;
3296 		const char *var_name;
3297 		Elf64_Sym *sym;
3298 
3299 		t_var = btf__type_by_id(btf, vsi->type);
3300 		if (!t_var || !btf_is_var(t_var)) {
3301 			pr_debug("sec '%s': unexpected non-VAR type found\n", sec_name);
3302 			return -EINVAL;
3303 		}
3304 
3305 		var = btf_var(t_var);
3306 		if (var->linkage == BTF_VAR_STATIC || var->linkage == BTF_VAR_GLOBAL_EXTERN)
3307 			continue;
3308 
3309 		var_name = btf__name_by_offset(btf, t_var->name_off);
3310 		if (!var_name) {
3311 			pr_debug("sec '%s': failed to find name of DATASEC's member #%d\n",
3312 				 sec_name, i);
3313 			return -ENOENT;
3314 		}
3315 
3316 		sym = find_elf_var_sym(obj, var_name);
3317 		if (IS_ERR(sym)) {
3318 			pr_debug("sec '%s': failed to find ELF symbol for VAR '%s'\n",
3319 				 sec_name, var_name);
3320 			return -ENOENT;
3321 		}
3322 
3323 		if (fixup_offsets)
3324 			vsi->offset = sym->st_value;
3325 
3326 		/* if variable is a global/weak symbol, but has restricted
3327 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF VAR
3328 		 * as static. This follows similar logic for functions (BPF
3329 		 * subprogs) and influences libbpf's further decisions about
3330 		 * whether to make global data BPF array maps as
3331 		 * BPF_F_MMAPABLE.
3332 		 */
3333 		if (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
3334 		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL)
3335 			var->linkage = BTF_VAR_STATIC;
3336 	}
3337 
3338 sort_vars:
3339 	qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
3340 	return 0;
3341 }
3342 
3343 static int bpf_object_fixup_btf(struct bpf_object *obj)
3344 {
3345 	int i, n, err = 0;
3346 
3347 	if (!obj->btf)
3348 		return 0;
3349 
3350 	n = btf__type_cnt(obj->btf);
3351 	for (i = 1; i < n; i++) {
3352 		struct btf_type *t = btf_type_by_id(obj->btf, i);
3353 
3354 		/* Loader needs to fix up some of the things compiler
3355 		 * couldn't get its hands on while emitting BTF. This
3356 		 * is section size and global variable offset. We use
3357 		 * the info from the ELF itself for this purpose.
3358 		 */
3359 		if (btf_is_datasec(t)) {
3360 			err = btf_fixup_datasec(obj, obj->btf, t);
3361 			if (err)
3362 				return err;
3363 		}
3364 	}
3365 
3366 	return 0;
3367 }
3368 
3369 static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
3370 {
3371 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
3372 	    prog->type == BPF_PROG_TYPE_LSM)
3373 		return true;
3374 
3375 	/* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
3376 	 * also need vmlinux BTF
3377 	 */
3378 	if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
3379 		return true;
3380 
3381 	return false;
3382 }
3383 
3384 static bool map_needs_vmlinux_btf(struct bpf_map *map)
3385 {
3386 	return bpf_map__is_struct_ops(map);
3387 }
3388 
3389 static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
3390 {
3391 	struct bpf_program *prog;
3392 	struct bpf_map *map;
3393 	int i;
3394 
3395 	/* CO-RE relocations need kernel BTF, only when btf_custom_path
3396 	 * is not specified
3397 	 */
3398 	if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
3399 		return true;
3400 
3401 	/* Support for typed ksyms needs kernel BTF */
3402 	for (i = 0; i < obj->nr_extern; i++) {
3403 		const struct extern_desc *ext;
3404 
3405 		ext = &obj->externs[i];
3406 		if (ext->type == EXT_KSYM && ext->ksym.type_id)
3407 			return true;
3408 	}
3409 
3410 	bpf_object__for_each_program(prog, obj) {
3411 		if (!prog->autoload)
3412 			continue;
3413 		if (prog_needs_vmlinux_btf(prog))
3414 			return true;
3415 	}
3416 
3417 	bpf_object__for_each_map(map, obj) {
3418 		if (map_needs_vmlinux_btf(map))
3419 			return true;
3420 	}
3421 
3422 	return false;
3423 }
3424 
3425 static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
3426 {
3427 	int err;
3428 
3429 	/* btf_vmlinux could be loaded earlier */
3430 	if (obj->btf_vmlinux || obj->gen_loader)
3431 		return 0;
3432 
3433 	if (!force && !obj_needs_vmlinux_btf(obj))
3434 		return 0;
3435 
3436 	obj->btf_vmlinux = btf__load_vmlinux_btf();
3437 	err = libbpf_get_error(obj->btf_vmlinux);
3438 	if (err) {
3439 		pr_warn("Error loading vmlinux BTF: %d\n", err);
3440 		obj->btf_vmlinux = NULL;
3441 		return err;
3442 	}
3443 	return 0;
3444 }
3445 
3446 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
3447 {
3448 	struct btf *kern_btf = obj->btf;
3449 	bool btf_mandatory, sanitize;
3450 	int i, err = 0;
3451 
3452 	if (!obj->btf)
3453 		return 0;
3454 
3455 	if (!kernel_supports(obj, FEAT_BTF)) {
3456 		if (kernel_needs_btf(obj)) {
3457 			err = -EOPNOTSUPP;
3458 			goto report;
3459 		}
3460 		pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
3461 		return 0;
3462 	}
3463 
3464 	/* Even though some subprogs are global/weak, user might prefer more
3465 	 * permissive BPF verification process that BPF verifier performs for
3466 	 * static functions, taking into account more context from the caller
3467 	 * functions. In such case, they need to mark such subprogs with
3468 	 * __attribute__((visibility("hidden"))) and libbpf will adjust
3469 	 * corresponding FUNC BTF type to be marked as static and trigger more
3470 	 * involved BPF verification process.
3471 	 */
3472 	for (i = 0; i < obj->nr_programs; i++) {
3473 		struct bpf_program *prog = &obj->programs[i];
3474 		struct btf_type *t;
3475 		const char *name;
3476 		int j, n;
3477 
3478 		if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
3479 			continue;
3480 
3481 		n = btf__type_cnt(obj->btf);
3482 		for (j = 1; j < n; j++) {
3483 			t = btf_type_by_id(obj->btf, j);
3484 			if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
3485 				continue;
3486 
3487 			name = btf__str_by_offset(obj->btf, t->name_off);
3488 			if (strcmp(name, prog->name) != 0)
3489 				continue;
3490 
3491 			t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
3492 			break;
3493 		}
3494 	}
3495 
3496 	sanitize = btf_needs_sanitization(obj);
3497 	if (sanitize) {
3498 		const void *raw_data;
3499 		__u32 sz;
3500 
3501 		/* clone BTF to sanitize a copy and leave the original intact */
3502 		raw_data = btf__raw_data(obj->btf, &sz);
3503 		kern_btf = btf__new(raw_data, sz);
3504 		err = libbpf_get_error(kern_btf);
3505 		if (err)
3506 			return err;
3507 
3508 		/* enforce 8-byte pointers for BPF-targeted BTFs */
3509 		btf__set_pointer_size(obj->btf, 8);
3510 		err = bpf_object__sanitize_btf(obj, kern_btf);
3511 		if (err)
3512 			return err;
3513 	}
3514 
3515 	if (obj->gen_loader) {
3516 		__u32 raw_size = 0;
3517 		const void *raw_data = btf__raw_data(kern_btf, &raw_size);
3518 
3519 		if (!raw_data)
3520 			return -ENOMEM;
3521 		bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
3522 		/* Pretend to have valid FD to pass various fd >= 0 checks.
3523 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
3524 		 */
3525 		btf__set_fd(kern_btf, 0);
3526 	} else {
3527 		/* currently BPF_BTF_LOAD only supports log_level 1 */
3528 		err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
3529 					   obj->log_level ? 1 : 0, obj->token_fd);
3530 	}
3531 	if (sanitize) {
3532 		if (!err) {
3533 			/* move fd to libbpf's BTF */
3534 			btf__set_fd(obj->btf, btf__fd(kern_btf));
3535 			btf__set_fd(kern_btf, -1);
3536 		}
3537 		btf__free(kern_btf);
3538 	}
3539 report:
3540 	if (err) {
3541 		btf_mandatory = kernel_needs_btf(obj);
3542 		pr_warn("Error loading .BTF into kernel: %d. %s\n", err,
3543 			btf_mandatory ? "BTF is mandatory, can't proceed."
3544 				      : "BTF is optional, ignoring.");
3545 		if (!btf_mandatory)
3546 			err = 0;
3547 	}
3548 	return err;
3549 }
3550 
3551 static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
3552 {
3553 	const char *name;
3554 
3555 	name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
3556 	if (!name) {
3557 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3558 			off, obj->path, elf_errmsg(-1));
3559 		return NULL;
3560 	}
3561 
3562 	return name;
3563 }
3564 
3565 static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
3566 {
3567 	const char *name;
3568 
3569 	name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
3570 	if (!name) {
3571 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3572 			off, obj->path, elf_errmsg(-1));
3573 		return NULL;
3574 	}
3575 
3576 	return name;
3577 }
3578 
3579 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
3580 {
3581 	Elf_Scn *scn;
3582 
3583 	scn = elf_getscn(obj->efile.elf, idx);
3584 	if (!scn) {
3585 		pr_warn("elf: failed to get section(%zu) from %s: %s\n",
3586 			idx, obj->path, elf_errmsg(-1));
3587 		return NULL;
3588 	}
3589 	return scn;
3590 }
3591 
3592 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
3593 {
3594 	Elf_Scn *scn = NULL;
3595 	Elf *elf = obj->efile.elf;
3596 	const char *sec_name;
3597 
3598 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3599 		sec_name = elf_sec_name(obj, scn);
3600 		if (!sec_name)
3601 			return NULL;
3602 
3603 		if (strcmp(sec_name, name) != 0)
3604 			continue;
3605 
3606 		return scn;
3607 	}
3608 	return NULL;
3609 }
3610 
3611 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn)
3612 {
3613 	Elf64_Shdr *shdr;
3614 
3615 	if (!scn)
3616 		return NULL;
3617 
3618 	shdr = elf64_getshdr(scn);
3619 	if (!shdr) {
3620 		pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
3621 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3622 		return NULL;
3623 	}
3624 
3625 	return shdr;
3626 }
3627 
3628 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
3629 {
3630 	const char *name;
3631 	Elf64_Shdr *sh;
3632 
3633 	if (!scn)
3634 		return NULL;
3635 
3636 	sh = elf_sec_hdr(obj, scn);
3637 	if (!sh)
3638 		return NULL;
3639 
3640 	name = elf_sec_str(obj, sh->sh_name);
3641 	if (!name) {
3642 		pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
3643 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3644 		return NULL;
3645 	}
3646 
3647 	return name;
3648 }
3649 
3650 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
3651 {
3652 	Elf_Data *data;
3653 
3654 	if (!scn)
3655 		return NULL;
3656 
3657 	data = elf_getdata(scn, 0);
3658 	if (!data) {
3659 		pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
3660 			elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
3661 			obj->path, elf_errmsg(-1));
3662 		return NULL;
3663 	}
3664 
3665 	return data;
3666 }
3667 
3668 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx)
3669 {
3670 	if (idx >= obj->efile.symbols->d_size / sizeof(Elf64_Sym))
3671 		return NULL;
3672 
3673 	return (Elf64_Sym *)obj->efile.symbols->d_buf + idx;
3674 }
3675 
3676 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx)
3677 {
3678 	if (idx >= data->d_size / sizeof(Elf64_Rel))
3679 		return NULL;
3680 
3681 	return (Elf64_Rel *)data->d_buf + idx;
3682 }
3683 
3684 static bool is_sec_name_dwarf(const char *name)
3685 {
3686 	/* approximation, but the actual list is too long */
3687 	return str_has_pfx(name, ".debug_");
3688 }
3689 
3690 static bool ignore_elf_section(Elf64_Shdr *hdr, const char *name)
3691 {
3692 	/* no special handling of .strtab */
3693 	if (hdr->sh_type == SHT_STRTAB)
3694 		return true;
3695 
3696 	/* ignore .llvm_addrsig section as well */
3697 	if (hdr->sh_type == SHT_LLVM_ADDRSIG)
3698 		return true;
3699 
3700 	/* no subprograms will lead to an empty .text section, ignore it */
3701 	if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
3702 	    strcmp(name, ".text") == 0)
3703 		return true;
3704 
3705 	/* DWARF sections */
3706 	if (is_sec_name_dwarf(name))
3707 		return true;
3708 
3709 	if (str_has_pfx(name, ".rel")) {
3710 		name += sizeof(".rel") - 1;
3711 		/* DWARF section relocations */
3712 		if (is_sec_name_dwarf(name))
3713 			return true;
3714 
3715 		/* .BTF and .BTF.ext don't need relocations */
3716 		if (strcmp(name, BTF_ELF_SEC) == 0 ||
3717 		    strcmp(name, BTF_EXT_ELF_SEC) == 0)
3718 			return true;
3719 	}
3720 
3721 	return false;
3722 }
3723 
3724 static int cmp_progs(const void *_a, const void *_b)
3725 {
3726 	const struct bpf_program *a = _a;
3727 	const struct bpf_program *b = _b;
3728 
3729 	if (a->sec_idx != b->sec_idx)
3730 		return a->sec_idx < b->sec_idx ? -1 : 1;
3731 
3732 	/* sec_insn_off can't be the same within the section */
3733 	return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
3734 }
3735 
3736 static int bpf_object__elf_collect(struct bpf_object *obj)
3737 {
3738 	struct elf_sec_desc *sec_desc;
3739 	Elf *elf = obj->efile.elf;
3740 	Elf_Data *btf_ext_data = NULL;
3741 	Elf_Data *btf_data = NULL;
3742 	int idx = 0, err = 0;
3743 	const char *name;
3744 	Elf_Data *data;
3745 	Elf_Scn *scn;
3746 	Elf64_Shdr *sh;
3747 
3748 	/* ELF section indices are 0-based, but sec #0 is special "invalid"
3749 	 * section. Since section count retrieved by elf_getshdrnum() does
3750 	 * include sec #0, it is already the necessary size of an array to keep
3751 	 * all the sections.
3752 	 */
3753 	if (elf_getshdrnum(obj->efile.elf, &obj->efile.sec_cnt)) {
3754 		pr_warn("elf: failed to get the number of sections for %s: %s\n",
3755 			obj->path, elf_errmsg(-1));
3756 		return -LIBBPF_ERRNO__FORMAT;
3757 	}
3758 	obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs));
3759 	if (!obj->efile.secs)
3760 		return -ENOMEM;
3761 
3762 	/* a bunch of ELF parsing functionality depends on processing symbols,
3763 	 * so do the first pass and find the symbol table
3764 	 */
3765 	scn = NULL;
3766 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3767 		sh = elf_sec_hdr(obj, scn);
3768 		if (!sh)
3769 			return -LIBBPF_ERRNO__FORMAT;
3770 
3771 		if (sh->sh_type == SHT_SYMTAB) {
3772 			if (obj->efile.symbols) {
3773 				pr_warn("elf: multiple symbol tables in %s\n", obj->path);
3774 				return -LIBBPF_ERRNO__FORMAT;
3775 			}
3776 
3777 			data = elf_sec_data(obj, scn);
3778 			if (!data)
3779 				return -LIBBPF_ERRNO__FORMAT;
3780 
3781 			idx = elf_ndxscn(scn);
3782 
3783 			obj->efile.symbols = data;
3784 			obj->efile.symbols_shndx = idx;
3785 			obj->efile.strtabidx = sh->sh_link;
3786 		}
3787 	}
3788 
3789 	if (!obj->efile.symbols) {
3790 		pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
3791 			obj->path);
3792 		return -ENOENT;
3793 	}
3794 
3795 	scn = NULL;
3796 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3797 		idx = elf_ndxscn(scn);
3798 		sec_desc = &obj->efile.secs[idx];
3799 
3800 		sh = elf_sec_hdr(obj, scn);
3801 		if (!sh)
3802 			return -LIBBPF_ERRNO__FORMAT;
3803 
3804 		name = elf_sec_str(obj, sh->sh_name);
3805 		if (!name)
3806 			return -LIBBPF_ERRNO__FORMAT;
3807 
3808 		if (ignore_elf_section(sh, name))
3809 			continue;
3810 
3811 		data = elf_sec_data(obj, scn);
3812 		if (!data)
3813 			return -LIBBPF_ERRNO__FORMAT;
3814 
3815 		pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
3816 			 idx, name, (unsigned long)data->d_size,
3817 			 (int)sh->sh_link, (unsigned long)sh->sh_flags,
3818 			 (int)sh->sh_type);
3819 
3820 		if (strcmp(name, "license") == 0) {
3821 			err = bpf_object__init_license(obj, data->d_buf, data->d_size);
3822 			if (err)
3823 				return err;
3824 		} else if (strcmp(name, "version") == 0) {
3825 			err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
3826 			if (err)
3827 				return err;
3828 		} else if (strcmp(name, "maps") == 0) {
3829 			pr_warn("elf: legacy map definitions in 'maps' section are not supported by libbpf v1.0+\n");
3830 			return -ENOTSUP;
3831 		} else if (strcmp(name, MAPS_ELF_SEC) == 0) {
3832 			obj->efile.btf_maps_shndx = idx;
3833 		} else if (strcmp(name, BTF_ELF_SEC) == 0) {
3834 			if (sh->sh_type != SHT_PROGBITS)
3835 				return -LIBBPF_ERRNO__FORMAT;
3836 			btf_data = data;
3837 		} else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
3838 			if (sh->sh_type != SHT_PROGBITS)
3839 				return -LIBBPF_ERRNO__FORMAT;
3840 			btf_ext_data = data;
3841 		} else if (sh->sh_type == SHT_SYMTAB) {
3842 			/* already processed during the first pass above */
3843 		} else if (sh->sh_type == SHT_PROGBITS && data->d_size > 0) {
3844 			if (sh->sh_flags & SHF_EXECINSTR) {
3845 				if (strcmp(name, ".text") == 0)
3846 					obj->efile.text_shndx = idx;
3847 				err = bpf_object__add_programs(obj, data, name, idx);
3848 				if (err)
3849 					return err;
3850 			} else if (strcmp(name, DATA_SEC) == 0 ||
3851 				   str_has_pfx(name, DATA_SEC ".")) {
3852 				sec_desc->sec_type = SEC_DATA;
3853 				sec_desc->shdr = sh;
3854 				sec_desc->data = data;
3855 			} else if (strcmp(name, RODATA_SEC) == 0 ||
3856 				   str_has_pfx(name, RODATA_SEC ".")) {
3857 				sec_desc->sec_type = SEC_RODATA;
3858 				sec_desc->shdr = sh;
3859 				sec_desc->data = data;
3860 			} else if (strcmp(name, STRUCT_OPS_SEC) == 0 ||
3861 				   strcmp(name, STRUCT_OPS_LINK_SEC) == 0 ||
3862 				   strcmp(name, "?" STRUCT_OPS_SEC) == 0 ||
3863 				   strcmp(name, "?" STRUCT_OPS_LINK_SEC) == 0) {
3864 				sec_desc->sec_type = SEC_ST_OPS;
3865 				sec_desc->shdr = sh;
3866 				sec_desc->data = data;
3867 				obj->efile.has_st_ops = true;
3868 			} else if (strcmp(name, ARENA_SEC) == 0) {
3869 				obj->efile.arena_data = data;
3870 				obj->efile.arena_data_shndx = idx;
3871 			} else {
3872 				pr_info("elf: skipping unrecognized data section(%d) %s\n",
3873 					idx, name);
3874 			}
3875 		} else if (sh->sh_type == SHT_REL) {
3876 			int targ_sec_idx = sh->sh_info; /* points to other section */
3877 
3878 			if (sh->sh_entsize != sizeof(Elf64_Rel) ||
3879 			    targ_sec_idx >= obj->efile.sec_cnt)
3880 				return -LIBBPF_ERRNO__FORMAT;
3881 
3882 			/* Only do relo for section with exec instructions */
3883 			if (!section_have_execinstr(obj, targ_sec_idx) &&
3884 			    strcmp(name, ".rel" STRUCT_OPS_SEC) &&
3885 			    strcmp(name, ".rel" STRUCT_OPS_LINK_SEC) &&
3886 			    strcmp(name, ".rel?" STRUCT_OPS_SEC) &&
3887 			    strcmp(name, ".rel?" STRUCT_OPS_LINK_SEC) &&
3888 			    strcmp(name, ".rel" MAPS_ELF_SEC)) {
3889 				pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
3890 					idx, name, targ_sec_idx,
3891 					elf_sec_name(obj, elf_sec_by_idx(obj, targ_sec_idx)) ?: "<?>");
3892 				continue;
3893 			}
3894 
3895 			sec_desc->sec_type = SEC_RELO;
3896 			sec_desc->shdr = sh;
3897 			sec_desc->data = data;
3898 		} else if (sh->sh_type == SHT_NOBITS && (strcmp(name, BSS_SEC) == 0 ||
3899 							 str_has_pfx(name, BSS_SEC "."))) {
3900 			sec_desc->sec_type = SEC_BSS;
3901 			sec_desc->shdr = sh;
3902 			sec_desc->data = data;
3903 		} else {
3904 			pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
3905 				(size_t)sh->sh_size);
3906 		}
3907 	}
3908 
3909 	if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
3910 		pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
3911 		return -LIBBPF_ERRNO__FORMAT;
3912 	}
3913 
3914 	/* sort BPF programs by section name and in-section instruction offset
3915 	 * for faster search
3916 	 */
3917 	if (obj->nr_programs)
3918 		qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
3919 
3920 	return bpf_object__init_btf(obj, btf_data, btf_ext_data);
3921 }
3922 
3923 static bool sym_is_extern(const Elf64_Sym *sym)
3924 {
3925 	int bind = ELF64_ST_BIND(sym->st_info);
3926 	/* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
3927 	return sym->st_shndx == SHN_UNDEF &&
3928 	       (bind == STB_GLOBAL || bind == STB_WEAK) &&
3929 	       ELF64_ST_TYPE(sym->st_info) == STT_NOTYPE;
3930 }
3931 
3932 static bool sym_is_subprog(const Elf64_Sym *sym, int text_shndx)
3933 {
3934 	int bind = ELF64_ST_BIND(sym->st_info);
3935 	int type = ELF64_ST_TYPE(sym->st_info);
3936 
3937 	/* in .text section */
3938 	if (sym->st_shndx != text_shndx)
3939 		return false;
3940 
3941 	/* local function */
3942 	if (bind == STB_LOCAL && type == STT_SECTION)
3943 		return true;
3944 
3945 	/* global function */
3946 	return bind == STB_GLOBAL && type == STT_FUNC;
3947 }
3948 
3949 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
3950 {
3951 	const struct btf_type *t;
3952 	const char *tname;
3953 	int i, n;
3954 
3955 	if (!btf)
3956 		return -ESRCH;
3957 
3958 	n = btf__type_cnt(btf);
3959 	for (i = 1; i < n; i++) {
3960 		t = btf__type_by_id(btf, i);
3961 
3962 		if (!btf_is_var(t) && !btf_is_func(t))
3963 			continue;
3964 
3965 		tname = btf__name_by_offset(btf, t->name_off);
3966 		if (strcmp(tname, ext_name))
3967 			continue;
3968 
3969 		if (btf_is_var(t) &&
3970 		    btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
3971 			return -EINVAL;
3972 
3973 		if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
3974 			return -EINVAL;
3975 
3976 		return i;
3977 	}
3978 
3979 	return -ENOENT;
3980 }
3981 
3982 static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
3983 	const struct btf_var_secinfo *vs;
3984 	const struct btf_type *t;
3985 	int i, j, n;
3986 
3987 	if (!btf)
3988 		return -ESRCH;
3989 
3990 	n = btf__type_cnt(btf);
3991 	for (i = 1; i < n; i++) {
3992 		t = btf__type_by_id(btf, i);
3993 
3994 		if (!btf_is_datasec(t))
3995 			continue;
3996 
3997 		vs = btf_var_secinfos(t);
3998 		for (j = 0; j < btf_vlen(t); j++, vs++) {
3999 			if (vs->type == ext_btf_id)
4000 				return i;
4001 		}
4002 	}
4003 
4004 	return -ENOENT;
4005 }
4006 
4007 static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
4008 				     bool *is_signed)
4009 {
4010 	const struct btf_type *t;
4011 	const char *name;
4012 
4013 	t = skip_mods_and_typedefs(btf, id, NULL);
4014 	name = btf__name_by_offset(btf, t->name_off);
4015 
4016 	if (is_signed)
4017 		*is_signed = false;
4018 	switch (btf_kind(t)) {
4019 	case BTF_KIND_INT: {
4020 		int enc = btf_int_encoding(t);
4021 
4022 		if (enc & BTF_INT_BOOL)
4023 			return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
4024 		if (is_signed)
4025 			*is_signed = enc & BTF_INT_SIGNED;
4026 		if (t->size == 1)
4027 			return KCFG_CHAR;
4028 		if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
4029 			return KCFG_UNKNOWN;
4030 		return KCFG_INT;
4031 	}
4032 	case BTF_KIND_ENUM:
4033 		if (t->size != 4)
4034 			return KCFG_UNKNOWN;
4035 		if (strcmp(name, "libbpf_tristate"))
4036 			return KCFG_UNKNOWN;
4037 		return KCFG_TRISTATE;
4038 	case BTF_KIND_ENUM64:
4039 		if (strcmp(name, "libbpf_tristate"))
4040 			return KCFG_UNKNOWN;
4041 		return KCFG_TRISTATE;
4042 	case BTF_KIND_ARRAY:
4043 		if (btf_array(t)->nelems == 0)
4044 			return KCFG_UNKNOWN;
4045 		if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
4046 			return KCFG_UNKNOWN;
4047 		return KCFG_CHAR_ARR;
4048 	default:
4049 		return KCFG_UNKNOWN;
4050 	}
4051 }
4052 
4053 static int cmp_externs(const void *_a, const void *_b)
4054 {
4055 	const struct extern_desc *a = _a;
4056 	const struct extern_desc *b = _b;
4057 
4058 	if (a->type != b->type)
4059 		return a->type < b->type ? -1 : 1;
4060 
4061 	if (a->type == EXT_KCFG) {
4062 		/* descending order by alignment requirements */
4063 		if (a->kcfg.align != b->kcfg.align)
4064 			return a->kcfg.align > b->kcfg.align ? -1 : 1;
4065 		/* ascending order by size, within same alignment class */
4066 		if (a->kcfg.sz != b->kcfg.sz)
4067 			return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
4068 	}
4069 
4070 	/* resolve ties by name */
4071 	return strcmp(a->name, b->name);
4072 }
4073 
4074 static int find_int_btf_id(const struct btf *btf)
4075 {
4076 	const struct btf_type *t;
4077 	int i, n;
4078 
4079 	n = btf__type_cnt(btf);
4080 	for (i = 1; i < n; i++) {
4081 		t = btf__type_by_id(btf, i);
4082 
4083 		if (btf_is_int(t) && btf_int_bits(t) == 32)
4084 			return i;
4085 	}
4086 
4087 	return 0;
4088 }
4089 
4090 static int add_dummy_ksym_var(struct btf *btf)
4091 {
4092 	int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
4093 	const struct btf_var_secinfo *vs;
4094 	const struct btf_type *sec;
4095 
4096 	if (!btf)
4097 		return 0;
4098 
4099 	sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
4100 					    BTF_KIND_DATASEC);
4101 	if (sec_btf_id < 0)
4102 		return 0;
4103 
4104 	sec = btf__type_by_id(btf, sec_btf_id);
4105 	vs = btf_var_secinfos(sec);
4106 	for (i = 0; i < btf_vlen(sec); i++, vs++) {
4107 		const struct btf_type *vt;
4108 
4109 		vt = btf__type_by_id(btf, vs->type);
4110 		if (btf_is_func(vt))
4111 			break;
4112 	}
4113 
4114 	/* No func in ksyms sec.  No need to add dummy var. */
4115 	if (i == btf_vlen(sec))
4116 		return 0;
4117 
4118 	int_btf_id = find_int_btf_id(btf);
4119 	dummy_var_btf_id = btf__add_var(btf,
4120 					"dummy_ksym",
4121 					BTF_VAR_GLOBAL_ALLOCATED,
4122 					int_btf_id);
4123 	if (dummy_var_btf_id < 0)
4124 		pr_warn("cannot create a dummy_ksym var\n");
4125 
4126 	return dummy_var_btf_id;
4127 }
4128 
4129 static int bpf_object__collect_externs(struct bpf_object *obj)
4130 {
4131 	struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
4132 	const struct btf_type *t;
4133 	struct extern_desc *ext;
4134 	int i, n, off, dummy_var_btf_id;
4135 	const char *ext_name, *sec_name;
4136 	size_t ext_essent_len;
4137 	Elf_Scn *scn;
4138 	Elf64_Shdr *sh;
4139 
4140 	if (!obj->efile.symbols)
4141 		return 0;
4142 
4143 	scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
4144 	sh = elf_sec_hdr(obj, scn);
4145 	if (!sh || sh->sh_entsize != sizeof(Elf64_Sym))
4146 		return -LIBBPF_ERRNO__FORMAT;
4147 
4148 	dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
4149 	if (dummy_var_btf_id < 0)
4150 		return dummy_var_btf_id;
4151 
4152 	n = sh->sh_size / sh->sh_entsize;
4153 	pr_debug("looking for externs among %d symbols...\n", n);
4154 
4155 	for (i = 0; i < n; i++) {
4156 		Elf64_Sym *sym = elf_sym_by_idx(obj, i);
4157 
4158 		if (!sym)
4159 			return -LIBBPF_ERRNO__FORMAT;
4160 		if (!sym_is_extern(sym))
4161 			continue;
4162 		ext_name = elf_sym_str(obj, sym->st_name);
4163 		if (!ext_name || !ext_name[0])
4164 			continue;
4165 
4166 		ext = obj->externs;
4167 		ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
4168 		if (!ext)
4169 			return -ENOMEM;
4170 		obj->externs = ext;
4171 		ext = &ext[obj->nr_extern];
4172 		memset(ext, 0, sizeof(*ext));
4173 		obj->nr_extern++;
4174 
4175 		ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
4176 		if (ext->btf_id <= 0) {
4177 			pr_warn("failed to find BTF for extern '%s': %d\n",
4178 				ext_name, ext->btf_id);
4179 			return ext->btf_id;
4180 		}
4181 		t = btf__type_by_id(obj->btf, ext->btf_id);
4182 		ext->name = btf__name_by_offset(obj->btf, t->name_off);
4183 		ext->sym_idx = i;
4184 		ext->is_weak = ELF64_ST_BIND(sym->st_info) == STB_WEAK;
4185 
4186 		ext_essent_len = bpf_core_essential_name_len(ext->name);
4187 		ext->essent_name = NULL;
4188 		if (ext_essent_len != strlen(ext->name)) {
4189 			ext->essent_name = strndup(ext->name, ext_essent_len);
4190 			if (!ext->essent_name)
4191 				return -ENOMEM;
4192 		}
4193 
4194 		ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
4195 		if (ext->sec_btf_id <= 0) {
4196 			pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
4197 				ext_name, ext->btf_id, ext->sec_btf_id);
4198 			return ext->sec_btf_id;
4199 		}
4200 		sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
4201 		sec_name = btf__name_by_offset(obj->btf, sec->name_off);
4202 
4203 		if (strcmp(sec_name, KCONFIG_SEC) == 0) {
4204 			if (btf_is_func(t)) {
4205 				pr_warn("extern function %s is unsupported under %s section\n",
4206 					ext->name, KCONFIG_SEC);
4207 				return -ENOTSUP;
4208 			}
4209 			kcfg_sec = sec;
4210 			ext->type = EXT_KCFG;
4211 			ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
4212 			if (ext->kcfg.sz <= 0) {
4213 				pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
4214 					ext_name, ext->kcfg.sz);
4215 				return ext->kcfg.sz;
4216 			}
4217 			ext->kcfg.align = btf__align_of(obj->btf, t->type);
4218 			if (ext->kcfg.align <= 0) {
4219 				pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
4220 					ext_name, ext->kcfg.align);
4221 				return -EINVAL;
4222 			}
4223 			ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
4224 							&ext->kcfg.is_signed);
4225 			if (ext->kcfg.type == KCFG_UNKNOWN) {
4226 				pr_warn("extern (kcfg) '%s': type is unsupported\n", ext_name);
4227 				return -ENOTSUP;
4228 			}
4229 		} else if (strcmp(sec_name, KSYMS_SEC) == 0) {
4230 			ksym_sec = sec;
4231 			ext->type = EXT_KSYM;
4232 			skip_mods_and_typedefs(obj->btf, t->type,
4233 					       &ext->ksym.type_id);
4234 		} else {
4235 			pr_warn("unrecognized extern section '%s'\n", sec_name);
4236 			return -ENOTSUP;
4237 		}
4238 	}
4239 	pr_debug("collected %d externs total\n", obj->nr_extern);
4240 
4241 	if (!obj->nr_extern)
4242 		return 0;
4243 
4244 	/* sort externs by type, for kcfg ones also by (align, size, name) */
4245 	qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
4246 
4247 	/* for .ksyms section, we need to turn all externs into allocated
4248 	 * variables in BTF to pass kernel verification; we do this by
4249 	 * pretending that each extern is a 8-byte variable
4250 	 */
4251 	if (ksym_sec) {
4252 		/* find existing 4-byte integer type in BTF to use for fake
4253 		 * extern variables in DATASEC
4254 		 */
4255 		int int_btf_id = find_int_btf_id(obj->btf);
4256 		/* For extern function, a dummy_var added earlier
4257 		 * will be used to replace the vs->type and
4258 		 * its name string will be used to refill
4259 		 * the missing param's name.
4260 		 */
4261 		const struct btf_type *dummy_var;
4262 
4263 		dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
4264 		for (i = 0; i < obj->nr_extern; i++) {
4265 			ext = &obj->externs[i];
4266 			if (ext->type != EXT_KSYM)
4267 				continue;
4268 			pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
4269 				 i, ext->sym_idx, ext->name);
4270 		}
4271 
4272 		sec = ksym_sec;
4273 		n = btf_vlen(sec);
4274 		for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
4275 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4276 			struct btf_type *vt;
4277 
4278 			vt = (void *)btf__type_by_id(obj->btf, vs->type);
4279 			ext_name = btf__name_by_offset(obj->btf, vt->name_off);
4280 			ext = find_extern_by_name(obj, ext_name);
4281 			if (!ext) {
4282 				pr_warn("failed to find extern definition for BTF %s '%s'\n",
4283 					btf_kind_str(vt), ext_name);
4284 				return -ESRCH;
4285 			}
4286 			if (btf_is_func(vt)) {
4287 				const struct btf_type *func_proto;
4288 				struct btf_param *param;
4289 				int j;
4290 
4291 				func_proto = btf__type_by_id(obj->btf,
4292 							     vt->type);
4293 				param = btf_params(func_proto);
4294 				/* Reuse the dummy_var string if the
4295 				 * func proto does not have param name.
4296 				 */
4297 				for (j = 0; j < btf_vlen(func_proto); j++)
4298 					if (param[j].type && !param[j].name_off)
4299 						param[j].name_off =
4300 							dummy_var->name_off;
4301 				vs->type = dummy_var_btf_id;
4302 				vt->info &= ~0xffff;
4303 				vt->info |= BTF_FUNC_GLOBAL;
4304 			} else {
4305 				btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4306 				vt->type = int_btf_id;
4307 			}
4308 			vs->offset = off;
4309 			vs->size = sizeof(int);
4310 		}
4311 		sec->size = off;
4312 	}
4313 
4314 	if (kcfg_sec) {
4315 		sec = kcfg_sec;
4316 		/* for kcfg externs calculate their offsets within a .kconfig map */
4317 		off = 0;
4318 		for (i = 0; i < obj->nr_extern; i++) {
4319 			ext = &obj->externs[i];
4320 			if (ext->type != EXT_KCFG)
4321 				continue;
4322 
4323 			ext->kcfg.data_off = roundup(off, ext->kcfg.align);
4324 			off = ext->kcfg.data_off + ext->kcfg.sz;
4325 			pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
4326 				 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
4327 		}
4328 		sec->size = off;
4329 		n = btf_vlen(sec);
4330 		for (i = 0; i < n; i++) {
4331 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4332 
4333 			t = btf__type_by_id(obj->btf, vs->type);
4334 			ext_name = btf__name_by_offset(obj->btf, t->name_off);
4335 			ext = find_extern_by_name(obj, ext_name);
4336 			if (!ext) {
4337 				pr_warn("failed to find extern definition for BTF var '%s'\n",
4338 					ext_name);
4339 				return -ESRCH;
4340 			}
4341 			btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4342 			vs->offset = ext->kcfg.data_off;
4343 		}
4344 	}
4345 	return 0;
4346 }
4347 
4348 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog)
4349 {
4350 	return prog->sec_idx == obj->efile.text_shndx && obj->nr_programs > 1;
4351 }
4352 
4353 struct bpf_program *
4354 bpf_object__find_program_by_name(const struct bpf_object *obj,
4355 				 const char *name)
4356 {
4357 	struct bpf_program *prog;
4358 
4359 	bpf_object__for_each_program(prog, obj) {
4360 		if (prog_is_subprog(obj, prog))
4361 			continue;
4362 		if (!strcmp(prog->name, name))
4363 			return prog;
4364 	}
4365 	return errno = ENOENT, NULL;
4366 }
4367 
4368 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
4369 				      int shndx)
4370 {
4371 	switch (obj->efile.secs[shndx].sec_type) {
4372 	case SEC_BSS:
4373 	case SEC_DATA:
4374 	case SEC_RODATA:
4375 		return true;
4376 	default:
4377 		return false;
4378 	}
4379 }
4380 
4381 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
4382 				      int shndx)
4383 {
4384 	return shndx == obj->efile.btf_maps_shndx;
4385 }
4386 
4387 static enum libbpf_map_type
4388 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
4389 {
4390 	if (shndx == obj->efile.symbols_shndx)
4391 		return LIBBPF_MAP_KCONFIG;
4392 
4393 	switch (obj->efile.secs[shndx].sec_type) {
4394 	case SEC_BSS:
4395 		return LIBBPF_MAP_BSS;
4396 	case SEC_DATA:
4397 		return LIBBPF_MAP_DATA;
4398 	case SEC_RODATA:
4399 		return LIBBPF_MAP_RODATA;
4400 	default:
4401 		return LIBBPF_MAP_UNSPEC;
4402 	}
4403 }
4404 
4405 static int bpf_program__record_reloc(struct bpf_program *prog,
4406 				     struct reloc_desc *reloc_desc,
4407 				     __u32 insn_idx, const char *sym_name,
4408 				     const Elf64_Sym *sym, const Elf64_Rel *rel)
4409 {
4410 	struct bpf_insn *insn = &prog->insns[insn_idx];
4411 	size_t map_idx, nr_maps = prog->obj->nr_maps;
4412 	struct bpf_object *obj = prog->obj;
4413 	__u32 shdr_idx = sym->st_shndx;
4414 	enum libbpf_map_type type;
4415 	const char *sym_sec_name;
4416 	struct bpf_map *map;
4417 
4418 	if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
4419 		pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n",
4420 			prog->name, sym_name, insn_idx, insn->code);
4421 		return -LIBBPF_ERRNO__RELOC;
4422 	}
4423 
4424 	if (sym_is_extern(sym)) {
4425 		int sym_idx = ELF64_R_SYM(rel->r_info);
4426 		int i, n = obj->nr_extern;
4427 		struct extern_desc *ext;
4428 
4429 		for (i = 0; i < n; i++) {
4430 			ext = &obj->externs[i];
4431 			if (ext->sym_idx == sym_idx)
4432 				break;
4433 		}
4434 		if (i >= n) {
4435 			pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
4436 				prog->name, sym_name, sym_idx);
4437 			return -LIBBPF_ERRNO__RELOC;
4438 		}
4439 		pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
4440 			 prog->name, i, ext->name, ext->sym_idx, insn_idx);
4441 		if (insn->code == (BPF_JMP | BPF_CALL))
4442 			reloc_desc->type = RELO_EXTERN_CALL;
4443 		else
4444 			reloc_desc->type = RELO_EXTERN_LD64;
4445 		reloc_desc->insn_idx = insn_idx;
4446 		reloc_desc->ext_idx = i;
4447 		return 0;
4448 	}
4449 
4450 	/* sub-program call relocation */
4451 	if (is_call_insn(insn)) {
4452 		if (insn->src_reg != BPF_PSEUDO_CALL) {
4453 			pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
4454 			return -LIBBPF_ERRNO__RELOC;
4455 		}
4456 		/* text_shndx can be 0, if no default "main" program exists */
4457 		if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
4458 			sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4459 			pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
4460 				prog->name, sym_name, sym_sec_name);
4461 			return -LIBBPF_ERRNO__RELOC;
4462 		}
4463 		if (sym->st_value % BPF_INSN_SZ) {
4464 			pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
4465 				prog->name, sym_name, (size_t)sym->st_value);
4466 			return -LIBBPF_ERRNO__RELOC;
4467 		}
4468 		reloc_desc->type = RELO_CALL;
4469 		reloc_desc->insn_idx = insn_idx;
4470 		reloc_desc->sym_off = sym->st_value;
4471 		return 0;
4472 	}
4473 
4474 	if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
4475 		pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
4476 			prog->name, sym_name, shdr_idx);
4477 		return -LIBBPF_ERRNO__RELOC;
4478 	}
4479 
4480 	/* loading subprog addresses */
4481 	if (sym_is_subprog(sym, obj->efile.text_shndx)) {
4482 		/* global_func: sym->st_value = offset in the section, insn->imm = 0.
4483 		 * local_func: sym->st_value = 0, insn->imm = offset in the section.
4484 		 */
4485 		if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
4486 			pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
4487 				prog->name, sym_name, (size_t)sym->st_value, insn->imm);
4488 			return -LIBBPF_ERRNO__RELOC;
4489 		}
4490 
4491 		reloc_desc->type = RELO_SUBPROG_ADDR;
4492 		reloc_desc->insn_idx = insn_idx;
4493 		reloc_desc->sym_off = sym->st_value;
4494 		return 0;
4495 	}
4496 
4497 	type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
4498 	sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4499 
4500 	/* arena data relocation */
4501 	if (shdr_idx == obj->efile.arena_data_shndx) {
4502 		reloc_desc->type = RELO_DATA;
4503 		reloc_desc->insn_idx = insn_idx;
4504 		reloc_desc->map_idx = obj->arena_map - obj->maps;
4505 		reloc_desc->sym_off = sym->st_value;
4506 		return 0;
4507 	}
4508 
4509 	/* generic map reference relocation */
4510 	if (type == LIBBPF_MAP_UNSPEC) {
4511 		if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
4512 			pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
4513 				prog->name, sym_name, sym_sec_name);
4514 			return -LIBBPF_ERRNO__RELOC;
4515 		}
4516 		for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4517 			map = &obj->maps[map_idx];
4518 			if (map->libbpf_type != type ||
4519 			    map->sec_idx != sym->st_shndx ||
4520 			    map->sec_offset != sym->st_value)
4521 				continue;
4522 			pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n",
4523 				 prog->name, map_idx, map->name, map->sec_idx,
4524 				 map->sec_offset, insn_idx);
4525 			break;
4526 		}
4527 		if (map_idx >= nr_maps) {
4528 			pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
4529 				prog->name, sym_sec_name, (size_t)sym->st_value);
4530 			return -LIBBPF_ERRNO__RELOC;
4531 		}
4532 		reloc_desc->type = RELO_LD64;
4533 		reloc_desc->insn_idx = insn_idx;
4534 		reloc_desc->map_idx = map_idx;
4535 		reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
4536 		return 0;
4537 	}
4538 
4539 	/* global data map relocation */
4540 	if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
4541 		pr_warn("prog '%s': bad data relo against section '%s'\n",
4542 			prog->name, sym_sec_name);
4543 		return -LIBBPF_ERRNO__RELOC;
4544 	}
4545 	for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4546 		map = &obj->maps[map_idx];
4547 		if (map->libbpf_type != type || map->sec_idx != sym->st_shndx)
4548 			continue;
4549 		pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n",
4550 			 prog->name, map_idx, map->name, map->sec_idx,
4551 			 map->sec_offset, insn_idx);
4552 		break;
4553 	}
4554 	if (map_idx >= nr_maps) {
4555 		pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
4556 			prog->name, sym_sec_name);
4557 		return -LIBBPF_ERRNO__RELOC;
4558 	}
4559 
4560 	reloc_desc->type = RELO_DATA;
4561 	reloc_desc->insn_idx = insn_idx;
4562 	reloc_desc->map_idx = map_idx;
4563 	reloc_desc->sym_off = sym->st_value;
4564 	return 0;
4565 }
4566 
4567 static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
4568 {
4569 	return insn_idx >= prog->sec_insn_off &&
4570 	       insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
4571 }
4572 
4573 static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
4574 						 size_t sec_idx, size_t insn_idx)
4575 {
4576 	int l = 0, r = obj->nr_programs - 1, m;
4577 	struct bpf_program *prog;
4578 
4579 	if (!obj->nr_programs)
4580 		return NULL;
4581 
4582 	while (l < r) {
4583 		m = l + (r - l + 1) / 2;
4584 		prog = &obj->programs[m];
4585 
4586 		if (prog->sec_idx < sec_idx ||
4587 		    (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
4588 			l = m;
4589 		else
4590 			r = m - 1;
4591 	}
4592 	/* matching program could be at index l, but it still might be the
4593 	 * wrong one, so we need to double check conditions for the last time
4594 	 */
4595 	prog = &obj->programs[l];
4596 	if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
4597 		return prog;
4598 	return NULL;
4599 }
4600 
4601 static int
4602 bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
4603 {
4604 	const char *relo_sec_name, *sec_name;
4605 	size_t sec_idx = shdr->sh_info, sym_idx;
4606 	struct bpf_program *prog;
4607 	struct reloc_desc *relos;
4608 	int err, i, nrels;
4609 	const char *sym_name;
4610 	__u32 insn_idx;
4611 	Elf_Scn *scn;
4612 	Elf_Data *scn_data;
4613 	Elf64_Sym *sym;
4614 	Elf64_Rel *rel;
4615 
4616 	if (sec_idx >= obj->efile.sec_cnt)
4617 		return -EINVAL;
4618 
4619 	scn = elf_sec_by_idx(obj, sec_idx);
4620 	scn_data = elf_sec_data(obj, scn);
4621 	if (!scn_data)
4622 		return -LIBBPF_ERRNO__FORMAT;
4623 
4624 	relo_sec_name = elf_sec_str(obj, shdr->sh_name);
4625 	sec_name = elf_sec_name(obj, scn);
4626 	if (!relo_sec_name || !sec_name)
4627 		return -EINVAL;
4628 
4629 	pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
4630 		 relo_sec_name, sec_idx, sec_name);
4631 	nrels = shdr->sh_size / shdr->sh_entsize;
4632 
4633 	for (i = 0; i < nrels; i++) {
4634 		rel = elf_rel_by_idx(data, i);
4635 		if (!rel) {
4636 			pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
4637 			return -LIBBPF_ERRNO__FORMAT;
4638 		}
4639 
4640 		sym_idx = ELF64_R_SYM(rel->r_info);
4641 		sym = elf_sym_by_idx(obj, sym_idx);
4642 		if (!sym) {
4643 			pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
4644 				relo_sec_name, sym_idx, i);
4645 			return -LIBBPF_ERRNO__FORMAT;
4646 		}
4647 
4648 		if (sym->st_shndx >= obj->efile.sec_cnt) {
4649 			pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
4650 				relo_sec_name, sym_idx, (size_t)sym->st_shndx, i);
4651 			return -LIBBPF_ERRNO__FORMAT;
4652 		}
4653 
4654 		if (rel->r_offset % BPF_INSN_SZ || rel->r_offset >= scn_data->d_size) {
4655 			pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
4656 				relo_sec_name, (size_t)rel->r_offset, i);
4657 			return -LIBBPF_ERRNO__FORMAT;
4658 		}
4659 
4660 		insn_idx = rel->r_offset / BPF_INSN_SZ;
4661 		/* relocations against static functions are recorded as
4662 		 * relocations against the section that contains a function;
4663 		 * in such case, symbol will be STT_SECTION and sym.st_name
4664 		 * will point to empty string (0), so fetch section name
4665 		 * instead
4666 		 */
4667 		if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
4668 			sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx));
4669 		else
4670 			sym_name = elf_sym_str(obj, sym->st_name);
4671 		sym_name = sym_name ?: "<?";
4672 
4673 		pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
4674 			 relo_sec_name, i, insn_idx, sym_name);
4675 
4676 		prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
4677 		if (!prog) {
4678 			pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
4679 				relo_sec_name, i, sec_name, insn_idx);
4680 			continue;
4681 		}
4682 
4683 		relos = libbpf_reallocarray(prog->reloc_desc,
4684 					    prog->nr_reloc + 1, sizeof(*relos));
4685 		if (!relos)
4686 			return -ENOMEM;
4687 		prog->reloc_desc = relos;
4688 
4689 		/* adjust insn_idx to local BPF program frame of reference */
4690 		insn_idx -= prog->sec_insn_off;
4691 		err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
4692 						insn_idx, sym_name, sym, rel);
4693 		if (err)
4694 			return err;
4695 
4696 		prog->nr_reloc++;
4697 	}
4698 	return 0;
4699 }
4700 
4701 static int map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map)
4702 {
4703 	int id;
4704 
4705 	if (!obj->btf)
4706 		return -ENOENT;
4707 
4708 	/* if it's BTF-defined map, we don't need to search for type IDs.
4709 	 * For struct_ops map, it does not need btf_key_type_id and
4710 	 * btf_value_type_id.
4711 	 */
4712 	if (map->sec_idx == obj->efile.btf_maps_shndx || bpf_map__is_struct_ops(map))
4713 		return 0;
4714 
4715 	/*
4716 	 * LLVM annotates global data differently in BTF, that is,
4717 	 * only as '.data', '.bss' or '.rodata'.
4718 	 */
4719 	if (!bpf_map__is_internal(map))
4720 		return -ENOENT;
4721 
4722 	id = btf__find_by_name(obj->btf, map->real_name);
4723 	if (id < 0)
4724 		return id;
4725 
4726 	map->btf_key_type_id = 0;
4727 	map->btf_value_type_id = id;
4728 	return 0;
4729 }
4730 
4731 static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
4732 {
4733 	char file[PATH_MAX], buff[4096];
4734 	FILE *fp;
4735 	__u32 val;
4736 	int err;
4737 
4738 	snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
4739 	memset(info, 0, sizeof(*info));
4740 
4741 	fp = fopen(file, "re");
4742 	if (!fp) {
4743 		err = -errno;
4744 		pr_warn("failed to open %s: %d. No procfs support?\n", file,
4745 			err);
4746 		return err;
4747 	}
4748 
4749 	while (fgets(buff, sizeof(buff), fp)) {
4750 		if (sscanf(buff, "map_type:\t%u", &val) == 1)
4751 			info->type = val;
4752 		else if (sscanf(buff, "key_size:\t%u", &val) == 1)
4753 			info->key_size = val;
4754 		else if (sscanf(buff, "value_size:\t%u", &val) == 1)
4755 			info->value_size = val;
4756 		else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
4757 			info->max_entries = val;
4758 		else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
4759 			info->map_flags = val;
4760 	}
4761 
4762 	fclose(fp);
4763 
4764 	return 0;
4765 }
4766 
4767 bool bpf_map__autocreate(const struct bpf_map *map)
4768 {
4769 	return map->autocreate;
4770 }
4771 
4772 int bpf_map__set_autocreate(struct bpf_map *map, bool autocreate)
4773 {
4774 	if (map->obj->loaded)
4775 		return libbpf_err(-EBUSY);
4776 
4777 	map->autocreate = autocreate;
4778 	return 0;
4779 }
4780 
4781 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
4782 {
4783 	struct bpf_map_info info;
4784 	__u32 len = sizeof(info), name_len;
4785 	int new_fd, err;
4786 	char *new_name;
4787 
4788 	memset(&info, 0, len);
4789 	err = bpf_map_get_info_by_fd(fd, &info, &len);
4790 	if (err && errno == EINVAL)
4791 		err = bpf_get_map_info_from_fdinfo(fd, &info);
4792 	if (err)
4793 		return libbpf_err(err);
4794 
4795 	name_len = strlen(info.name);
4796 	if (name_len == BPF_OBJ_NAME_LEN - 1 && strncmp(map->name, info.name, name_len) == 0)
4797 		new_name = strdup(map->name);
4798 	else
4799 		new_name = strdup(info.name);
4800 
4801 	if (!new_name)
4802 		return libbpf_err(-errno);
4803 
4804 	/*
4805 	 * Like dup(), but make sure new FD is >= 3 and has O_CLOEXEC set.
4806 	 * This is similar to what we do in ensure_good_fd(), but without
4807 	 * closing original FD.
4808 	 */
4809 	new_fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
4810 	if (new_fd < 0) {
4811 		err = -errno;
4812 		goto err_free_new_name;
4813 	}
4814 
4815 	err = reuse_fd(map->fd, new_fd);
4816 	if (err)
4817 		goto err_free_new_name;
4818 
4819 	free(map->name);
4820 
4821 	map->name = new_name;
4822 	map->def.type = info.type;
4823 	map->def.key_size = info.key_size;
4824 	map->def.value_size = info.value_size;
4825 	map->def.max_entries = info.max_entries;
4826 	map->def.map_flags = info.map_flags;
4827 	map->btf_key_type_id = info.btf_key_type_id;
4828 	map->btf_value_type_id = info.btf_value_type_id;
4829 	map->reused = true;
4830 	map->map_extra = info.map_extra;
4831 
4832 	return 0;
4833 
4834 err_free_new_name:
4835 	free(new_name);
4836 	return libbpf_err(err);
4837 }
4838 
4839 __u32 bpf_map__max_entries(const struct bpf_map *map)
4840 {
4841 	return map->def.max_entries;
4842 }
4843 
4844 struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
4845 {
4846 	if (!bpf_map_type__is_map_in_map(map->def.type))
4847 		return errno = EINVAL, NULL;
4848 
4849 	return map->inner_map;
4850 }
4851 
4852 int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
4853 {
4854 	if (map->obj->loaded)
4855 		return libbpf_err(-EBUSY);
4856 
4857 	map->def.max_entries = max_entries;
4858 
4859 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
4860 	if (map_is_ringbuf(map))
4861 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
4862 
4863 	return 0;
4864 }
4865 
4866 static int bpf_object_prepare_token(struct bpf_object *obj)
4867 {
4868 	const char *bpffs_path;
4869 	int bpffs_fd = -1, token_fd, err;
4870 	bool mandatory;
4871 	enum libbpf_print_level level;
4872 
4873 	/* token is explicitly prevented */
4874 	if (obj->token_path && obj->token_path[0] == '\0') {
4875 		pr_debug("object '%s': token is prevented, skipping...\n", obj->name);
4876 		return 0;
4877 	}
4878 
4879 	mandatory = obj->token_path != NULL;
4880 	level = mandatory ? LIBBPF_WARN : LIBBPF_DEBUG;
4881 
4882 	bpffs_path = obj->token_path ?: BPF_FS_DEFAULT_PATH;
4883 	bpffs_fd = open(bpffs_path, O_DIRECTORY, O_RDWR);
4884 	if (bpffs_fd < 0) {
4885 		err = -errno;
4886 		__pr(level, "object '%s': failed (%d) to open BPF FS mount at '%s'%s\n",
4887 		     obj->name, err, bpffs_path,
4888 		     mandatory ? "" : ", skipping optional step...");
4889 		return mandatory ? err : 0;
4890 	}
4891 
4892 	token_fd = bpf_token_create(bpffs_fd, 0);
4893 	close(bpffs_fd);
4894 	if (token_fd < 0) {
4895 		if (!mandatory && token_fd == -ENOENT) {
4896 			pr_debug("object '%s': BPF FS at '%s' doesn't have BPF token delegation set up, skipping...\n",
4897 				 obj->name, bpffs_path);
4898 			return 0;
4899 		}
4900 		__pr(level, "object '%s': failed (%d) to create BPF token from '%s'%s\n",
4901 		     obj->name, token_fd, bpffs_path,
4902 		     mandatory ? "" : ", skipping optional step...");
4903 		return mandatory ? token_fd : 0;
4904 	}
4905 
4906 	obj->feat_cache = calloc(1, sizeof(*obj->feat_cache));
4907 	if (!obj->feat_cache) {
4908 		close(token_fd);
4909 		return -ENOMEM;
4910 	}
4911 
4912 	obj->token_fd = token_fd;
4913 	obj->feat_cache->token_fd = token_fd;
4914 
4915 	return 0;
4916 }
4917 
4918 static int
4919 bpf_object__probe_loading(struct bpf_object *obj)
4920 {
4921 	char *cp, errmsg[STRERR_BUFSIZE];
4922 	struct bpf_insn insns[] = {
4923 		BPF_MOV64_IMM(BPF_REG_0, 0),
4924 		BPF_EXIT_INSN(),
4925 	};
4926 	int ret, insn_cnt = ARRAY_SIZE(insns);
4927 	LIBBPF_OPTS(bpf_prog_load_opts, opts,
4928 		.token_fd = obj->token_fd,
4929 		.prog_flags = obj->token_fd ? BPF_F_TOKEN_FD : 0,
4930 	);
4931 
4932 	if (obj->gen_loader)
4933 		return 0;
4934 
4935 	ret = bump_rlimit_memlock();
4936 	if (ret)
4937 		pr_warn("Failed to bump RLIMIT_MEMLOCK (err = %d), you might need to do it explicitly!\n", ret);
4938 
4939 	/* make sure basic loading works */
4940 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, &opts);
4941 	if (ret < 0)
4942 		ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, &opts);
4943 	if (ret < 0) {
4944 		ret = errno;
4945 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4946 		pr_warn("Error in %s():%s(%d). Couldn't load trivial BPF "
4947 			"program. Make sure your kernel supports BPF "
4948 			"(CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is "
4949 			"set to big enough value.\n", __func__, cp, ret);
4950 		return -ret;
4951 	}
4952 	close(ret);
4953 
4954 	return 0;
4955 }
4956 
4957 bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
4958 {
4959 	if (obj->gen_loader)
4960 		/* To generate loader program assume the latest kernel
4961 		 * to avoid doing extra prog_load, map_create syscalls.
4962 		 */
4963 		return true;
4964 
4965 	if (obj->token_fd)
4966 		return feat_supported(obj->feat_cache, feat_id);
4967 
4968 	return feat_supported(NULL, feat_id);
4969 }
4970 
4971 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
4972 {
4973 	struct bpf_map_info map_info;
4974 	char msg[STRERR_BUFSIZE];
4975 	__u32 map_info_len = sizeof(map_info);
4976 	int err;
4977 
4978 	memset(&map_info, 0, map_info_len);
4979 	err = bpf_map_get_info_by_fd(map_fd, &map_info, &map_info_len);
4980 	if (err && errno == EINVAL)
4981 		err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
4982 	if (err) {
4983 		pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
4984 			libbpf_strerror_r(errno, msg, sizeof(msg)));
4985 		return false;
4986 	}
4987 
4988 	return (map_info.type == map->def.type &&
4989 		map_info.key_size == map->def.key_size &&
4990 		map_info.value_size == map->def.value_size &&
4991 		map_info.max_entries == map->def.max_entries &&
4992 		map_info.map_flags == map->def.map_flags &&
4993 		map_info.map_extra == map->map_extra);
4994 }
4995 
4996 static int
4997 bpf_object__reuse_map(struct bpf_map *map)
4998 {
4999 	char *cp, errmsg[STRERR_BUFSIZE];
5000 	int err, pin_fd;
5001 
5002 	pin_fd = bpf_obj_get(map->pin_path);
5003 	if (pin_fd < 0) {
5004 		err = -errno;
5005 		if (err == -ENOENT) {
5006 			pr_debug("found no pinned map to reuse at '%s'\n",
5007 				 map->pin_path);
5008 			return 0;
5009 		}
5010 
5011 		cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
5012 		pr_warn("couldn't retrieve pinned map '%s': %s\n",
5013 			map->pin_path, cp);
5014 		return err;
5015 	}
5016 
5017 	if (!map_is_reuse_compat(map, pin_fd)) {
5018 		pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
5019 			map->pin_path);
5020 		close(pin_fd);
5021 		return -EINVAL;
5022 	}
5023 
5024 	err = bpf_map__reuse_fd(map, pin_fd);
5025 	close(pin_fd);
5026 	if (err)
5027 		return err;
5028 
5029 	map->pinned = true;
5030 	pr_debug("reused pinned map at '%s'\n", map->pin_path);
5031 
5032 	return 0;
5033 }
5034 
5035 static int
5036 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
5037 {
5038 	enum libbpf_map_type map_type = map->libbpf_type;
5039 	char *cp, errmsg[STRERR_BUFSIZE];
5040 	int err, zero = 0;
5041 
5042 	if (obj->gen_loader) {
5043 		bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
5044 					 map->mmaped, map->def.value_size);
5045 		if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
5046 			bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
5047 		return 0;
5048 	}
5049 
5050 	err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
5051 	if (err) {
5052 		err = -errno;
5053 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5054 		pr_warn("Error setting initial map(%s) contents: %s\n",
5055 			map->name, cp);
5056 		return err;
5057 	}
5058 
5059 	/* Freeze .rodata and .kconfig map as read-only from syscall side. */
5060 	if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
5061 		err = bpf_map_freeze(map->fd);
5062 		if (err) {
5063 			err = -errno;
5064 			cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5065 			pr_warn("Error freezing map(%s) as read-only: %s\n",
5066 				map->name, cp);
5067 			return err;
5068 		}
5069 	}
5070 	return 0;
5071 }
5072 
5073 static void bpf_map__destroy(struct bpf_map *map);
5074 
5075 static bool map_is_created(const struct bpf_map *map)
5076 {
5077 	return map->obj->loaded || map->reused;
5078 }
5079 
5080 static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
5081 {
5082 	LIBBPF_OPTS(bpf_map_create_opts, create_attr);
5083 	struct bpf_map_def *def = &map->def;
5084 	const char *map_name = NULL;
5085 	int err = 0, map_fd;
5086 
5087 	if (kernel_supports(obj, FEAT_PROG_NAME))
5088 		map_name = map->name;
5089 	create_attr.map_ifindex = map->map_ifindex;
5090 	create_attr.map_flags = def->map_flags;
5091 	create_attr.numa_node = map->numa_node;
5092 	create_attr.map_extra = map->map_extra;
5093 	create_attr.token_fd = obj->token_fd;
5094 	if (obj->token_fd)
5095 		create_attr.map_flags |= BPF_F_TOKEN_FD;
5096 
5097 	if (bpf_map__is_struct_ops(map)) {
5098 		create_attr.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
5099 		if (map->mod_btf_fd >= 0) {
5100 			create_attr.value_type_btf_obj_fd = map->mod_btf_fd;
5101 			create_attr.map_flags |= BPF_F_VTYPE_BTF_OBJ_FD;
5102 		}
5103 	}
5104 
5105 	if (obj->btf && btf__fd(obj->btf) >= 0) {
5106 		create_attr.btf_fd = btf__fd(obj->btf);
5107 		create_attr.btf_key_type_id = map->btf_key_type_id;
5108 		create_attr.btf_value_type_id = map->btf_value_type_id;
5109 	}
5110 
5111 	if (bpf_map_type__is_map_in_map(def->type)) {
5112 		if (map->inner_map) {
5113 			err = map_set_def_max_entries(map->inner_map);
5114 			if (err)
5115 				return err;
5116 			err = bpf_object__create_map(obj, map->inner_map, true);
5117 			if (err) {
5118 				pr_warn("map '%s': failed to create inner map: %d\n",
5119 					map->name, err);
5120 				return err;
5121 			}
5122 			map->inner_map_fd = map->inner_map->fd;
5123 		}
5124 		if (map->inner_map_fd >= 0)
5125 			create_attr.inner_map_fd = map->inner_map_fd;
5126 	}
5127 
5128 	switch (def->type) {
5129 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5130 	case BPF_MAP_TYPE_CGROUP_ARRAY:
5131 	case BPF_MAP_TYPE_STACK_TRACE:
5132 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5133 	case BPF_MAP_TYPE_HASH_OF_MAPS:
5134 	case BPF_MAP_TYPE_DEVMAP:
5135 	case BPF_MAP_TYPE_DEVMAP_HASH:
5136 	case BPF_MAP_TYPE_CPUMAP:
5137 	case BPF_MAP_TYPE_XSKMAP:
5138 	case BPF_MAP_TYPE_SOCKMAP:
5139 	case BPF_MAP_TYPE_SOCKHASH:
5140 	case BPF_MAP_TYPE_QUEUE:
5141 	case BPF_MAP_TYPE_STACK:
5142 	case BPF_MAP_TYPE_ARENA:
5143 		create_attr.btf_fd = 0;
5144 		create_attr.btf_key_type_id = 0;
5145 		create_attr.btf_value_type_id = 0;
5146 		map->btf_key_type_id = 0;
5147 		map->btf_value_type_id = 0;
5148 		break;
5149 	case BPF_MAP_TYPE_STRUCT_OPS:
5150 		create_attr.btf_value_type_id = 0;
5151 		break;
5152 	default:
5153 		break;
5154 	}
5155 
5156 	if (obj->gen_loader) {
5157 		bpf_gen__map_create(obj->gen_loader, def->type, map_name,
5158 				    def->key_size, def->value_size, def->max_entries,
5159 				    &create_attr, is_inner ? -1 : map - obj->maps);
5160 		/* We keep pretenting we have valid FD to pass various fd >= 0
5161 		 * checks by just keeping original placeholder FDs in place.
5162 		 * See bpf_object__add_map() comment.
5163 		 * This placeholder fd will not be used with any syscall and
5164 		 * will be reset to -1 eventually.
5165 		 */
5166 		map_fd = map->fd;
5167 	} else {
5168 		map_fd = bpf_map_create(def->type, map_name,
5169 					def->key_size, def->value_size,
5170 					def->max_entries, &create_attr);
5171 	}
5172 	if (map_fd < 0 && (create_attr.btf_key_type_id || create_attr.btf_value_type_id)) {
5173 		char *cp, errmsg[STRERR_BUFSIZE];
5174 
5175 		err = -errno;
5176 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5177 		pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
5178 			map->name, cp, err);
5179 		create_attr.btf_fd = 0;
5180 		create_attr.btf_key_type_id = 0;
5181 		create_attr.btf_value_type_id = 0;
5182 		map->btf_key_type_id = 0;
5183 		map->btf_value_type_id = 0;
5184 		map_fd = bpf_map_create(def->type, map_name,
5185 					def->key_size, def->value_size,
5186 					def->max_entries, &create_attr);
5187 	}
5188 
5189 	if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
5190 		if (obj->gen_loader)
5191 			map->inner_map->fd = -1;
5192 		bpf_map__destroy(map->inner_map);
5193 		zfree(&map->inner_map);
5194 	}
5195 
5196 	if (map_fd < 0)
5197 		return map_fd;
5198 
5199 	/* obj->gen_loader case, prevent reuse_fd() from closing map_fd */
5200 	if (map->fd == map_fd)
5201 		return 0;
5202 
5203 	/* Keep placeholder FD value but now point it to the BPF map object.
5204 	 * This way everything that relied on this map's FD (e.g., relocated
5205 	 * ldimm64 instructions) will stay valid and won't need adjustments.
5206 	 * map->fd stays valid but now point to what map_fd points to.
5207 	 */
5208 	return reuse_fd(map->fd, map_fd);
5209 }
5210 
5211 static int init_map_in_map_slots(struct bpf_object *obj, struct bpf_map *map)
5212 {
5213 	const struct bpf_map *targ_map;
5214 	unsigned int i;
5215 	int fd, err = 0;
5216 
5217 	for (i = 0; i < map->init_slots_sz; i++) {
5218 		if (!map->init_slots[i])
5219 			continue;
5220 
5221 		targ_map = map->init_slots[i];
5222 		fd = targ_map->fd;
5223 
5224 		if (obj->gen_loader) {
5225 			bpf_gen__populate_outer_map(obj->gen_loader,
5226 						    map - obj->maps, i,
5227 						    targ_map - obj->maps);
5228 		} else {
5229 			err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5230 		}
5231 		if (err) {
5232 			err = -errno;
5233 			pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %d\n",
5234 				map->name, i, targ_map->name, fd, err);
5235 			return err;
5236 		}
5237 		pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
5238 			 map->name, i, targ_map->name, fd);
5239 	}
5240 
5241 	zfree(&map->init_slots);
5242 	map->init_slots_sz = 0;
5243 
5244 	return 0;
5245 }
5246 
5247 static int init_prog_array_slots(struct bpf_object *obj, struct bpf_map *map)
5248 {
5249 	const struct bpf_program *targ_prog;
5250 	unsigned int i;
5251 	int fd, err;
5252 
5253 	if (obj->gen_loader)
5254 		return -ENOTSUP;
5255 
5256 	for (i = 0; i < map->init_slots_sz; i++) {
5257 		if (!map->init_slots[i])
5258 			continue;
5259 
5260 		targ_prog = map->init_slots[i];
5261 		fd = bpf_program__fd(targ_prog);
5262 
5263 		err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5264 		if (err) {
5265 			err = -errno;
5266 			pr_warn("map '%s': failed to initialize slot [%d] to prog '%s' fd=%d: %d\n",
5267 				map->name, i, targ_prog->name, fd, err);
5268 			return err;
5269 		}
5270 		pr_debug("map '%s': slot [%d] set to prog '%s' fd=%d\n",
5271 			 map->name, i, targ_prog->name, fd);
5272 	}
5273 
5274 	zfree(&map->init_slots);
5275 	map->init_slots_sz = 0;
5276 
5277 	return 0;
5278 }
5279 
5280 static int bpf_object_init_prog_arrays(struct bpf_object *obj)
5281 {
5282 	struct bpf_map *map;
5283 	int i, err;
5284 
5285 	for (i = 0; i < obj->nr_maps; i++) {
5286 		map = &obj->maps[i];
5287 
5288 		if (!map->init_slots_sz || map->def.type != BPF_MAP_TYPE_PROG_ARRAY)
5289 			continue;
5290 
5291 		err = init_prog_array_slots(obj, map);
5292 		if (err < 0)
5293 			return err;
5294 	}
5295 	return 0;
5296 }
5297 
5298 static int map_set_def_max_entries(struct bpf_map *map)
5299 {
5300 	if (map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !map->def.max_entries) {
5301 		int nr_cpus;
5302 
5303 		nr_cpus = libbpf_num_possible_cpus();
5304 		if (nr_cpus < 0) {
5305 			pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
5306 				map->name, nr_cpus);
5307 			return nr_cpus;
5308 		}
5309 		pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
5310 		map->def.max_entries = nr_cpus;
5311 	}
5312 
5313 	return 0;
5314 }
5315 
5316 static int
5317 bpf_object__create_maps(struct bpf_object *obj)
5318 {
5319 	struct bpf_map *map;
5320 	char *cp, errmsg[STRERR_BUFSIZE];
5321 	unsigned int i, j;
5322 	int err;
5323 	bool retried;
5324 
5325 	for (i = 0; i < obj->nr_maps; i++) {
5326 		map = &obj->maps[i];
5327 
5328 		/* To support old kernels, we skip creating global data maps
5329 		 * (.rodata, .data, .kconfig, etc); later on, during program
5330 		 * loading, if we detect that at least one of the to-be-loaded
5331 		 * programs is referencing any global data map, we'll error
5332 		 * out with program name and relocation index logged.
5333 		 * This approach allows to accommodate Clang emitting
5334 		 * unnecessary .rodata.str1.1 sections for string literals,
5335 		 * but also it allows to have CO-RE applications that use
5336 		 * global variables in some of BPF programs, but not others.
5337 		 * If those global variable-using programs are not loaded at
5338 		 * runtime due to bpf_program__set_autoload(prog, false),
5339 		 * bpf_object loading will succeed just fine even on old
5340 		 * kernels.
5341 		 */
5342 		if (bpf_map__is_internal(map) && !kernel_supports(obj, FEAT_GLOBAL_DATA))
5343 			map->autocreate = false;
5344 
5345 		if (!map->autocreate) {
5346 			pr_debug("map '%s': skipped auto-creating...\n", map->name);
5347 			continue;
5348 		}
5349 
5350 		err = map_set_def_max_entries(map);
5351 		if (err)
5352 			goto err_out;
5353 
5354 		retried = false;
5355 retry:
5356 		if (map->pin_path) {
5357 			err = bpf_object__reuse_map(map);
5358 			if (err) {
5359 				pr_warn("map '%s': error reusing pinned map\n",
5360 					map->name);
5361 				goto err_out;
5362 			}
5363 			if (retried && map->fd < 0) {
5364 				pr_warn("map '%s': cannot find pinned map\n",
5365 					map->name);
5366 				err = -ENOENT;
5367 				goto err_out;
5368 			}
5369 		}
5370 
5371 		if (map->reused) {
5372 			pr_debug("map '%s': skipping creation (preset fd=%d)\n",
5373 				 map->name, map->fd);
5374 		} else {
5375 			err = bpf_object__create_map(obj, map, false);
5376 			if (err)
5377 				goto err_out;
5378 
5379 			pr_debug("map '%s': created successfully, fd=%d\n",
5380 				 map->name, map->fd);
5381 
5382 			if (bpf_map__is_internal(map)) {
5383 				err = bpf_object__populate_internal_map(obj, map);
5384 				if (err < 0)
5385 					goto err_out;
5386 			}
5387 			if (map->def.type == BPF_MAP_TYPE_ARENA) {
5388 				map->mmaped = mmap((void *)(long)map->map_extra,
5389 						   bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
5390 						   map->map_extra ? MAP_SHARED | MAP_FIXED : MAP_SHARED,
5391 						   map->fd, 0);
5392 				if (map->mmaped == MAP_FAILED) {
5393 					err = -errno;
5394 					map->mmaped = NULL;
5395 					pr_warn("map '%s': failed to mmap arena: %d\n",
5396 						map->name, err);
5397 					return err;
5398 				}
5399 				if (obj->arena_data) {
5400 					memcpy(map->mmaped, obj->arena_data, obj->arena_data_sz);
5401 					zfree(&obj->arena_data);
5402 				}
5403 			}
5404 			if (map->init_slots_sz && map->def.type != BPF_MAP_TYPE_PROG_ARRAY) {
5405 				err = init_map_in_map_slots(obj, map);
5406 				if (err < 0)
5407 					goto err_out;
5408 			}
5409 		}
5410 
5411 		if (map->pin_path && !map->pinned) {
5412 			err = bpf_map__pin(map, NULL);
5413 			if (err) {
5414 				if (!retried && err == -EEXIST) {
5415 					retried = true;
5416 					goto retry;
5417 				}
5418 				pr_warn("map '%s': failed to auto-pin at '%s': %d\n",
5419 					map->name, map->pin_path, err);
5420 				goto err_out;
5421 			}
5422 		}
5423 	}
5424 
5425 	return 0;
5426 
5427 err_out:
5428 	cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5429 	pr_warn("map '%s': failed to create: %s(%d)\n", map->name, cp, err);
5430 	pr_perm_msg(err);
5431 	for (j = 0; j < i; j++)
5432 		zclose(obj->maps[j].fd);
5433 	return err;
5434 }
5435 
5436 static bool bpf_core_is_flavor_sep(const char *s)
5437 {
5438 	/* check X___Y name pattern, where X and Y are not underscores */
5439 	return s[0] != '_' &&				      /* X */
5440 	       s[1] == '_' && s[2] == '_' && s[3] == '_' &&   /* ___ */
5441 	       s[4] != '_';				      /* Y */
5442 }
5443 
5444 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
5445  * before last triple underscore. Struct name part after last triple
5446  * underscore is ignored by BPF CO-RE relocation during relocation matching.
5447  */
5448 size_t bpf_core_essential_name_len(const char *name)
5449 {
5450 	size_t n = strlen(name);
5451 	int i;
5452 
5453 	for (i = n - 5; i >= 0; i--) {
5454 		if (bpf_core_is_flavor_sep(name + i))
5455 			return i + 1;
5456 	}
5457 	return n;
5458 }
5459 
5460 void bpf_core_free_cands(struct bpf_core_cand_list *cands)
5461 {
5462 	if (!cands)
5463 		return;
5464 
5465 	free(cands->cands);
5466 	free(cands);
5467 }
5468 
5469 int bpf_core_add_cands(struct bpf_core_cand *local_cand,
5470 		       size_t local_essent_len,
5471 		       const struct btf *targ_btf,
5472 		       const char *targ_btf_name,
5473 		       int targ_start_id,
5474 		       struct bpf_core_cand_list *cands)
5475 {
5476 	struct bpf_core_cand *new_cands, *cand;
5477 	const struct btf_type *t, *local_t;
5478 	const char *targ_name, *local_name;
5479 	size_t targ_essent_len;
5480 	int n, i;
5481 
5482 	local_t = btf__type_by_id(local_cand->btf, local_cand->id);
5483 	local_name = btf__str_by_offset(local_cand->btf, local_t->name_off);
5484 
5485 	n = btf__type_cnt(targ_btf);
5486 	for (i = targ_start_id; i < n; i++) {
5487 		t = btf__type_by_id(targ_btf, i);
5488 		if (!btf_kind_core_compat(t, local_t))
5489 			continue;
5490 
5491 		targ_name = btf__name_by_offset(targ_btf, t->name_off);
5492 		if (str_is_empty(targ_name))
5493 			continue;
5494 
5495 		targ_essent_len = bpf_core_essential_name_len(targ_name);
5496 		if (targ_essent_len != local_essent_len)
5497 			continue;
5498 
5499 		if (strncmp(local_name, targ_name, local_essent_len) != 0)
5500 			continue;
5501 
5502 		pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s in [%s]\n",
5503 			 local_cand->id, btf_kind_str(local_t),
5504 			 local_name, i, btf_kind_str(t), targ_name,
5505 			 targ_btf_name);
5506 		new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
5507 					      sizeof(*cands->cands));
5508 		if (!new_cands)
5509 			return -ENOMEM;
5510 
5511 		cand = &new_cands[cands->len];
5512 		cand->btf = targ_btf;
5513 		cand->id = i;
5514 
5515 		cands->cands = new_cands;
5516 		cands->len++;
5517 	}
5518 	return 0;
5519 }
5520 
5521 static int load_module_btfs(struct bpf_object *obj)
5522 {
5523 	struct bpf_btf_info info;
5524 	struct module_btf *mod_btf;
5525 	struct btf *btf;
5526 	char name[64];
5527 	__u32 id = 0, len;
5528 	int err, fd;
5529 
5530 	if (obj->btf_modules_loaded)
5531 		return 0;
5532 
5533 	if (obj->gen_loader)
5534 		return 0;
5535 
5536 	/* don't do this again, even if we find no module BTFs */
5537 	obj->btf_modules_loaded = true;
5538 
5539 	/* kernel too old to support module BTFs */
5540 	if (!kernel_supports(obj, FEAT_MODULE_BTF))
5541 		return 0;
5542 
5543 	while (true) {
5544 		err = bpf_btf_get_next_id(id, &id);
5545 		if (err && errno == ENOENT)
5546 			return 0;
5547 		if (err && errno == EPERM) {
5548 			pr_debug("skipping module BTFs loading, missing privileges\n");
5549 			return 0;
5550 		}
5551 		if (err) {
5552 			err = -errno;
5553 			pr_warn("failed to iterate BTF objects: %d\n", err);
5554 			return err;
5555 		}
5556 
5557 		fd = bpf_btf_get_fd_by_id(id);
5558 		if (fd < 0) {
5559 			if (errno == ENOENT)
5560 				continue; /* expected race: BTF was unloaded */
5561 			err = -errno;
5562 			pr_warn("failed to get BTF object #%d FD: %d\n", id, err);
5563 			return err;
5564 		}
5565 
5566 		len = sizeof(info);
5567 		memset(&info, 0, sizeof(info));
5568 		info.name = ptr_to_u64(name);
5569 		info.name_len = sizeof(name);
5570 
5571 		err = bpf_btf_get_info_by_fd(fd, &info, &len);
5572 		if (err) {
5573 			err = -errno;
5574 			pr_warn("failed to get BTF object #%d info: %d\n", id, err);
5575 			goto err_out;
5576 		}
5577 
5578 		/* ignore non-module BTFs */
5579 		if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
5580 			close(fd);
5581 			continue;
5582 		}
5583 
5584 		btf = btf_get_from_fd(fd, obj->btf_vmlinux);
5585 		err = libbpf_get_error(btf);
5586 		if (err) {
5587 			pr_warn("failed to load module [%s]'s BTF object #%d: %d\n",
5588 				name, id, err);
5589 			goto err_out;
5590 		}
5591 
5592 		err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
5593 					sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
5594 		if (err)
5595 			goto err_out;
5596 
5597 		mod_btf = &obj->btf_modules[obj->btf_module_cnt++];
5598 
5599 		mod_btf->btf = btf;
5600 		mod_btf->id = id;
5601 		mod_btf->fd = fd;
5602 		mod_btf->name = strdup(name);
5603 		if (!mod_btf->name) {
5604 			err = -ENOMEM;
5605 			goto err_out;
5606 		}
5607 		continue;
5608 
5609 err_out:
5610 		close(fd);
5611 		return err;
5612 	}
5613 
5614 	return 0;
5615 }
5616 
5617 static struct bpf_core_cand_list *
5618 bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
5619 {
5620 	struct bpf_core_cand local_cand = {};
5621 	struct bpf_core_cand_list *cands;
5622 	const struct btf *main_btf;
5623 	const struct btf_type *local_t;
5624 	const char *local_name;
5625 	size_t local_essent_len;
5626 	int err, i;
5627 
5628 	local_cand.btf = local_btf;
5629 	local_cand.id = local_type_id;
5630 	local_t = btf__type_by_id(local_btf, local_type_id);
5631 	if (!local_t)
5632 		return ERR_PTR(-EINVAL);
5633 
5634 	local_name = btf__name_by_offset(local_btf, local_t->name_off);
5635 	if (str_is_empty(local_name))
5636 		return ERR_PTR(-EINVAL);
5637 	local_essent_len = bpf_core_essential_name_len(local_name);
5638 
5639 	cands = calloc(1, sizeof(*cands));
5640 	if (!cands)
5641 		return ERR_PTR(-ENOMEM);
5642 
5643 	/* Attempt to find target candidates in vmlinux BTF first */
5644 	main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
5645 	err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
5646 	if (err)
5647 		goto err_out;
5648 
5649 	/* if vmlinux BTF has any candidate, don't got for module BTFs */
5650 	if (cands->len)
5651 		return cands;
5652 
5653 	/* if vmlinux BTF was overridden, don't attempt to load module BTFs */
5654 	if (obj->btf_vmlinux_override)
5655 		return cands;
5656 
5657 	/* now look through module BTFs, trying to still find candidates */
5658 	err = load_module_btfs(obj);
5659 	if (err)
5660 		goto err_out;
5661 
5662 	for (i = 0; i < obj->btf_module_cnt; i++) {
5663 		err = bpf_core_add_cands(&local_cand, local_essent_len,
5664 					 obj->btf_modules[i].btf,
5665 					 obj->btf_modules[i].name,
5666 					 btf__type_cnt(obj->btf_vmlinux),
5667 					 cands);
5668 		if (err)
5669 			goto err_out;
5670 	}
5671 
5672 	return cands;
5673 err_out:
5674 	bpf_core_free_cands(cands);
5675 	return ERR_PTR(err);
5676 }
5677 
5678 /* Check local and target types for compatibility. This check is used for
5679  * type-based CO-RE relocations and follow slightly different rules than
5680  * field-based relocations. This function assumes that root types were already
5681  * checked for name match. Beyond that initial root-level name check, names
5682  * are completely ignored. Compatibility rules are as follows:
5683  *   - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
5684  *     kind should match for local and target types (i.e., STRUCT is not
5685  *     compatible with UNION);
5686  *   - for ENUMs, the size is ignored;
5687  *   - for INT, size and signedness are ignored;
5688  *   - for ARRAY, dimensionality is ignored, element types are checked for
5689  *     compatibility recursively;
5690  *   - CONST/VOLATILE/RESTRICT modifiers are ignored;
5691  *   - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
5692  *   - FUNC_PROTOs are compatible if they have compatible signature: same
5693  *     number of input args and compatible return and argument types.
5694  * These rules are not set in stone and probably will be adjusted as we get
5695  * more experience with using BPF CO-RE relocations.
5696  */
5697 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
5698 			      const struct btf *targ_btf, __u32 targ_id)
5699 {
5700 	return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id, 32);
5701 }
5702 
5703 int bpf_core_types_match(const struct btf *local_btf, __u32 local_id,
5704 			 const struct btf *targ_btf, __u32 targ_id)
5705 {
5706 	return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false, 32);
5707 }
5708 
5709 static size_t bpf_core_hash_fn(const long key, void *ctx)
5710 {
5711 	return key;
5712 }
5713 
5714 static bool bpf_core_equal_fn(const long k1, const long k2, void *ctx)
5715 {
5716 	return k1 == k2;
5717 }
5718 
5719 static int record_relo_core(struct bpf_program *prog,
5720 			    const struct bpf_core_relo *core_relo, int insn_idx)
5721 {
5722 	struct reloc_desc *relos, *relo;
5723 
5724 	relos = libbpf_reallocarray(prog->reloc_desc,
5725 				    prog->nr_reloc + 1, sizeof(*relos));
5726 	if (!relos)
5727 		return -ENOMEM;
5728 	relo = &relos[prog->nr_reloc];
5729 	relo->type = RELO_CORE;
5730 	relo->insn_idx = insn_idx;
5731 	relo->core_relo = core_relo;
5732 	prog->reloc_desc = relos;
5733 	prog->nr_reloc++;
5734 	return 0;
5735 }
5736 
5737 static const struct bpf_core_relo *find_relo_core(struct bpf_program *prog, int insn_idx)
5738 {
5739 	struct reloc_desc *relo;
5740 	int i;
5741 
5742 	for (i = 0; i < prog->nr_reloc; i++) {
5743 		relo = &prog->reloc_desc[i];
5744 		if (relo->type != RELO_CORE || relo->insn_idx != insn_idx)
5745 			continue;
5746 
5747 		return relo->core_relo;
5748 	}
5749 
5750 	return NULL;
5751 }
5752 
5753 static int bpf_core_resolve_relo(struct bpf_program *prog,
5754 				 const struct bpf_core_relo *relo,
5755 				 int relo_idx,
5756 				 const struct btf *local_btf,
5757 				 struct hashmap *cand_cache,
5758 				 struct bpf_core_relo_res *targ_res)
5759 {
5760 	struct bpf_core_spec specs_scratch[3] = {};
5761 	struct bpf_core_cand_list *cands = NULL;
5762 	const char *prog_name = prog->name;
5763 	const struct btf_type *local_type;
5764 	const char *local_name;
5765 	__u32 local_id = relo->type_id;
5766 	int err;
5767 
5768 	local_type = btf__type_by_id(local_btf, local_id);
5769 	if (!local_type)
5770 		return -EINVAL;
5771 
5772 	local_name = btf__name_by_offset(local_btf, local_type->name_off);
5773 	if (!local_name)
5774 		return -EINVAL;
5775 
5776 	if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
5777 	    !hashmap__find(cand_cache, local_id, &cands)) {
5778 		cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
5779 		if (IS_ERR(cands)) {
5780 			pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n",
5781 				prog_name, relo_idx, local_id, btf_kind_str(local_type),
5782 				local_name, PTR_ERR(cands));
5783 			return PTR_ERR(cands);
5784 		}
5785 		err = hashmap__set(cand_cache, local_id, cands, NULL, NULL);
5786 		if (err) {
5787 			bpf_core_free_cands(cands);
5788 			return err;
5789 		}
5790 	}
5791 
5792 	return bpf_core_calc_relo_insn(prog_name, relo, relo_idx, local_btf, cands, specs_scratch,
5793 				       targ_res);
5794 }
5795 
5796 static int
5797 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
5798 {
5799 	const struct btf_ext_info_sec *sec;
5800 	struct bpf_core_relo_res targ_res;
5801 	const struct bpf_core_relo *rec;
5802 	const struct btf_ext_info *seg;
5803 	struct hashmap_entry *entry;
5804 	struct hashmap *cand_cache = NULL;
5805 	struct bpf_program *prog;
5806 	struct bpf_insn *insn;
5807 	const char *sec_name;
5808 	int i, err = 0, insn_idx, sec_idx, sec_num;
5809 
5810 	if (obj->btf_ext->core_relo_info.len == 0)
5811 		return 0;
5812 
5813 	if (targ_btf_path) {
5814 		obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
5815 		err = libbpf_get_error(obj->btf_vmlinux_override);
5816 		if (err) {
5817 			pr_warn("failed to parse target BTF: %d\n", err);
5818 			return err;
5819 		}
5820 	}
5821 
5822 	cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
5823 	if (IS_ERR(cand_cache)) {
5824 		err = PTR_ERR(cand_cache);
5825 		goto out;
5826 	}
5827 
5828 	seg = &obj->btf_ext->core_relo_info;
5829 	sec_num = 0;
5830 	for_each_btf_ext_sec(seg, sec) {
5831 		sec_idx = seg->sec_idxs[sec_num];
5832 		sec_num++;
5833 
5834 		sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
5835 		if (str_is_empty(sec_name)) {
5836 			err = -EINVAL;
5837 			goto out;
5838 		}
5839 
5840 		pr_debug("sec '%s': found %d CO-RE relocations\n", sec_name, sec->num_info);
5841 
5842 		for_each_btf_ext_rec(seg, sec, i, rec) {
5843 			if (rec->insn_off % BPF_INSN_SZ)
5844 				return -EINVAL;
5845 			insn_idx = rec->insn_off / BPF_INSN_SZ;
5846 			prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
5847 			if (!prog) {
5848 				/* When __weak subprog is "overridden" by another instance
5849 				 * of the subprog from a different object file, linker still
5850 				 * appends all the .BTF.ext info that used to belong to that
5851 				 * eliminated subprogram.
5852 				 * This is similar to what x86-64 linker does for relocations.
5853 				 * So just ignore such relocations just like we ignore
5854 				 * subprog instructions when discovering subprograms.
5855 				 */
5856 				pr_debug("sec '%s': skipping CO-RE relocation #%d for insn #%d belonging to eliminated weak subprogram\n",
5857 					 sec_name, i, insn_idx);
5858 				continue;
5859 			}
5860 			/* no need to apply CO-RE relocation if the program is
5861 			 * not going to be loaded
5862 			 */
5863 			if (!prog->autoload)
5864 				continue;
5865 
5866 			/* adjust insn_idx from section frame of reference to the local
5867 			 * program's frame of reference; (sub-)program code is not yet
5868 			 * relocated, so it's enough to just subtract in-section offset
5869 			 */
5870 			insn_idx = insn_idx - prog->sec_insn_off;
5871 			if (insn_idx >= prog->insns_cnt)
5872 				return -EINVAL;
5873 			insn = &prog->insns[insn_idx];
5874 
5875 			err = record_relo_core(prog, rec, insn_idx);
5876 			if (err) {
5877 				pr_warn("prog '%s': relo #%d: failed to record relocation: %d\n",
5878 					prog->name, i, err);
5879 				goto out;
5880 			}
5881 
5882 			if (prog->obj->gen_loader)
5883 				continue;
5884 
5885 			err = bpf_core_resolve_relo(prog, rec, i, obj->btf, cand_cache, &targ_res);
5886 			if (err) {
5887 				pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
5888 					prog->name, i, err);
5889 				goto out;
5890 			}
5891 
5892 			err = bpf_core_patch_insn(prog->name, insn, insn_idx, rec, i, &targ_res);
5893 			if (err) {
5894 				pr_warn("prog '%s': relo #%d: failed to patch insn #%u: %d\n",
5895 					prog->name, i, insn_idx, err);
5896 				goto out;
5897 			}
5898 		}
5899 	}
5900 
5901 out:
5902 	/* obj->btf_vmlinux and module BTFs are freed after object load */
5903 	btf__free(obj->btf_vmlinux_override);
5904 	obj->btf_vmlinux_override = NULL;
5905 
5906 	if (!IS_ERR_OR_NULL(cand_cache)) {
5907 		hashmap__for_each_entry(cand_cache, entry, i) {
5908 			bpf_core_free_cands(entry->pvalue);
5909 		}
5910 		hashmap__free(cand_cache);
5911 	}
5912 	return err;
5913 }
5914 
5915 /* base map load ldimm64 special constant, used also for log fixup logic */
5916 #define POISON_LDIMM64_MAP_BASE 2001000000
5917 #define POISON_LDIMM64_MAP_PFX "200100"
5918 
5919 static void poison_map_ldimm64(struct bpf_program *prog, int relo_idx,
5920 			       int insn_idx, struct bpf_insn *insn,
5921 			       int map_idx, const struct bpf_map *map)
5922 {
5923 	int i;
5924 
5925 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that loads map #%d '%s'\n",
5926 		 prog->name, relo_idx, insn_idx, map_idx, map->name);
5927 
5928 	/* we turn single ldimm64 into two identical invalid calls */
5929 	for (i = 0; i < 2; i++) {
5930 		insn->code = BPF_JMP | BPF_CALL;
5931 		insn->dst_reg = 0;
5932 		insn->src_reg = 0;
5933 		insn->off = 0;
5934 		/* if this instruction is reachable (not a dead code),
5935 		 * verifier will complain with something like:
5936 		 * invalid func unknown#2001000123
5937 		 * where lower 123 is map index into obj->maps[] array
5938 		 */
5939 		insn->imm = POISON_LDIMM64_MAP_BASE + map_idx;
5940 
5941 		insn++;
5942 	}
5943 }
5944 
5945 /* unresolved kfunc call special constant, used also for log fixup logic */
5946 #define POISON_CALL_KFUNC_BASE 2002000000
5947 #define POISON_CALL_KFUNC_PFX "2002"
5948 
5949 static void poison_kfunc_call(struct bpf_program *prog, int relo_idx,
5950 			      int insn_idx, struct bpf_insn *insn,
5951 			      int ext_idx, const struct extern_desc *ext)
5952 {
5953 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that calls kfunc '%s'\n",
5954 		 prog->name, relo_idx, insn_idx, ext->name);
5955 
5956 	/* we turn kfunc call into invalid helper call with identifiable constant */
5957 	insn->code = BPF_JMP | BPF_CALL;
5958 	insn->dst_reg = 0;
5959 	insn->src_reg = 0;
5960 	insn->off = 0;
5961 	/* if this instruction is reachable (not a dead code),
5962 	 * verifier will complain with something like:
5963 	 * invalid func unknown#2001000123
5964 	 * where lower 123 is extern index into obj->externs[] array
5965 	 */
5966 	insn->imm = POISON_CALL_KFUNC_BASE + ext_idx;
5967 }
5968 
5969 /* Relocate data references within program code:
5970  *  - map references;
5971  *  - global variable references;
5972  *  - extern references.
5973  */
5974 static int
5975 bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
5976 {
5977 	int i;
5978 
5979 	for (i = 0; i < prog->nr_reloc; i++) {
5980 		struct reloc_desc *relo = &prog->reloc_desc[i];
5981 		struct bpf_insn *insn = &prog->insns[relo->insn_idx];
5982 		const struct bpf_map *map;
5983 		struct extern_desc *ext;
5984 
5985 		switch (relo->type) {
5986 		case RELO_LD64:
5987 			map = &obj->maps[relo->map_idx];
5988 			if (obj->gen_loader) {
5989 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
5990 				insn[0].imm = relo->map_idx;
5991 			} else if (map->autocreate) {
5992 				insn[0].src_reg = BPF_PSEUDO_MAP_FD;
5993 				insn[0].imm = map->fd;
5994 			} else {
5995 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
5996 						   relo->map_idx, map);
5997 			}
5998 			break;
5999 		case RELO_DATA:
6000 			map = &obj->maps[relo->map_idx];
6001 			insn[1].imm = insn[0].imm + relo->sym_off;
6002 			if (obj->gen_loader) {
6003 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6004 				insn[0].imm = relo->map_idx;
6005 			} else if (map->autocreate) {
6006 				insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6007 				insn[0].imm = map->fd;
6008 			} else {
6009 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6010 						   relo->map_idx, map);
6011 			}
6012 			break;
6013 		case RELO_EXTERN_LD64:
6014 			ext = &obj->externs[relo->ext_idx];
6015 			if (ext->type == EXT_KCFG) {
6016 				if (obj->gen_loader) {
6017 					insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6018 					insn[0].imm = obj->kconfig_map_idx;
6019 				} else {
6020 					insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6021 					insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
6022 				}
6023 				insn[1].imm = ext->kcfg.data_off;
6024 			} else /* EXT_KSYM */ {
6025 				if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
6026 					insn[0].src_reg = BPF_PSEUDO_BTF_ID;
6027 					insn[0].imm = ext->ksym.kernel_btf_id;
6028 					insn[1].imm = ext->ksym.kernel_btf_obj_fd;
6029 				} else { /* typeless ksyms or unresolved typed ksyms */
6030 					insn[0].imm = (__u32)ext->ksym.addr;
6031 					insn[1].imm = ext->ksym.addr >> 32;
6032 				}
6033 			}
6034 			break;
6035 		case RELO_EXTERN_CALL:
6036 			ext = &obj->externs[relo->ext_idx];
6037 			insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
6038 			if (ext->is_set) {
6039 				insn[0].imm = ext->ksym.kernel_btf_id;
6040 				insn[0].off = ext->ksym.btf_fd_idx;
6041 			} else { /* unresolved weak kfunc call */
6042 				poison_kfunc_call(prog, i, relo->insn_idx, insn,
6043 						  relo->ext_idx, ext);
6044 			}
6045 			break;
6046 		case RELO_SUBPROG_ADDR:
6047 			if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
6048 				pr_warn("prog '%s': relo #%d: bad insn\n",
6049 					prog->name, i);
6050 				return -EINVAL;
6051 			}
6052 			/* handled already */
6053 			break;
6054 		case RELO_CALL:
6055 			/* handled already */
6056 			break;
6057 		case RELO_CORE:
6058 			/* will be handled by bpf_program_record_relos() */
6059 			break;
6060 		default:
6061 			pr_warn("prog '%s': relo #%d: bad relo type %d\n",
6062 				prog->name, i, relo->type);
6063 			return -EINVAL;
6064 		}
6065 	}
6066 
6067 	return 0;
6068 }
6069 
6070 static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
6071 				    const struct bpf_program *prog,
6072 				    const struct btf_ext_info *ext_info,
6073 				    void **prog_info, __u32 *prog_rec_cnt,
6074 				    __u32 *prog_rec_sz)
6075 {
6076 	void *copy_start = NULL, *copy_end = NULL;
6077 	void *rec, *rec_end, *new_prog_info;
6078 	const struct btf_ext_info_sec *sec;
6079 	size_t old_sz, new_sz;
6080 	int i, sec_num, sec_idx, off_adj;
6081 
6082 	sec_num = 0;
6083 	for_each_btf_ext_sec(ext_info, sec) {
6084 		sec_idx = ext_info->sec_idxs[sec_num];
6085 		sec_num++;
6086 		if (prog->sec_idx != sec_idx)
6087 			continue;
6088 
6089 		for_each_btf_ext_rec(ext_info, sec, i, rec) {
6090 			__u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
6091 
6092 			if (insn_off < prog->sec_insn_off)
6093 				continue;
6094 			if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
6095 				break;
6096 
6097 			if (!copy_start)
6098 				copy_start = rec;
6099 			copy_end = rec + ext_info->rec_size;
6100 		}
6101 
6102 		if (!copy_start)
6103 			return -ENOENT;
6104 
6105 		/* append func/line info of a given (sub-)program to the main
6106 		 * program func/line info
6107 		 */
6108 		old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
6109 		new_sz = old_sz + (copy_end - copy_start);
6110 		new_prog_info = realloc(*prog_info, new_sz);
6111 		if (!new_prog_info)
6112 			return -ENOMEM;
6113 		*prog_info = new_prog_info;
6114 		*prog_rec_cnt = new_sz / ext_info->rec_size;
6115 		memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
6116 
6117 		/* Kernel instruction offsets are in units of 8-byte
6118 		 * instructions, while .BTF.ext instruction offsets generated
6119 		 * by Clang are in units of bytes. So convert Clang offsets
6120 		 * into kernel offsets and adjust offset according to program
6121 		 * relocated position.
6122 		 */
6123 		off_adj = prog->sub_insn_off - prog->sec_insn_off;
6124 		rec = new_prog_info + old_sz;
6125 		rec_end = new_prog_info + new_sz;
6126 		for (; rec < rec_end; rec += ext_info->rec_size) {
6127 			__u32 *insn_off = rec;
6128 
6129 			*insn_off = *insn_off / BPF_INSN_SZ + off_adj;
6130 		}
6131 		*prog_rec_sz = ext_info->rec_size;
6132 		return 0;
6133 	}
6134 
6135 	return -ENOENT;
6136 }
6137 
6138 static int
6139 reloc_prog_func_and_line_info(const struct bpf_object *obj,
6140 			      struct bpf_program *main_prog,
6141 			      const struct bpf_program *prog)
6142 {
6143 	int err;
6144 
6145 	/* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
6146 	 * support func/line info
6147 	 */
6148 	if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
6149 		return 0;
6150 
6151 	/* only attempt func info relocation if main program's func_info
6152 	 * relocation was successful
6153 	 */
6154 	if (main_prog != prog && !main_prog->func_info)
6155 		goto line_info;
6156 
6157 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
6158 				       &main_prog->func_info,
6159 				       &main_prog->func_info_cnt,
6160 				       &main_prog->func_info_rec_size);
6161 	if (err) {
6162 		if (err != -ENOENT) {
6163 			pr_warn("prog '%s': error relocating .BTF.ext function info: %d\n",
6164 				prog->name, err);
6165 			return err;
6166 		}
6167 		if (main_prog->func_info) {
6168 			/*
6169 			 * Some info has already been found but has problem
6170 			 * in the last btf_ext reloc. Must have to error out.
6171 			 */
6172 			pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
6173 			return err;
6174 		}
6175 		/* Have problem loading the very first info. Ignore the rest. */
6176 		pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
6177 			prog->name);
6178 	}
6179 
6180 line_info:
6181 	/* don't relocate line info if main program's relocation failed */
6182 	if (main_prog != prog && !main_prog->line_info)
6183 		return 0;
6184 
6185 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
6186 				       &main_prog->line_info,
6187 				       &main_prog->line_info_cnt,
6188 				       &main_prog->line_info_rec_size);
6189 	if (err) {
6190 		if (err != -ENOENT) {
6191 			pr_warn("prog '%s': error relocating .BTF.ext line info: %d\n",
6192 				prog->name, err);
6193 			return err;
6194 		}
6195 		if (main_prog->line_info) {
6196 			/*
6197 			 * Some info has already been found but has problem
6198 			 * in the last btf_ext reloc. Must have to error out.
6199 			 */
6200 			pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
6201 			return err;
6202 		}
6203 		/* Have problem loading the very first info. Ignore the rest. */
6204 		pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
6205 			prog->name);
6206 	}
6207 	return 0;
6208 }
6209 
6210 static int cmp_relo_by_insn_idx(const void *key, const void *elem)
6211 {
6212 	size_t insn_idx = *(const size_t *)key;
6213 	const struct reloc_desc *relo = elem;
6214 
6215 	if (insn_idx == relo->insn_idx)
6216 		return 0;
6217 	return insn_idx < relo->insn_idx ? -1 : 1;
6218 }
6219 
6220 static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
6221 {
6222 	if (!prog->nr_reloc)
6223 		return NULL;
6224 	return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
6225 		       sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
6226 }
6227 
6228 static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
6229 {
6230 	int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
6231 	struct reloc_desc *relos;
6232 	int i;
6233 
6234 	if (main_prog == subprog)
6235 		return 0;
6236 	relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
6237 	/* if new count is zero, reallocarray can return a valid NULL result;
6238 	 * in this case the previous pointer will be freed, so we *have to*
6239 	 * reassign old pointer to the new value (even if it's NULL)
6240 	 */
6241 	if (!relos && new_cnt)
6242 		return -ENOMEM;
6243 	if (subprog->nr_reloc)
6244 		memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
6245 		       sizeof(*relos) * subprog->nr_reloc);
6246 
6247 	for (i = main_prog->nr_reloc; i < new_cnt; i++)
6248 		relos[i].insn_idx += subprog->sub_insn_off;
6249 	/* After insn_idx adjustment the 'relos' array is still sorted
6250 	 * by insn_idx and doesn't break bsearch.
6251 	 */
6252 	main_prog->reloc_desc = relos;
6253 	main_prog->nr_reloc = new_cnt;
6254 	return 0;
6255 }
6256 
6257 static int
6258 bpf_object__append_subprog_code(struct bpf_object *obj, struct bpf_program *main_prog,
6259 				struct bpf_program *subprog)
6260 {
6261        struct bpf_insn *insns;
6262        size_t new_cnt;
6263        int err;
6264 
6265        subprog->sub_insn_off = main_prog->insns_cnt;
6266 
6267        new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
6268        insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
6269        if (!insns) {
6270                pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
6271                return -ENOMEM;
6272        }
6273        main_prog->insns = insns;
6274        main_prog->insns_cnt = new_cnt;
6275 
6276        memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
6277               subprog->insns_cnt * sizeof(*insns));
6278 
6279        pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
6280                 main_prog->name, subprog->insns_cnt, subprog->name);
6281 
6282        /* The subprog insns are now appended. Append its relos too. */
6283        err = append_subprog_relos(main_prog, subprog);
6284        if (err)
6285                return err;
6286        return 0;
6287 }
6288 
6289 static int
6290 bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
6291 		       struct bpf_program *prog)
6292 {
6293 	size_t sub_insn_idx, insn_idx;
6294 	struct bpf_program *subprog;
6295 	struct reloc_desc *relo;
6296 	struct bpf_insn *insn;
6297 	int err;
6298 
6299 	err = reloc_prog_func_and_line_info(obj, main_prog, prog);
6300 	if (err)
6301 		return err;
6302 
6303 	for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
6304 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6305 		if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
6306 			continue;
6307 
6308 		relo = find_prog_insn_relo(prog, insn_idx);
6309 		if (relo && relo->type == RELO_EXTERN_CALL)
6310 			/* kfunc relocations will be handled later
6311 			 * in bpf_object__relocate_data()
6312 			 */
6313 			continue;
6314 		if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
6315 			pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
6316 				prog->name, insn_idx, relo->type);
6317 			return -LIBBPF_ERRNO__RELOC;
6318 		}
6319 		if (relo) {
6320 			/* sub-program instruction index is a combination of
6321 			 * an offset of a symbol pointed to by relocation and
6322 			 * call instruction's imm field; for global functions,
6323 			 * call always has imm = -1, but for static functions
6324 			 * relocation is against STT_SECTION and insn->imm
6325 			 * points to a start of a static function
6326 			 *
6327 			 * for subprog addr relocation, the relo->sym_off + insn->imm is
6328 			 * the byte offset in the corresponding section.
6329 			 */
6330 			if (relo->type == RELO_CALL)
6331 				sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
6332 			else
6333 				sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
6334 		} else if (insn_is_pseudo_func(insn)) {
6335 			/*
6336 			 * RELO_SUBPROG_ADDR relo is always emitted even if both
6337 			 * functions are in the same section, so it shouldn't reach here.
6338 			 */
6339 			pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
6340 				prog->name, insn_idx);
6341 			return -LIBBPF_ERRNO__RELOC;
6342 		} else {
6343 			/* if subprogram call is to a static function within
6344 			 * the same ELF section, there won't be any relocation
6345 			 * emitted, but it also means there is no additional
6346 			 * offset necessary, insns->imm is relative to
6347 			 * instruction's original position within the section
6348 			 */
6349 			sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
6350 		}
6351 
6352 		/* we enforce that sub-programs should be in .text section */
6353 		subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
6354 		if (!subprog) {
6355 			pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
6356 				prog->name);
6357 			return -LIBBPF_ERRNO__RELOC;
6358 		}
6359 
6360 		/* if it's the first call instruction calling into this
6361 		 * subprogram (meaning this subprog hasn't been processed
6362 		 * yet) within the context of current main program:
6363 		 *   - append it at the end of main program's instructions blog;
6364 		 *   - process is recursively, while current program is put on hold;
6365 		 *   - if that subprogram calls some other not yet processes
6366 		 *   subprogram, same thing will happen recursively until
6367 		 *   there are no more unprocesses subprograms left to append
6368 		 *   and relocate.
6369 		 */
6370 		if (subprog->sub_insn_off == 0) {
6371 			err = bpf_object__append_subprog_code(obj, main_prog, subprog);
6372 			if (err)
6373 				return err;
6374 			err = bpf_object__reloc_code(obj, main_prog, subprog);
6375 			if (err)
6376 				return err;
6377 		}
6378 
6379 		/* main_prog->insns memory could have been re-allocated, so
6380 		 * calculate pointer again
6381 		 */
6382 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6383 		/* calculate correct instruction position within current main
6384 		 * prog; each main prog can have a different set of
6385 		 * subprograms appended (potentially in different order as
6386 		 * well), so position of any subprog can be different for
6387 		 * different main programs
6388 		 */
6389 		insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
6390 
6391 		pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
6392 			 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
6393 	}
6394 
6395 	return 0;
6396 }
6397 
6398 /*
6399  * Relocate sub-program calls.
6400  *
6401  * Algorithm operates as follows. Each entry-point BPF program (referred to as
6402  * main prog) is processed separately. For each subprog (non-entry functions,
6403  * that can be called from either entry progs or other subprogs) gets their
6404  * sub_insn_off reset to zero. This serves as indicator that this subprogram
6405  * hasn't been yet appended and relocated within current main prog. Once its
6406  * relocated, sub_insn_off will point at the position within current main prog
6407  * where given subprog was appended. This will further be used to relocate all
6408  * the call instructions jumping into this subprog.
6409  *
6410  * We start with main program and process all call instructions. If the call
6411  * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
6412  * is zero), subprog instructions are appended at the end of main program's
6413  * instruction array. Then main program is "put on hold" while we recursively
6414  * process newly appended subprogram. If that subprogram calls into another
6415  * subprogram that hasn't been appended, new subprogram is appended again to
6416  * the *main* prog's instructions (subprog's instructions are always left
6417  * untouched, as they need to be in unmodified state for subsequent main progs
6418  * and subprog instructions are always sent only as part of a main prog) and
6419  * the process continues recursively. Once all the subprogs called from a main
6420  * prog or any of its subprogs are appended (and relocated), all their
6421  * positions within finalized instructions array are known, so it's easy to
6422  * rewrite call instructions with correct relative offsets, corresponding to
6423  * desired target subprog.
6424  *
6425  * Its important to realize that some subprogs might not be called from some
6426  * main prog and any of its called/used subprogs. Those will keep their
6427  * subprog->sub_insn_off as zero at all times and won't be appended to current
6428  * main prog and won't be relocated within the context of current main prog.
6429  * They might still be used from other main progs later.
6430  *
6431  * Visually this process can be shown as below. Suppose we have two main
6432  * programs mainA and mainB and BPF object contains three subprogs: subA,
6433  * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
6434  * subC both call subB:
6435  *
6436  *        +--------+ +-------+
6437  *        |        v v       |
6438  *     +--+---+ +--+-+-+ +---+--+
6439  *     | subA | | subB | | subC |
6440  *     +--+---+ +------+ +---+--+
6441  *        ^                  ^
6442  *        |                  |
6443  *    +---+-------+   +------+----+
6444  *    |   mainA   |   |   mainB   |
6445  *    +-----------+   +-----------+
6446  *
6447  * We'll start relocating mainA, will find subA, append it and start
6448  * processing sub A recursively:
6449  *
6450  *    +-----------+------+
6451  *    |   mainA   | subA |
6452  *    +-----------+------+
6453  *
6454  * At this point we notice that subB is used from subA, so we append it and
6455  * relocate (there are no further subcalls from subB):
6456  *
6457  *    +-----------+------+------+
6458  *    |   mainA   | subA | subB |
6459  *    +-----------+------+------+
6460  *
6461  * At this point, we relocate subA calls, then go one level up and finish with
6462  * relocatin mainA calls. mainA is done.
6463  *
6464  * For mainB process is similar but results in different order. We start with
6465  * mainB and skip subA and subB, as mainB never calls them (at least
6466  * directly), but we see subC is needed, so we append and start processing it:
6467  *
6468  *    +-----------+------+
6469  *    |   mainB   | subC |
6470  *    +-----------+------+
6471  * Now we see subC needs subB, so we go back to it, append and relocate it:
6472  *
6473  *    +-----------+------+------+
6474  *    |   mainB   | subC | subB |
6475  *    +-----------+------+------+
6476  *
6477  * At this point we unwind recursion, relocate calls in subC, then in mainB.
6478  */
6479 static int
6480 bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
6481 {
6482 	struct bpf_program *subprog;
6483 	int i, err;
6484 
6485 	/* mark all subprogs as not relocated (yet) within the context of
6486 	 * current main program
6487 	 */
6488 	for (i = 0; i < obj->nr_programs; i++) {
6489 		subprog = &obj->programs[i];
6490 		if (!prog_is_subprog(obj, subprog))
6491 			continue;
6492 
6493 		subprog->sub_insn_off = 0;
6494 	}
6495 
6496 	err = bpf_object__reloc_code(obj, prog, prog);
6497 	if (err)
6498 		return err;
6499 
6500 	return 0;
6501 }
6502 
6503 static void
6504 bpf_object__free_relocs(struct bpf_object *obj)
6505 {
6506 	struct bpf_program *prog;
6507 	int i;
6508 
6509 	/* free up relocation descriptors */
6510 	for (i = 0; i < obj->nr_programs; i++) {
6511 		prog = &obj->programs[i];
6512 		zfree(&prog->reloc_desc);
6513 		prog->nr_reloc = 0;
6514 	}
6515 }
6516 
6517 static int cmp_relocs(const void *_a, const void *_b)
6518 {
6519 	const struct reloc_desc *a = _a;
6520 	const struct reloc_desc *b = _b;
6521 
6522 	if (a->insn_idx != b->insn_idx)
6523 		return a->insn_idx < b->insn_idx ? -1 : 1;
6524 
6525 	/* no two relocations should have the same insn_idx, but ... */
6526 	if (a->type != b->type)
6527 		return a->type < b->type ? -1 : 1;
6528 
6529 	return 0;
6530 }
6531 
6532 static void bpf_object__sort_relos(struct bpf_object *obj)
6533 {
6534 	int i;
6535 
6536 	for (i = 0; i < obj->nr_programs; i++) {
6537 		struct bpf_program *p = &obj->programs[i];
6538 
6539 		if (!p->nr_reloc)
6540 			continue;
6541 
6542 		qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
6543 	}
6544 }
6545 
6546 static int bpf_prog_assign_exc_cb(struct bpf_object *obj, struct bpf_program *prog)
6547 {
6548 	const char *str = "exception_callback:";
6549 	size_t pfx_len = strlen(str);
6550 	int i, j, n;
6551 
6552 	if (!obj->btf || !kernel_supports(obj, FEAT_BTF_DECL_TAG))
6553 		return 0;
6554 
6555 	n = btf__type_cnt(obj->btf);
6556 	for (i = 1; i < n; i++) {
6557 		const char *name;
6558 		struct btf_type *t;
6559 
6560 		t = btf_type_by_id(obj->btf, i);
6561 		if (!btf_is_decl_tag(t) || btf_decl_tag(t)->component_idx != -1)
6562 			continue;
6563 
6564 		name = btf__str_by_offset(obj->btf, t->name_off);
6565 		if (strncmp(name, str, pfx_len) != 0)
6566 			continue;
6567 
6568 		t = btf_type_by_id(obj->btf, t->type);
6569 		if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
6570 			pr_warn("prog '%s': exception_callback:<value> decl tag not applied to the main program\n",
6571 				prog->name);
6572 			return -EINVAL;
6573 		}
6574 		if (strcmp(prog->name, btf__str_by_offset(obj->btf, t->name_off)) != 0)
6575 			continue;
6576 		/* Multiple callbacks are specified for the same prog,
6577 		 * the verifier will eventually return an error for this
6578 		 * case, hence simply skip appending a subprog.
6579 		 */
6580 		if (prog->exception_cb_idx >= 0) {
6581 			prog->exception_cb_idx = -1;
6582 			break;
6583 		}
6584 
6585 		name += pfx_len;
6586 		if (str_is_empty(name)) {
6587 			pr_warn("prog '%s': exception_callback:<value> decl tag contains empty value\n",
6588 				prog->name);
6589 			return -EINVAL;
6590 		}
6591 
6592 		for (j = 0; j < obj->nr_programs; j++) {
6593 			struct bpf_program *subprog = &obj->programs[j];
6594 
6595 			if (!prog_is_subprog(obj, subprog))
6596 				continue;
6597 			if (strcmp(name, subprog->name) != 0)
6598 				continue;
6599 			/* Enforce non-hidden, as from verifier point of
6600 			 * view it expects global functions, whereas the
6601 			 * mark_btf_static fixes up linkage as static.
6602 			 */
6603 			if (!subprog->sym_global || subprog->mark_btf_static) {
6604 				pr_warn("prog '%s': exception callback %s must be a global non-hidden function\n",
6605 					prog->name, subprog->name);
6606 				return -EINVAL;
6607 			}
6608 			/* Let's see if we already saw a static exception callback with the same name */
6609 			if (prog->exception_cb_idx >= 0) {
6610 				pr_warn("prog '%s': multiple subprogs with same name as exception callback '%s'\n",
6611 					prog->name, subprog->name);
6612 				return -EINVAL;
6613 			}
6614 			prog->exception_cb_idx = j;
6615 			break;
6616 		}
6617 
6618 		if (prog->exception_cb_idx >= 0)
6619 			continue;
6620 
6621 		pr_warn("prog '%s': cannot find exception callback '%s'\n", prog->name, name);
6622 		return -ENOENT;
6623 	}
6624 
6625 	return 0;
6626 }
6627 
6628 static struct {
6629 	enum bpf_prog_type prog_type;
6630 	const char *ctx_name;
6631 } global_ctx_map[] = {
6632 	{ BPF_PROG_TYPE_CGROUP_DEVICE,           "bpf_cgroup_dev_ctx" },
6633 	{ BPF_PROG_TYPE_CGROUP_SKB,              "__sk_buff" },
6634 	{ BPF_PROG_TYPE_CGROUP_SOCK,             "bpf_sock" },
6635 	{ BPF_PROG_TYPE_CGROUP_SOCK_ADDR,        "bpf_sock_addr" },
6636 	{ BPF_PROG_TYPE_CGROUP_SOCKOPT,          "bpf_sockopt" },
6637 	{ BPF_PROG_TYPE_CGROUP_SYSCTL,           "bpf_sysctl" },
6638 	{ BPF_PROG_TYPE_FLOW_DISSECTOR,          "__sk_buff" },
6639 	{ BPF_PROG_TYPE_KPROBE,                  "bpf_user_pt_regs_t" },
6640 	{ BPF_PROG_TYPE_LWT_IN,                  "__sk_buff" },
6641 	{ BPF_PROG_TYPE_LWT_OUT,                 "__sk_buff" },
6642 	{ BPF_PROG_TYPE_LWT_SEG6LOCAL,           "__sk_buff" },
6643 	{ BPF_PROG_TYPE_LWT_XMIT,                "__sk_buff" },
6644 	{ BPF_PROG_TYPE_NETFILTER,               "bpf_nf_ctx" },
6645 	{ BPF_PROG_TYPE_PERF_EVENT,              "bpf_perf_event_data" },
6646 	{ BPF_PROG_TYPE_RAW_TRACEPOINT,          "bpf_raw_tracepoint_args" },
6647 	{ BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE, "bpf_raw_tracepoint_args" },
6648 	{ BPF_PROG_TYPE_SCHED_ACT,               "__sk_buff" },
6649 	{ BPF_PROG_TYPE_SCHED_CLS,               "__sk_buff" },
6650 	{ BPF_PROG_TYPE_SK_LOOKUP,               "bpf_sk_lookup" },
6651 	{ BPF_PROG_TYPE_SK_MSG,                  "sk_msg_md" },
6652 	{ BPF_PROG_TYPE_SK_REUSEPORT,            "sk_reuseport_md" },
6653 	{ BPF_PROG_TYPE_SK_SKB,                  "__sk_buff" },
6654 	{ BPF_PROG_TYPE_SOCK_OPS,                "bpf_sock_ops" },
6655 	{ BPF_PROG_TYPE_SOCKET_FILTER,           "__sk_buff" },
6656 	{ BPF_PROG_TYPE_XDP,                     "xdp_md" },
6657 	/* all other program types don't have "named" context structs */
6658 };
6659 
6660 /* forward declarations for arch-specific underlying types of bpf_user_pt_regs_t typedef,
6661  * for below __builtin_types_compatible_p() checks;
6662  * with this approach we don't need any extra arch-specific #ifdef guards
6663  */
6664 struct pt_regs;
6665 struct user_pt_regs;
6666 struct user_regs_struct;
6667 
6668 static bool need_func_arg_type_fixup(const struct btf *btf, const struct bpf_program *prog,
6669 				     const char *subprog_name, int arg_idx,
6670 				     int arg_type_id, const char *ctx_name)
6671 {
6672 	const struct btf_type *t;
6673 	const char *tname;
6674 
6675 	/* check if existing parameter already matches verifier expectations */
6676 	t = skip_mods_and_typedefs(btf, arg_type_id, NULL);
6677 	if (!btf_is_ptr(t))
6678 		goto out_warn;
6679 
6680 	/* typedef bpf_user_pt_regs_t is a special PITA case, valid for kprobe
6681 	 * and perf_event programs, so check this case early on and forget
6682 	 * about it for subsequent checks
6683 	 */
6684 	while (btf_is_mod(t))
6685 		t = btf__type_by_id(btf, t->type);
6686 	if (btf_is_typedef(t) &&
6687 	    (prog->type == BPF_PROG_TYPE_KPROBE || prog->type == BPF_PROG_TYPE_PERF_EVENT)) {
6688 		tname = btf__str_by_offset(btf, t->name_off) ?: "<anon>";
6689 		if (strcmp(tname, "bpf_user_pt_regs_t") == 0)
6690 			return false; /* canonical type for kprobe/perf_event */
6691 	}
6692 
6693 	/* now we can ignore typedefs moving forward */
6694 	t = skip_mods_and_typedefs(btf, t->type, NULL);
6695 
6696 	/* if it's `void *`, definitely fix up BTF info */
6697 	if (btf_is_void(t))
6698 		return true;
6699 
6700 	/* if it's already proper canonical type, no need to fix up */
6701 	tname = btf__str_by_offset(btf, t->name_off) ?: "<anon>";
6702 	if (btf_is_struct(t) && strcmp(tname, ctx_name) == 0)
6703 		return false;
6704 
6705 	/* special cases */
6706 	switch (prog->type) {
6707 	case BPF_PROG_TYPE_KPROBE:
6708 		/* `struct pt_regs *` is expected, but we need to fix up */
6709 		if (btf_is_struct(t) && strcmp(tname, "pt_regs") == 0)
6710 			return true;
6711 		break;
6712 	case BPF_PROG_TYPE_PERF_EVENT:
6713 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct pt_regs) &&
6714 		    btf_is_struct(t) && strcmp(tname, "pt_regs") == 0)
6715 			return true;
6716 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_pt_regs) &&
6717 		    btf_is_struct(t) && strcmp(tname, "user_pt_regs") == 0)
6718 			return true;
6719 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_regs_struct) &&
6720 		    btf_is_struct(t) && strcmp(tname, "user_regs_struct") == 0)
6721 			return true;
6722 		break;
6723 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
6724 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
6725 		/* allow u64* as ctx */
6726 		if (btf_is_int(t) && t->size == 8)
6727 			return true;
6728 		break;
6729 	default:
6730 		break;
6731 	}
6732 
6733 out_warn:
6734 	pr_warn("prog '%s': subprog '%s' arg#%d is expected to be of `struct %s *` type\n",
6735 		prog->name, subprog_name, arg_idx, ctx_name);
6736 	return false;
6737 }
6738 
6739 static int clone_func_btf_info(struct btf *btf, int orig_fn_id, struct bpf_program *prog)
6740 {
6741 	int fn_id, fn_proto_id, ret_type_id, orig_proto_id;
6742 	int i, err, arg_cnt, fn_name_off, linkage;
6743 	struct btf_type *fn_t, *fn_proto_t, *t;
6744 	struct btf_param *p;
6745 
6746 	/* caller already validated FUNC -> FUNC_PROTO validity */
6747 	fn_t = btf_type_by_id(btf, orig_fn_id);
6748 	fn_proto_t = btf_type_by_id(btf, fn_t->type);
6749 
6750 	/* Note that each btf__add_xxx() operation invalidates
6751 	 * all btf_type and string pointers, so we need to be
6752 	 * very careful when cloning BTF types. BTF type
6753 	 * pointers have to be always refetched. And to avoid
6754 	 * problems with invalidated string pointers, we
6755 	 * add empty strings initially, then just fix up
6756 	 * name_off offsets in place. Offsets are stable for
6757 	 * existing strings, so that works out.
6758 	 */
6759 	fn_name_off = fn_t->name_off; /* we are about to invalidate fn_t */
6760 	linkage = btf_func_linkage(fn_t);
6761 	orig_proto_id = fn_t->type; /* original FUNC_PROTO ID */
6762 	ret_type_id = fn_proto_t->type; /* fn_proto_t will be invalidated */
6763 	arg_cnt = btf_vlen(fn_proto_t);
6764 
6765 	/* clone FUNC_PROTO and its params */
6766 	fn_proto_id = btf__add_func_proto(btf, ret_type_id);
6767 	if (fn_proto_id < 0)
6768 		return -EINVAL;
6769 
6770 	for (i = 0; i < arg_cnt; i++) {
6771 		int name_off;
6772 
6773 		/* copy original parameter data */
6774 		t = btf_type_by_id(btf, orig_proto_id);
6775 		p = &btf_params(t)[i];
6776 		name_off = p->name_off;
6777 
6778 		err = btf__add_func_param(btf, "", p->type);
6779 		if (err)
6780 			return err;
6781 
6782 		fn_proto_t = btf_type_by_id(btf, fn_proto_id);
6783 		p = &btf_params(fn_proto_t)[i];
6784 		p->name_off = name_off; /* use remembered str offset */
6785 	}
6786 
6787 	/* clone FUNC now, btf__add_func() enforces non-empty name, so use
6788 	 * entry program's name as a placeholder, which we replace immediately
6789 	 * with original name_off
6790 	 */
6791 	fn_id = btf__add_func(btf, prog->name, linkage, fn_proto_id);
6792 	if (fn_id < 0)
6793 		return -EINVAL;
6794 
6795 	fn_t = btf_type_by_id(btf, fn_id);
6796 	fn_t->name_off = fn_name_off; /* reuse original string */
6797 
6798 	return fn_id;
6799 }
6800 
6801 /* Check if main program or global subprog's function prototype has `arg:ctx`
6802  * argument tags, and, if necessary, substitute correct type to match what BPF
6803  * verifier would expect, taking into account specific program type. This
6804  * allows to support __arg_ctx tag transparently on old kernels that don't yet
6805  * have a native support for it in the verifier, making user's life much
6806  * easier.
6807  */
6808 static int bpf_program_fixup_func_info(struct bpf_object *obj, struct bpf_program *prog)
6809 {
6810 	const char *ctx_name = NULL, *ctx_tag = "arg:ctx", *fn_name;
6811 	struct bpf_func_info_min *func_rec;
6812 	struct btf_type *fn_t, *fn_proto_t;
6813 	struct btf *btf = obj->btf;
6814 	const struct btf_type *t;
6815 	struct btf_param *p;
6816 	int ptr_id = 0, struct_id, tag_id, orig_fn_id;
6817 	int i, n, arg_idx, arg_cnt, err, rec_idx;
6818 	int *orig_ids;
6819 
6820 	/* no .BTF.ext, no problem */
6821 	if (!obj->btf_ext || !prog->func_info)
6822 		return 0;
6823 
6824 	/* don't do any fix ups if kernel natively supports __arg_ctx */
6825 	if (kernel_supports(obj, FEAT_ARG_CTX_TAG))
6826 		return 0;
6827 
6828 	/* some BPF program types just don't have named context structs, so
6829 	 * this fallback mechanism doesn't work for them
6830 	 */
6831 	for (i = 0; i < ARRAY_SIZE(global_ctx_map); i++) {
6832 		if (global_ctx_map[i].prog_type != prog->type)
6833 			continue;
6834 		ctx_name = global_ctx_map[i].ctx_name;
6835 		break;
6836 	}
6837 	if (!ctx_name)
6838 		return 0;
6839 
6840 	/* remember original func BTF IDs to detect if we already cloned them */
6841 	orig_ids = calloc(prog->func_info_cnt, sizeof(*orig_ids));
6842 	if (!orig_ids)
6843 		return -ENOMEM;
6844 	for (i = 0; i < prog->func_info_cnt; i++) {
6845 		func_rec = prog->func_info + prog->func_info_rec_size * i;
6846 		orig_ids[i] = func_rec->type_id;
6847 	}
6848 
6849 	/* go through each DECL_TAG with "arg:ctx" and see if it points to one
6850 	 * of our subprogs; if yes and subprog is global and needs adjustment,
6851 	 * clone and adjust FUNC -> FUNC_PROTO combo
6852 	 */
6853 	for (i = 1, n = btf__type_cnt(btf); i < n; i++) {
6854 		/* only DECL_TAG with "arg:ctx" value are interesting */
6855 		t = btf__type_by_id(btf, i);
6856 		if (!btf_is_decl_tag(t))
6857 			continue;
6858 		if (strcmp(btf__str_by_offset(btf, t->name_off), ctx_tag) != 0)
6859 			continue;
6860 
6861 		/* only global funcs need adjustment, if at all */
6862 		orig_fn_id = t->type;
6863 		fn_t = btf_type_by_id(btf, orig_fn_id);
6864 		if (!btf_is_func(fn_t) || btf_func_linkage(fn_t) != BTF_FUNC_GLOBAL)
6865 			continue;
6866 
6867 		/* sanity check FUNC -> FUNC_PROTO chain, just in case */
6868 		fn_proto_t = btf_type_by_id(btf, fn_t->type);
6869 		if (!fn_proto_t || !btf_is_func_proto(fn_proto_t))
6870 			continue;
6871 
6872 		/* find corresponding func_info record */
6873 		func_rec = NULL;
6874 		for (rec_idx = 0; rec_idx < prog->func_info_cnt; rec_idx++) {
6875 			if (orig_ids[rec_idx] == t->type) {
6876 				func_rec = prog->func_info + prog->func_info_rec_size * rec_idx;
6877 				break;
6878 			}
6879 		}
6880 		/* current main program doesn't call into this subprog */
6881 		if (!func_rec)
6882 			continue;
6883 
6884 		/* some more sanity checking of DECL_TAG */
6885 		arg_cnt = btf_vlen(fn_proto_t);
6886 		arg_idx = btf_decl_tag(t)->component_idx;
6887 		if (arg_idx < 0 || arg_idx >= arg_cnt)
6888 			continue;
6889 
6890 		/* check if we should fix up argument type */
6891 		p = &btf_params(fn_proto_t)[arg_idx];
6892 		fn_name = btf__str_by_offset(btf, fn_t->name_off) ?: "<anon>";
6893 		if (!need_func_arg_type_fixup(btf, prog, fn_name, arg_idx, p->type, ctx_name))
6894 			continue;
6895 
6896 		/* clone fn/fn_proto, unless we already did it for another arg */
6897 		if (func_rec->type_id == orig_fn_id) {
6898 			int fn_id;
6899 
6900 			fn_id = clone_func_btf_info(btf, orig_fn_id, prog);
6901 			if (fn_id < 0) {
6902 				err = fn_id;
6903 				goto err_out;
6904 			}
6905 
6906 			/* point func_info record to a cloned FUNC type */
6907 			func_rec->type_id = fn_id;
6908 		}
6909 
6910 		/* create PTR -> STRUCT type chain to mark PTR_TO_CTX argument;
6911 		 * we do it just once per main BPF program, as all global
6912 		 * funcs share the same program type, so need only PTR ->
6913 		 * STRUCT type chain
6914 		 */
6915 		if (ptr_id == 0) {
6916 			struct_id = btf__add_struct(btf, ctx_name, 0);
6917 			ptr_id = btf__add_ptr(btf, struct_id);
6918 			if (ptr_id < 0 || struct_id < 0) {
6919 				err = -EINVAL;
6920 				goto err_out;
6921 			}
6922 		}
6923 
6924 		/* for completeness, clone DECL_TAG and point it to cloned param */
6925 		tag_id = btf__add_decl_tag(btf, ctx_tag, func_rec->type_id, arg_idx);
6926 		if (tag_id < 0) {
6927 			err = -EINVAL;
6928 			goto err_out;
6929 		}
6930 
6931 		/* all the BTF manipulations invalidated pointers, refetch them */
6932 		fn_t = btf_type_by_id(btf, func_rec->type_id);
6933 		fn_proto_t = btf_type_by_id(btf, fn_t->type);
6934 
6935 		/* fix up type ID pointed to by param */
6936 		p = &btf_params(fn_proto_t)[arg_idx];
6937 		p->type = ptr_id;
6938 	}
6939 
6940 	free(orig_ids);
6941 	return 0;
6942 err_out:
6943 	free(orig_ids);
6944 	return err;
6945 }
6946 
6947 static int bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
6948 {
6949 	struct bpf_program *prog;
6950 	size_t i, j;
6951 	int err;
6952 
6953 	if (obj->btf_ext) {
6954 		err = bpf_object__relocate_core(obj, targ_btf_path);
6955 		if (err) {
6956 			pr_warn("failed to perform CO-RE relocations: %d\n",
6957 				err);
6958 			return err;
6959 		}
6960 		bpf_object__sort_relos(obj);
6961 	}
6962 
6963 	/* Before relocating calls pre-process relocations and mark
6964 	 * few ld_imm64 instructions that points to subprogs.
6965 	 * Otherwise bpf_object__reloc_code() later would have to consider
6966 	 * all ld_imm64 insns as relocation candidates. That would
6967 	 * reduce relocation speed, since amount of find_prog_insn_relo()
6968 	 * would increase and most of them will fail to find a relo.
6969 	 */
6970 	for (i = 0; i < obj->nr_programs; i++) {
6971 		prog = &obj->programs[i];
6972 		for (j = 0; j < prog->nr_reloc; j++) {
6973 			struct reloc_desc *relo = &prog->reloc_desc[j];
6974 			struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6975 
6976 			/* mark the insn, so it's recognized by insn_is_pseudo_func() */
6977 			if (relo->type == RELO_SUBPROG_ADDR)
6978 				insn[0].src_reg = BPF_PSEUDO_FUNC;
6979 		}
6980 	}
6981 
6982 	/* relocate subprogram calls and append used subprograms to main
6983 	 * programs; each copy of subprogram code needs to be relocated
6984 	 * differently for each main program, because its code location might
6985 	 * have changed.
6986 	 * Append subprog relos to main programs to allow data relos to be
6987 	 * processed after text is completely relocated.
6988 	 */
6989 	for (i = 0; i < obj->nr_programs; i++) {
6990 		prog = &obj->programs[i];
6991 		/* sub-program's sub-calls are relocated within the context of
6992 		 * its main program only
6993 		 */
6994 		if (prog_is_subprog(obj, prog))
6995 			continue;
6996 		if (!prog->autoload)
6997 			continue;
6998 
6999 		err = bpf_object__relocate_calls(obj, prog);
7000 		if (err) {
7001 			pr_warn("prog '%s': failed to relocate calls: %d\n",
7002 				prog->name, err);
7003 			return err;
7004 		}
7005 
7006 		err = bpf_prog_assign_exc_cb(obj, prog);
7007 		if (err)
7008 			return err;
7009 		/* Now, also append exception callback if it has not been done already. */
7010 		if (prog->exception_cb_idx >= 0) {
7011 			struct bpf_program *subprog = &obj->programs[prog->exception_cb_idx];
7012 
7013 			/* Calling exception callback directly is disallowed, which the
7014 			 * verifier will reject later. In case it was processed already,
7015 			 * we can skip this step, otherwise for all other valid cases we
7016 			 * have to append exception callback now.
7017 			 */
7018 			if (subprog->sub_insn_off == 0) {
7019 				err = bpf_object__append_subprog_code(obj, prog, subprog);
7020 				if (err)
7021 					return err;
7022 				err = bpf_object__reloc_code(obj, prog, subprog);
7023 				if (err)
7024 					return err;
7025 			}
7026 		}
7027 	}
7028 	for (i = 0; i < obj->nr_programs; i++) {
7029 		prog = &obj->programs[i];
7030 		if (prog_is_subprog(obj, prog))
7031 			continue;
7032 		if (!prog->autoload)
7033 			continue;
7034 
7035 		/* Process data relos for main programs */
7036 		err = bpf_object__relocate_data(obj, prog);
7037 		if (err) {
7038 			pr_warn("prog '%s': failed to relocate data references: %d\n",
7039 				prog->name, err);
7040 			return err;
7041 		}
7042 
7043 		/* Fix up .BTF.ext information, if necessary */
7044 		err = bpf_program_fixup_func_info(obj, prog);
7045 		if (err) {
7046 			pr_warn("prog '%s': failed to perform .BTF.ext fix ups: %d\n",
7047 				prog->name, err);
7048 			return err;
7049 		}
7050 	}
7051 
7052 	return 0;
7053 }
7054 
7055 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
7056 					    Elf64_Shdr *shdr, Elf_Data *data);
7057 
7058 static int bpf_object__collect_map_relos(struct bpf_object *obj,
7059 					 Elf64_Shdr *shdr, Elf_Data *data)
7060 {
7061 	const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
7062 	int i, j, nrels, new_sz;
7063 	const struct btf_var_secinfo *vi = NULL;
7064 	const struct btf_type *sec, *var, *def;
7065 	struct bpf_map *map = NULL, *targ_map = NULL;
7066 	struct bpf_program *targ_prog = NULL;
7067 	bool is_prog_array, is_map_in_map;
7068 	const struct btf_member *member;
7069 	const char *name, *mname, *type;
7070 	unsigned int moff;
7071 	Elf64_Sym *sym;
7072 	Elf64_Rel *rel;
7073 	void *tmp;
7074 
7075 	if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
7076 		return -EINVAL;
7077 	sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
7078 	if (!sec)
7079 		return -EINVAL;
7080 
7081 	nrels = shdr->sh_size / shdr->sh_entsize;
7082 	for (i = 0; i < nrels; i++) {
7083 		rel = elf_rel_by_idx(data, i);
7084 		if (!rel) {
7085 			pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
7086 			return -LIBBPF_ERRNO__FORMAT;
7087 		}
7088 
7089 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
7090 		if (!sym) {
7091 			pr_warn(".maps relo #%d: symbol %zx not found\n",
7092 				i, (size_t)ELF64_R_SYM(rel->r_info));
7093 			return -LIBBPF_ERRNO__FORMAT;
7094 		}
7095 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
7096 
7097 		pr_debug(".maps relo #%d: for %zd value %zd rel->r_offset %zu name %d ('%s')\n",
7098 			 i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
7099 			 (size_t)rel->r_offset, sym->st_name, name);
7100 
7101 		for (j = 0; j < obj->nr_maps; j++) {
7102 			map = &obj->maps[j];
7103 			if (map->sec_idx != obj->efile.btf_maps_shndx)
7104 				continue;
7105 
7106 			vi = btf_var_secinfos(sec) + map->btf_var_idx;
7107 			if (vi->offset <= rel->r_offset &&
7108 			    rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size)
7109 				break;
7110 		}
7111 		if (j == obj->nr_maps) {
7112 			pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
7113 				i, name, (size_t)rel->r_offset);
7114 			return -EINVAL;
7115 		}
7116 
7117 		is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
7118 		is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
7119 		type = is_map_in_map ? "map" : "prog";
7120 		if (is_map_in_map) {
7121 			if (sym->st_shndx != obj->efile.btf_maps_shndx) {
7122 				pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
7123 					i, name);
7124 				return -LIBBPF_ERRNO__RELOC;
7125 			}
7126 			if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
7127 			    map->def.key_size != sizeof(int)) {
7128 				pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
7129 					i, map->name, sizeof(int));
7130 				return -EINVAL;
7131 			}
7132 			targ_map = bpf_object__find_map_by_name(obj, name);
7133 			if (!targ_map) {
7134 				pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
7135 					i, name);
7136 				return -ESRCH;
7137 			}
7138 		} else if (is_prog_array) {
7139 			targ_prog = bpf_object__find_program_by_name(obj, name);
7140 			if (!targ_prog) {
7141 				pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
7142 					i, name);
7143 				return -ESRCH;
7144 			}
7145 			if (targ_prog->sec_idx != sym->st_shndx ||
7146 			    targ_prog->sec_insn_off * 8 != sym->st_value ||
7147 			    prog_is_subprog(obj, targ_prog)) {
7148 				pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
7149 					i, name);
7150 				return -LIBBPF_ERRNO__RELOC;
7151 			}
7152 		} else {
7153 			return -EINVAL;
7154 		}
7155 
7156 		var = btf__type_by_id(obj->btf, vi->type);
7157 		def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
7158 		if (btf_vlen(def) == 0)
7159 			return -EINVAL;
7160 		member = btf_members(def) + btf_vlen(def) - 1;
7161 		mname = btf__name_by_offset(obj->btf, member->name_off);
7162 		if (strcmp(mname, "values"))
7163 			return -EINVAL;
7164 
7165 		moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
7166 		if (rel->r_offset - vi->offset < moff)
7167 			return -EINVAL;
7168 
7169 		moff = rel->r_offset - vi->offset - moff;
7170 		/* here we use BPF pointer size, which is always 64 bit, as we
7171 		 * are parsing ELF that was built for BPF target
7172 		 */
7173 		if (moff % bpf_ptr_sz)
7174 			return -EINVAL;
7175 		moff /= bpf_ptr_sz;
7176 		if (moff >= map->init_slots_sz) {
7177 			new_sz = moff + 1;
7178 			tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
7179 			if (!tmp)
7180 				return -ENOMEM;
7181 			map->init_slots = tmp;
7182 			memset(map->init_slots + map->init_slots_sz, 0,
7183 			       (new_sz - map->init_slots_sz) * host_ptr_sz);
7184 			map->init_slots_sz = new_sz;
7185 		}
7186 		map->init_slots[moff] = is_map_in_map ? (void *)targ_map : (void *)targ_prog;
7187 
7188 		pr_debug(".maps relo #%d: map '%s' slot [%d] points to %s '%s'\n",
7189 			 i, map->name, moff, type, name);
7190 	}
7191 
7192 	return 0;
7193 }
7194 
7195 static int bpf_object__collect_relos(struct bpf_object *obj)
7196 {
7197 	int i, err;
7198 
7199 	for (i = 0; i < obj->efile.sec_cnt; i++) {
7200 		struct elf_sec_desc *sec_desc = &obj->efile.secs[i];
7201 		Elf64_Shdr *shdr;
7202 		Elf_Data *data;
7203 		int idx;
7204 
7205 		if (sec_desc->sec_type != SEC_RELO)
7206 			continue;
7207 
7208 		shdr = sec_desc->shdr;
7209 		data = sec_desc->data;
7210 		idx = shdr->sh_info;
7211 
7212 		if (shdr->sh_type != SHT_REL || idx < 0 || idx >= obj->efile.sec_cnt) {
7213 			pr_warn("internal error at %d\n", __LINE__);
7214 			return -LIBBPF_ERRNO__INTERNAL;
7215 		}
7216 
7217 		if (obj->efile.secs[idx].sec_type == SEC_ST_OPS)
7218 			err = bpf_object__collect_st_ops_relos(obj, shdr, data);
7219 		else if (idx == obj->efile.btf_maps_shndx)
7220 			err = bpf_object__collect_map_relos(obj, shdr, data);
7221 		else
7222 			err = bpf_object__collect_prog_relos(obj, shdr, data);
7223 		if (err)
7224 			return err;
7225 	}
7226 
7227 	bpf_object__sort_relos(obj);
7228 	return 0;
7229 }
7230 
7231 static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
7232 {
7233 	if (BPF_CLASS(insn->code) == BPF_JMP &&
7234 	    BPF_OP(insn->code) == BPF_CALL &&
7235 	    BPF_SRC(insn->code) == BPF_K &&
7236 	    insn->src_reg == 0 &&
7237 	    insn->dst_reg == 0) {
7238 		    *func_id = insn->imm;
7239 		    return true;
7240 	}
7241 	return false;
7242 }
7243 
7244 static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
7245 {
7246 	struct bpf_insn *insn = prog->insns;
7247 	enum bpf_func_id func_id;
7248 	int i;
7249 
7250 	if (obj->gen_loader)
7251 		return 0;
7252 
7253 	for (i = 0; i < prog->insns_cnt; i++, insn++) {
7254 		if (!insn_is_helper_call(insn, &func_id))
7255 			continue;
7256 
7257 		/* on kernels that don't yet support
7258 		 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
7259 		 * to bpf_probe_read() which works well for old kernels
7260 		 */
7261 		switch (func_id) {
7262 		case BPF_FUNC_probe_read_kernel:
7263 		case BPF_FUNC_probe_read_user:
7264 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
7265 				insn->imm = BPF_FUNC_probe_read;
7266 			break;
7267 		case BPF_FUNC_probe_read_kernel_str:
7268 		case BPF_FUNC_probe_read_user_str:
7269 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
7270 				insn->imm = BPF_FUNC_probe_read_str;
7271 			break;
7272 		default:
7273 			break;
7274 		}
7275 	}
7276 	return 0;
7277 }
7278 
7279 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
7280 				     int *btf_obj_fd, int *btf_type_id);
7281 
7282 /* this is called as prog->sec_def->prog_prepare_load_fn for libbpf-supported sec_defs */
7283 static int libbpf_prepare_prog_load(struct bpf_program *prog,
7284 				    struct bpf_prog_load_opts *opts, long cookie)
7285 {
7286 	enum sec_def_flags def = cookie;
7287 
7288 	/* old kernels might not support specifying expected_attach_type */
7289 	if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
7290 		opts->expected_attach_type = 0;
7291 
7292 	if (def & SEC_SLEEPABLE)
7293 		opts->prog_flags |= BPF_F_SLEEPABLE;
7294 
7295 	if (prog->type == BPF_PROG_TYPE_XDP && (def & SEC_XDP_FRAGS))
7296 		opts->prog_flags |= BPF_F_XDP_HAS_FRAGS;
7297 
7298 	/* special check for usdt to use uprobe_multi link */
7299 	if ((def & SEC_USDT) && kernel_supports(prog->obj, FEAT_UPROBE_MULTI_LINK))
7300 		prog->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
7301 
7302 	if ((def & SEC_ATTACH_BTF) && !prog->attach_btf_id) {
7303 		int btf_obj_fd = 0, btf_type_id = 0, err;
7304 		const char *attach_name;
7305 
7306 		attach_name = strchr(prog->sec_name, '/');
7307 		if (!attach_name) {
7308 			/* if BPF program is annotated with just SEC("fentry")
7309 			 * (or similar) without declaratively specifying
7310 			 * target, then it is expected that target will be
7311 			 * specified with bpf_program__set_attach_target() at
7312 			 * runtime before BPF object load step. If not, then
7313 			 * there is nothing to load into the kernel as BPF
7314 			 * verifier won't be able to validate BPF program
7315 			 * correctness anyways.
7316 			 */
7317 			pr_warn("prog '%s': no BTF-based attach target is specified, use bpf_program__set_attach_target()\n",
7318 				prog->name);
7319 			return -EINVAL;
7320 		}
7321 		attach_name++; /* skip over / */
7322 
7323 		err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
7324 		if (err)
7325 			return err;
7326 
7327 		/* cache resolved BTF FD and BTF type ID in the prog */
7328 		prog->attach_btf_obj_fd = btf_obj_fd;
7329 		prog->attach_btf_id = btf_type_id;
7330 
7331 		/* but by now libbpf common logic is not utilizing
7332 		 * prog->atach_btf_obj_fd/prog->attach_btf_id anymore because
7333 		 * this callback is called after opts were populated by
7334 		 * libbpf, so this callback has to update opts explicitly here
7335 		 */
7336 		opts->attach_btf_obj_fd = btf_obj_fd;
7337 		opts->attach_btf_id = btf_type_id;
7338 	}
7339 	return 0;
7340 }
7341 
7342 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz);
7343 
7344 static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
7345 				struct bpf_insn *insns, int insns_cnt,
7346 				const char *license, __u32 kern_version, int *prog_fd)
7347 {
7348 	LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
7349 	const char *prog_name = NULL;
7350 	char *cp, errmsg[STRERR_BUFSIZE];
7351 	size_t log_buf_size = 0;
7352 	char *log_buf = NULL, *tmp;
7353 	bool own_log_buf = true;
7354 	__u32 log_level = prog->log_level;
7355 	int ret, err;
7356 
7357 	if (prog->type == BPF_PROG_TYPE_UNSPEC) {
7358 		/*
7359 		 * The program type must be set.  Most likely we couldn't find a proper
7360 		 * section definition at load time, and thus we didn't infer the type.
7361 		 */
7362 		pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
7363 			prog->name, prog->sec_name);
7364 		return -EINVAL;
7365 	}
7366 
7367 	if (!insns || !insns_cnt)
7368 		return -EINVAL;
7369 
7370 	if (kernel_supports(obj, FEAT_PROG_NAME))
7371 		prog_name = prog->name;
7372 	load_attr.attach_prog_fd = prog->attach_prog_fd;
7373 	load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
7374 	load_attr.attach_btf_id = prog->attach_btf_id;
7375 	load_attr.kern_version = kern_version;
7376 	load_attr.prog_ifindex = prog->prog_ifindex;
7377 
7378 	/* specify func_info/line_info only if kernel supports them */
7379 	if (obj->btf && btf__fd(obj->btf) >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
7380 		load_attr.prog_btf_fd = btf__fd(obj->btf);
7381 		load_attr.func_info = prog->func_info;
7382 		load_attr.func_info_rec_size = prog->func_info_rec_size;
7383 		load_attr.func_info_cnt = prog->func_info_cnt;
7384 		load_attr.line_info = prog->line_info;
7385 		load_attr.line_info_rec_size = prog->line_info_rec_size;
7386 		load_attr.line_info_cnt = prog->line_info_cnt;
7387 	}
7388 	load_attr.log_level = log_level;
7389 	load_attr.prog_flags = prog->prog_flags;
7390 	load_attr.fd_array = obj->fd_array;
7391 
7392 	load_attr.token_fd = obj->token_fd;
7393 	if (obj->token_fd)
7394 		load_attr.prog_flags |= BPF_F_TOKEN_FD;
7395 
7396 	/* adjust load_attr if sec_def provides custom preload callback */
7397 	if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
7398 		err = prog->sec_def->prog_prepare_load_fn(prog, &load_attr, prog->sec_def->cookie);
7399 		if (err < 0) {
7400 			pr_warn("prog '%s': failed to prepare load attributes: %d\n",
7401 				prog->name, err);
7402 			return err;
7403 		}
7404 		insns = prog->insns;
7405 		insns_cnt = prog->insns_cnt;
7406 	}
7407 
7408 	/* allow prog_prepare_load_fn to change expected_attach_type */
7409 	load_attr.expected_attach_type = prog->expected_attach_type;
7410 
7411 	if (obj->gen_loader) {
7412 		bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
7413 				   license, insns, insns_cnt, &load_attr,
7414 				   prog - obj->programs);
7415 		*prog_fd = -1;
7416 		return 0;
7417 	}
7418 
7419 retry_load:
7420 	/* if log_level is zero, we don't request logs initially even if
7421 	 * custom log_buf is specified; if the program load fails, then we'll
7422 	 * bump log_level to 1 and use either custom log_buf or we'll allocate
7423 	 * our own and retry the load to get details on what failed
7424 	 */
7425 	if (log_level) {
7426 		if (prog->log_buf) {
7427 			log_buf = prog->log_buf;
7428 			log_buf_size = prog->log_size;
7429 			own_log_buf = false;
7430 		} else if (obj->log_buf) {
7431 			log_buf = obj->log_buf;
7432 			log_buf_size = obj->log_size;
7433 			own_log_buf = false;
7434 		} else {
7435 			log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
7436 			tmp = realloc(log_buf, log_buf_size);
7437 			if (!tmp) {
7438 				ret = -ENOMEM;
7439 				goto out;
7440 			}
7441 			log_buf = tmp;
7442 			log_buf[0] = '\0';
7443 			own_log_buf = true;
7444 		}
7445 	}
7446 
7447 	load_attr.log_buf = log_buf;
7448 	load_attr.log_size = log_buf_size;
7449 	load_attr.log_level = log_level;
7450 
7451 	ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
7452 	if (ret >= 0) {
7453 		if (log_level && own_log_buf) {
7454 			pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
7455 				 prog->name, log_buf);
7456 		}
7457 
7458 		if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
7459 			struct bpf_map *map;
7460 			int i;
7461 
7462 			for (i = 0; i < obj->nr_maps; i++) {
7463 				map = &prog->obj->maps[i];
7464 				if (map->libbpf_type != LIBBPF_MAP_RODATA)
7465 					continue;
7466 
7467 				if (bpf_prog_bind_map(ret, map->fd, NULL)) {
7468 					cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
7469 					pr_warn("prog '%s': failed to bind map '%s': %s\n",
7470 						prog->name, map->real_name, cp);
7471 					/* Don't fail hard if can't bind rodata. */
7472 				}
7473 			}
7474 		}
7475 
7476 		*prog_fd = ret;
7477 		ret = 0;
7478 		goto out;
7479 	}
7480 
7481 	if (log_level == 0) {
7482 		log_level = 1;
7483 		goto retry_load;
7484 	}
7485 	/* On ENOSPC, increase log buffer size and retry, unless custom
7486 	 * log_buf is specified.
7487 	 * Be careful to not overflow u32, though. Kernel's log buf size limit
7488 	 * isn't part of UAPI so it can always be bumped to full 4GB. So don't
7489 	 * multiply by 2 unless we are sure we'll fit within 32 bits.
7490 	 * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
7491 	 */
7492 	if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
7493 		goto retry_load;
7494 
7495 	ret = -errno;
7496 
7497 	/* post-process verifier log to improve error descriptions */
7498 	fixup_verifier_log(prog, log_buf, log_buf_size);
7499 
7500 	cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
7501 	pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, cp);
7502 	pr_perm_msg(ret);
7503 
7504 	if (own_log_buf && log_buf && log_buf[0] != '\0') {
7505 		pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
7506 			prog->name, log_buf);
7507 	}
7508 
7509 out:
7510 	if (own_log_buf)
7511 		free(log_buf);
7512 	return ret;
7513 }
7514 
7515 static char *find_prev_line(char *buf, char *cur)
7516 {
7517 	char *p;
7518 
7519 	if (cur == buf) /* end of a log buf */
7520 		return NULL;
7521 
7522 	p = cur - 1;
7523 	while (p - 1 >= buf && *(p - 1) != '\n')
7524 		p--;
7525 
7526 	return p;
7527 }
7528 
7529 static void patch_log(char *buf, size_t buf_sz, size_t log_sz,
7530 		      char *orig, size_t orig_sz, const char *patch)
7531 {
7532 	/* size of the remaining log content to the right from the to-be-replaced part */
7533 	size_t rem_sz = (buf + log_sz) - (orig + orig_sz);
7534 	size_t patch_sz = strlen(patch);
7535 
7536 	if (patch_sz != orig_sz) {
7537 		/* If patch line(s) are longer than original piece of verifier log,
7538 		 * shift log contents by (patch_sz - orig_sz) bytes to the right
7539 		 * starting from after to-be-replaced part of the log.
7540 		 *
7541 		 * If patch line(s) are shorter than original piece of verifier log,
7542 		 * shift log contents by (orig_sz - patch_sz) bytes to the left
7543 		 * starting from after to-be-replaced part of the log
7544 		 *
7545 		 * We need to be careful about not overflowing available
7546 		 * buf_sz capacity. If that's the case, we'll truncate the end
7547 		 * of the original log, as necessary.
7548 		 */
7549 		if (patch_sz > orig_sz) {
7550 			if (orig + patch_sz >= buf + buf_sz) {
7551 				/* patch is big enough to cover remaining space completely */
7552 				patch_sz -= (orig + patch_sz) - (buf + buf_sz) + 1;
7553 				rem_sz = 0;
7554 			} else if (patch_sz - orig_sz > buf_sz - log_sz) {
7555 				/* patch causes part of remaining log to be truncated */
7556 				rem_sz -= (patch_sz - orig_sz) - (buf_sz - log_sz);
7557 			}
7558 		}
7559 		/* shift remaining log to the right by calculated amount */
7560 		memmove(orig + patch_sz, orig + orig_sz, rem_sz);
7561 	}
7562 
7563 	memcpy(orig, patch, patch_sz);
7564 }
7565 
7566 static void fixup_log_failed_core_relo(struct bpf_program *prog,
7567 				       char *buf, size_t buf_sz, size_t log_sz,
7568 				       char *line1, char *line2, char *line3)
7569 {
7570 	/* Expected log for failed and not properly guarded CO-RE relocation:
7571 	 * line1 -> 123: (85) call unknown#195896080
7572 	 * line2 -> invalid func unknown#195896080
7573 	 * line3 -> <anything else or end of buffer>
7574 	 *
7575 	 * "123" is the index of the instruction that was poisoned. We extract
7576 	 * instruction index to find corresponding CO-RE relocation and
7577 	 * replace this part of the log with more relevant information about
7578 	 * failed CO-RE relocation.
7579 	 */
7580 	const struct bpf_core_relo *relo;
7581 	struct bpf_core_spec spec;
7582 	char patch[512], spec_buf[256];
7583 	int insn_idx, err, spec_len;
7584 
7585 	if (sscanf(line1, "%d: (%*d) call unknown#195896080\n", &insn_idx) != 1)
7586 		return;
7587 
7588 	relo = find_relo_core(prog, insn_idx);
7589 	if (!relo)
7590 		return;
7591 
7592 	err = bpf_core_parse_spec(prog->name, prog->obj->btf, relo, &spec);
7593 	if (err)
7594 		return;
7595 
7596 	spec_len = bpf_core_format_spec(spec_buf, sizeof(spec_buf), &spec);
7597 	snprintf(patch, sizeof(patch),
7598 		 "%d: <invalid CO-RE relocation>\n"
7599 		 "failed to resolve CO-RE relocation %s%s\n",
7600 		 insn_idx, spec_buf, spec_len >= sizeof(spec_buf) ? "..." : "");
7601 
7602 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7603 }
7604 
7605 static void fixup_log_missing_map_load(struct bpf_program *prog,
7606 				       char *buf, size_t buf_sz, size_t log_sz,
7607 				       char *line1, char *line2, char *line3)
7608 {
7609 	/* Expected log for failed and not properly guarded map reference:
7610 	 * line1 -> 123: (85) call unknown#2001000345
7611 	 * line2 -> invalid func unknown#2001000345
7612 	 * line3 -> <anything else or end of buffer>
7613 	 *
7614 	 * "123" is the index of the instruction that was poisoned.
7615 	 * "345" in "2001000345" is a map index in obj->maps to fetch map name.
7616 	 */
7617 	struct bpf_object *obj = prog->obj;
7618 	const struct bpf_map *map;
7619 	int insn_idx, map_idx;
7620 	char patch[128];
7621 
7622 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &map_idx) != 2)
7623 		return;
7624 
7625 	map_idx -= POISON_LDIMM64_MAP_BASE;
7626 	if (map_idx < 0 || map_idx >= obj->nr_maps)
7627 		return;
7628 	map = &obj->maps[map_idx];
7629 
7630 	snprintf(patch, sizeof(patch),
7631 		 "%d: <invalid BPF map reference>\n"
7632 		 "BPF map '%s' is referenced but wasn't created\n",
7633 		 insn_idx, map->name);
7634 
7635 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7636 }
7637 
7638 static void fixup_log_missing_kfunc_call(struct bpf_program *prog,
7639 					 char *buf, size_t buf_sz, size_t log_sz,
7640 					 char *line1, char *line2, char *line3)
7641 {
7642 	/* Expected log for failed and not properly guarded kfunc call:
7643 	 * line1 -> 123: (85) call unknown#2002000345
7644 	 * line2 -> invalid func unknown#2002000345
7645 	 * line3 -> <anything else or end of buffer>
7646 	 *
7647 	 * "123" is the index of the instruction that was poisoned.
7648 	 * "345" in "2002000345" is an extern index in obj->externs to fetch kfunc name.
7649 	 */
7650 	struct bpf_object *obj = prog->obj;
7651 	const struct extern_desc *ext;
7652 	int insn_idx, ext_idx;
7653 	char patch[128];
7654 
7655 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &ext_idx) != 2)
7656 		return;
7657 
7658 	ext_idx -= POISON_CALL_KFUNC_BASE;
7659 	if (ext_idx < 0 || ext_idx >= obj->nr_extern)
7660 		return;
7661 	ext = &obj->externs[ext_idx];
7662 
7663 	snprintf(patch, sizeof(patch),
7664 		 "%d: <invalid kfunc call>\n"
7665 		 "kfunc '%s' is referenced but wasn't resolved\n",
7666 		 insn_idx, ext->name);
7667 
7668 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7669 }
7670 
7671 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz)
7672 {
7673 	/* look for familiar error patterns in last N lines of the log */
7674 	const size_t max_last_line_cnt = 10;
7675 	char *prev_line, *cur_line, *next_line;
7676 	size_t log_sz;
7677 	int i;
7678 
7679 	if (!buf)
7680 		return;
7681 
7682 	log_sz = strlen(buf) + 1;
7683 	next_line = buf + log_sz - 1;
7684 
7685 	for (i = 0; i < max_last_line_cnt; i++, next_line = cur_line) {
7686 		cur_line = find_prev_line(buf, next_line);
7687 		if (!cur_line)
7688 			return;
7689 
7690 		if (str_has_pfx(cur_line, "invalid func unknown#195896080\n")) {
7691 			prev_line = find_prev_line(buf, cur_line);
7692 			if (!prev_line)
7693 				continue;
7694 
7695 			/* failed CO-RE relocation case */
7696 			fixup_log_failed_core_relo(prog, buf, buf_sz, log_sz,
7697 						   prev_line, cur_line, next_line);
7698 			return;
7699 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_LDIMM64_MAP_PFX)) {
7700 			prev_line = find_prev_line(buf, cur_line);
7701 			if (!prev_line)
7702 				continue;
7703 
7704 			/* reference to uncreated BPF map */
7705 			fixup_log_missing_map_load(prog, buf, buf_sz, log_sz,
7706 						   prev_line, cur_line, next_line);
7707 			return;
7708 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_CALL_KFUNC_PFX)) {
7709 			prev_line = find_prev_line(buf, cur_line);
7710 			if (!prev_line)
7711 				continue;
7712 
7713 			/* reference to unresolved kfunc */
7714 			fixup_log_missing_kfunc_call(prog, buf, buf_sz, log_sz,
7715 						     prev_line, cur_line, next_line);
7716 			return;
7717 		}
7718 	}
7719 }
7720 
7721 static int bpf_program_record_relos(struct bpf_program *prog)
7722 {
7723 	struct bpf_object *obj = prog->obj;
7724 	int i;
7725 
7726 	for (i = 0; i < prog->nr_reloc; i++) {
7727 		struct reloc_desc *relo = &prog->reloc_desc[i];
7728 		struct extern_desc *ext = &obj->externs[relo->ext_idx];
7729 		int kind;
7730 
7731 		switch (relo->type) {
7732 		case RELO_EXTERN_LD64:
7733 			if (ext->type != EXT_KSYM)
7734 				continue;
7735 			kind = btf_is_var(btf__type_by_id(obj->btf, ext->btf_id)) ?
7736 				BTF_KIND_VAR : BTF_KIND_FUNC;
7737 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7738 					       ext->is_weak, !ext->ksym.type_id,
7739 					       true, kind, relo->insn_idx);
7740 			break;
7741 		case RELO_EXTERN_CALL:
7742 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7743 					       ext->is_weak, false, false, BTF_KIND_FUNC,
7744 					       relo->insn_idx);
7745 			break;
7746 		case RELO_CORE: {
7747 			struct bpf_core_relo cr = {
7748 				.insn_off = relo->insn_idx * 8,
7749 				.type_id = relo->core_relo->type_id,
7750 				.access_str_off = relo->core_relo->access_str_off,
7751 				.kind = relo->core_relo->kind,
7752 			};
7753 
7754 			bpf_gen__record_relo_core(obj->gen_loader, &cr);
7755 			break;
7756 		}
7757 		default:
7758 			continue;
7759 		}
7760 	}
7761 	return 0;
7762 }
7763 
7764 static int
7765 bpf_object__load_progs(struct bpf_object *obj, int log_level)
7766 {
7767 	struct bpf_program *prog;
7768 	size_t i;
7769 	int err;
7770 
7771 	for (i = 0; i < obj->nr_programs; i++) {
7772 		prog = &obj->programs[i];
7773 		err = bpf_object__sanitize_prog(obj, prog);
7774 		if (err)
7775 			return err;
7776 	}
7777 
7778 	for (i = 0; i < obj->nr_programs; i++) {
7779 		prog = &obj->programs[i];
7780 		if (prog_is_subprog(obj, prog))
7781 			continue;
7782 		if (!prog->autoload) {
7783 			pr_debug("prog '%s': skipped loading\n", prog->name);
7784 			continue;
7785 		}
7786 		prog->log_level |= log_level;
7787 
7788 		if (obj->gen_loader)
7789 			bpf_program_record_relos(prog);
7790 
7791 		err = bpf_object_load_prog(obj, prog, prog->insns, prog->insns_cnt,
7792 					   obj->license, obj->kern_version, &prog->fd);
7793 		if (err) {
7794 			pr_warn("prog '%s': failed to load: %d\n", prog->name, err);
7795 			return err;
7796 		}
7797 	}
7798 
7799 	bpf_object__free_relocs(obj);
7800 	return 0;
7801 }
7802 
7803 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
7804 
7805 static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
7806 {
7807 	struct bpf_program *prog;
7808 	int err;
7809 
7810 	bpf_object__for_each_program(prog, obj) {
7811 		prog->sec_def = find_sec_def(prog->sec_name);
7812 		if (!prog->sec_def) {
7813 			/* couldn't guess, but user might manually specify */
7814 			pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
7815 				prog->name, prog->sec_name);
7816 			continue;
7817 		}
7818 
7819 		prog->type = prog->sec_def->prog_type;
7820 		prog->expected_attach_type = prog->sec_def->expected_attach_type;
7821 
7822 		/* sec_def can have custom callback which should be called
7823 		 * after bpf_program is initialized to adjust its properties
7824 		 */
7825 		if (prog->sec_def->prog_setup_fn) {
7826 			err = prog->sec_def->prog_setup_fn(prog, prog->sec_def->cookie);
7827 			if (err < 0) {
7828 				pr_warn("prog '%s': failed to initialize: %d\n",
7829 					prog->name, err);
7830 				return err;
7831 			}
7832 		}
7833 	}
7834 
7835 	return 0;
7836 }
7837 
7838 static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
7839 					  const struct bpf_object_open_opts *opts)
7840 {
7841 	const char *obj_name, *kconfig, *btf_tmp_path, *token_path;
7842 	struct bpf_object *obj;
7843 	char tmp_name[64];
7844 	int err;
7845 	char *log_buf;
7846 	size_t log_size;
7847 	__u32 log_level;
7848 
7849 	if (elf_version(EV_CURRENT) == EV_NONE) {
7850 		pr_warn("failed to init libelf for %s\n",
7851 			path ? : "(mem buf)");
7852 		return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
7853 	}
7854 
7855 	if (!OPTS_VALID(opts, bpf_object_open_opts))
7856 		return ERR_PTR(-EINVAL);
7857 
7858 	obj_name = OPTS_GET(opts, object_name, NULL);
7859 	if (obj_buf) {
7860 		if (!obj_name) {
7861 			snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
7862 				 (unsigned long)obj_buf,
7863 				 (unsigned long)obj_buf_sz);
7864 			obj_name = tmp_name;
7865 		}
7866 		path = obj_name;
7867 		pr_debug("loading object '%s' from buffer\n", obj_name);
7868 	}
7869 
7870 	log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
7871 	log_size = OPTS_GET(opts, kernel_log_size, 0);
7872 	log_level = OPTS_GET(opts, kernel_log_level, 0);
7873 	if (log_size > UINT_MAX)
7874 		return ERR_PTR(-EINVAL);
7875 	if (log_size && !log_buf)
7876 		return ERR_PTR(-EINVAL);
7877 
7878 	token_path = OPTS_GET(opts, bpf_token_path, NULL);
7879 	/* if user didn't specify bpf_token_path explicitly, check if
7880 	 * LIBBPF_BPF_TOKEN_PATH envvar was set and treat it as bpf_token_path
7881 	 * option
7882 	 */
7883 	if (!token_path)
7884 		token_path = getenv("LIBBPF_BPF_TOKEN_PATH");
7885 	if (token_path && strlen(token_path) >= PATH_MAX)
7886 		return ERR_PTR(-ENAMETOOLONG);
7887 
7888 	obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
7889 	if (IS_ERR(obj))
7890 		return obj;
7891 
7892 	obj->log_buf = log_buf;
7893 	obj->log_size = log_size;
7894 	obj->log_level = log_level;
7895 
7896 	if (token_path) {
7897 		obj->token_path = strdup(token_path);
7898 		if (!obj->token_path) {
7899 			err = -ENOMEM;
7900 			goto out;
7901 		}
7902 	}
7903 
7904 	btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
7905 	if (btf_tmp_path) {
7906 		if (strlen(btf_tmp_path) >= PATH_MAX) {
7907 			err = -ENAMETOOLONG;
7908 			goto out;
7909 		}
7910 		obj->btf_custom_path = strdup(btf_tmp_path);
7911 		if (!obj->btf_custom_path) {
7912 			err = -ENOMEM;
7913 			goto out;
7914 		}
7915 	}
7916 
7917 	kconfig = OPTS_GET(opts, kconfig, NULL);
7918 	if (kconfig) {
7919 		obj->kconfig = strdup(kconfig);
7920 		if (!obj->kconfig) {
7921 			err = -ENOMEM;
7922 			goto out;
7923 		}
7924 	}
7925 
7926 	err = bpf_object__elf_init(obj);
7927 	err = err ? : bpf_object__check_endianness(obj);
7928 	err = err ? : bpf_object__elf_collect(obj);
7929 	err = err ? : bpf_object__collect_externs(obj);
7930 	err = err ? : bpf_object_fixup_btf(obj);
7931 	err = err ? : bpf_object__init_maps(obj, opts);
7932 	err = err ? : bpf_object_init_progs(obj, opts);
7933 	err = err ? : bpf_object__collect_relos(obj);
7934 	if (err)
7935 		goto out;
7936 
7937 	bpf_object__elf_finish(obj);
7938 
7939 	return obj;
7940 out:
7941 	bpf_object__close(obj);
7942 	return ERR_PTR(err);
7943 }
7944 
7945 struct bpf_object *
7946 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
7947 {
7948 	if (!path)
7949 		return libbpf_err_ptr(-EINVAL);
7950 
7951 	pr_debug("loading %s\n", path);
7952 
7953 	return libbpf_ptr(bpf_object_open(path, NULL, 0, opts));
7954 }
7955 
7956 struct bpf_object *bpf_object__open(const char *path)
7957 {
7958 	return bpf_object__open_file(path, NULL);
7959 }
7960 
7961 struct bpf_object *
7962 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
7963 		     const struct bpf_object_open_opts *opts)
7964 {
7965 	if (!obj_buf || obj_buf_sz == 0)
7966 		return libbpf_err_ptr(-EINVAL);
7967 
7968 	return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, opts));
7969 }
7970 
7971 static int bpf_object_unload(struct bpf_object *obj)
7972 {
7973 	size_t i;
7974 
7975 	if (!obj)
7976 		return libbpf_err(-EINVAL);
7977 
7978 	for (i = 0; i < obj->nr_maps; i++) {
7979 		zclose(obj->maps[i].fd);
7980 		if (obj->maps[i].st_ops)
7981 			zfree(&obj->maps[i].st_ops->kern_vdata);
7982 	}
7983 
7984 	for (i = 0; i < obj->nr_programs; i++)
7985 		bpf_program__unload(&obj->programs[i]);
7986 
7987 	return 0;
7988 }
7989 
7990 static int bpf_object__sanitize_maps(struct bpf_object *obj)
7991 {
7992 	struct bpf_map *m;
7993 
7994 	bpf_object__for_each_map(m, obj) {
7995 		if (!bpf_map__is_internal(m))
7996 			continue;
7997 		if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
7998 			m->def.map_flags &= ~BPF_F_MMAPABLE;
7999 	}
8000 
8001 	return 0;
8002 }
8003 
8004 typedef int (*kallsyms_cb_t)(unsigned long long sym_addr, char sym_type,
8005 			     const char *sym_name, void *ctx);
8006 
8007 static int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
8008 {
8009 	char sym_type, sym_name[500];
8010 	unsigned long long sym_addr;
8011 	int ret, err = 0;
8012 	FILE *f;
8013 
8014 	f = fopen("/proc/kallsyms", "re");
8015 	if (!f) {
8016 		err = -errno;
8017 		pr_warn("failed to open /proc/kallsyms: %d\n", err);
8018 		return err;
8019 	}
8020 
8021 	while (true) {
8022 		ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
8023 			     &sym_addr, &sym_type, sym_name);
8024 		if (ret == EOF && feof(f))
8025 			break;
8026 		if (ret != 3) {
8027 			pr_warn("failed to read kallsyms entry: %d\n", ret);
8028 			err = -EINVAL;
8029 			break;
8030 		}
8031 
8032 		err = cb(sym_addr, sym_type, sym_name, ctx);
8033 		if (err)
8034 			break;
8035 	}
8036 
8037 	fclose(f);
8038 	return err;
8039 }
8040 
8041 static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
8042 		       const char *sym_name, void *ctx)
8043 {
8044 	struct bpf_object *obj = ctx;
8045 	const struct btf_type *t;
8046 	struct extern_desc *ext;
8047 	char *res;
8048 
8049 	res = strstr(sym_name, ".llvm.");
8050 	if (sym_type == 'd' && res)
8051 		ext = find_extern_by_name_with_len(obj, sym_name, res - sym_name);
8052 	else
8053 		ext = find_extern_by_name(obj, sym_name);
8054 	if (!ext || ext->type != EXT_KSYM)
8055 		return 0;
8056 
8057 	t = btf__type_by_id(obj->btf, ext->btf_id);
8058 	if (!btf_is_var(t))
8059 		return 0;
8060 
8061 	if (ext->is_set && ext->ksym.addr != sym_addr) {
8062 		pr_warn("extern (ksym) '%s': resolution is ambiguous: 0x%llx or 0x%llx\n",
8063 			sym_name, ext->ksym.addr, sym_addr);
8064 		return -EINVAL;
8065 	}
8066 	if (!ext->is_set) {
8067 		ext->is_set = true;
8068 		ext->ksym.addr = sym_addr;
8069 		pr_debug("extern (ksym) '%s': set to 0x%llx\n", sym_name, sym_addr);
8070 	}
8071 	return 0;
8072 }
8073 
8074 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
8075 {
8076 	return libbpf_kallsyms_parse(kallsyms_cb, obj);
8077 }
8078 
8079 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
8080 			    __u16 kind, struct btf **res_btf,
8081 			    struct module_btf **res_mod_btf)
8082 {
8083 	struct module_btf *mod_btf;
8084 	struct btf *btf;
8085 	int i, id, err;
8086 
8087 	btf = obj->btf_vmlinux;
8088 	mod_btf = NULL;
8089 	id = btf__find_by_name_kind(btf, ksym_name, kind);
8090 
8091 	if (id == -ENOENT) {
8092 		err = load_module_btfs(obj);
8093 		if (err)
8094 			return err;
8095 
8096 		for (i = 0; i < obj->btf_module_cnt; i++) {
8097 			/* we assume module_btf's BTF FD is always >0 */
8098 			mod_btf = &obj->btf_modules[i];
8099 			btf = mod_btf->btf;
8100 			id = btf__find_by_name_kind_own(btf, ksym_name, kind);
8101 			if (id != -ENOENT)
8102 				break;
8103 		}
8104 	}
8105 	if (id <= 0)
8106 		return -ESRCH;
8107 
8108 	*res_btf = btf;
8109 	*res_mod_btf = mod_btf;
8110 	return id;
8111 }
8112 
8113 static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
8114 					       struct extern_desc *ext)
8115 {
8116 	const struct btf_type *targ_var, *targ_type;
8117 	__u32 targ_type_id, local_type_id;
8118 	struct module_btf *mod_btf = NULL;
8119 	const char *targ_var_name;
8120 	struct btf *btf = NULL;
8121 	int id, err;
8122 
8123 	id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
8124 	if (id < 0) {
8125 		if (id == -ESRCH && ext->is_weak)
8126 			return 0;
8127 		pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
8128 			ext->name);
8129 		return id;
8130 	}
8131 
8132 	/* find local type_id */
8133 	local_type_id = ext->ksym.type_id;
8134 
8135 	/* find target type_id */
8136 	targ_var = btf__type_by_id(btf, id);
8137 	targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
8138 	targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
8139 
8140 	err = bpf_core_types_are_compat(obj->btf, local_type_id,
8141 					btf, targ_type_id);
8142 	if (err <= 0) {
8143 		const struct btf_type *local_type;
8144 		const char *targ_name, *local_name;
8145 
8146 		local_type = btf__type_by_id(obj->btf, local_type_id);
8147 		local_name = btf__name_by_offset(obj->btf, local_type->name_off);
8148 		targ_name = btf__name_by_offset(btf, targ_type->name_off);
8149 
8150 		pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
8151 			ext->name, local_type_id,
8152 			btf_kind_str(local_type), local_name, targ_type_id,
8153 			btf_kind_str(targ_type), targ_name);
8154 		return -EINVAL;
8155 	}
8156 
8157 	ext->is_set = true;
8158 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
8159 	ext->ksym.kernel_btf_id = id;
8160 	pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
8161 		 ext->name, id, btf_kind_str(targ_var), targ_var_name);
8162 
8163 	return 0;
8164 }
8165 
8166 static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
8167 						struct extern_desc *ext)
8168 {
8169 	int local_func_proto_id, kfunc_proto_id, kfunc_id;
8170 	struct module_btf *mod_btf = NULL;
8171 	const struct btf_type *kern_func;
8172 	struct btf *kern_btf = NULL;
8173 	int ret;
8174 
8175 	local_func_proto_id = ext->ksym.type_id;
8176 
8177 	kfunc_id = find_ksym_btf_id(obj, ext->essent_name ?: ext->name, BTF_KIND_FUNC, &kern_btf,
8178 				    &mod_btf);
8179 	if (kfunc_id < 0) {
8180 		if (kfunc_id == -ESRCH && ext->is_weak)
8181 			return 0;
8182 		pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
8183 			ext->name);
8184 		return kfunc_id;
8185 	}
8186 
8187 	kern_func = btf__type_by_id(kern_btf, kfunc_id);
8188 	kfunc_proto_id = kern_func->type;
8189 
8190 	ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
8191 					kern_btf, kfunc_proto_id);
8192 	if (ret <= 0) {
8193 		if (ext->is_weak)
8194 			return 0;
8195 
8196 		pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with %s [%d]\n",
8197 			ext->name, local_func_proto_id,
8198 			mod_btf ? mod_btf->name : "vmlinux", kfunc_proto_id);
8199 		return -EINVAL;
8200 	}
8201 
8202 	/* set index for module BTF fd in fd_array, if unset */
8203 	if (mod_btf && !mod_btf->fd_array_idx) {
8204 		/* insn->off is s16 */
8205 		if (obj->fd_array_cnt == INT16_MAX) {
8206 			pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
8207 				ext->name, mod_btf->fd_array_idx);
8208 			return -E2BIG;
8209 		}
8210 		/* Cannot use index 0 for module BTF fd */
8211 		if (!obj->fd_array_cnt)
8212 			obj->fd_array_cnt = 1;
8213 
8214 		ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
8215 					obj->fd_array_cnt + 1);
8216 		if (ret)
8217 			return ret;
8218 		mod_btf->fd_array_idx = obj->fd_array_cnt;
8219 		/* we assume module BTF FD is always >0 */
8220 		obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
8221 	}
8222 
8223 	ext->is_set = true;
8224 	ext->ksym.kernel_btf_id = kfunc_id;
8225 	ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
8226 	/* Also set kernel_btf_obj_fd to make sure that bpf_object__relocate_data()
8227 	 * populates FD into ld_imm64 insn when it's used to point to kfunc.
8228 	 * {kernel_btf_id, btf_fd_idx} -> fixup bpf_call.
8229 	 * {kernel_btf_id, kernel_btf_obj_fd} -> fixup ld_imm64.
8230 	 */
8231 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
8232 	pr_debug("extern (func ksym) '%s': resolved to %s [%d]\n",
8233 		 ext->name, mod_btf ? mod_btf->name : "vmlinux", kfunc_id);
8234 
8235 	return 0;
8236 }
8237 
8238 static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
8239 {
8240 	const struct btf_type *t;
8241 	struct extern_desc *ext;
8242 	int i, err;
8243 
8244 	for (i = 0; i < obj->nr_extern; i++) {
8245 		ext = &obj->externs[i];
8246 		if (ext->type != EXT_KSYM || !ext->ksym.type_id)
8247 			continue;
8248 
8249 		if (obj->gen_loader) {
8250 			ext->is_set = true;
8251 			ext->ksym.kernel_btf_obj_fd = 0;
8252 			ext->ksym.kernel_btf_id = 0;
8253 			continue;
8254 		}
8255 		t = btf__type_by_id(obj->btf, ext->btf_id);
8256 		if (btf_is_var(t))
8257 			err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
8258 		else
8259 			err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
8260 		if (err)
8261 			return err;
8262 	}
8263 	return 0;
8264 }
8265 
8266 static int bpf_object__resolve_externs(struct bpf_object *obj,
8267 				       const char *extra_kconfig)
8268 {
8269 	bool need_config = false, need_kallsyms = false;
8270 	bool need_vmlinux_btf = false;
8271 	struct extern_desc *ext;
8272 	void *kcfg_data = NULL;
8273 	int err, i;
8274 
8275 	if (obj->nr_extern == 0)
8276 		return 0;
8277 
8278 	if (obj->kconfig_map_idx >= 0)
8279 		kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
8280 
8281 	for (i = 0; i < obj->nr_extern; i++) {
8282 		ext = &obj->externs[i];
8283 
8284 		if (ext->type == EXT_KSYM) {
8285 			if (ext->ksym.type_id)
8286 				need_vmlinux_btf = true;
8287 			else
8288 				need_kallsyms = true;
8289 			continue;
8290 		} else if (ext->type == EXT_KCFG) {
8291 			void *ext_ptr = kcfg_data + ext->kcfg.data_off;
8292 			__u64 value = 0;
8293 
8294 			/* Kconfig externs need actual /proc/config.gz */
8295 			if (str_has_pfx(ext->name, "CONFIG_")) {
8296 				need_config = true;
8297 				continue;
8298 			}
8299 
8300 			/* Virtual kcfg externs are customly handled by libbpf */
8301 			if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
8302 				value = get_kernel_version();
8303 				if (!value) {
8304 					pr_warn("extern (kcfg) '%s': failed to get kernel version\n", ext->name);
8305 					return -EINVAL;
8306 				}
8307 			} else if (strcmp(ext->name, "LINUX_HAS_BPF_COOKIE") == 0) {
8308 				value = kernel_supports(obj, FEAT_BPF_COOKIE);
8309 			} else if (strcmp(ext->name, "LINUX_HAS_SYSCALL_WRAPPER") == 0) {
8310 				value = kernel_supports(obj, FEAT_SYSCALL_WRAPPER);
8311 			} else if (!str_has_pfx(ext->name, "LINUX_") || !ext->is_weak) {
8312 				/* Currently libbpf supports only CONFIG_ and LINUX_ prefixed
8313 				 * __kconfig externs, where LINUX_ ones are virtual and filled out
8314 				 * customly by libbpf (their values don't come from Kconfig).
8315 				 * If LINUX_xxx variable is not recognized by libbpf, but is marked
8316 				 * __weak, it defaults to zero value, just like for CONFIG_xxx
8317 				 * externs.
8318 				 */
8319 				pr_warn("extern (kcfg) '%s': unrecognized virtual extern\n", ext->name);
8320 				return -EINVAL;
8321 			}
8322 
8323 			err = set_kcfg_value_num(ext, ext_ptr, value);
8324 			if (err)
8325 				return err;
8326 			pr_debug("extern (kcfg) '%s': set to 0x%llx\n",
8327 				 ext->name, (long long)value);
8328 		} else {
8329 			pr_warn("extern '%s': unrecognized extern kind\n", ext->name);
8330 			return -EINVAL;
8331 		}
8332 	}
8333 	if (need_config && extra_kconfig) {
8334 		err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
8335 		if (err)
8336 			return -EINVAL;
8337 		need_config = false;
8338 		for (i = 0; i < obj->nr_extern; i++) {
8339 			ext = &obj->externs[i];
8340 			if (ext->type == EXT_KCFG && !ext->is_set) {
8341 				need_config = true;
8342 				break;
8343 			}
8344 		}
8345 	}
8346 	if (need_config) {
8347 		err = bpf_object__read_kconfig_file(obj, kcfg_data);
8348 		if (err)
8349 			return -EINVAL;
8350 	}
8351 	if (need_kallsyms) {
8352 		err = bpf_object__read_kallsyms_file(obj);
8353 		if (err)
8354 			return -EINVAL;
8355 	}
8356 	if (need_vmlinux_btf) {
8357 		err = bpf_object__resolve_ksyms_btf_id(obj);
8358 		if (err)
8359 			return -EINVAL;
8360 	}
8361 	for (i = 0; i < obj->nr_extern; i++) {
8362 		ext = &obj->externs[i];
8363 
8364 		if (!ext->is_set && !ext->is_weak) {
8365 			pr_warn("extern '%s' (strong): not resolved\n", ext->name);
8366 			return -ESRCH;
8367 		} else if (!ext->is_set) {
8368 			pr_debug("extern '%s' (weak): not resolved, defaulting to zero\n",
8369 				 ext->name);
8370 		}
8371 	}
8372 
8373 	return 0;
8374 }
8375 
8376 static void bpf_map_prepare_vdata(const struct bpf_map *map)
8377 {
8378 	struct bpf_struct_ops *st_ops;
8379 	__u32 i;
8380 
8381 	st_ops = map->st_ops;
8382 	for (i = 0; i < btf_vlen(st_ops->type); i++) {
8383 		struct bpf_program *prog = st_ops->progs[i];
8384 		void *kern_data;
8385 		int prog_fd;
8386 
8387 		if (!prog)
8388 			continue;
8389 
8390 		prog_fd = bpf_program__fd(prog);
8391 		kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
8392 		*(unsigned long *)kern_data = prog_fd;
8393 	}
8394 }
8395 
8396 static int bpf_object_prepare_struct_ops(struct bpf_object *obj)
8397 {
8398 	struct bpf_map *map;
8399 	int i;
8400 
8401 	for (i = 0; i < obj->nr_maps; i++) {
8402 		map = &obj->maps[i];
8403 
8404 		if (!bpf_map__is_struct_ops(map))
8405 			continue;
8406 
8407 		if (!map->autocreate)
8408 			continue;
8409 
8410 		bpf_map_prepare_vdata(map);
8411 	}
8412 
8413 	return 0;
8414 }
8415 
8416 static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
8417 {
8418 	int err, i;
8419 
8420 	if (!obj)
8421 		return libbpf_err(-EINVAL);
8422 
8423 	if (obj->loaded) {
8424 		pr_warn("object '%s': load can't be attempted twice\n", obj->name);
8425 		return libbpf_err(-EINVAL);
8426 	}
8427 
8428 	if (obj->gen_loader)
8429 		bpf_gen__init(obj->gen_loader, extra_log_level, obj->nr_programs, obj->nr_maps);
8430 
8431 	err = bpf_object_prepare_token(obj);
8432 	err = err ? : bpf_object__probe_loading(obj);
8433 	err = err ? : bpf_object__load_vmlinux_btf(obj, false);
8434 	err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
8435 	err = err ? : bpf_object__sanitize_maps(obj);
8436 	err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
8437 	err = err ? : bpf_object_adjust_struct_ops_autoload(obj);
8438 	err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
8439 	err = err ? : bpf_object__sanitize_and_load_btf(obj);
8440 	err = err ? : bpf_object__create_maps(obj);
8441 	err = err ? : bpf_object__load_progs(obj, extra_log_level);
8442 	err = err ? : bpf_object_init_prog_arrays(obj);
8443 	err = err ? : bpf_object_prepare_struct_ops(obj);
8444 
8445 	if (obj->gen_loader) {
8446 		/* reset FDs */
8447 		if (obj->btf)
8448 			btf__set_fd(obj->btf, -1);
8449 		if (!err)
8450 			err = bpf_gen__finish(obj->gen_loader, obj->nr_programs, obj->nr_maps);
8451 	}
8452 
8453 	/* clean up fd_array */
8454 	zfree(&obj->fd_array);
8455 
8456 	/* clean up module BTFs */
8457 	for (i = 0; i < obj->btf_module_cnt; i++) {
8458 		close(obj->btf_modules[i].fd);
8459 		btf__free(obj->btf_modules[i].btf);
8460 		free(obj->btf_modules[i].name);
8461 	}
8462 	free(obj->btf_modules);
8463 
8464 	/* clean up vmlinux BTF */
8465 	btf__free(obj->btf_vmlinux);
8466 	obj->btf_vmlinux = NULL;
8467 
8468 	obj->loaded = true; /* doesn't matter if successfully or not */
8469 
8470 	if (err)
8471 		goto out;
8472 
8473 	return 0;
8474 out:
8475 	/* unpin any maps that were auto-pinned during load */
8476 	for (i = 0; i < obj->nr_maps; i++)
8477 		if (obj->maps[i].pinned && !obj->maps[i].reused)
8478 			bpf_map__unpin(&obj->maps[i], NULL);
8479 
8480 	bpf_object_unload(obj);
8481 	pr_warn("failed to load object '%s'\n", obj->path);
8482 	return libbpf_err(err);
8483 }
8484 
8485 int bpf_object__load(struct bpf_object *obj)
8486 {
8487 	return bpf_object_load(obj, 0, NULL);
8488 }
8489 
8490 static int make_parent_dir(const char *path)
8491 {
8492 	char *cp, errmsg[STRERR_BUFSIZE];
8493 	char *dname, *dir;
8494 	int err = 0;
8495 
8496 	dname = strdup(path);
8497 	if (dname == NULL)
8498 		return -ENOMEM;
8499 
8500 	dir = dirname(dname);
8501 	if (mkdir(dir, 0700) && errno != EEXIST)
8502 		err = -errno;
8503 
8504 	free(dname);
8505 	if (err) {
8506 		cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
8507 		pr_warn("failed to mkdir %s: %s\n", path, cp);
8508 	}
8509 	return err;
8510 }
8511 
8512 static int check_path(const char *path)
8513 {
8514 	char *cp, errmsg[STRERR_BUFSIZE];
8515 	struct statfs st_fs;
8516 	char *dname, *dir;
8517 	int err = 0;
8518 
8519 	if (path == NULL)
8520 		return -EINVAL;
8521 
8522 	dname = strdup(path);
8523 	if (dname == NULL)
8524 		return -ENOMEM;
8525 
8526 	dir = dirname(dname);
8527 	if (statfs(dir, &st_fs)) {
8528 		cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
8529 		pr_warn("failed to statfs %s: %s\n", dir, cp);
8530 		err = -errno;
8531 	}
8532 	free(dname);
8533 
8534 	if (!err && st_fs.f_type != BPF_FS_MAGIC) {
8535 		pr_warn("specified path %s is not on BPF FS\n", path);
8536 		err = -EINVAL;
8537 	}
8538 
8539 	return err;
8540 }
8541 
8542 int bpf_program__pin(struct bpf_program *prog, const char *path)
8543 {
8544 	char *cp, errmsg[STRERR_BUFSIZE];
8545 	int err;
8546 
8547 	if (prog->fd < 0) {
8548 		pr_warn("prog '%s': can't pin program that wasn't loaded\n", prog->name);
8549 		return libbpf_err(-EINVAL);
8550 	}
8551 
8552 	err = make_parent_dir(path);
8553 	if (err)
8554 		return libbpf_err(err);
8555 
8556 	err = check_path(path);
8557 	if (err)
8558 		return libbpf_err(err);
8559 
8560 	if (bpf_obj_pin(prog->fd, path)) {
8561 		err = -errno;
8562 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
8563 		pr_warn("prog '%s': failed to pin at '%s': %s\n", prog->name, path, cp);
8564 		return libbpf_err(err);
8565 	}
8566 
8567 	pr_debug("prog '%s': pinned at '%s'\n", prog->name, path);
8568 	return 0;
8569 }
8570 
8571 int bpf_program__unpin(struct bpf_program *prog, const char *path)
8572 {
8573 	int err;
8574 
8575 	if (prog->fd < 0) {
8576 		pr_warn("prog '%s': can't unpin program that wasn't loaded\n", prog->name);
8577 		return libbpf_err(-EINVAL);
8578 	}
8579 
8580 	err = check_path(path);
8581 	if (err)
8582 		return libbpf_err(err);
8583 
8584 	err = unlink(path);
8585 	if (err)
8586 		return libbpf_err(-errno);
8587 
8588 	pr_debug("prog '%s': unpinned from '%s'\n", prog->name, path);
8589 	return 0;
8590 }
8591 
8592 int bpf_map__pin(struct bpf_map *map, const char *path)
8593 {
8594 	char *cp, errmsg[STRERR_BUFSIZE];
8595 	int err;
8596 
8597 	if (map == NULL) {
8598 		pr_warn("invalid map pointer\n");
8599 		return libbpf_err(-EINVAL);
8600 	}
8601 
8602 	if (map->fd < 0) {
8603 		pr_warn("map '%s': can't pin BPF map without FD (was it created?)\n", map->name);
8604 		return libbpf_err(-EINVAL);
8605 	}
8606 
8607 	if (map->pin_path) {
8608 		if (path && strcmp(path, map->pin_path)) {
8609 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8610 				bpf_map__name(map), map->pin_path, path);
8611 			return libbpf_err(-EINVAL);
8612 		} else if (map->pinned) {
8613 			pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
8614 				 bpf_map__name(map), map->pin_path);
8615 			return 0;
8616 		}
8617 	} else {
8618 		if (!path) {
8619 			pr_warn("missing a path to pin map '%s' at\n",
8620 				bpf_map__name(map));
8621 			return libbpf_err(-EINVAL);
8622 		} else if (map->pinned) {
8623 			pr_warn("map '%s' already pinned\n", bpf_map__name(map));
8624 			return libbpf_err(-EEXIST);
8625 		}
8626 
8627 		map->pin_path = strdup(path);
8628 		if (!map->pin_path) {
8629 			err = -errno;
8630 			goto out_err;
8631 		}
8632 	}
8633 
8634 	err = make_parent_dir(map->pin_path);
8635 	if (err)
8636 		return libbpf_err(err);
8637 
8638 	err = check_path(map->pin_path);
8639 	if (err)
8640 		return libbpf_err(err);
8641 
8642 	if (bpf_obj_pin(map->fd, map->pin_path)) {
8643 		err = -errno;
8644 		goto out_err;
8645 	}
8646 
8647 	map->pinned = true;
8648 	pr_debug("pinned map '%s'\n", map->pin_path);
8649 
8650 	return 0;
8651 
8652 out_err:
8653 	cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
8654 	pr_warn("failed to pin map: %s\n", cp);
8655 	return libbpf_err(err);
8656 }
8657 
8658 int bpf_map__unpin(struct bpf_map *map, const char *path)
8659 {
8660 	int err;
8661 
8662 	if (map == NULL) {
8663 		pr_warn("invalid map pointer\n");
8664 		return libbpf_err(-EINVAL);
8665 	}
8666 
8667 	if (map->pin_path) {
8668 		if (path && strcmp(path, map->pin_path)) {
8669 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8670 				bpf_map__name(map), map->pin_path, path);
8671 			return libbpf_err(-EINVAL);
8672 		}
8673 		path = map->pin_path;
8674 	} else if (!path) {
8675 		pr_warn("no path to unpin map '%s' from\n",
8676 			bpf_map__name(map));
8677 		return libbpf_err(-EINVAL);
8678 	}
8679 
8680 	err = check_path(path);
8681 	if (err)
8682 		return libbpf_err(err);
8683 
8684 	err = unlink(path);
8685 	if (err != 0)
8686 		return libbpf_err(-errno);
8687 
8688 	map->pinned = false;
8689 	pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
8690 
8691 	return 0;
8692 }
8693 
8694 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
8695 {
8696 	char *new = NULL;
8697 
8698 	if (path) {
8699 		new = strdup(path);
8700 		if (!new)
8701 			return libbpf_err(-errno);
8702 	}
8703 
8704 	free(map->pin_path);
8705 	map->pin_path = new;
8706 	return 0;
8707 }
8708 
8709 __alias(bpf_map__pin_path)
8710 const char *bpf_map__get_pin_path(const struct bpf_map *map);
8711 
8712 const char *bpf_map__pin_path(const struct bpf_map *map)
8713 {
8714 	return map->pin_path;
8715 }
8716 
8717 bool bpf_map__is_pinned(const struct bpf_map *map)
8718 {
8719 	return map->pinned;
8720 }
8721 
8722 static void sanitize_pin_path(char *s)
8723 {
8724 	/* bpffs disallows periods in path names */
8725 	while (*s) {
8726 		if (*s == '.')
8727 			*s = '_';
8728 		s++;
8729 	}
8730 }
8731 
8732 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
8733 {
8734 	struct bpf_map *map;
8735 	int err;
8736 
8737 	if (!obj)
8738 		return libbpf_err(-ENOENT);
8739 
8740 	if (!obj->loaded) {
8741 		pr_warn("object not yet loaded; load it first\n");
8742 		return libbpf_err(-ENOENT);
8743 	}
8744 
8745 	bpf_object__for_each_map(map, obj) {
8746 		char *pin_path = NULL;
8747 		char buf[PATH_MAX];
8748 
8749 		if (!map->autocreate)
8750 			continue;
8751 
8752 		if (path) {
8753 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8754 			if (err)
8755 				goto err_unpin_maps;
8756 			sanitize_pin_path(buf);
8757 			pin_path = buf;
8758 		} else if (!map->pin_path) {
8759 			continue;
8760 		}
8761 
8762 		err = bpf_map__pin(map, pin_path);
8763 		if (err)
8764 			goto err_unpin_maps;
8765 	}
8766 
8767 	return 0;
8768 
8769 err_unpin_maps:
8770 	while ((map = bpf_object__prev_map(obj, map))) {
8771 		if (!map->pin_path)
8772 			continue;
8773 
8774 		bpf_map__unpin(map, NULL);
8775 	}
8776 
8777 	return libbpf_err(err);
8778 }
8779 
8780 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
8781 {
8782 	struct bpf_map *map;
8783 	int err;
8784 
8785 	if (!obj)
8786 		return libbpf_err(-ENOENT);
8787 
8788 	bpf_object__for_each_map(map, obj) {
8789 		char *pin_path = NULL;
8790 		char buf[PATH_MAX];
8791 
8792 		if (path) {
8793 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8794 			if (err)
8795 				return libbpf_err(err);
8796 			sanitize_pin_path(buf);
8797 			pin_path = buf;
8798 		} else if (!map->pin_path) {
8799 			continue;
8800 		}
8801 
8802 		err = bpf_map__unpin(map, pin_path);
8803 		if (err)
8804 			return libbpf_err(err);
8805 	}
8806 
8807 	return 0;
8808 }
8809 
8810 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
8811 {
8812 	struct bpf_program *prog;
8813 	char buf[PATH_MAX];
8814 	int err;
8815 
8816 	if (!obj)
8817 		return libbpf_err(-ENOENT);
8818 
8819 	if (!obj->loaded) {
8820 		pr_warn("object not yet loaded; load it first\n");
8821 		return libbpf_err(-ENOENT);
8822 	}
8823 
8824 	bpf_object__for_each_program(prog, obj) {
8825 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
8826 		if (err)
8827 			goto err_unpin_programs;
8828 
8829 		err = bpf_program__pin(prog, buf);
8830 		if (err)
8831 			goto err_unpin_programs;
8832 	}
8833 
8834 	return 0;
8835 
8836 err_unpin_programs:
8837 	while ((prog = bpf_object__prev_program(obj, prog))) {
8838 		if (pathname_concat(buf, sizeof(buf), path, prog->name))
8839 			continue;
8840 
8841 		bpf_program__unpin(prog, buf);
8842 	}
8843 
8844 	return libbpf_err(err);
8845 }
8846 
8847 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
8848 {
8849 	struct bpf_program *prog;
8850 	int err;
8851 
8852 	if (!obj)
8853 		return libbpf_err(-ENOENT);
8854 
8855 	bpf_object__for_each_program(prog, obj) {
8856 		char buf[PATH_MAX];
8857 
8858 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
8859 		if (err)
8860 			return libbpf_err(err);
8861 
8862 		err = bpf_program__unpin(prog, buf);
8863 		if (err)
8864 			return libbpf_err(err);
8865 	}
8866 
8867 	return 0;
8868 }
8869 
8870 int bpf_object__pin(struct bpf_object *obj, const char *path)
8871 {
8872 	int err;
8873 
8874 	err = bpf_object__pin_maps(obj, path);
8875 	if (err)
8876 		return libbpf_err(err);
8877 
8878 	err = bpf_object__pin_programs(obj, path);
8879 	if (err) {
8880 		bpf_object__unpin_maps(obj, path);
8881 		return libbpf_err(err);
8882 	}
8883 
8884 	return 0;
8885 }
8886 
8887 int bpf_object__unpin(struct bpf_object *obj, const char *path)
8888 {
8889 	int err;
8890 
8891 	err = bpf_object__unpin_programs(obj, path);
8892 	if (err)
8893 		return libbpf_err(err);
8894 
8895 	err = bpf_object__unpin_maps(obj, path);
8896 	if (err)
8897 		return libbpf_err(err);
8898 
8899 	return 0;
8900 }
8901 
8902 static void bpf_map__destroy(struct bpf_map *map)
8903 {
8904 	if (map->inner_map) {
8905 		bpf_map__destroy(map->inner_map);
8906 		zfree(&map->inner_map);
8907 	}
8908 
8909 	zfree(&map->init_slots);
8910 	map->init_slots_sz = 0;
8911 
8912 	if (map->mmaped && map->mmaped != map->obj->arena_data)
8913 		munmap(map->mmaped, bpf_map_mmap_sz(map));
8914 	map->mmaped = NULL;
8915 
8916 	if (map->st_ops) {
8917 		zfree(&map->st_ops->data);
8918 		zfree(&map->st_ops->progs);
8919 		zfree(&map->st_ops->kern_func_off);
8920 		zfree(&map->st_ops);
8921 	}
8922 
8923 	zfree(&map->name);
8924 	zfree(&map->real_name);
8925 	zfree(&map->pin_path);
8926 
8927 	if (map->fd >= 0)
8928 		zclose(map->fd);
8929 }
8930 
8931 void bpf_object__close(struct bpf_object *obj)
8932 {
8933 	size_t i;
8934 
8935 	if (IS_ERR_OR_NULL(obj))
8936 		return;
8937 
8938 	usdt_manager_free(obj->usdt_man);
8939 	obj->usdt_man = NULL;
8940 
8941 	bpf_gen__free(obj->gen_loader);
8942 	bpf_object__elf_finish(obj);
8943 	bpf_object_unload(obj);
8944 	btf__free(obj->btf);
8945 	btf__free(obj->btf_vmlinux);
8946 	btf_ext__free(obj->btf_ext);
8947 
8948 	for (i = 0; i < obj->nr_maps; i++)
8949 		bpf_map__destroy(&obj->maps[i]);
8950 
8951 	zfree(&obj->btf_custom_path);
8952 	zfree(&obj->kconfig);
8953 
8954 	for (i = 0; i < obj->nr_extern; i++)
8955 		zfree(&obj->externs[i].essent_name);
8956 
8957 	zfree(&obj->externs);
8958 	obj->nr_extern = 0;
8959 
8960 	zfree(&obj->maps);
8961 	obj->nr_maps = 0;
8962 
8963 	if (obj->programs && obj->nr_programs) {
8964 		for (i = 0; i < obj->nr_programs; i++)
8965 			bpf_program__exit(&obj->programs[i]);
8966 	}
8967 	zfree(&obj->programs);
8968 
8969 	zfree(&obj->feat_cache);
8970 	zfree(&obj->token_path);
8971 	if (obj->token_fd > 0)
8972 		close(obj->token_fd);
8973 
8974 	zfree(&obj->arena_data);
8975 
8976 	free(obj);
8977 }
8978 
8979 const char *bpf_object__name(const struct bpf_object *obj)
8980 {
8981 	return obj ? obj->name : libbpf_err_ptr(-EINVAL);
8982 }
8983 
8984 unsigned int bpf_object__kversion(const struct bpf_object *obj)
8985 {
8986 	return obj ? obj->kern_version : 0;
8987 }
8988 
8989 struct btf *bpf_object__btf(const struct bpf_object *obj)
8990 {
8991 	return obj ? obj->btf : NULL;
8992 }
8993 
8994 int bpf_object__btf_fd(const struct bpf_object *obj)
8995 {
8996 	return obj->btf ? btf__fd(obj->btf) : -1;
8997 }
8998 
8999 int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
9000 {
9001 	if (obj->loaded)
9002 		return libbpf_err(-EINVAL);
9003 
9004 	obj->kern_version = kern_version;
9005 
9006 	return 0;
9007 }
9008 
9009 int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
9010 {
9011 	struct bpf_gen *gen;
9012 
9013 	if (!opts)
9014 		return -EFAULT;
9015 	if (!OPTS_VALID(opts, gen_loader_opts))
9016 		return -EINVAL;
9017 	gen = calloc(sizeof(*gen), 1);
9018 	if (!gen)
9019 		return -ENOMEM;
9020 	gen->opts = opts;
9021 	obj->gen_loader = gen;
9022 	return 0;
9023 }
9024 
9025 static struct bpf_program *
9026 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
9027 		    bool forward)
9028 {
9029 	size_t nr_programs = obj->nr_programs;
9030 	ssize_t idx;
9031 
9032 	if (!nr_programs)
9033 		return NULL;
9034 
9035 	if (!p)
9036 		/* Iter from the beginning */
9037 		return forward ? &obj->programs[0] :
9038 			&obj->programs[nr_programs - 1];
9039 
9040 	if (p->obj != obj) {
9041 		pr_warn("error: program handler doesn't match object\n");
9042 		return errno = EINVAL, NULL;
9043 	}
9044 
9045 	idx = (p - obj->programs) + (forward ? 1 : -1);
9046 	if (idx >= obj->nr_programs || idx < 0)
9047 		return NULL;
9048 	return &obj->programs[idx];
9049 }
9050 
9051 struct bpf_program *
9052 bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
9053 {
9054 	struct bpf_program *prog = prev;
9055 
9056 	do {
9057 		prog = __bpf_program__iter(prog, obj, true);
9058 	} while (prog && prog_is_subprog(obj, prog));
9059 
9060 	return prog;
9061 }
9062 
9063 struct bpf_program *
9064 bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
9065 {
9066 	struct bpf_program *prog = next;
9067 
9068 	do {
9069 		prog = __bpf_program__iter(prog, obj, false);
9070 	} while (prog && prog_is_subprog(obj, prog));
9071 
9072 	return prog;
9073 }
9074 
9075 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
9076 {
9077 	prog->prog_ifindex = ifindex;
9078 }
9079 
9080 const char *bpf_program__name(const struct bpf_program *prog)
9081 {
9082 	return prog->name;
9083 }
9084 
9085 const char *bpf_program__section_name(const struct bpf_program *prog)
9086 {
9087 	return prog->sec_name;
9088 }
9089 
9090 bool bpf_program__autoload(const struct bpf_program *prog)
9091 {
9092 	return prog->autoload;
9093 }
9094 
9095 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
9096 {
9097 	if (prog->obj->loaded)
9098 		return libbpf_err(-EINVAL);
9099 
9100 	prog->autoload = autoload;
9101 	return 0;
9102 }
9103 
9104 bool bpf_program__autoattach(const struct bpf_program *prog)
9105 {
9106 	return prog->autoattach;
9107 }
9108 
9109 void bpf_program__set_autoattach(struct bpf_program *prog, bool autoattach)
9110 {
9111 	prog->autoattach = autoattach;
9112 }
9113 
9114 const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
9115 {
9116 	return prog->insns;
9117 }
9118 
9119 size_t bpf_program__insn_cnt(const struct bpf_program *prog)
9120 {
9121 	return prog->insns_cnt;
9122 }
9123 
9124 int bpf_program__set_insns(struct bpf_program *prog,
9125 			   struct bpf_insn *new_insns, size_t new_insn_cnt)
9126 {
9127 	struct bpf_insn *insns;
9128 
9129 	if (prog->obj->loaded)
9130 		return -EBUSY;
9131 
9132 	insns = libbpf_reallocarray(prog->insns, new_insn_cnt, sizeof(*insns));
9133 	/* NULL is a valid return from reallocarray if the new count is zero */
9134 	if (!insns && new_insn_cnt) {
9135 		pr_warn("prog '%s': failed to realloc prog code\n", prog->name);
9136 		return -ENOMEM;
9137 	}
9138 	memcpy(insns, new_insns, new_insn_cnt * sizeof(*insns));
9139 
9140 	prog->insns = insns;
9141 	prog->insns_cnt = new_insn_cnt;
9142 	return 0;
9143 }
9144 
9145 int bpf_program__fd(const struct bpf_program *prog)
9146 {
9147 	if (!prog)
9148 		return libbpf_err(-EINVAL);
9149 
9150 	if (prog->fd < 0)
9151 		return libbpf_err(-ENOENT);
9152 
9153 	return prog->fd;
9154 }
9155 
9156 __alias(bpf_program__type)
9157 enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog);
9158 
9159 enum bpf_prog_type bpf_program__type(const struct bpf_program *prog)
9160 {
9161 	return prog->type;
9162 }
9163 
9164 static size_t custom_sec_def_cnt;
9165 static struct bpf_sec_def *custom_sec_defs;
9166 static struct bpf_sec_def custom_fallback_def;
9167 static bool has_custom_fallback_def;
9168 static int last_custom_sec_def_handler_id;
9169 
9170 int bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
9171 {
9172 	if (prog->obj->loaded)
9173 		return libbpf_err(-EBUSY);
9174 
9175 	/* if type is not changed, do nothing */
9176 	if (prog->type == type)
9177 		return 0;
9178 
9179 	prog->type = type;
9180 
9181 	/* If a program type was changed, we need to reset associated SEC()
9182 	 * handler, as it will be invalid now. The only exception is a generic
9183 	 * fallback handler, which by definition is program type-agnostic and
9184 	 * is a catch-all custom handler, optionally set by the application,
9185 	 * so should be able to handle any type of BPF program.
9186 	 */
9187 	if (prog->sec_def != &custom_fallback_def)
9188 		prog->sec_def = NULL;
9189 	return 0;
9190 }
9191 
9192 __alias(bpf_program__expected_attach_type)
9193 enum bpf_attach_type bpf_program__get_expected_attach_type(const struct bpf_program *prog);
9194 
9195 enum bpf_attach_type bpf_program__expected_attach_type(const struct bpf_program *prog)
9196 {
9197 	return prog->expected_attach_type;
9198 }
9199 
9200 int bpf_program__set_expected_attach_type(struct bpf_program *prog,
9201 					   enum bpf_attach_type type)
9202 {
9203 	if (prog->obj->loaded)
9204 		return libbpf_err(-EBUSY);
9205 
9206 	prog->expected_attach_type = type;
9207 	return 0;
9208 }
9209 
9210 __u32 bpf_program__flags(const struct bpf_program *prog)
9211 {
9212 	return prog->prog_flags;
9213 }
9214 
9215 int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
9216 {
9217 	if (prog->obj->loaded)
9218 		return libbpf_err(-EBUSY);
9219 
9220 	prog->prog_flags = flags;
9221 	return 0;
9222 }
9223 
9224 __u32 bpf_program__log_level(const struct bpf_program *prog)
9225 {
9226 	return prog->log_level;
9227 }
9228 
9229 int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
9230 {
9231 	if (prog->obj->loaded)
9232 		return libbpf_err(-EBUSY);
9233 
9234 	prog->log_level = log_level;
9235 	return 0;
9236 }
9237 
9238 const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
9239 {
9240 	*log_size = prog->log_size;
9241 	return prog->log_buf;
9242 }
9243 
9244 int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
9245 {
9246 	if (log_size && !log_buf)
9247 		return -EINVAL;
9248 	if (prog->log_size > UINT_MAX)
9249 		return -EINVAL;
9250 	if (prog->obj->loaded)
9251 		return -EBUSY;
9252 
9253 	prog->log_buf = log_buf;
9254 	prog->log_size = log_size;
9255 	return 0;
9256 }
9257 
9258 #define SEC_DEF(sec_pfx, ptype, atype, flags, ...) {			    \
9259 	.sec = (char *)sec_pfx,						    \
9260 	.prog_type = BPF_PROG_TYPE_##ptype,				    \
9261 	.expected_attach_type = atype,					    \
9262 	.cookie = (long)(flags),					    \
9263 	.prog_prepare_load_fn = libbpf_prepare_prog_load,		    \
9264 	__VA_ARGS__							    \
9265 }
9266 
9267 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9268 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9269 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9270 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9271 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9272 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9273 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9274 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9275 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9276 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9277 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9278 
9279 static const struct bpf_sec_def section_defs[] = {
9280 	SEC_DEF("socket",		SOCKET_FILTER, 0, SEC_NONE),
9281 	SEC_DEF("sk_reuseport/migrate",	SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE),
9282 	SEC_DEF("sk_reuseport",		SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE),
9283 	SEC_DEF("kprobe+",		KPROBE,	0, SEC_NONE, attach_kprobe),
9284 	SEC_DEF("uprobe+",		KPROBE,	0, SEC_NONE, attach_uprobe),
9285 	SEC_DEF("uprobe.s+",		KPROBE,	0, SEC_SLEEPABLE, attach_uprobe),
9286 	SEC_DEF("kretprobe+",		KPROBE, 0, SEC_NONE, attach_kprobe),
9287 	SEC_DEF("uretprobe+",		KPROBE, 0, SEC_NONE, attach_uprobe),
9288 	SEC_DEF("uretprobe.s+",		KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
9289 	SEC_DEF("kprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
9290 	SEC_DEF("kretprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
9291 	SEC_DEF("uprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
9292 	SEC_DEF("uretprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
9293 	SEC_DEF("uprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
9294 	SEC_DEF("uretprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
9295 	SEC_DEF("ksyscall+",		KPROBE,	0, SEC_NONE, attach_ksyscall),
9296 	SEC_DEF("kretsyscall+",		KPROBE, 0, SEC_NONE, attach_ksyscall),
9297 	SEC_DEF("usdt+",		KPROBE,	0, SEC_USDT, attach_usdt),
9298 	SEC_DEF("usdt.s+",		KPROBE,	0, SEC_USDT | SEC_SLEEPABLE, attach_usdt),
9299 	SEC_DEF("tc/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE), /* alias for tcx */
9300 	SEC_DEF("tc/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),  /* alias for tcx */
9301 	SEC_DEF("tcx/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE),
9302 	SEC_DEF("tcx/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),
9303 	SEC_DEF("tc",			SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
9304 	SEC_DEF("classifier",		SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
9305 	SEC_DEF("action",		SCHED_ACT, 0, SEC_NONE), /* deprecated / legacy, use tcx */
9306 	SEC_DEF("netkit/primary",	SCHED_CLS, BPF_NETKIT_PRIMARY, SEC_NONE),
9307 	SEC_DEF("netkit/peer",		SCHED_CLS, BPF_NETKIT_PEER, SEC_NONE),
9308 	SEC_DEF("tracepoint+",		TRACEPOINT, 0, SEC_NONE, attach_tp),
9309 	SEC_DEF("tp+",			TRACEPOINT, 0, SEC_NONE, attach_tp),
9310 	SEC_DEF("raw_tracepoint+",	RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
9311 	SEC_DEF("raw_tp+",		RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
9312 	SEC_DEF("raw_tracepoint.w+",	RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
9313 	SEC_DEF("raw_tp.w+",		RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
9314 	SEC_DEF("tp_btf+",		TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
9315 	SEC_DEF("fentry+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
9316 	SEC_DEF("fmod_ret+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
9317 	SEC_DEF("fexit+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
9318 	SEC_DEF("fentry.s+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
9319 	SEC_DEF("fmod_ret.s+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
9320 	SEC_DEF("fexit.s+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
9321 	SEC_DEF("freplace+",		EXT, 0, SEC_ATTACH_BTF, attach_trace),
9322 	SEC_DEF("lsm+",			LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
9323 	SEC_DEF("lsm.s+",		LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
9324 	SEC_DEF("lsm_cgroup+",		LSM, BPF_LSM_CGROUP, SEC_ATTACH_BTF),
9325 	SEC_DEF("iter+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
9326 	SEC_DEF("iter.s+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_iter),
9327 	SEC_DEF("syscall",		SYSCALL, 0, SEC_SLEEPABLE),
9328 	SEC_DEF("xdp.frags/devmap",	XDP, BPF_XDP_DEVMAP, SEC_XDP_FRAGS),
9329 	SEC_DEF("xdp/devmap",		XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
9330 	SEC_DEF("xdp.frags/cpumap",	XDP, BPF_XDP_CPUMAP, SEC_XDP_FRAGS),
9331 	SEC_DEF("xdp/cpumap",		XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
9332 	SEC_DEF("xdp.frags",		XDP, BPF_XDP, SEC_XDP_FRAGS),
9333 	SEC_DEF("xdp",			XDP, BPF_XDP, SEC_ATTACHABLE_OPT),
9334 	SEC_DEF("perf_event",		PERF_EVENT, 0, SEC_NONE),
9335 	SEC_DEF("lwt_in",		LWT_IN, 0, SEC_NONE),
9336 	SEC_DEF("lwt_out",		LWT_OUT, 0, SEC_NONE),
9337 	SEC_DEF("lwt_xmit",		LWT_XMIT, 0, SEC_NONE),
9338 	SEC_DEF("lwt_seg6local",	LWT_SEG6LOCAL, 0, SEC_NONE),
9339 	SEC_DEF("sockops",		SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT),
9340 	SEC_DEF("sk_skb/stream_parser",	SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT),
9341 	SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT),
9342 	SEC_DEF("sk_skb/verdict",	SK_SKB, BPF_SK_SKB_VERDICT, SEC_ATTACHABLE_OPT),
9343 	SEC_DEF("sk_skb",		SK_SKB, 0, SEC_NONE),
9344 	SEC_DEF("sk_msg",		SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT),
9345 	SEC_DEF("lirc_mode2",		LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT),
9346 	SEC_DEF("flow_dissector",	FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT),
9347 	SEC_DEF("cgroup_skb/ingress",	CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT),
9348 	SEC_DEF("cgroup_skb/egress",	CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT),
9349 	SEC_DEF("cgroup/skb",		CGROUP_SKB, 0, SEC_NONE),
9350 	SEC_DEF("cgroup/sock_create",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE),
9351 	SEC_DEF("cgroup/sock_release",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE),
9352 	SEC_DEF("cgroup/sock",		CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT),
9353 	SEC_DEF("cgroup/post_bind4",	CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE),
9354 	SEC_DEF("cgroup/post_bind6",	CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE),
9355 	SEC_DEF("cgroup/bind4",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE),
9356 	SEC_DEF("cgroup/bind6",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE),
9357 	SEC_DEF("cgroup/connect4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE),
9358 	SEC_DEF("cgroup/connect6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE),
9359 	SEC_DEF("cgroup/connect_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_CONNECT, SEC_ATTACHABLE),
9360 	SEC_DEF("cgroup/sendmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE),
9361 	SEC_DEF("cgroup/sendmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE),
9362 	SEC_DEF("cgroup/sendmsg_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_SENDMSG, SEC_ATTACHABLE),
9363 	SEC_DEF("cgroup/recvmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE),
9364 	SEC_DEF("cgroup/recvmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE),
9365 	SEC_DEF("cgroup/recvmsg_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_RECVMSG, SEC_ATTACHABLE),
9366 	SEC_DEF("cgroup/getpeername4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE),
9367 	SEC_DEF("cgroup/getpeername6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE),
9368 	SEC_DEF("cgroup/getpeername_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETPEERNAME, SEC_ATTACHABLE),
9369 	SEC_DEF("cgroup/getsockname4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE),
9370 	SEC_DEF("cgroup/getsockname6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE),
9371 	SEC_DEF("cgroup/getsockname_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETSOCKNAME, SEC_ATTACHABLE),
9372 	SEC_DEF("cgroup/sysctl",	CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE),
9373 	SEC_DEF("cgroup/getsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE),
9374 	SEC_DEF("cgroup/setsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE),
9375 	SEC_DEF("cgroup/dev",		CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT),
9376 	SEC_DEF("struct_ops+",		STRUCT_OPS, 0, SEC_NONE),
9377 	SEC_DEF("struct_ops.s+",	STRUCT_OPS, 0, SEC_SLEEPABLE),
9378 	SEC_DEF("sk_lookup",		SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE),
9379 	SEC_DEF("netfilter",		NETFILTER, BPF_NETFILTER, SEC_NONE),
9380 };
9381 
9382 int libbpf_register_prog_handler(const char *sec,
9383 				 enum bpf_prog_type prog_type,
9384 				 enum bpf_attach_type exp_attach_type,
9385 				 const struct libbpf_prog_handler_opts *opts)
9386 {
9387 	struct bpf_sec_def *sec_def;
9388 
9389 	if (!OPTS_VALID(opts, libbpf_prog_handler_opts))
9390 		return libbpf_err(-EINVAL);
9391 
9392 	if (last_custom_sec_def_handler_id == INT_MAX) /* prevent overflow */
9393 		return libbpf_err(-E2BIG);
9394 
9395 	if (sec) {
9396 		sec_def = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt + 1,
9397 					      sizeof(*sec_def));
9398 		if (!sec_def)
9399 			return libbpf_err(-ENOMEM);
9400 
9401 		custom_sec_defs = sec_def;
9402 		sec_def = &custom_sec_defs[custom_sec_def_cnt];
9403 	} else {
9404 		if (has_custom_fallback_def)
9405 			return libbpf_err(-EBUSY);
9406 
9407 		sec_def = &custom_fallback_def;
9408 	}
9409 
9410 	sec_def->sec = sec ? strdup(sec) : NULL;
9411 	if (sec && !sec_def->sec)
9412 		return libbpf_err(-ENOMEM);
9413 
9414 	sec_def->prog_type = prog_type;
9415 	sec_def->expected_attach_type = exp_attach_type;
9416 	sec_def->cookie = OPTS_GET(opts, cookie, 0);
9417 
9418 	sec_def->prog_setup_fn = OPTS_GET(opts, prog_setup_fn, NULL);
9419 	sec_def->prog_prepare_load_fn = OPTS_GET(opts, prog_prepare_load_fn, NULL);
9420 	sec_def->prog_attach_fn = OPTS_GET(opts, prog_attach_fn, NULL);
9421 
9422 	sec_def->handler_id = ++last_custom_sec_def_handler_id;
9423 
9424 	if (sec)
9425 		custom_sec_def_cnt++;
9426 	else
9427 		has_custom_fallback_def = true;
9428 
9429 	return sec_def->handler_id;
9430 }
9431 
9432 int libbpf_unregister_prog_handler(int handler_id)
9433 {
9434 	struct bpf_sec_def *sec_defs;
9435 	int i;
9436 
9437 	if (handler_id <= 0)
9438 		return libbpf_err(-EINVAL);
9439 
9440 	if (has_custom_fallback_def && custom_fallback_def.handler_id == handler_id) {
9441 		memset(&custom_fallback_def, 0, sizeof(custom_fallback_def));
9442 		has_custom_fallback_def = false;
9443 		return 0;
9444 	}
9445 
9446 	for (i = 0; i < custom_sec_def_cnt; i++) {
9447 		if (custom_sec_defs[i].handler_id == handler_id)
9448 			break;
9449 	}
9450 
9451 	if (i == custom_sec_def_cnt)
9452 		return libbpf_err(-ENOENT);
9453 
9454 	free(custom_sec_defs[i].sec);
9455 	for (i = i + 1; i < custom_sec_def_cnt; i++)
9456 		custom_sec_defs[i - 1] = custom_sec_defs[i];
9457 	custom_sec_def_cnt--;
9458 
9459 	/* try to shrink the array, but it's ok if we couldn't */
9460 	sec_defs = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt, sizeof(*sec_defs));
9461 	/* if new count is zero, reallocarray can return a valid NULL result;
9462 	 * in this case the previous pointer will be freed, so we *have to*
9463 	 * reassign old pointer to the new value (even if it's NULL)
9464 	 */
9465 	if (sec_defs || custom_sec_def_cnt == 0)
9466 		custom_sec_defs = sec_defs;
9467 
9468 	return 0;
9469 }
9470 
9471 static bool sec_def_matches(const struct bpf_sec_def *sec_def, const char *sec_name)
9472 {
9473 	size_t len = strlen(sec_def->sec);
9474 
9475 	/* "type/" always has to have proper SEC("type/extras") form */
9476 	if (sec_def->sec[len - 1] == '/') {
9477 		if (str_has_pfx(sec_name, sec_def->sec))
9478 			return true;
9479 		return false;
9480 	}
9481 
9482 	/* "type+" means it can be either exact SEC("type") or
9483 	 * well-formed SEC("type/extras") with proper '/' separator
9484 	 */
9485 	if (sec_def->sec[len - 1] == '+') {
9486 		len--;
9487 		/* not even a prefix */
9488 		if (strncmp(sec_name, sec_def->sec, len) != 0)
9489 			return false;
9490 		/* exact match or has '/' separator */
9491 		if (sec_name[len] == '\0' || sec_name[len] == '/')
9492 			return true;
9493 		return false;
9494 	}
9495 
9496 	return strcmp(sec_name, sec_def->sec) == 0;
9497 }
9498 
9499 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
9500 {
9501 	const struct bpf_sec_def *sec_def;
9502 	int i, n;
9503 
9504 	n = custom_sec_def_cnt;
9505 	for (i = 0; i < n; i++) {
9506 		sec_def = &custom_sec_defs[i];
9507 		if (sec_def_matches(sec_def, sec_name))
9508 			return sec_def;
9509 	}
9510 
9511 	n = ARRAY_SIZE(section_defs);
9512 	for (i = 0; i < n; i++) {
9513 		sec_def = &section_defs[i];
9514 		if (sec_def_matches(sec_def, sec_name))
9515 			return sec_def;
9516 	}
9517 
9518 	if (has_custom_fallback_def)
9519 		return &custom_fallback_def;
9520 
9521 	return NULL;
9522 }
9523 
9524 #define MAX_TYPE_NAME_SIZE 32
9525 
9526 static char *libbpf_get_type_names(bool attach_type)
9527 {
9528 	int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
9529 	char *buf;
9530 
9531 	buf = malloc(len);
9532 	if (!buf)
9533 		return NULL;
9534 
9535 	buf[0] = '\0';
9536 	/* Forge string buf with all available names */
9537 	for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
9538 		const struct bpf_sec_def *sec_def = &section_defs[i];
9539 
9540 		if (attach_type) {
9541 			if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
9542 				continue;
9543 
9544 			if (!(sec_def->cookie & SEC_ATTACHABLE))
9545 				continue;
9546 		}
9547 
9548 		if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
9549 			free(buf);
9550 			return NULL;
9551 		}
9552 		strcat(buf, " ");
9553 		strcat(buf, section_defs[i].sec);
9554 	}
9555 
9556 	return buf;
9557 }
9558 
9559 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
9560 			     enum bpf_attach_type *expected_attach_type)
9561 {
9562 	const struct bpf_sec_def *sec_def;
9563 	char *type_names;
9564 
9565 	if (!name)
9566 		return libbpf_err(-EINVAL);
9567 
9568 	sec_def = find_sec_def(name);
9569 	if (sec_def) {
9570 		*prog_type = sec_def->prog_type;
9571 		*expected_attach_type = sec_def->expected_attach_type;
9572 		return 0;
9573 	}
9574 
9575 	pr_debug("failed to guess program type from ELF section '%s'\n", name);
9576 	type_names = libbpf_get_type_names(false);
9577 	if (type_names != NULL) {
9578 		pr_debug("supported section(type) names are:%s\n", type_names);
9579 		free(type_names);
9580 	}
9581 
9582 	return libbpf_err(-ESRCH);
9583 }
9584 
9585 const char *libbpf_bpf_attach_type_str(enum bpf_attach_type t)
9586 {
9587 	if (t < 0 || t >= ARRAY_SIZE(attach_type_name))
9588 		return NULL;
9589 
9590 	return attach_type_name[t];
9591 }
9592 
9593 const char *libbpf_bpf_link_type_str(enum bpf_link_type t)
9594 {
9595 	if (t < 0 || t >= ARRAY_SIZE(link_type_name))
9596 		return NULL;
9597 
9598 	return link_type_name[t];
9599 }
9600 
9601 const char *libbpf_bpf_map_type_str(enum bpf_map_type t)
9602 {
9603 	if (t < 0 || t >= ARRAY_SIZE(map_type_name))
9604 		return NULL;
9605 
9606 	return map_type_name[t];
9607 }
9608 
9609 const char *libbpf_bpf_prog_type_str(enum bpf_prog_type t)
9610 {
9611 	if (t < 0 || t >= ARRAY_SIZE(prog_type_name))
9612 		return NULL;
9613 
9614 	return prog_type_name[t];
9615 }
9616 
9617 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
9618 						     int sec_idx,
9619 						     size_t offset)
9620 {
9621 	struct bpf_map *map;
9622 	size_t i;
9623 
9624 	for (i = 0; i < obj->nr_maps; i++) {
9625 		map = &obj->maps[i];
9626 		if (!bpf_map__is_struct_ops(map))
9627 			continue;
9628 		if (map->sec_idx == sec_idx &&
9629 		    map->sec_offset <= offset &&
9630 		    offset - map->sec_offset < map->def.value_size)
9631 			return map;
9632 	}
9633 
9634 	return NULL;
9635 }
9636 
9637 /* Collect the reloc from ELF, populate the st_ops->progs[], and update
9638  * st_ops->data for shadow type.
9639  */
9640 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
9641 					    Elf64_Shdr *shdr, Elf_Data *data)
9642 {
9643 	const struct btf_member *member;
9644 	struct bpf_struct_ops *st_ops;
9645 	struct bpf_program *prog;
9646 	unsigned int shdr_idx;
9647 	const struct btf *btf;
9648 	struct bpf_map *map;
9649 	unsigned int moff, insn_idx;
9650 	const char *name;
9651 	__u32 member_idx;
9652 	Elf64_Sym *sym;
9653 	Elf64_Rel *rel;
9654 	int i, nrels;
9655 
9656 	btf = obj->btf;
9657 	nrels = shdr->sh_size / shdr->sh_entsize;
9658 	for (i = 0; i < nrels; i++) {
9659 		rel = elf_rel_by_idx(data, i);
9660 		if (!rel) {
9661 			pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
9662 			return -LIBBPF_ERRNO__FORMAT;
9663 		}
9664 
9665 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
9666 		if (!sym) {
9667 			pr_warn("struct_ops reloc: symbol %zx not found\n",
9668 				(size_t)ELF64_R_SYM(rel->r_info));
9669 			return -LIBBPF_ERRNO__FORMAT;
9670 		}
9671 
9672 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
9673 		map = find_struct_ops_map_by_offset(obj, shdr->sh_info, rel->r_offset);
9674 		if (!map) {
9675 			pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
9676 				(size_t)rel->r_offset);
9677 			return -EINVAL;
9678 		}
9679 
9680 		moff = rel->r_offset - map->sec_offset;
9681 		shdr_idx = sym->st_shndx;
9682 		st_ops = map->st_ops;
9683 		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",
9684 			 map->name,
9685 			 (long long)(rel->r_info >> 32),
9686 			 (long long)sym->st_value,
9687 			 shdr_idx, (size_t)rel->r_offset,
9688 			 map->sec_offset, sym->st_name, name);
9689 
9690 		if (shdr_idx >= SHN_LORESERVE) {
9691 			pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
9692 				map->name, (size_t)rel->r_offset, shdr_idx);
9693 			return -LIBBPF_ERRNO__RELOC;
9694 		}
9695 		if (sym->st_value % BPF_INSN_SZ) {
9696 			pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
9697 				map->name, (unsigned long long)sym->st_value);
9698 			return -LIBBPF_ERRNO__FORMAT;
9699 		}
9700 		insn_idx = sym->st_value / BPF_INSN_SZ;
9701 
9702 		member = find_member_by_offset(st_ops->type, moff * 8);
9703 		if (!member) {
9704 			pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
9705 				map->name, moff);
9706 			return -EINVAL;
9707 		}
9708 		member_idx = member - btf_members(st_ops->type);
9709 		name = btf__name_by_offset(btf, member->name_off);
9710 
9711 		if (!resolve_func_ptr(btf, member->type, NULL)) {
9712 			pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
9713 				map->name, name);
9714 			return -EINVAL;
9715 		}
9716 
9717 		prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
9718 		if (!prog) {
9719 			pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
9720 				map->name, shdr_idx, name);
9721 			return -EINVAL;
9722 		}
9723 
9724 		/* prevent the use of BPF prog with invalid type */
9725 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
9726 			pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
9727 				map->name, prog->name);
9728 			return -EINVAL;
9729 		}
9730 
9731 		st_ops->progs[member_idx] = prog;
9732 
9733 		/* st_ops->data will be exposed to users, being returned by
9734 		 * bpf_map__initial_value() as a pointer to the shadow
9735 		 * type. All function pointers in the original struct type
9736 		 * should be converted to a pointer to struct bpf_program
9737 		 * in the shadow type.
9738 		 */
9739 		*((struct bpf_program **)(st_ops->data + moff)) = prog;
9740 	}
9741 
9742 	return 0;
9743 }
9744 
9745 #define BTF_TRACE_PREFIX "btf_trace_"
9746 #define BTF_LSM_PREFIX "bpf_lsm_"
9747 #define BTF_ITER_PREFIX "bpf_iter_"
9748 #define BTF_MAX_NAME_SIZE 128
9749 
9750 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
9751 				const char **prefix, int *kind)
9752 {
9753 	switch (attach_type) {
9754 	case BPF_TRACE_RAW_TP:
9755 		*prefix = BTF_TRACE_PREFIX;
9756 		*kind = BTF_KIND_TYPEDEF;
9757 		break;
9758 	case BPF_LSM_MAC:
9759 	case BPF_LSM_CGROUP:
9760 		*prefix = BTF_LSM_PREFIX;
9761 		*kind = BTF_KIND_FUNC;
9762 		break;
9763 	case BPF_TRACE_ITER:
9764 		*prefix = BTF_ITER_PREFIX;
9765 		*kind = BTF_KIND_FUNC;
9766 		break;
9767 	default:
9768 		*prefix = "";
9769 		*kind = BTF_KIND_FUNC;
9770 	}
9771 }
9772 
9773 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
9774 				   const char *name, __u32 kind)
9775 {
9776 	char btf_type_name[BTF_MAX_NAME_SIZE];
9777 	int ret;
9778 
9779 	ret = snprintf(btf_type_name, sizeof(btf_type_name),
9780 		       "%s%s", prefix, name);
9781 	/* snprintf returns the number of characters written excluding the
9782 	 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
9783 	 * indicates truncation.
9784 	 */
9785 	if (ret < 0 || ret >= sizeof(btf_type_name))
9786 		return -ENAMETOOLONG;
9787 	return btf__find_by_name_kind(btf, btf_type_name, kind);
9788 }
9789 
9790 static inline int find_attach_btf_id(struct btf *btf, const char *name,
9791 				     enum bpf_attach_type attach_type)
9792 {
9793 	const char *prefix;
9794 	int kind;
9795 
9796 	btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
9797 	return find_btf_by_prefix_kind(btf, prefix, name, kind);
9798 }
9799 
9800 int libbpf_find_vmlinux_btf_id(const char *name,
9801 			       enum bpf_attach_type attach_type)
9802 {
9803 	struct btf *btf;
9804 	int err;
9805 
9806 	btf = btf__load_vmlinux_btf();
9807 	err = libbpf_get_error(btf);
9808 	if (err) {
9809 		pr_warn("vmlinux BTF is not found\n");
9810 		return libbpf_err(err);
9811 	}
9812 
9813 	err = find_attach_btf_id(btf, name, attach_type);
9814 	if (err <= 0)
9815 		pr_warn("%s is not found in vmlinux BTF\n", name);
9816 
9817 	btf__free(btf);
9818 	return libbpf_err(err);
9819 }
9820 
9821 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
9822 {
9823 	struct bpf_prog_info info;
9824 	__u32 info_len = sizeof(info);
9825 	struct btf *btf;
9826 	int err;
9827 
9828 	memset(&info, 0, info_len);
9829 	err = bpf_prog_get_info_by_fd(attach_prog_fd, &info, &info_len);
9830 	if (err) {
9831 		pr_warn("failed bpf_prog_get_info_by_fd for FD %d: %d\n",
9832 			attach_prog_fd, err);
9833 		return err;
9834 	}
9835 
9836 	err = -EINVAL;
9837 	if (!info.btf_id) {
9838 		pr_warn("The target program doesn't have BTF\n");
9839 		goto out;
9840 	}
9841 	btf = btf__load_from_kernel_by_id(info.btf_id);
9842 	err = libbpf_get_error(btf);
9843 	if (err) {
9844 		pr_warn("Failed to get BTF %d of the program: %d\n", info.btf_id, err);
9845 		goto out;
9846 	}
9847 	err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
9848 	btf__free(btf);
9849 	if (err <= 0) {
9850 		pr_warn("%s is not found in prog's BTF\n", name);
9851 		goto out;
9852 	}
9853 out:
9854 	return err;
9855 }
9856 
9857 static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
9858 			      enum bpf_attach_type attach_type,
9859 			      int *btf_obj_fd, int *btf_type_id)
9860 {
9861 	int ret, i;
9862 
9863 	ret = find_attach_btf_id(obj->btf_vmlinux, attach_name, attach_type);
9864 	if (ret > 0) {
9865 		*btf_obj_fd = 0; /* vmlinux BTF */
9866 		*btf_type_id = ret;
9867 		return 0;
9868 	}
9869 	if (ret != -ENOENT)
9870 		return ret;
9871 
9872 	ret = load_module_btfs(obj);
9873 	if (ret)
9874 		return ret;
9875 
9876 	for (i = 0; i < obj->btf_module_cnt; i++) {
9877 		const struct module_btf *mod = &obj->btf_modules[i];
9878 
9879 		ret = find_attach_btf_id(mod->btf, attach_name, attach_type);
9880 		if (ret > 0) {
9881 			*btf_obj_fd = mod->fd;
9882 			*btf_type_id = ret;
9883 			return 0;
9884 		}
9885 		if (ret == -ENOENT)
9886 			continue;
9887 
9888 		return ret;
9889 	}
9890 
9891 	return -ESRCH;
9892 }
9893 
9894 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
9895 				     int *btf_obj_fd, int *btf_type_id)
9896 {
9897 	enum bpf_attach_type attach_type = prog->expected_attach_type;
9898 	__u32 attach_prog_fd = prog->attach_prog_fd;
9899 	int err = 0;
9900 
9901 	/* BPF program's BTF ID */
9902 	if (prog->type == BPF_PROG_TYPE_EXT || attach_prog_fd) {
9903 		if (!attach_prog_fd) {
9904 			pr_warn("prog '%s': attach program FD is not set\n", prog->name);
9905 			return -EINVAL;
9906 		}
9907 		err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd);
9908 		if (err < 0) {
9909 			pr_warn("prog '%s': failed to find BPF program (FD %d) BTF ID for '%s': %d\n",
9910 				 prog->name, attach_prog_fd, attach_name, err);
9911 			return err;
9912 		}
9913 		*btf_obj_fd = 0;
9914 		*btf_type_id = err;
9915 		return 0;
9916 	}
9917 
9918 	/* kernel/module BTF ID */
9919 	if (prog->obj->gen_loader) {
9920 		bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
9921 		*btf_obj_fd = 0;
9922 		*btf_type_id = 1;
9923 	} else {
9924 		err = find_kernel_btf_id(prog->obj, attach_name,
9925 					 attach_type, btf_obj_fd,
9926 					 btf_type_id);
9927 	}
9928 	if (err) {
9929 		pr_warn("prog '%s': failed to find kernel BTF type ID of '%s': %d\n",
9930 			prog->name, attach_name, err);
9931 		return err;
9932 	}
9933 	return 0;
9934 }
9935 
9936 int libbpf_attach_type_by_name(const char *name,
9937 			       enum bpf_attach_type *attach_type)
9938 {
9939 	char *type_names;
9940 	const struct bpf_sec_def *sec_def;
9941 
9942 	if (!name)
9943 		return libbpf_err(-EINVAL);
9944 
9945 	sec_def = find_sec_def(name);
9946 	if (!sec_def) {
9947 		pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
9948 		type_names = libbpf_get_type_names(true);
9949 		if (type_names != NULL) {
9950 			pr_debug("attachable section(type) names are:%s\n", type_names);
9951 			free(type_names);
9952 		}
9953 
9954 		return libbpf_err(-EINVAL);
9955 	}
9956 
9957 	if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
9958 		return libbpf_err(-EINVAL);
9959 	if (!(sec_def->cookie & SEC_ATTACHABLE))
9960 		return libbpf_err(-EINVAL);
9961 
9962 	*attach_type = sec_def->expected_attach_type;
9963 	return 0;
9964 }
9965 
9966 int bpf_map__fd(const struct bpf_map *map)
9967 {
9968 	if (!map)
9969 		return libbpf_err(-EINVAL);
9970 	if (!map_is_created(map))
9971 		return -1;
9972 	return map->fd;
9973 }
9974 
9975 static bool map_uses_real_name(const struct bpf_map *map)
9976 {
9977 	/* Since libbpf started to support custom .data.* and .rodata.* maps,
9978 	 * their user-visible name differs from kernel-visible name. Users see
9979 	 * such map's corresponding ELF section name as a map name.
9980 	 * This check distinguishes .data/.rodata from .data.* and .rodata.*
9981 	 * maps to know which name has to be returned to the user.
9982 	 */
9983 	if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
9984 		return true;
9985 	if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
9986 		return true;
9987 	return false;
9988 }
9989 
9990 const char *bpf_map__name(const struct bpf_map *map)
9991 {
9992 	if (!map)
9993 		return NULL;
9994 
9995 	if (map_uses_real_name(map))
9996 		return map->real_name;
9997 
9998 	return map->name;
9999 }
10000 
10001 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
10002 {
10003 	return map->def.type;
10004 }
10005 
10006 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
10007 {
10008 	if (map_is_created(map))
10009 		return libbpf_err(-EBUSY);
10010 	map->def.type = type;
10011 	return 0;
10012 }
10013 
10014 __u32 bpf_map__map_flags(const struct bpf_map *map)
10015 {
10016 	return map->def.map_flags;
10017 }
10018 
10019 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
10020 {
10021 	if (map_is_created(map))
10022 		return libbpf_err(-EBUSY);
10023 	map->def.map_flags = flags;
10024 	return 0;
10025 }
10026 
10027 __u64 bpf_map__map_extra(const struct bpf_map *map)
10028 {
10029 	return map->map_extra;
10030 }
10031 
10032 int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
10033 {
10034 	if (map_is_created(map))
10035 		return libbpf_err(-EBUSY);
10036 	map->map_extra = map_extra;
10037 	return 0;
10038 }
10039 
10040 __u32 bpf_map__numa_node(const struct bpf_map *map)
10041 {
10042 	return map->numa_node;
10043 }
10044 
10045 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
10046 {
10047 	if (map_is_created(map))
10048 		return libbpf_err(-EBUSY);
10049 	map->numa_node = numa_node;
10050 	return 0;
10051 }
10052 
10053 __u32 bpf_map__key_size(const struct bpf_map *map)
10054 {
10055 	return map->def.key_size;
10056 }
10057 
10058 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
10059 {
10060 	if (map_is_created(map))
10061 		return libbpf_err(-EBUSY);
10062 	map->def.key_size = size;
10063 	return 0;
10064 }
10065 
10066 __u32 bpf_map__value_size(const struct bpf_map *map)
10067 {
10068 	return map->def.value_size;
10069 }
10070 
10071 static int map_btf_datasec_resize(struct bpf_map *map, __u32 size)
10072 {
10073 	struct btf *btf;
10074 	struct btf_type *datasec_type, *var_type;
10075 	struct btf_var_secinfo *var;
10076 	const struct btf_type *array_type;
10077 	const struct btf_array *array;
10078 	int vlen, element_sz, new_array_id;
10079 	__u32 nr_elements;
10080 
10081 	/* check btf existence */
10082 	btf = bpf_object__btf(map->obj);
10083 	if (!btf)
10084 		return -ENOENT;
10085 
10086 	/* verify map is datasec */
10087 	datasec_type = btf_type_by_id(btf, bpf_map__btf_value_type_id(map));
10088 	if (!btf_is_datasec(datasec_type)) {
10089 		pr_warn("map '%s': cannot be resized, map value type is not a datasec\n",
10090 			bpf_map__name(map));
10091 		return -EINVAL;
10092 	}
10093 
10094 	/* verify datasec has at least one var */
10095 	vlen = btf_vlen(datasec_type);
10096 	if (vlen == 0) {
10097 		pr_warn("map '%s': cannot be resized, map value datasec is empty\n",
10098 			bpf_map__name(map));
10099 		return -EINVAL;
10100 	}
10101 
10102 	/* verify last var in the datasec is an array */
10103 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
10104 	var_type = btf_type_by_id(btf, var->type);
10105 	array_type = skip_mods_and_typedefs(btf, var_type->type, NULL);
10106 	if (!btf_is_array(array_type)) {
10107 		pr_warn("map '%s': cannot be resized, last var must be an array\n",
10108 			bpf_map__name(map));
10109 		return -EINVAL;
10110 	}
10111 
10112 	/* verify request size aligns with array */
10113 	array = btf_array(array_type);
10114 	element_sz = btf__resolve_size(btf, array->type);
10115 	if (element_sz <= 0 || (size - var->offset) % element_sz != 0) {
10116 		pr_warn("map '%s': cannot be resized, element size (%d) doesn't align with new total size (%u)\n",
10117 			bpf_map__name(map), element_sz, size);
10118 		return -EINVAL;
10119 	}
10120 
10121 	/* create a new array based on the existing array, but with new length */
10122 	nr_elements = (size - var->offset) / element_sz;
10123 	new_array_id = btf__add_array(btf, array->index_type, array->type, nr_elements);
10124 	if (new_array_id < 0)
10125 		return new_array_id;
10126 
10127 	/* adding a new btf type invalidates existing pointers to btf objects,
10128 	 * so refresh pointers before proceeding
10129 	 */
10130 	datasec_type = btf_type_by_id(btf, map->btf_value_type_id);
10131 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
10132 	var_type = btf_type_by_id(btf, var->type);
10133 
10134 	/* finally update btf info */
10135 	datasec_type->size = size;
10136 	var->size = size - var->offset;
10137 	var_type->type = new_array_id;
10138 
10139 	return 0;
10140 }
10141 
10142 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
10143 {
10144 	if (map->obj->loaded || map->reused)
10145 		return libbpf_err(-EBUSY);
10146 
10147 	if (map->mmaped) {
10148 		size_t mmap_old_sz, mmap_new_sz;
10149 		int err;
10150 
10151 		if (map->def.type != BPF_MAP_TYPE_ARRAY)
10152 			return -EOPNOTSUPP;
10153 
10154 		mmap_old_sz = bpf_map_mmap_sz(map);
10155 		mmap_new_sz = array_map_mmap_sz(size, map->def.max_entries);
10156 		err = bpf_map_mmap_resize(map, mmap_old_sz, mmap_new_sz);
10157 		if (err) {
10158 			pr_warn("map '%s': failed to resize memory-mapped region: %d\n",
10159 				bpf_map__name(map), err);
10160 			return err;
10161 		}
10162 		err = map_btf_datasec_resize(map, size);
10163 		if (err && err != -ENOENT) {
10164 			pr_warn("map '%s': failed to adjust resized BTF, clearing BTF key/value info: %d\n",
10165 				bpf_map__name(map), err);
10166 			map->btf_value_type_id = 0;
10167 			map->btf_key_type_id = 0;
10168 		}
10169 	}
10170 
10171 	map->def.value_size = size;
10172 	return 0;
10173 }
10174 
10175 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
10176 {
10177 	return map ? map->btf_key_type_id : 0;
10178 }
10179 
10180 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
10181 {
10182 	return map ? map->btf_value_type_id : 0;
10183 }
10184 
10185 int bpf_map__set_initial_value(struct bpf_map *map,
10186 			       const void *data, size_t size)
10187 {
10188 	size_t actual_sz;
10189 
10190 	if (map->obj->loaded || map->reused)
10191 		return libbpf_err(-EBUSY);
10192 
10193 	if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG)
10194 		return libbpf_err(-EINVAL);
10195 
10196 	if (map->def.type == BPF_MAP_TYPE_ARENA)
10197 		actual_sz = map->obj->arena_data_sz;
10198 	else
10199 		actual_sz = map->def.value_size;
10200 	if (size != actual_sz)
10201 		return libbpf_err(-EINVAL);
10202 
10203 	memcpy(map->mmaped, data, size);
10204 	return 0;
10205 }
10206 
10207 void *bpf_map__initial_value(const struct bpf_map *map, size_t *psize)
10208 {
10209 	if (bpf_map__is_struct_ops(map)) {
10210 		if (psize)
10211 			*psize = map->def.value_size;
10212 		return map->st_ops->data;
10213 	}
10214 
10215 	if (!map->mmaped)
10216 		return NULL;
10217 
10218 	if (map->def.type == BPF_MAP_TYPE_ARENA)
10219 		*psize = map->obj->arena_data_sz;
10220 	else
10221 		*psize = map->def.value_size;
10222 
10223 	return map->mmaped;
10224 }
10225 
10226 bool bpf_map__is_internal(const struct bpf_map *map)
10227 {
10228 	return map->libbpf_type != LIBBPF_MAP_UNSPEC;
10229 }
10230 
10231 __u32 bpf_map__ifindex(const struct bpf_map *map)
10232 {
10233 	return map->map_ifindex;
10234 }
10235 
10236 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
10237 {
10238 	if (map_is_created(map))
10239 		return libbpf_err(-EBUSY);
10240 	map->map_ifindex = ifindex;
10241 	return 0;
10242 }
10243 
10244 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
10245 {
10246 	if (!bpf_map_type__is_map_in_map(map->def.type)) {
10247 		pr_warn("error: unsupported map type\n");
10248 		return libbpf_err(-EINVAL);
10249 	}
10250 	if (map->inner_map_fd != -1) {
10251 		pr_warn("error: inner_map_fd already specified\n");
10252 		return libbpf_err(-EINVAL);
10253 	}
10254 	if (map->inner_map) {
10255 		bpf_map__destroy(map->inner_map);
10256 		zfree(&map->inner_map);
10257 	}
10258 	map->inner_map_fd = fd;
10259 	return 0;
10260 }
10261 
10262 static struct bpf_map *
10263 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
10264 {
10265 	ssize_t idx;
10266 	struct bpf_map *s, *e;
10267 
10268 	if (!obj || !obj->maps)
10269 		return errno = EINVAL, NULL;
10270 
10271 	s = obj->maps;
10272 	e = obj->maps + obj->nr_maps;
10273 
10274 	if ((m < s) || (m >= e)) {
10275 		pr_warn("error in %s: map handler doesn't belong to object\n",
10276 			 __func__);
10277 		return errno = EINVAL, NULL;
10278 	}
10279 
10280 	idx = (m - obj->maps) + i;
10281 	if (idx >= obj->nr_maps || idx < 0)
10282 		return NULL;
10283 	return &obj->maps[idx];
10284 }
10285 
10286 struct bpf_map *
10287 bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
10288 {
10289 	if (prev == NULL)
10290 		return obj->maps;
10291 
10292 	return __bpf_map__iter(prev, obj, 1);
10293 }
10294 
10295 struct bpf_map *
10296 bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
10297 {
10298 	if (next == NULL) {
10299 		if (!obj->nr_maps)
10300 			return NULL;
10301 		return obj->maps + obj->nr_maps - 1;
10302 	}
10303 
10304 	return __bpf_map__iter(next, obj, -1);
10305 }
10306 
10307 struct bpf_map *
10308 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
10309 {
10310 	struct bpf_map *pos;
10311 
10312 	bpf_object__for_each_map(pos, obj) {
10313 		/* if it's a special internal map name (which always starts
10314 		 * with dot) then check if that special name matches the
10315 		 * real map name (ELF section name)
10316 		 */
10317 		if (name[0] == '.') {
10318 			if (pos->real_name && strcmp(pos->real_name, name) == 0)
10319 				return pos;
10320 			continue;
10321 		}
10322 		/* otherwise map name has to be an exact match */
10323 		if (map_uses_real_name(pos)) {
10324 			if (strcmp(pos->real_name, name) == 0)
10325 				return pos;
10326 			continue;
10327 		}
10328 		if (strcmp(pos->name, name) == 0)
10329 			return pos;
10330 	}
10331 	return errno = ENOENT, NULL;
10332 }
10333 
10334 int
10335 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
10336 {
10337 	return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
10338 }
10339 
10340 static int validate_map_op(const struct bpf_map *map, size_t key_sz,
10341 			   size_t value_sz, bool check_value_sz)
10342 {
10343 	if (!map_is_created(map)) /* map is not yet created */
10344 		return -ENOENT;
10345 
10346 	if (map->def.key_size != key_sz) {
10347 		pr_warn("map '%s': unexpected key size %zu provided, expected %u\n",
10348 			map->name, key_sz, map->def.key_size);
10349 		return -EINVAL;
10350 	}
10351 
10352 	if (map->fd < 0) {
10353 		pr_warn("map '%s': can't use BPF map without FD (was it created?)\n", map->name);
10354 		return -EINVAL;
10355 	}
10356 
10357 	if (!check_value_sz)
10358 		return 0;
10359 
10360 	switch (map->def.type) {
10361 	case BPF_MAP_TYPE_PERCPU_ARRAY:
10362 	case BPF_MAP_TYPE_PERCPU_HASH:
10363 	case BPF_MAP_TYPE_LRU_PERCPU_HASH:
10364 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: {
10365 		int num_cpu = libbpf_num_possible_cpus();
10366 		size_t elem_sz = roundup(map->def.value_size, 8);
10367 
10368 		if (value_sz != num_cpu * elem_sz) {
10369 			pr_warn("map '%s': unexpected value size %zu provided for per-CPU map, expected %d * %zu = %zd\n",
10370 				map->name, value_sz, num_cpu, elem_sz, num_cpu * elem_sz);
10371 			return -EINVAL;
10372 		}
10373 		break;
10374 	}
10375 	default:
10376 		if (map->def.value_size != value_sz) {
10377 			pr_warn("map '%s': unexpected value size %zu provided, expected %u\n",
10378 				map->name, value_sz, map->def.value_size);
10379 			return -EINVAL;
10380 		}
10381 		break;
10382 	}
10383 	return 0;
10384 }
10385 
10386 int bpf_map__lookup_elem(const struct bpf_map *map,
10387 			 const void *key, size_t key_sz,
10388 			 void *value, size_t value_sz, __u64 flags)
10389 {
10390 	int err;
10391 
10392 	err = validate_map_op(map, key_sz, value_sz, true);
10393 	if (err)
10394 		return libbpf_err(err);
10395 
10396 	return bpf_map_lookup_elem_flags(map->fd, key, value, flags);
10397 }
10398 
10399 int bpf_map__update_elem(const struct bpf_map *map,
10400 			 const void *key, size_t key_sz,
10401 			 const void *value, size_t value_sz, __u64 flags)
10402 {
10403 	int err;
10404 
10405 	err = validate_map_op(map, key_sz, value_sz, true);
10406 	if (err)
10407 		return libbpf_err(err);
10408 
10409 	return bpf_map_update_elem(map->fd, key, value, flags);
10410 }
10411 
10412 int bpf_map__delete_elem(const struct bpf_map *map,
10413 			 const void *key, size_t key_sz, __u64 flags)
10414 {
10415 	int err;
10416 
10417 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
10418 	if (err)
10419 		return libbpf_err(err);
10420 
10421 	return bpf_map_delete_elem_flags(map->fd, key, flags);
10422 }
10423 
10424 int bpf_map__lookup_and_delete_elem(const struct bpf_map *map,
10425 				    const void *key, size_t key_sz,
10426 				    void *value, size_t value_sz, __u64 flags)
10427 {
10428 	int err;
10429 
10430 	err = validate_map_op(map, key_sz, value_sz, true);
10431 	if (err)
10432 		return libbpf_err(err);
10433 
10434 	return bpf_map_lookup_and_delete_elem_flags(map->fd, key, value, flags);
10435 }
10436 
10437 int bpf_map__get_next_key(const struct bpf_map *map,
10438 			  const void *cur_key, void *next_key, size_t key_sz)
10439 {
10440 	int err;
10441 
10442 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
10443 	if (err)
10444 		return libbpf_err(err);
10445 
10446 	return bpf_map_get_next_key(map->fd, cur_key, next_key);
10447 }
10448 
10449 long libbpf_get_error(const void *ptr)
10450 {
10451 	if (!IS_ERR_OR_NULL(ptr))
10452 		return 0;
10453 
10454 	if (IS_ERR(ptr))
10455 		errno = -PTR_ERR(ptr);
10456 
10457 	/* If ptr == NULL, then errno should be already set by the failing
10458 	 * API, because libbpf never returns NULL on success and it now always
10459 	 * sets errno on error. So no extra errno handling for ptr == NULL
10460 	 * case.
10461 	 */
10462 	return -errno;
10463 }
10464 
10465 /* Replace link's underlying BPF program with the new one */
10466 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
10467 {
10468 	int ret;
10469 	int prog_fd = bpf_program__fd(prog);
10470 
10471 	if (prog_fd < 0) {
10472 		pr_warn("prog '%s': can't use BPF program without FD (was it loaded?)\n",
10473 			prog->name);
10474 		return libbpf_err(-EINVAL);
10475 	}
10476 
10477 	ret = bpf_link_update(bpf_link__fd(link), prog_fd, NULL);
10478 	return libbpf_err_errno(ret);
10479 }
10480 
10481 /* Release "ownership" of underlying BPF resource (typically, BPF program
10482  * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
10483  * link, when destructed through bpf_link__destroy() call won't attempt to
10484  * detach/unregisted that BPF resource. This is useful in situations where,
10485  * say, attached BPF program has to outlive userspace program that attached it
10486  * in the system. Depending on type of BPF program, though, there might be
10487  * additional steps (like pinning BPF program in BPF FS) necessary to ensure
10488  * exit of userspace program doesn't trigger automatic detachment and clean up
10489  * inside the kernel.
10490  */
10491 void bpf_link__disconnect(struct bpf_link *link)
10492 {
10493 	link->disconnected = true;
10494 }
10495 
10496 int bpf_link__destroy(struct bpf_link *link)
10497 {
10498 	int err = 0;
10499 
10500 	if (IS_ERR_OR_NULL(link))
10501 		return 0;
10502 
10503 	if (!link->disconnected && link->detach)
10504 		err = link->detach(link);
10505 	if (link->pin_path)
10506 		free(link->pin_path);
10507 	if (link->dealloc)
10508 		link->dealloc(link);
10509 	else
10510 		free(link);
10511 
10512 	return libbpf_err(err);
10513 }
10514 
10515 int bpf_link__fd(const struct bpf_link *link)
10516 {
10517 	return link->fd;
10518 }
10519 
10520 const char *bpf_link__pin_path(const struct bpf_link *link)
10521 {
10522 	return link->pin_path;
10523 }
10524 
10525 static int bpf_link__detach_fd(struct bpf_link *link)
10526 {
10527 	return libbpf_err_errno(close(link->fd));
10528 }
10529 
10530 struct bpf_link *bpf_link__open(const char *path)
10531 {
10532 	struct bpf_link *link;
10533 	int fd;
10534 
10535 	fd = bpf_obj_get(path);
10536 	if (fd < 0) {
10537 		fd = -errno;
10538 		pr_warn("failed to open link at %s: %d\n", path, fd);
10539 		return libbpf_err_ptr(fd);
10540 	}
10541 
10542 	link = calloc(1, sizeof(*link));
10543 	if (!link) {
10544 		close(fd);
10545 		return libbpf_err_ptr(-ENOMEM);
10546 	}
10547 	link->detach = &bpf_link__detach_fd;
10548 	link->fd = fd;
10549 
10550 	link->pin_path = strdup(path);
10551 	if (!link->pin_path) {
10552 		bpf_link__destroy(link);
10553 		return libbpf_err_ptr(-ENOMEM);
10554 	}
10555 
10556 	return link;
10557 }
10558 
10559 int bpf_link__detach(struct bpf_link *link)
10560 {
10561 	return bpf_link_detach(link->fd) ? -errno : 0;
10562 }
10563 
10564 int bpf_link__pin(struct bpf_link *link, const char *path)
10565 {
10566 	int err;
10567 
10568 	if (link->pin_path)
10569 		return libbpf_err(-EBUSY);
10570 	err = make_parent_dir(path);
10571 	if (err)
10572 		return libbpf_err(err);
10573 	err = check_path(path);
10574 	if (err)
10575 		return libbpf_err(err);
10576 
10577 	link->pin_path = strdup(path);
10578 	if (!link->pin_path)
10579 		return libbpf_err(-ENOMEM);
10580 
10581 	if (bpf_obj_pin(link->fd, link->pin_path)) {
10582 		err = -errno;
10583 		zfree(&link->pin_path);
10584 		return libbpf_err(err);
10585 	}
10586 
10587 	pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
10588 	return 0;
10589 }
10590 
10591 int bpf_link__unpin(struct bpf_link *link)
10592 {
10593 	int err;
10594 
10595 	if (!link->pin_path)
10596 		return libbpf_err(-EINVAL);
10597 
10598 	err = unlink(link->pin_path);
10599 	if (err != 0)
10600 		return -errno;
10601 
10602 	pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
10603 	zfree(&link->pin_path);
10604 	return 0;
10605 }
10606 
10607 struct bpf_link_perf {
10608 	struct bpf_link link;
10609 	int perf_event_fd;
10610 	/* legacy kprobe support: keep track of probe identifier and type */
10611 	char *legacy_probe_name;
10612 	bool legacy_is_kprobe;
10613 	bool legacy_is_retprobe;
10614 };
10615 
10616 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
10617 static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
10618 
10619 static int bpf_link_perf_detach(struct bpf_link *link)
10620 {
10621 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10622 	int err = 0;
10623 
10624 	if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
10625 		err = -errno;
10626 
10627 	if (perf_link->perf_event_fd != link->fd)
10628 		close(perf_link->perf_event_fd);
10629 	close(link->fd);
10630 
10631 	/* legacy uprobe/kprobe needs to be removed after perf event fd closure */
10632 	if (perf_link->legacy_probe_name) {
10633 		if (perf_link->legacy_is_kprobe) {
10634 			err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
10635 							 perf_link->legacy_is_retprobe);
10636 		} else {
10637 			err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
10638 							 perf_link->legacy_is_retprobe);
10639 		}
10640 	}
10641 
10642 	return err;
10643 }
10644 
10645 static void bpf_link_perf_dealloc(struct bpf_link *link)
10646 {
10647 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10648 
10649 	free(perf_link->legacy_probe_name);
10650 	free(perf_link);
10651 }
10652 
10653 struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
10654 						     const struct bpf_perf_event_opts *opts)
10655 {
10656 	char errmsg[STRERR_BUFSIZE];
10657 	struct bpf_link_perf *link;
10658 	int prog_fd, link_fd = -1, err;
10659 	bool force_ioctl_attach;
10660 
10661 	if (!OPTS_VALID(opts, bpf_perf_event_opts))
10662 		return libbpf_err_ptr(-EINVAL);
10663 
10664 	if (pfd < 0) {
10665 		pr_warn("prog '%s': invalid perf event FD %d\n",
10666 			prog->name, pfd);
10667 		return libbpf_err_ptr(-EINVAL);
10668 	}
10669 	prog_fd = bpf_program__fd(prog);
10670 	if (prog_fd < 0) {
10671 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
10672 			prog->name);
10673 		return libbpf_err_ptr(-EINVAL);
10674 	}
10675 
10676 	link = calloc(1, sizeof(*link));
10677 	if (!link)
10678 		return libbpf_err_ptr(-ENOMEM);
10679 	link->link.detach = &bpf_link_perf_detach;
10680 	link->link.dealloc = &bpf_link_perf_dealloc;
10681 	link->perf_event_fd = pfd;
10682 
10683 	force_ioctl_attach = OPTS_GET(opts, force_ioctl_attach, false);
10684 	if (kernel_supports(prog->obj, FEAT_PERF_LINK) && !force_ioctl_attach) {
10685 		DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
10686 			.perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
10687 
10688 		link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
10689 		if (link_fd < 0) {
10690 			err = -errno;
10691 			pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %d (%s)\n",
10692 				prog->name, pfd,
10693 				err, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10694 			goto err_out;
10695 		}
10696 		link->link.fd = link_fd;
10697 	} else {
10698 		if (OPTS_GET(opts, bpf_cookie, 0)) {
10699 			pr_warn("prog '%s': user context value is not supported\n", prog->name);
10700 			err = -EOPNOTSUPP;
10701 			goto err_out;
10702 		}
10703 
10704 		if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
10705 			err = -errno;
10706 			pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
10707 				prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10708 			if (err == -EPROTO)
10709 				pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
10710 					prog->name, pfd);
10711 			goto err_out;
10712 		}
10713 		link->link.fd = pfd;
10714 	}
10715 	if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
10716 		err = -errno;
10717 		pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
10718 			prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10719 		goto err_out;
10720 	}
10721 
10722 	return &link->link;
10723 err_out:
10724 	if (link_fd >= 0)
10725 		close(link_fd);
10726 	free(link);
10727 	return libbpf_err_ptr(err);
10728 }
10729 
10730 struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
10731 {
10732 	return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
10733 }
10734 
10735 /*
10736  * this function is expected to parse integer in the range of [0, 2^31-1] from
10737  * given file using scanf format string fmt. If actual parsed value is
10738  * negative, the result might be indistinguishable from error
10739  */
10740 static int parse_uint_from_file(const char *file, const char *fmt)
10741 {
10742 	char buf[STRERR_BUFSIZE];
10743 	int err, ret;
10744 	FILE *f;
10745 
10746 	f = fopen(file, "re");
10747 	if (!f) {
10748 		err = -errno;
10749 		pr_debug("failed to open '%s': %s\n", file,
10750 			 libbpf_strerror_r(err, buf, sizeof(buf)));
10751 		return err;
10752 	}
10753 	err = fscanf(f, fmt, &ret);
10754 	if (err != 1) {
10755 		err = err == EOF ? -EIO : -errno;
10756 		pr_debug("failed to parse '%s': %s\n", file,
10757 			libbpf_strerror_r(err, buf, sizeof(buf)));
10758 		fclose(f);
10759 		return err;
10760 	}
10761 	fclose(f);
10762 	return ret;
10763 }
10764 
10765 static int determine_kprobe_perf_type(void)
10766 {
10767 	const char *file = "/sys/bus/event_source/devices/kprobe/type";
10768 
10769 	return parse_uint_from_file(file, "%d\n");
10770 }
10771 
10772 static int determine_uprobe_perf_type(void)
10773 {
10774 	const char *file = "/sys/bus/event_source/devices/uprobe/type";
10775 
10776 	return parse_uint_from_file(file, "%d\n");
10777 }
10778 
10779 static int determine_kprobe_retprobe_bit(void)
10780 {
10781 	const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
10782 
10783 	return parse_uint_from_file(file, "config:%d\n");
10784 }
10785 
10786 static int determine_uprobe_retprobe_bit(void)
10787 {
10788 	const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
10789 
10790 	return parse_uint_from_file(file, "config:%d\n");
10791 }
10792 
10793 #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
10794 #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
10795 
10796 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
10797 				 uint64_t offset, int pid, size_t ref_ctr_off)
10798 {
10799 	const size_t attr_sz = sizeof(struct perf_event_attr);
10800 	struct perf_event_attr attr;
10801 	char errmsg[STRERR_BUFSIZE];
10802 	int type, pfd;
10803 
10804 	if ((__u64)ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
10805 		return -EINVAL;
10806 
10807 	memset(&attr, 0, attr_sz);
10808 
10809 	type = uprobe ? determine_uprobe_perf_type()
10810 		      : determine_kprobe_perf_type();
10811 	if (type < 0) {
10812 		pr_warn("failed to determine %s perf type: %s\n",
10813 			uprobe ? "uprobe" : "kprobe",
10814 			libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
10815 		return type;
10816 	}
10817 	if (retprobe) {
10818 		int bit = uprobe ? determine_uprobe_retprobe_bit()
10819 				 : determine_kprobe_retprobe_bit();
10820 
10821 		if (bit < 0) {
10822 			pr_warn("failed to determine %s retprobe bit: %s\n",
10823 				uprobe ? "uprobe" : "kprobe",
10824 				libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
10825 			return bit;
10826 		}
10827 		attr.config |= 1 << bit;
10828 	}
10829 	attr.size = attr_sz;
10830 	attr.type = type;
10831 	attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
10832 	attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
10833 	attr.config2 = offset;		 /* kprobe_addr or probe_offset */
10834 
10835 	/* pid filter is meaningful only for uprobes */
10836 	pfd = syscall(__NR_perf_event_open, &attr,
10837 		      pid < 0 ? -1 : pid /* pid */,
10838 		      pid == -1 ? 0 : -1 /* cpu */,
10839 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
10840 	return pfd >= 0 ? pfd : -errno;
10841 }
10842 
10843 static int append_to_file(const char *file, const char *fmt, ...)
10844 {
10845 	int fd, n, err = 0;
10846 	va_list ap;
10847 	char buf[1024];
10848 
10849 	va_start(ap, fmt);
10850 	n = vsnprintf(buf, sizeof(buf), fmt, ap);
10851 	va_end(ap);
10852 
10853 	if (n < 0 || n >= sizeof(buf))
10854 		return -EINVAL;
10855 
10856 	fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
10857 	if (fd < 0)
10858 		return -errno;
10859 
10860 	if (write(fd, buf, n) < 0)
10861 		err = -errno;
10862 
10863 	close(fd);
10864 	return err;
10865 }
10866 
10867 #define DEBUGFS "/sys/kernel/debug/tracing"
10868 #define TRACEFS "/sys/kernel/tracing"
10869 
10870 static bool use_debugfs(void)
10871 {
10872 	static int has_debugfs = -1;
10873 
10874 	if (has_debugfs < 0)
10875 		has_debugfs = faccessat(AT_FDCWD, DEBUGFS, F_OK, AT_EACCESS) == 0;
10876 
10877 	return has_debugfs == 1;
10878 }
10879 
10880 static const char *tracefs_path(void)
10881 {
10882 	return use_debugfs() ? DEBUGFS : TRACEFS;
10883 }
10884 
10885 static const char *tracefs_kprobe_events(void)
10886 {
10887 	return use_debugfs() ? DEBUGFS"/kprobe_events" : TRACEFS"/kprobe_events";
10888 }
10889 
10890 static const char *tracefs_uprobe_events(void)
10891 {
10892 	return use_debugfs() ? DEBUGFS"/uprobe_events" : TRACEFS"/uprobe_events";
10893 }
10894 
10895 static const char *tracefs_available_filter_functions(void)
10896 {
10897 	return use_debugfs() ? DEBUGFS"/available_filter_functions"
10898 			     : TRACEFS"/available_filter_functions";
10899 }
10900 
10901 static const char *tracefs_available_filter_functions_addrs(void)
10902 {
10903 	return use_debugfs() ? DEBUGFS"/available_filter_functions_addrs"
10904 			     : TRACEFS"/available_filter_functions_addrs";
10905 }
10906 
10907 static void gen_kprobe_legacy_event_name(char *buf, size_t buf_sz,
10908 					 const char *kfunc_name, size_t offset)
10909 {
10910 	static int index = 0;
10911 	int i;
10912 
10913 	snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx_%d", getpid(), kfunc_name, offset,
10914 		 __sync_fetch_and_add(&index, 1));
10915 
10916 	/* sanitize binary_path in the probe name */
10917 	for (i = 0; buf[i]; i++) {
10918 		if (!isalnum(buf[i]))
10919 			buf[i] = '_';
10920 	}
10921 }
10922 
10923 static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
10924 				   const char *kfunc_name, size_t offset)
10925 {
10926 	return append_to_file(tracefs_kprobe_events(), "%c:%s/%s %s+0x%zx",
10927 			      retprobe ? 'r' : 'p',
10928 			      retprobe ? "kretprobes" : "kprobes",
10929 			      probe_name, kfunc_name, offset);
10930 }
10931 
10932 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
10933 {
10934 	return append_to_file(tracefs_kprobe_events(), "-:%s/%s",
10935 			      retprobe ? "kretprobes" : "kprobes", probe_name);
10936 }
10937 
10938 static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
10939 {
10940 	char file[256];
10941 
10942 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
10943 		 tracefs_path(), retprobe ? "kretprobes" : "kprobes", probe_name);
10944 
10945 	return parse_uint_from_file(file, "%d\n");
10946 }
10947 
10948 static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
10949 					 const char *kfunc_name, size_t offset, int pid)
10950 {
10951 	const size_t attr_sz = sizeof(struct perf_event_attr);
10952 	struct perf_event_attr attr;
10953 	char errmsg[STRERR_BUFSIZE];
10954 	int type, pfd, err;
10955 
10956 	err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
10957 	if (err < 0) {
10958 		pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
10959 			kfunc_name, offset,
10960 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10961 		return err;
10962 	}
10963 	type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
10964 	if (type < 0) {
10965 		err = type;
10966 		pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
10967 			kfunc_name, offset,
10968 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10969 		goto err_clean_legacy;
10970 	}
10971 
10972 	memset(&attr, 0, attr_sz);
10973 	attr.size = attr_sz;
10974 	attr.config = type;
10975 	attr.type = PERF_TYPE_TRACEPOINT;
10976 
10977 	pfd = syscall(__NR_perf_event_open, &attr,
10978 		      pid < 0 ? -1 : pid, /* pid */
10979 		      pid == -1 ? 0 : -1, /* cpu */
10980 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
10981 	if (pfd < 0) {
10982 		err = -errno;
10983 		pr_warn("legacy kprobe perf_event_open() failed: %s\n",
10984 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10985 		goto err_clean_legacy;
10986 	}
10987 	return pfd;
10988 
10989 err_clean_legacy:
10990 	/* Clear the newly added legacy kprobe_event */
10991 	remove_kprobe_event_legacy(probe_name, retprobe);
10992 	return err;
10993 }
10994 
10995 static const char *arch_specific_syscall_pfx(void)
10996 {
10997 #if defined(__x86_64__)
10998 	return "x64";
10999 #elif defined(__i386__)
11000 	return "ia32";
11001 #elif defined(__s390x__)
11002 	return "s390x";
11003 #elif defined(__s390__)
11004 	return "s390";
11005 #elif defined(__arm__)
11006 	return "arm";
11007 #elif defined(__aarch64__)
11008 	return "arm64";
11009 #elif defined(__mips__)
11010 	return "mips";
11011 #elif defined(__riscv)
11012 	return "riscv";
11013 #elif defined(__powerpc__)
11014 	return "powerpc";
11015 #elif defined(__powerpc64__)
11016 	return "powerpc64";
11017 #else
11018 	return NULL;
11019 #endif
11020 }
11021 
11022 int probe_kern_syscall_wrapper(int token_fd)
11023 {
11024 	char syscall_name[64];
11025 	const char *ksys_pfx;
11026 
11027 	ksys_pfx = arch_specific_syscall_pfx();
11028 	if (!ksys_pfx)
11029 		return 0;
11030 
11031 	snprintf(syscall_name, sizeof(syscall_name), "__%s_sys_bpf", ksys_pfx);
11032 
11033 	if (determine_kprobe_perf_type() >= 0) {
11034 		int pfd;
11035 
11036 		pfd = perf_event_open_probe(false, false, syscall_name, 0, getpid(), 0);
11037 		if (pfd >= 0)
11038 			close(pfd);
11039 
11040 		return pfd >= 0 ? 1 : 0;
11041 	} else { /* legacy mode */
11042 		char probe_name[128];
11043 
11044 		gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name), syscall_name, 0);
11045 		if (add_kprobe_event_legacy(probe_name, false, syscall_name, 0) < 0)
11046 			return 0;
11047 
11048 		(void)remove_kprobe_event_legacy(probe_name, false);
11049 		return 1;
11050 	}
11051 }
11052 
11053 struct bpf_link *
11054 bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
11055 				const char *func_name,
11056 				const struct bpf_kprobe_opts *opts)
11057 {
11058 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11059 	enum probe_attach_mode attach_mode;
11060 	char errmsg[STRERR_BUFSIZE];
11061 	char *legacy_probe = NULL;
11062 	struct bpf_link *link;
11063 	size_t offset;
11064 	bool retprobe, legacy;
11065 	int pfd, err;
11066 
11067 	if (!OPTS_VALID(opts, bpf_kprobe_opts))
11068 		return libbpf_err_ptr(-EINVAL);
11069 
11070 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
11071 	retprobe = OPTS_GET(opts, retprobe, false);
11072 	offset = OPTS_GET(opts, offset, 0);
11073 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11074 
11075 	legacy = determine_kprobe_perf_type() < 0;
11076 	switch (attach_mode) {
11077 	case PROBE_ATTACH_MODE_LEGACY:
11078 		legacy = true;
11079 		pe_opts.force_ioctl_attach = true;
11080 		break;
11081 	case PROBE_ATTACH_MODE_PERF:
11082 		if (legacy)
11083 			return libbpf_err_ptr(-ENOTSUP);
11084 		pe_opts.force_ioctl_attach = true;
11085 		break;
11086 	case PROBE_ATTACH_MODE_LINK:
11087 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
11088 			return libbpf_err_ptr(-ENOTSUP);
11089 		break;
11090 	case PROBE_ATTACH_MODE_DEFAULT:
11091 		break;
11092 	default:
11093 		return libbpf_err_ptr(-EINVAL);
11094 	}
11095 
11096 	if (!legacy) {
11097 		pfd = perf_event_open_probe(false /* uprobe */, retprobe,
11098 					    func_name, offset,
11099 					    -1 /* pid */, 0 /* ref_ctr_off */);
11100 	} else {
11101 		char probe_name[256];
11102 
11103 		gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name),
11104 					     func_name, offset);
11105 
11106 		legacy_probe = strdup(probe_name);
11107 		if (!legacy_probe)
11108 			return libbpf_err_ptr(-ENOMEM);
11109 
11110 		pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
11111 						    offset, -1 /* pid */);
11112 	}
11113 	if (pfd < 0) {
11114 		err = -errno;
11115 		pr_warn("prog '%s': failed to create %s '%s+0x%zx' perf event: %s\n",
11116 			prog->name, retprobe ? "kretprobe" : "kprobe",
11117 			func_name, offset,
11118 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11119 		goto err_out;
11120 	}
11121 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11122 	err = libbpf_get_error(link);
11123 	if (err) {
11124 		close(pfd);
11125 		pr_warn("prog '%s': failed to attach to %s '%s+0x%zx': %s\n",
11126 			prog->name, retprobe ? "kretprobe" : "kprobe",
11127 			func_name, offset,
11128 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11129 		goto err_clean_legacy;
11130 	}
11131 	if (legacy) {
11132 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
11133 
11134 		perf_link->legacy_probe_name = legacy_probe;
11135 		perf_link->legacy_is_kprobe = true;
11136 		perf_link->legacy_is_retprobe = retprobe;
11137 	}
11138 
11139 	return link;
11140 
11141 err_clean_legacy:
11142 	if (legacy)
11143 		remove_kprobe_event_legacy(legacy_probe, retprobe);
11144 err_out:
11145 	free(legacy_probe);
11146 	return libbpf_err_ptr(err);
11147 }
11148 
11149 struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
11150 					    bool retprobe,
11151 					    const char *func_name)
11152 {
11153 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
11154 		.retprobe = retprobe,
11155 	);
11156 
11157 	return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
11158 }
11159 
11160 struct bpf_link *bpf_program__attach_ksyscall(const struct bpf_program *prog,
11161 					      const char *syscall_name,
11162 					      const struct bpf_ksyscall_opts *opts)
11163 {
11164 	LIBBPF_OPTS(bpf_kprobe_opts, kprobe_opts);
11165 	char func_name[128];
11166 
11167 	if (!OPTS_VALID(opts, bpf_ksyscall_opts))
11168 		return libbpf_err_ptr(-EINVAL);
11169 
11170 	if (kernel_supports(prog->obj, FEAT_SYSCALL_WRAPPER)) {
11171 		/* arch_specific_syscall_pfx() should never return NULL here
11172 		 * because it is guarded by kernel_supports(). However, since
11173 		 * compiler does not know that we have an explicit conditional
11174 		 * as well.
11175 		 */
11176 		snprintf(func_name, sizeof(func_name), "__%s_sys_%s",
11177 			 arch_specific_syscall_pfx() ? : "", syscall_name);
11178 	} else {
11179 		snprintf(func_name, sizeof(func_name), "__se_sys_%s", syscall_name);
11180 	}
11181 
11182 	kprobe_opts.retprobe = OPTS_GET(opts, retprobe, false);
11183 	kprobe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11184 
11185 	return bpf_program__attach_kprobe_opts(prog, func_name, &kprobe_opts);
11186 }
11187 
11188 /* Adapted from perf/util/string.c */
11189 bool glob_match(const char *str, const char *pat)
11190 {
11191 	while (*str && *pat && *pat != '*') {
11192 		if (*pat == '?') {      /* Matches any single character */
11193 			str++;
11194 			pat++;
11195 			continue;
11196 		}
11197 		if (*str != *pat)
11198 			return false;
11199 		str++;
11200 		pat++;
11201 	}
11202 	/* Check wild card */
11203 	if (*pat == '*') {
11204 		while (*pat == '*')
11205 			pat++;
11206 		if (!*pat) /* Tail wild card matches all */
11207 			return true;
11208 		while (*str)
11209 			if (glob_match(str++, pat))
11210 				return true;
11211 	}
11212 	return !*str && !*pat;
11213 }
11214 
11215 struct kprobe_multi_resolve {
11216 	const char *pattern;
11217 	unsigned long *addrs;
11218 	size_t cap;
11219 	size_t cnt;
11220 };
11221 
11222 struct avail_kallsyms_data {
11223 	char **syms;
11224 	size_t cnt;
11225 	struct kprobe_multi_resolve *res;
11226 };
11227 
11228 static int avail_func_cmp(const void *a, const void *b)
11229 {
11230 	return strcmp(*(const char **)a, *(const char **)b);
11231 }
11232 
11233 static int avail_kallsyms_cb(unsigned long long sym_addr, char sym_type,
11234 			     const char *sym_name, void *ctx)
11235 {
11236 	struct avail_kallsyms_data *data = ctx;
11237 	struct kprobe_multi_resolve *res = data->res;
11238 	int err;
11239 
11240 	if (!bsearch(&sym_name, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp))
11241 		return 0;
11242 
11243 	err = libbpf_ensure_mem((void **)&res->addrs, &res->cap, sizeof(*res->addrs), res->cnt + 1);
11244 	if (err)
11245 		return err;
11246 
11247 	res->addrs[res->cnt++] = (unsigned long)sym_addr;
11248 	return 0;
11249 }
11250 
11251 static int libbpf_available_kallsyms_parse(struct kprobe_multi_resolve *res)
11252 {
11253 	const char *available_functions_file = tracefs_available_filter_functions();
11254 	struct avail_kallsyms_data data;
11255 	char sym_name[500];
11256 	FILE *f;
11257 	int err = 0, ret, i;
11258 	char **syms = NULL;
11259 	size_t cap = 0, cnt = 0;
11260 
11261 	f = fopen(available_functions_file, "re");
11262 	if (!f) {
11263 		err = -errno;
11264 		pr_warn("failed to open %s: %d\n", available_functions_file, err);
11265 		return err;
11266 	}
11267 
11268 	while (true) {
11269 		char *name;
11270 
11271 		ret = fscanf(f, "%499s%*[^\n]\n", sym_name);
11272 		if (ret == EOF && feof(f))
11273 			break;
11274 
11275 		if (ret != 1) {
11276 			pr_warn("failed to parse available_filter_functions entry: %d\n", ret);
11277 			err = -EINVAL;
11278 			goto cleanup;
11279 		}
11280 
11281 		if (!glob_match(sym_name, res->pattern))
11282 			continue;
11283 
11284 		err = libbpf_ensure_mem((void **)&syms, &cap, sizeof(*syms), cnt + 1);
11285 		if (err)
11286 			goto cleanup;
11287 
11288 		name = strdup(sym_name);
11289 		if (!name) {
11290 			err = -errno;
11291 			goto cleanup;
11292 		}
11293 
11294 		syms[cnt++] = name;
11295 	}
11296 
11297 	/* no entries found, bail out */
11298 	if (cnt == 0) {
11299 		err = -ENOENT;
11300 		goto cleanup;
11301 	}
11302 
11303 	/* sort available functions */
11304 	qsort(syms, cnt, sizeof(*syms), avail_func_cmp);
11305 
11306 	data.syms = syms;
11307 	data.res = res;
11308 	data.cnt = cnt;
11309 	libbpf_kallsyms_parse(avail_kallsyms_cb, &data);
11310 
11311 	if (res->cnt == 0)
11312 		err = -ENOENT;
11313 
11314 cleanup:
11315 	for (i = 0; i < cnt; i++)
11316 		free((char *)syms[i]);
11317 	free(syms);
11318 
11319 	fclose(f);
11320 	return err;
11321 }
11322 
11323 static bool has_available_filter_functions_addrs(void)
11324 {
11325 	return access(tracefs_available_filter_functions_addrs(), R_OK) != -1;
11326 }
11327 
11328 static int libbpf_available_kprobes_parse(struct kprobe_multi_resolve *res)
11329 {
11330 	const char *available_path = tracefs_available_filter_functions_addrs();
11331 	char sym_name[500];
11332 	FILE *f;
11333 	int ret, err = 0;
11334 	unsigned long long sym_addr;
11335 
11336 	f = fopen(available_path, "re");
11337 	if (!f) {
11338 		err = -errno;
11339 		pr_warn("failed to open %s: %d\n", available_path, err);
11340 		return err;
11341 	}
11342 
11343 	while (true) {
11344 		ret = fscanf(f, "%llx %499s%*[^\n]\n", &sym_addr, sym_name);
11345 		if (ret == EOF && feof(f))
11346 			break;
11347 
11348 		if (ret != 2) {
11349 			pr_warn("failed to parse available_filter_functions_addrs entry: %d\n",
11350 				ret);
11351 			err = -EINVAL;
11352 			goto cleanup;
11353 		}
11354 
11355 		if (!glob_match(sym_name, res->pattern))
11356 			continue;
11357 
11358 		err = libbpf_ensure_mem((void **)&res->addrs, &res->cap,
11359 					sizeof(*res->addrs), res->cnt + 1);
11360 		if (err)
11361 			goto cleanup;
11362 
11363 		res->addrs[res->cnt++] = (unsigned long)sym_addr;
11364 	}
11365 
11366 	if (res->cnt == 0)
11367 		err = -ENOENT;
11368 
11369 cleanup:
11370 	fclose(f);
11371 	return err;
11372 }
11373 
11374 struct bpf_link *
11375 bpf_program__attach_kprobe_multi_opts(const struct bpf_program *prog,
11376 				      const char *pattern,
11377 				      const struct bpf_kprobe_multi_opts *opts)
11378 {
11379 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
11380 	struct kprobe_multi_resolve res = {
11381 		.pattern = pattern,
11382 	};
11383 	struct bpf_link *link = NULL;
11384 	char errmsg[STRERR_BUFSIZE];
11385 	const unsigned long *addrs;
11386 	int err, link_fd, prog_fd;
11387 	const __u64 *cookies;
11388 	const char **syms;
11389 	bool retprobe;
11390 	size_t cnt;
11391 
11392 	if (!OPTS_VALID(opts, bpf_kprobe_multi_opts))
11393 		return libbpf_err_ptr(-EINVAL);
11394 
11395 	prog_fd = bpf_program__fd(prog);
11396 	if (prog_fd < 0) {
11397 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
11398 			prog->name);
11399 		return libbpf_err_ptr(-EINVAL);
11400 	}
11401 
11402 	syms    = OPTS_GET(opts, syms, false);
11403 	addrs   = OPTS_GET(opts, addrs, false);
11404 	cnt     = OPTS_GET(opts, cnt, false);
11405 	cookies = OPTS_GET(opts, cookies, false);
11406 
11407 	if (!pattern && !addrs && !syms)
11408 		return libbpf_err_ptr(-EINVAL);
11409 	if (pattern && (addrs || syms || cookies || cnt))
11410 		return libbpf_err_ptr(-EINVAL);
11411 	if (!pattern && !cnt)
11412 		return libbpf_err_ptr(-EINVAL);
11413 	if (addrs && syms)
11414 		return libbpf_err_ptr(-EINVAL);
11415 
11416 	if (pattern) {
11417 		if (has_available_filter_functions_addrs())
11418 			err = libbpf_available_kprobes_parse(&res);
11419 		else
11420 			err = libbpf_available_kallsyms_parse(&res);
11421 		if (err)
11422 			goto error;
11423 		addrs = res.addrs;
11424 		cnt = res.cnt;
11425 	}
11426 
11427 	retprobe = OPTS_GET(opts, retprobe, false);
11428 
11429 	lopts.kprobe_multi.syms = syms;
11430 	lopts.kprobe_multi.addrs = addrs;
11431 	lopts.kprobe_multi.cookies = cookies;
11432 	lopts.kprobe_multi.cnt = cnt;
11433 	lopts.kprobe_multi.flags = retprobe ? BPF_F_KPROBE_MULTI_RETURN : 0;
11434 
11435 	link = calloc(1, sizeof(*link));
11436 	if (!link) {
11437 		err = -ENOMEM;
11438 		goto error;
11439 	}
11440 	link->detach = &bpf_link__detach_fd;
11441 
11442 	link_fd = bpf_link_create(prog_fd, 0, BPF_TRACE_KPROBE_MULTI, &lopts);
11443 	if (link_fd < 0) {
11444 		err = -errno;
11445 		pr_warn("prog '%s': failed to attach: %s\n",
11446 			prog->name, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11447 		goto error;
11448 	}
11449 	link->fd = link_fd;
11450 	free(res.addrs);
11451 	return link;
11452 
11453 error:
11454 	free(link);
11455 	free(res.addrs);
11456 	return libbpf_err_ptr(err);
11457 }
11458 
11459 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11460 {
11461 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
11462 	unsigned long offset = 0;
11463 	const char *func_name;
11464 	char *func;
11465 	int n;
11466 
11467 	*link = NULL;
11468 
11469 	/* no auto-attach for SEC("kprobe") and SEC("kretprobe") */
11470 	if (strcmp(prog->sec_name, "kprobe") == 0 || strcmp(prog->sec_name, "kretprobe") == 0)
11471 		return 0;
11472 
11473 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
11474 	if (opts.retprobe)
11475 		func_name = prog->sec_name + sizeof("kretprobe/") - 1;
11476 	else
11477 		func_name = prog->sec_name + sizeof("kprobe/") - 1;
11478 
11479 	n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
11480 	if (n < 1) {
11481 		pr_warn("kprobe name is invalid: %s\n", func_name);
11482 		return -EINVAL;
11483 	}
11484 	if (opts.retprobe && offset != 0) {
11485 		free(func);
11486 		pr_warn("kretprobes do not support offset specification\n");
11487 		return -EINVAL;
11488 	}
11489 
11490 	opts.offset = offset;
11491 	*link = bpf_program__attach_kprobe_opts(prog, func, &opts);
11492 	free(func);
11493 	return libbpf_get_error(*link);
11494 }
11495 
11496 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11497 {
11498 	LIBBPF_OPTS(bpf_ksyscall_opts, opts);
11499 	const char *syscall_name;
11500 
11501 	*link = NULL;
11502 
11503 	/* no auto-attach for SEC("ksyscall") and SEC("kretsyscall") */
11504 	if (strcmp(prog->sec_name, "ksyscall") == 0 || strcmp(prog->sec_name, "kretsyscall") == 0)
11505 		return 0;
11506 
11507 	opts.retprobe = str_has_pfx(prog->sec_name, "kretsyscall/");
11508 	if (opts.retprobe)
11509 		syscall_name = prog->sec_name + sizeof("kretsyscall/") - 1;
11510 	else
11511 		syscall_name = prog->sec_name + sizeof("ksyscall/") - 1;
11512 
11513 	*link = bpf_program__attach_ksyscall(prog, syscall_name, &opts);
11514 	return *link ? 0 : -errno;
11515 }
11516 
11517 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11518 {
11519 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts);
11520 	const char *spec;
11521 	char *pattern;
11522 	int n;
11523 
11524 	*link = NULL;
11525 
11526 	/* no auto-attach for SEC("kprobe.multi") and SEC("kretprobe.multi") */
11527 	if (strcmp(prog->sec_name, "kprobe.multi") == 0 ||
11528 	    strcmp(prog->sec_name, "kretprobe.multi") == 0)
11529 		return 0;
11530 
11531 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe.multi/");
11532 	if (opts.retprobe)
11533 		spec = prog->sec_name + sizeof("kretprobe.multi/") - 1;
11534 	else
11535 		spec = prog->sec_name + sizeof("kprobe.multi/") - 1;
11536 
11537 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
11538 	if (n < 1) {
11539 		pr_warn("kprobe multi pattern is invalid: %s\n", pattern);
11540 		return -EINVAL;
11541 	}
11542 
11543 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
11544 	free(pattern);
11545 	return libbpf_get_error(*link);
11546 }
11547 
11548 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11549 {
11550 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
11551 	LIBBPF_OPTS(bpf_uprobe_multi_opts, opts);
11552 	int n, ret = -EINVAL;
11553 
11554 	*link = NULL;
11555 
11556 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
11557 		   &probe_type, &binary_path, &func_name);
11558 	switch (n) {
11559 	case 1:
11560 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
11561 		ret = 0;
11562 		break;
11563 	case 3:
11564 		opts.retprobe = strcmp(probe_type, "uretprobe.multi") == 0;
11565 		*link = bpf_program__attach_uprobe_multi(prog, -1, binary_path, func_name, &opts);
11566 		ret = libbpf_get_error(*link);
11567 		break;
11568 	default:
11569 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
11570 			prog->sec_name);
11571 		break;
11572 	}
11573 	free(probe_type);
11574 	free(binary_path);
11575 	free(func_name);
11576 	return ret;
11577 }
11578 
11579 static void gen_uprobe_legacy_event_name(char *buf, size_t buf_sz,
11580 					 const char *binary_path, uint64_t offset)
11581 {
11582 	int i;
11583 
11584 	snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx", getpid(), binary_path, (size_t)offset);
11585 
11586 	/* sanitize binary_path in the probe name */
11587 	for (i = 0; buf[i]; i++) {
11588 		if (!isalnum(buf[i]))
11589 			buf[i] = '_';
11590 	}
11591 }
11592 
11593 static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
11594 					  const char *binary_path, size_t offset)
11595 {
11596 	return append_to_file(tracefs_uprobe_events(), "%c:%s/%s %s:0x%zx",
11597 			      retprobe ? 'r' : 'p',
11598 			      retprobe ? "uretprobes" : "uprobes",
11599 			      probe_name, binary_path, offset);
11600 }
11601 
11602 static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
11603 {
11604 	return append_to_file(tracefs_uprobe_events(), "-:%s/%s",
11605 			      retprobe ? "uretprobes" : "uprobes", probe_name);
11606 }
11607 
11608 static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
11609 {
11610 	char file[512];
11611 
11612 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11613 		 tracefs_path(), retprobe ? "uretprobes" : "uprobes", probe_name);
11614 
11615 	return parse_uint_from_file(file, "%d\n");
11616 }
11617 
11618 static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
11619 					 const char *binary_path, size_t offset, int pid)
11620 {
11621 	const size_t attr_sz = sizeof(struct perf_event_attr);
11622 	struct perf_event_attr attr;
11623 	int type, pfd, err;
11624 
11625 	err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
11626 	if (err < 0) {
11627 		pr_warn("failed to add legacy uprobe event for %s:0x%zx: %d\n",
11628 			binary_path, (size_t)offset, err);
11629 		return err;
11630 	}
11631 	type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
11632 	if (type < 0) {
11633 		err = type;
11634 		pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %d\n",
11635 			binary_path, offset, err);
11636 		goto err_clean_legacy;
11637 	}
11638 
11639 	memset(&attr, 0, attr_sz);
11640 	attr.size = attr_sz;
11641 	attr.config = type;
11642 	attr.type = PERF_TYPE_TRACEPOINT;
11643 
11644 	pfd = syscall(__NR_perf_event_open, &attr,
11645 		      pid < 0 ? -1 : pid, /* pid */
11646 		      pid == -1 ? 0 : -1, /* cpu */
11647 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
11648 	if (pfd < 0) {
11649 		err = -errno;
11650 		pr_warn("legacy uprobe perf_event_open() failed: %d\n", err);
11651 		goto err_clean_legacy;
11652 	}
11653 	return pfd;
11654 
11655 err_clean_legacy:
11656 	/* Clear the newly added legacy uprobe_event */
11657 	remove_uprobe_event_legacy(probe_name, retprobe);
11658 	return err;
11659 }
11660 
11661 /* Find offset of function name in archive specified by path. Currently
11662  * supported are .zip files that do not compress their contents, as used on
11663  * Android in the form of APKs, for example. "file_name" is the name of the ELF
11664  * file inside the archive. "func_name" matches symbol name or name@@LIB for
11665  * library functions.
11666  *
11667  * An overview of the APK format specifically provided here:
11668  * https://en.wikipedia.org/w/index.php?title=Apk_(file_format)&oldid=1139099120#Package_contents
11669  */
11670 static long elf_find_func_offset_from_archive(const char *archive_path, const char *file_name,
11671 					      const char *func_name)
11672 {
11673 	struct zip_archive *archive;
11674 	struct zip_entry entry;
11675 	long ret;
11676 	Elf *elf;
11677 
11678 	archive = zip_archive_open(archive_path);
11679 	if (IS_ERR(archive)) {
11680 		ret = PTR_ERR(archive);
11681 		pr_warn("zip: failed to open %s: %ld\n", archive_path, ret);
11682 		return ret;
11683 	}
11684 
11685 	ret = zip_archive_find_entry(archive, file_name, &entry);
11686 	if (ret) {
11687 		pr_warn("zip: could not find archive member %s in %s: %ld\n", file_name,
11688 			archive_path, ret);
11689 		goto out;
11690 	}
11691 	pr_debug("zip: found entry for %s in %s at 0x%lx\n", file_name, archive_path,
11692 		 (unsigned long)entry.data_offset);
11693 
11694 	if (entry.compression) {
11695 		pr_warn("zip: entry %s of %s is compressed and cannot be handled\n", file_name,
11696 			archive_path);
11697 		ret = -LIBBPF_ERRNO__FORMAT;
11698 		goto out;
11699 	}
11700 
11701 	elf = elf_memory((void *)entry.data, entry.data_length);
11702 	if (!elf) {
11703 		pr_warn("elf: could not read elf file %s from %s: %s\n", file_name, archive_path,
11704 			elf_errmsg(-1));
11705 		ret = -LIBBPF_ERRNO__LIBELF;
11706 		goto out;
11707 	}
11708 
11709 	ret = elf_find_func_offset(elf, file_name, func_name);
11710 	if (ret > 0) {
11711 		pr_debug("elf: symbol address match for %s of %s in %s: 0x%x + 0x%lx = 0x%lx\n",
11712 			 func_name, file_name, archive_path, entry.data_offset, ret,
11713 			 ret + entry.data_offset);
11714 		ret += entry.data_offset;
11715 	}
11716 	elf_end(elf);
11717 
11718 out:
11719 	zip_archive_close(archive);
11720 	return ret;
11721 }
11722 
11723 static const char *arch_specific_lib_paths(void)
11724 {
11725 	/*
11726 	 * Based on https://packages.debian.org/sid/libc6.
11727 	 *
11728 	 * Assume that the traced program is built for the same architecture
11729 	 * as libbpf, which should cover the vast majority of cases.
11730 	 */
11731 #if defined(__x86_64__)
11732 	return "/lib/x86_64-linux-gnu";
11733 #elif defined(__i386__)
11734 	return "/lib/i386-linux-gnu";
11735 #elif defined(__s390x__)
11736 	return "/lib/s390x-linux-gnu";
11737 #elif defined(__s390__)
11738 	return "/lib/s390-linux-gnu";
11739 #elif defined(__arm__) && defined(__SOFTFP__)
11740 	return "/lib/arm-linux-gnueabi";
11741 #elif defined(__arm__) && !defined(__SOFTFP__)
11742 	return "/lib/arm-linux-gnueabihf";
11743 #elif defined(__aarch64__)
11744 	return "/lib/aarch64-linux-gnu";
11745 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 64
11746 	return "/lib/mips64el-linux-gnuabi64";
11747 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 32
11748 	return "/lib/mipsel-linux-gnu";
11749 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
11750 	return "/lib/powerpc64le-linux-gnu";
11751 #elif defined(__sparc__) && defined(__arch64__)
11752 	return "/lib/sparc64-linux-gnu";
11753 #elif defined(__riscv) && __riscv_xlen == 64
11754 	return "/lib/riscv64-linux-gnu";
11755 #else
11756 	return NULL;
11757 #endif
11758 }
11759 
11760 /* Get full path to program/shared library. */
11761 static int resolve_full_path(const char *file, char *result, size_t result_sz)
11762 {
11763 	const char *search_paths[3] = {};
11764 	int i, perm;
11765 
11766 	if (str_has_sfx(file, ".so") || strstr(file, ".so.")) {
11767 		search_paths[0] = getenv("LD_LIBRARY_PATH");
11768 		search_paths[1] = "/usr/lib64:/usr/lib";
11769 		search_paths[2] = arch_specific_lib_paths();
11770 		perm = R_OK;
11771 	} else {
11772 		search_paths[0] = getenv("PATH");
11773 		search_paths[1] = "/usr/bin:/usr/sbin";
11774 		perm = R_OK | X_OK;
11775 	}
11776 
11777 	for (i = 0; i < ARRAY_SIZE(search_paths); i++) {
11778 		const char *s;
11779 
11780 		if (!search_paths[i])
11781 			continue;
11782 		for (s = search_paths[i]; s != NULL; s = strchr(s, ':')) {
11783 			char *next_path;
11784 			int seg_len;
11785 
11786 			if (s[0] == ':')
11787 				s++;
11788 			next_path = strchr(s, ':');
11789 			seg_len = next_path ? next_path - s : strlen(s);
11790 			if (!seg_len)
11791 				continue;
11792 			snprintf(result, result_sz, "%.*s/%s", seg_len, s, file);
11793 			/* ensure it has required permissions */
11794 			if (faccessat(AT_FDCWD, result, perm, AT_EACCESS) < 0)
11795 				continue;
11796 			pr_debug("resolved '%s' to '%s'\n", file, result);
11797 			return 0;
11798 		}
11799 	}
11800 	return -ENOENT;
11801 }
11802 
11803 struct bpf_link *
11804 bpf_program__attach_uprobe_multi(const struct bpf_program *prog,
11805 				 pid_t pid,
11806 				 const char *path,
11807 				 const char *func_pattern,
11808 				 const struct bpf_uprobe_multi_opts *opts)
11809 {
11810 	const unsigned long *ref_ctr_offsets = NULL, *offsets = NULL;
11811 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
11812 	unsigned long *resolved_offsets = NULL;
11813 	int err = 0, link_fd, prog_fd;
11814 	struct bpf_link *link = NULL;
11815 	char errmsg[STRERR_BUFSIZE];
11816 	char full_path[PATH_MAX];
11817 	const __u64 *cookies;
11818 	const char **syms;
11819 	size_t cnt;
11820 
11821 	if (!OPTS_VALID(opts, bpf_uprobe_multi_opts))
11822 		return libbpf_err_ptr(-EINVAL);
11823 
11824 	prog_fd = bpf_program__fd(prog);
11825 	if (prog_fd < 0) {
11826 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
11827 			prog->name);
11828 		return libbpf_err_ptr(-EINVAL);
11829 	}
11830 
11831 	syms = OPTS_GET(opts, syms, NULL);
11832 	offsets = OPTS_GET(opts, offsets, NULL);
11833 	ref_ctr_offsets = OPTS_GET(opts, ref_ctr_offsets, NULL);
11834 	cookies = OPTS_GET(opts, cookies, NULL);
11835 	cnt = OPTS_GET(opts, cnt, 0);
11836 
11837 	/*
11838 	 * User can specify 2 mutually exclusive set of inputs:
11839 	 *
11840 	 * 1) use only path/func_pattern/pid arguments
11841 	 *
11842 	 * 2) use path/pid with allowed combinations of:
11843 	 *    syms/offsets/ref_ctr_offsets/cookies/cnt
11844 	 *
11845 	 *    - syms and offsets are mutually exclusive
11846 	 *    - ref_ctr_offsets and cookies are optional
11847 	 *
11848 	 * Any other usage results in error.
11849 	 */
11850 
11851 	if (!path)
11852 		return libbpf_err_ptr(-EINVAL);
11853 	if (!func_pattern && cnt == 0)
11854 		return libbpf_err_ptr(-EINVAL);
11855 
11856 	if (func_pattern) {
11857 		if (syms || offsets || ref_ctr_offsets || cookies || cnt)
11858 			return libbpf_err_ptr(-EINVAL);
11859 	} else {
11860 		if (!!syms == !!offsets)
11861 			return libbpf_err_ptr(-EINVAL);
11862 	}
11863 
11864 	if (func_pattern) {
11865 		if (!strchr(path, '/')) {
11866 			err = resolve_full_path(path, full_path, sizeof(full_path));
11867 			if (err) {
11868 				pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11869 					prog->name, path, err);
11870 				return libbpf_err_ptr(err);
11871 			}
11872 			path = full_path;
11873 		}
11874 
11875 		err = elf_resolve_pattern_offsets(path, func_pattern,
11876 						  &resolved_offsets, &cnt);
11877 		if (err < 0)
11878 			return libbpf_err_ptr(err);
11879 		offsets = resolved_offsets;
11880 	} else if (syms) {
11881 		err = elf_resolve_syms_offsets(path, cnt, syms, &resolved_offsets, STT_FUNC);
11882 		if (err < 0)
11883 			return libbpf_err_ptr(err);
11884 		offsets = resolved_offsets;
11885 	}
11886 
11887 	lopts.uprobe_multi.path = path;
11888 	lopts.uprobe_multi.offsets = offsets;
11889 	lopts.uprobe_multi.ref_ctr_offsets = ref_ctr_offsets;
11890 	lopts.uprobe_multi.cookies = cookies;
11891 	lopts.uprobe_multi.cnt = cnt;
11892 	lopts.uprobe_multi.flags = OPTS_GET(opts, retprobe, false) ? BPF_F_UPROBE_MULTI_RETURN : 0;
11893 
11894 	if (pid == 0)
11895 		pid = getpid();
11896 	if (pid > 0)
11897 		lopts.uprobe_multi.pid = pid;
11898 
11899 	link = calloc(1, sizeof(*link));
11900 	if (!link) {
11901 		err = -ENOMEM;
11902 		goto error;
11903 	}
11904 	link->detach = &bpf_link__detach_fd;
11905 
11906 	link_fd = bpf_link_create(prog_fd, 0, BPF_TRACE_UPROBE_MULTI, &lopts);
11907 	if (link_fd < 0) {
11908 		err = -errno;
11909 		pr_warn("prog '%s': failed to attach multi-uprobe: %s\n",
11910 			prog->name, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11911 		goto error;
11912 	}
11913 	link->fd = link_fd;
11914 	free(resolved_offsets);
11915 	return link;
11916 
11917 error:
11918 	free(resolved_offsets);
11919 	free(link);
11920 	return libbpf_err_ptr(err);
11921 }
11922 
11923 LIBBPF_API struct bpf_link *
11924 bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
11925 				const char *binary_path, size_t func_offset,
11926 				const struct bpf_uprobe_opts *opts)
11927 {
11928 	const char *archive_path = NULL, *archive_sep = NULL;
11929 	char errmsg[STRERR_BUFSIZE], *legacy_probe = NULL;
11930 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11931 	enum probe_attach_mode attach_mode;
11932 	char full_path[PATH_MAX];
11933 	struct bpf_link *link;
11934 	size_t ref_ctr_off;
11935 	int pfd, err;
11936 	bool retprobe, legacy;
11937 	const char *func_name;
11938 
11939 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
11940 		return libbpf_err_ptr(-EINVAL);
11941 
11942 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
11943 	retprobe = OPTS_GET(opts, retprobe, false);
11944 	ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
11945 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11946 
11947 	if (!binary_path)
11948 		return libbpf_err_ptr(-EINVAL);
11949 
11950 	/* Check if "binary_path" refers to an archive. */
11951 	archive_sep = strstr(binary_path, "!/");
11952 	if (archive_sep) {
11953 		full_path[0] = '\0';
11954 		libbpf_strlcpy(full_path, binary_path,
11955 			       min(sizeof(full_path), (size_t)(archive_sep - binary_path + 1)));
11956 		archive_path = full_path;
11957 		binary_path = archive_sep + 2;
11958 	} else if (!strchr(binary_path, '/')) {
11959 		err = resolve_full_path(binary_path, full_path, sizeof(full_path));
11960 		if (err) {
11961 			pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11962 				prog->name, binary_path, err);
11963 			return libbpf_err_ptr(err);
11964 		}
11965 		binary_path = full_path;
11966 	}
11967 	func_name = OPTS_GET(opts, func_name, NULL);
11968 	if (func_name) {
11969 		long sym_off;
11970 
11971 		if (archive_path) {
11972 			sym_off = elf_find_func_offset_from_archive(archive_path, binary_path,
11973 								    func_name);
11974 			binary_path = archive_path;
11975 		} else {
11976 			sym_off = elf_find_func_offset_from_file(binary_path, func_name);
11977 		}
11978 		if (sym_off < 0)
11979 			return libbpf_err_ptr(sym_off);
11980 		func_offset += sym_off;
11981 	}
11982 
11983 	legacy = determine_uprobe_perf_type() < 0;
11984 	switch (attach_mode) {
11985 	case PROBE_ATTACH_MODE_LEGACY:
11986 		legacy = true;
11987 		pe_opts.force_ioctl_attach = true;
11988 		break;
11989 	case PROBE_ATTACH_MODE_PERF:
11990 		if (legacy)
11991 			return libbpf_err_ptr(-ENOTSUP);
11992 		pe_opts.force_ioctl_attach = true;
11993 		break;
11994 	case PROBE_ATTACH_MODE_LINK:
11995 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
11996 			return libbpf_err_ptr(-ENOTSUP);
11997 		break;
11998 	case PROBE_ATTACH_MODE_DEFAULT:
11999 		break;
12000 	default:
12001 		return libbpf_err_ptr(-EINVAL);
12002 	}
12003 
12004 	if (!legacy) {
12005 		pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
12006 					    func_offset, pid, ref_ctr_off);
12007 	} else {
12008 		char probe_name[PATH_MAX + 64];
12009 
12010 		if (ref_ctr_off)
12011 			return libbpf_err_ptr(-EINVAL);
12012 
12013 		gen_uprobe_legacy_event_name(probe_name, sizeof(probe_name),
12014 					     binary_path, func_offset);
12015 
12016 		legacy_probe = strdup(probe_name);
12017 		if (!legacy_probe)
12018 			return libbpf_err_ptr(-ENOMEM);
12019 
12020 		pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
12021 						    binary_path, func_offset, pid);
12022 	}
12023 	if (pfd < 0) {
12024 		err = -errno;
12025 		pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
12026 			prog->name, retprobe ? "uretprobe" : "uprobe",
12027 			binary_path, func_offset,
12028 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
12029 		goto err_out;
12030 	}
12031 
12032 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
12033 	err = libbpf_get_error(link);
12034 	if (err) {
12035 		close(pfd);
12036 		pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
12037 			prog->name, retprobe ? "uretprobe" : "uprobe",
12038 			binary_path, func_offset,
12039 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
12040 		goto err_clean_legacy;
12041 	}
12042 	if (legacy) {
12043 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
12044 
12045 		perf_link->legacy_probe_name = legacy_probe;
12046 		perf_link->legacy_is_kprobe = false;
12047 		perf_link->legacy_is_retprobe = retprobe;
12048 	}
12049 	return link;
12050 
12051 err_clean_legacy:
12052 	if (legacy)
12053 		remove_uprobe_event_legacy(legacy_probe, retprobe);
12054 err_out:
12055 	free(legacy_probe);
12056 	return libbpf_err_ptr(err);
12057 }
12058 
12059 /* Format of u[ret]probe section definition supporting auto-attach:
12060  * u[ret]probe/binary:function[+offset]
12061  *
12062  * binary can be an absolute/relative path or a filename; the latter is resolved to a
12063  * full binary path via bpf_program__attach_uprobe_opts.
12064  *
12065  * Specifying uprobe+ ensures we carry out strict matching; either "uprobe" must be
12066  * specified (and auto-attach is not possible) or the above format is specified for
12067  * auto-attach.
12068  */
12069 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12070 {
12071 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts);
12072 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL, *func_off;
12073 	int n, c, ret = -EINVAL;
12074 	long offset = 0;
12075 
12076 	*link = NULL;
12077 
12078 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
12079 		   &probe_type, &binary_path, &func_name);
12080 	switch (n) {
12081 	case 1:
12082 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
12083 		ret = 0;
12084 		break;
12085 	case 2:
12086 		pr_warn("prog '%s': section '%s' missing ':function[+offset]' specification\n",
12087 			prog->name, prog->sec_name);
12088 		break;
12089 	case 3:
12090 		/* check if user specifies `+offset`, if yes, this should be
12091 		 * the last part of the string, make sure sscanf read to EOL
12092 		 */
12093 		func_off = strrchr(func_name, '+');
12094 		if (func_off) {
12095 			n = sscanf(func_off, "+%li%n", &offset, &c);
12096 			if (n == 1 && *(func_off + c) == '\0')
12097 				func_off[0] = '\0';
12098 			else
12099 				offset = 0;
12100 		}
12101 		opts.retprobe = strcmp(probe_type, "uretprobe") == 0 ||
12102 				strcmp(probe_type, "uretprobe.s") == 0;
12103 		if (opts.retprobe && offset != 0) {
12104 			pr_warn("prog '%s': uretprobes do not support offset specification\n",
12105 				prog->name);
12106 			break;
12107 		}
12108 		opts.func_name = func_name;
12109 		*link = bpf_program__attach_uprobe_opts(prog, -1, binary_path, offset, &opts);
12110 		ret = libbpf_get_error(*link);
12111 		break;
12112 	default:
12113 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
12114 			prog->sec_name);
12115 		break;
12116 	}
12117 	free(probe_type);
12118 	free(binary_path);
12119 	free(func_name);
12120 
12121 	return ret;
12122 }
12123 
12124 struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
12125 					    bool retprobe, pid_t pid,
12126 					    const char *binary_path,
12127 					    size_t func_offset)
12128 {
12129 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
12130 
12131 	return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
12132 }
12133 
12134 struct bpf_link *bpf_program__attach_usdt(const struct bpf_program *prog,
12135 					  pid_t pid, const char *binary_path,
12136 					  const char *usdt_provider, const char *usdt_name,
12137 					  const struct bpf_usdt_opts *opts)
12138 {
12139 	char resolved_path[512];
12140 	struct bpf_object *obj = prog->obj;
12141 	struct bpf_link *link;
12142 	__u64 usdt_cookie;
12143 	int err;
12144 
12145 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
12146 		return libbpf_err_ptr(-EINVAL);
12147 
12148 	if (bpf_program__fd(prog) < 0) {
12149 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
12150 			prog->name);
12151 		return libbpf_err_ptr(-EINVAL);
12152 	}
12153 
12154 	if (!binary_path)
12155 		return libbpf_err_ptr(-EINVAL);
12156 
12157 	if (!strchr(binary_path, '/')) {
12158 		err = resolve_full_path(binary_path, resolved_path, sizeof(resolved_path));
12159 		if (err) {
12160 			pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
12161 				prog->name, binary_path, err);
12162 			return libbpf_err_ptr(err);
12163 		}
12164 		binary_path = resolved_path;
12165 	}
12166 
12167 	/* USDT manager is instantiated lazily on first USDT attach. It will
12168 	 * be destroyed together with BPF object in bpf_object__close().
12169 	 */
12170 	if (IS_ERR(obj->usdt_man))
12171 		return libbpf_ptr(obj->usdt_man);
12172 	if (!obj->usdt_man) {
12173 		obj->usdt_man = usdt_manager_new(obj);
12174 		if (IS_ERR(obj->usdt_man))
12175 			return libbpf_ptr(obj->usdt_man);
12176 	}
12177 
12178 	usdt_cookie = OPTS_GET(opts, usdt_cookie, 0);
12179 	link = usdt_manager_attach_usdt(obj->usdt_man, prog, pid, binary_path,
12180 					usdt_provider, usdt_name, usdt_cookie);
12181 	err = libbpf_get_error(link);
12182 	if (err)
12183 		return libbpf_err_ptr(err);
12184 	return link;
12185 }
12186 
12187 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12188 {
12189 	char *path = NULL, *provider = NULL, *name = NULL;
12190 	const char *sec_name;
12191 	int n, err;
12192 
12193 	sec_name = bpf_program__section_name(prog);
12194 	if (strcmp(sec_name, "usdt") == 0) {
12195 		/* no auto-attach for just SEC("usdt") */
12196 		*link = NULL;
12197 		return 0;
12198 	}
12199 
12200 	n = sscanf(sec_name, "usdt/%m[^:]:%m[^:]:%m[^:]", &path, &provider, &name);
12201 	if (n != 3) {
12202 		pr_warn("invalid section '%s', expected SEC(\"usdt/<path>:<provider>:<name>\")\n",
12203 			sec_name);
12204 		err = -EINVAL;
12205 	} else {
12206 		*link = bpf_program__attach_usdt(prog, -1 /* any process */, path,
12207 						 provider, name, NULL);
12208 		err = libbpf_get_error(*link);
12209 	}
12210 	free(path);
12211 	free(provider);
12212 	free(name);
12213 	return err;
12214 }
12215 
12216 static int determine_tracepoint_id(const char *tp_category,
12217 				   const char *tp_name)
12218 {
12219 	char file[PATH_MAX];
12220 	int ret;
12221 
12222 	ret = snprintf(file, sizeof(file), "%s/events/%s/%s/id",
12223 		       tracefs_path(), tp_category, tp_name);
12224 	if (ret < 0)
12225 		return -errno;
12226 	if (ret >= sizeof(file)) {
12227 		pr_debug("tracepoint %s/%s path is too long\n",
12228 			 tp_category, tp_name);
12229 		return -E2BIG;
12230 	}
12231 	return parse_uint_from_file(file, "%d\n");
12232 }
12233 
12234 static int perf_event_open_tracepoint(const char *tp_category,
12235 				      const char *tp_name)
12236 {
12237 	const size_t attr_sz = sizeof(struct perf_event_attr);
12238 	struct perf_event_attr attr;
12239 	char errmsg[STRERR_BUFSIZE];
12240 	int tp_id, pfd, err;
12241 
12242 	tp_id = determine_tracepoint_id(tp_category, tp_name);
12243 	if (tp_id < 0) {
12244 		pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
12245 			tp_category, tp_name,
12246 			libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
12247 		return tp_id;
12248 	}
12249 
12250 	memset(&attr, 0, attr_sz);
12251 	attr.type = PERF_TYPE_TRACEPOINT;
12252 	attr.size = attr_sz;
12253 	attr.config = tp_id;
12254 
12255 	pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
12256 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
12257 	if (pfd < 0) {
12258 		err = -errno;
12259 		pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
12260 			tp_category, tp_name,
12261 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
12262 		return err;
12263 	}
12264 	return pfd;
12265 }
12266 
12267 struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
12268 						     const char *tp_category,
12269 						     const char *tp_name,
12270 						     const struct bpf_tracepoint_opts *opts)
12271 {
12272 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
12273 	char errmsg[STRERR_BUFSIZE];
12274 	struct bpf_link *link;
12275 	int pfd, err;
12276 
12277 	if (!OPTS_VALID(opts, bpf_tracepoint_opts))
12278 		return libbpf_err_ptr(-EINVAL);
12279 
12280 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
12281 
12282 	pfd = perf_event_open_tracepoint(tp_category, tp_name);
12283 	if (pfd < 0) {
12284 		pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
12285 			prog->name, tp_category, tp_name,
12286 			libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
12287 		return libbpf_err_ptr(pfd);
12288 	}
12289 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
12290 	err = libbpf_get_error(link);
12291 	if (err) {
12292 		close(pfd);
12293 		pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
12294 			prog->name, tp_category, tp_name,
12295 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
12296 		return libbpf_err_ptr(err);
12297 	}
12298 	return link;
12299 }
12300 
12301 struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
12302 						const char *tp_category,
12303 						const char *tp_name)
12304 {
12305 	return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
12306 }
12307 
12308 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12309 {
12310 	char *sec_name, *tp_cat, *tp_name;
12311 
12312 	*link = NULL;
12313 
12314 	/* no auto-attach for SEC("tp") or SEC("tracepoint") */
12315 	if (strcmp(prog->sec_name, "tp") == 0 || strcmp(prog->sec_name, "tracepoint") == 0)
12316 		return 0;
12317 
12318 	sec_name = strdup(prog->sec_name);
12319 	if (!sec_name)
12320 		return -ENOMEM;
12321 
12322 	/* extract "tp/<category>/<name>" or "tracepoint/<category>/<name>" */
12323 	if (str_has_pfx(prog->sec_name, "tp/"))
12324 		tp_cat = sec_name + sizeof("tp/") - 1;
12325 	else
12326 		tp_cat = sec_name + sizeof("tracepoint/") - 1;
12327 	tp_name = strchr(tp_cat, '/');
12328 	if (!tp_name) {
12329 		free(sec_name);
12330 		return -EINVAL;
12331 	}
12332 	*tp_name = '\0';
12333 	tp_name++;
12334 
12335 	*link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
12336 	free(sec_name);
12337 	return libbpf_get_error(*link);
12338 }
12339 
12340 struct bpf_link *
12341 bpf_program__attach_raw_tracepoint_opts(const struct bpf_program *prog,
12342 					const char *tp_name,
12343 					struct bpf_raw_tracepoint_opts *opts)
12344 {
12345 	LIBBPF_OPTS(bpf_raw_tp_opts, raw_opts);
12346 	char errmsg[STRERR_BUFSIZE];
12347 	struct bpf_link *link;
12348 	int prog_fd, pfd;
12349 
12350 	if (!OPTS_VALID(opts, bpf_raw_tracepoint_opts))
12351 		return libbpf_err_ptr(-EINVAL);
12352 
12353 	prog_fd = bpf_program__fd(prog);
12354 	if (prog_fd < 0) {
12355 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12356 		return libbpf_err_ptr(-EINVAL);
12357 	}
12358 
12359 	link = calloc(1, sizeof(*link));
12360 	if (!link)
12361 		return libbpf_err_ptr(-ENOMEM);
12362 	link->detach = &bpf_link__detach_fd;
12363 
12364 	raw_opts.tp_name = tp_name;
12365 	raw_opts.cookie = OPTS_GET(opts, cookie, 0);
12366 	pfd = bpf_raw_tracepoint_open_opts(prog_fd, &raw_opts);
12367 	if (pfd < 0) {
12368 		pfd = -errno;
12369 		free(link);
12370 		pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
12371 			prog->name, tp_name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
12372 		return libbpf_err_ptr(pfd);
12373 	}
12374 	link->fd = pfd;
12375 	return link;
12376 }
12377 
12378 struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
12379 						    const char *tp_name)
12380 {
12381 	return bpf_program__attach_raw_tracepoint_opts(prog, tp_name, NULL);
12382 }
12383 
12384 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12385 {
12386 	static const char *const prefixes[] = {
12387 		"raw_tp",
12388 		"raw_tracepoint",
12389 		"raw_tp.w",
12390 		"raw_tracepoint.w",
12391 	};
12392 	size_t i;
12393 	const char *tp_name = NULL;
12394 
12395 	*link = NULL;
12396 
12397 	for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
12398 		size_t pfx_len;
12399 
12400 		if (!str_has_pfx(prog->sec_name, prefixes[i]))
12401 			continue;
12402 
12403 		pfx_len = strlen(prefixes[i]);
12404 		/* no auto-attach case of, e.g., SEC("raw_tp") */
12405 		if (prog->sec_name[pfx_len] == '\0')
12406 			return 0;
12407 
12408 		if (prog->sec_name[pfx_len] != '/')
12409 			continue;
12410 
12411 		tp_name = prog->sec_name + pfx_len + 1;
12412 		break;
12413 	}
12414 
12415 	if (!tp_name) {
12416 		pr_warn("prog '%s': invalid section name '%s'\n",
12417 			prog->name, prog->sec_name);
12418 		return -EINVAL;
12419 	}
12420 
12421 	*link = bpf_program__attach_raw_tracepoint(prog, tp_name);
12422 	return libbpf_get_error(*link);
12423 }
12424 
12425 /* Common logic for all BPF program types that attach to a btf_id */
12426 static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog,
12427 						   const struct bpf_trace_opts *opts)
12428 {
12429 	LIBBPF_OPTS(bpf_link_create_opts, link_opts);
12430 	char errmsg[STRERR_BUFSIZE];
12431 	struct bpf_link *link;
12432 	int prog_fd, pfd;
12433 
12434 	if (!OPTS_VALID(opts, bpf_trace_opts))
12435 		return libbpf_err_ptr(-EINVAL);
12436 
12437 	prog_fd = bpf_program__fd(prog);
12438 	if (prog_fd < 0) {
12439 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12440 		return libbpf_err_ptr(-EINVAL);
12441 	}
12442 
12443 	link = calloc(1, sizeof(*link));
12444 	if (!link)
12445 		return libbpf_err_ptr(-ENOMEM);
12446 	link->detach = &bpf_link__detach_fd;
12447 
12448 	/* libbpf is smart enough to redirect to BPF_RAW_TRACEPOINT_OPEN on old kernels */
12449 	link_opts.tracing.cookie = OPTS_GET(opts, cookie, 0);
12450 	pfd = bpf_link_create(prog_fd, 0, bpf_program__expected_attach_type(prog), &link_opts);
12451 	if (pfd < 0) {
12452 		pfd = -errno;
12453 		free(link);
12454 		pr_warn("prog '%s': failed to attach: %s\n",
12455 			prog->name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
12456 		return libbpf_err_ptr(pfd);
12457 	}
12458 	link->fd = pfd;
12459 	return link;
12460 }
12461 
12462 struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
12463 {
12464 	return bpf_program__attach_btf_id(prog, NULL);
12465 }
12466 
12467 struct bpf_link *bpf_program__attach_trace_opts(const struct bpf_program *prog,
12468 						const struct bpf_trace_opts *opts)
12469 {
12470 	return bpf_program__attach_btf_id(prog, opts);
12471 }
12472 
12473 struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
12474 {
12475 	return bpf_program__attach_btf_id(prog, NULL);
12476 }
12477 
12478 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12479 {
12480 	*link = bpf_program__attach_trace(prog);
12481 	return libbpf_get_error(*link);
12482 }
12483 
12484 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12485 {
12486 	*link = bpf_program__attach_lsm(prog);
12487 	return libbpf_get_error(*link);
12488 }
12489 
12490 static struct bpf_link *
12491 bpf_program_attach_fd(const struct bpf_program *prog,
12492 		      int target_fd, const char *target_name,
12493 		      const struct bpf_link_create_opts *opts)
12494 {
12495 	enum bpf_attach_type attach_type;
12496 	char errmsg[STRERR_BUFSIZE];
12497 	struct bpf_link *link;
12498 	int prog_fd, link_fd;
12499 
12500 	prog_fd = bpf_program__fd(prog);
12501 	if (prog_fd < 0) {
12502 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12503 		return libbpf_err_ptr(-EINVAL);
12504 	}
12505 
12506 	link = calloc(1, sizeof(*link));
12507 	if (!link)
12508 		return libbpf_err_ptr(-ENOMEM);
12509 	link->detach = &bpf_link__detach_fd;
12510 
12511 	attach_type = bpf_program__expected_attach_type(prog);
12512 	link_fd = bpf_link_create(prog_fd, target_fd, attach_type, opts);
12513 	if (link_fd < 0) {
12514 		link_fd = -errno;
12515 		free(link);
12516 		pr_warn("prog '%s': failed to attach to %s: %s\n",
12517 			prog->name, target_name,
12518 			libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
12519 		return libbpf_err_ptr(link_fd);
12520 	}
12521 	link->fd = link_fd;
12522 	return link;
12523 }
12524 
12525 struct bpf_link *
12526 bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
12527 {
12528 	return bpf_program_attach_fd(prog, cgroup_fd, "cgroup", NULL);
12529 }
12530 
12531 struct bpf_link *
12532 bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
12533 {
12534 	return bpf_program_attach_fd(prog, netns_fd, "netns", NULL);
12535 }
12536 
12537 struct bpf_link *
12538 bpf_program__attach_sockmap(const struct bpf_program *prog, int map_fd)
12539 {
12540 	return bpf_program_attach_fd(prog, map_fd, "sockmap", NULL);
12541 }
12542 
12543 struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
12544 {
12545 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
12546 	return bpf_program_attach_fd(prog, ifindex, "xdp", NULL);
12547 }
12548 
12549 struct bpf_link *
12550 bpf_program__attach_tcx(const struct bpf_program *prog, int ifindex,
12551 			const struct bpf_tcx_opts *opts)
12552 {
12553 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12554 	__u32 relative_id;
12555 	int relative_fd;
12556 
12557 	if (!OPTS_VALID(opts, bpf_tcx_opts))
12558 		return libbpf_err_ptr(-EINVAL);
12559 
12560 	relative_id = OPTS_GET(opts, relative_id, 0);
12561 	relative_fd = OPTS_GET(opts, relative_fd, 0);
12562 
12563 	/* validate we don't have unexpected combinations of non-zero fields */
12564 	if (!ifindex) {
12565 		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
12566 			prog->name);
12567 		return libbpf_err_ptr(-EINVAL);
12568 	}
12569 	if (relative_fd && relative_id) {
12570 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
12571 			prog->name);
12572 		return libbpf_err_ptr(-EINVAL);
12573 	}
12574 
12575 	link_create_opts.tcx.expected_revision = OPTS_GET(opts, expected_revision, 0);
12576 	link_create_opts.tcx.relative_fd = relative_fd;
12577 	link_create_opts.tcx.relative_id = relative_id;
12578 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
12579 
12580 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
12581 	return bpf_program_attach_fd(prog, ifindex, "tcx", &link_create_opts);
12582 }
12583 
12584 struct bpf_link *
12585 bpf_program__attach_netkit(const struct bpf_program *prog, int ifindex,
12586 			   const struct bpf_netkit_opts *opts)
12587 {
12588 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12589 	__u32 relative_id;
12590 	int relative_fd;
12591 
12592 	if (!OPTS_VALID(opts, bpf_netkit_opts))
12593 		return libbpf_err_ptr(-EINVAL);
12594 
12595 	relative_id = OPTS_GET(opts, relative_id, 0);
12596 	relative_fd = OPTS_GET(opts, relative_fd, 0);
12597 
12598 	/* validate we don't have unexpected combinations of non-zero fields */
12599 	if (!ifindex) {
12600 		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
12601 			prog->name);
12602 		return libbpf_err_ptr(-EINVAL);
12603 	}
12604 	if (relative_fd && relative_id) {
12605 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
12606 			prog->name);
12607 		return libbpf_err_ptr(-EINVAL);
12608 	}
12609 
12610 	link_create_opts.netkit.expected_revision = OPTS_GET(opts, expected_revision, 0);
12611 	link_create_opts.netkit.relative_fd = relative_fd;
12612 	link_create_opts.netkit.relative_id = relative_id;
12613 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
12614 
12615 	return bpf_program_attach_fd(prog, ifindex, "netkit", &link_create_opts);
12616 }
12617 
12618 struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
12619 					      int target_fd,
12620 					      const char *attach_func_name)
12621 {
12622 	int btf_id;
12623 
12624 	if (!!target_fd != !!attach_func_name) {
12625 		pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
12626 			prog->name);
12627 		return libbpf_err_ptr(-EINVAL);
12628 	}
12629 
12630 	if (prog->type != BPF_PROG_TYPE_EXT) {
12631 		pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace",
12632 			prog->name);
12633 		return libbpf_err_ptr(-EINVAL);
12634 	}
12635 
12636 	if (target_fd) {
12637 		LIBBPF_OPTS(bpf_link_create_opts, target_opts);
12638 
12639 		btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd);
12640 		if (btf_id < 0)
12641 			return libbpf_err_ptr(btf_id);
12642 
12643 		target_opts.target_btf_id = btf_id;
12644 
12645 		return bpf_program_attach_fd(prog, target_fd, "freplace",
12646 					     &target_opts);
12647 	} else {
12648 		/* no target, so use raw_tracepoint_open for compatibility
12649 		 * with old kernels
12650 		 */
12651 		return bpf_program__attach_trace(prog);
12652 	}
12653 }
12654 
12655 struct bpf_link *
12656 bpf_program__attach_iter(const struct bpf_program *prog,
12657 			 const struct bpf_iter_attach_opts *opts)
12658 {
12659 	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12660 	char errmsg[STRERR_BUFSIZE];
12661 	struct bpf_link *link;
12662 	int prog_fd, link_fd;
12663 	__u32 target_fd = 0;
12664 
12665 	if (!OPTS_VALID(opts, bpf_iter_attach_opts))
12666 		return libbpf_err_ptr(-EINVAL);
12667 
12668 	link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
12669 	link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
12670 
12671 	prog_fd = bpf_program__fd(prog);
12672 	if (prog_fd < 0) {
12673 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12674 		return libbpf_err_ptr(-EINVAL);
12675 	}
12676 
12677 	link = calloc(1, sizeof(*link));
12678 	if (!link)
12679 		return libbpf_err_ptr(-ENOMEM);
12680 	link->detach = &bpf_link__detach_fd;
12681 
12682 	link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
12683 				  &link_create_opts);
12684 	if (link_fd < 0) {
12685 		link_fd = -errno;
12686 		free(link);
12687 		pr_warn("prog '%s': failed to attach to iterator: %s\n",
12688 			prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
12689 		return libbpf_err_ptr(link_fd);
12690 	}
12691 	link->fd = link_fd;
12692 	return link;
12693 }
12694 
12695 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12696 {
12697 	*link = bpf_program__attach_iter(prog, NULL);
12698 	return libbpf_get_error(*link);
12699 }
12700 
12701 struct bpf_link *bpf_program__attach_netfilter(const struct bpf_program *prog,
12702 					       const struct bpf_netfilter_opts *opts)
12703 {
12704 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
12705 	struct bpf_link *link;
12706 	int prog_fd, link_fd;
12707 
12708 	if (!OPTS_VALID(opts, bpf_netfilter_opts))
12709 		return libbpf_err_ptr(-EINVAL);
12710 
12711 	prog_fd = bpf_program__fd(prog);
12712 	if (prog_fd < 0) {
12713 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12714 		return libbpf_err_ptr(-EINVAL);
12715 	}
12716 
12717 	link = calloc(1, sizeof(*link));
12718 	if (!link)
12719 		return libbpf_err_ptr(-ENOMEM);
12720 
12721 	link->detach = &bpf_link__detach_fd;
12722 
12723 	lopts.netfilter.pf = OPTS_GET(opts, pf, 0);
12724 	lopts.netfilter.hooknum = OPTS_GET(opts, hooknum, 0);
12725 	lopts.netfilter.priority = OPTS_GET(opts, priority, 0);
12726 	lopts.netfilter.flags = OPTS_GET(opts, flags, 0);
12727 
12728 	link_fd = bpf_link_create(prog_fd, 0, BPF_NETFILTER, &lopts);
12729 	if (link_fd < 0) {
12730 		char errmsg[STRERR_BUFSIZE];
12731 
12732 		link_fd = -errno;
12733 		free(link);
12734 		pr_warn("prog '%s': failed to attach to netfilter: %s\n",
12735 			prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
12736 		return libbpf_err_ptr(link_fd);
12737 	}
12738 	link->fd = link_fd;
12739 
12740 	return link;
12741 }
12742 
12743 struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
12744 {
12745 	struct bpf_link *link = NULL;
12746 	int err;
12747 
12748 	if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
12749 		return libbpf_err_ptr(-EOPNOTSUPP);
12750 
12751 	if (bpf_program__fd(prog) < 0) {
12752 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
12753 			prog->name);
12754 		return libbpf_err_ptr(-EINVAL);
12755 	}
12756 
12757 	err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, &link);
12758 	if (err)
12759 		return libbpf_err_ptr(err);
12760 
12761 	/* When calling bpf_program__attach() explicitly, auto-attach support
12762 	 * is expected to work, so NULL returned link is considered an error.
12763 	 * This is different for skeleton's attach, see comment in
12764 	 * bpf_object__attach_skeleton().
12765 	 */
12766 	if (!link)
12767 		return libbpf_err_ptr(-EOPNOTSUPP);
12768 
12769 	return link;
12770 }
12771 
12772 struct bpf_link_struct_ops {
12773 	struct bpf_link link;
12774 	int map_fd;
12775 };
12776 
12777 static int bpf_link__detach_struct_ops(struct bpf_link *link)
12778 {
12779 	struct bpf_link_struct_ops *st_link;
12780 	__u32 zero = 0;
12781 
12782 	st_link = container_of(link, struct bpf_link_struct_ops, link);
12783 
12784 	if (st_link->map_fd < 0)
12785 		/* w/o a real link */
12786 		return bpf_map_delete_elem(link->fd, &zero);
12787 
12788 	return close(link->fd);
12789 }
12790 
12791 struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
12792 {
12793 	struct bpf_link_struct_ops *link;
12794 	__u32 zero = 0;
12795 	int err, fd;
12796 
12797 	if (!bpf_map__is_struct_ops(map))
12798 		return libbpf_err_ptr(-EINVAL);
12799 
12800 	if (map->fd < 0) {
12801 		pr_warn("map '%s': can't attach BPF map without FD (was it created?)\n", map->name);
12802 		return libbpf_err_ptr(-EINVAL);
12803 	}
12804 
12805 	link = calloc(1, sizeof(*link));
12806 	if (!link)
12807 		return libbpf_err_ptr(-EINVAL);
12808 
12809 	/* kern_vdata should be prepared during the loading phase. */
12810 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
12811 	/* It can be EBUSY if the map has been used to create or
12812 	 * update a link before.  We don't allow updating the value of
12813 	 * a struct_ops once it is set.  That ensures that the value
12814 	 * never changed.  So, it is safe to skip EBUSY.
12815 	 */
12816 	if (err && (!(map->def.map_flags & BPF_F_LINK) || err != -EBUSY)) {
12817 		free(link);
12818 		return libbpf_err_ptr(err);
12819 	}
12820 
12821 	link->link.detach = bpf_link__detach_struct_ops;
12822 
12823 	if (!(map->def.map_flags & BPF_F_LINK)) {
12824 		/* w/o a real link */
12825 		link->link.fd = map->fd;
12826 		link->map_fd = -1;
12827 		return &link->link;
12828 	}
12829 
12830 	fd = bpf_link_create(map->fd, 0, BPF_STRUCT_OPS, NULL);
12831 	if (fd < 0) {
12832 		free(link);
12833 		return libbpf_err_ptr(fd);
12834 	}
12835 
12836 	link->link.fd = fd;
12837 	link->map_fd = map->fd;
12838 
12839 	return &link->link;
12840 }
12841 
12842 /*
12843  * Swap the back struct_ops of a link with a new struct_ops map.
12844  */
12845 int bpf_link__update_map(struct bpf_link *link, const struct bpf_map *map)
12846 {
12847 	struct bpf_link_struct_ops *st_ops_link;
12848 	__u32 zero = 0;
12849 	int err;
12850 
12851 	if (!bpf_map__is_struct_ops(map))
12852 		return -EINVAL;
12853 
12854 	if (map->fd < 0) {
12855 		pr_warn("map '%s': can't use BPF map without FD (was it created?)\n", map->name);
12856 		return -EINVAL;
12857 	}
12858 
12859 	st_ops_link = container_of(link, struct bpf_link_struct_ops, link);
12860 	/* Ensure the type of a link is correct */
12861 	if (st_ops_link->map_fd < 0)
12862 		return -EINVAL;
12863 
12864 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
12865 	/* It can be EBUSY if the map has been used to create or
12866 	 * update a link before.  We don't allow updating the value of
12867 	 * a struct_ops once it is set.  That ensures that the value
12868 	 * never changed.  So, it is safe to skip EBUSY.
12869 	 */
12870 	if (err && err != -EBUSY)
12871 		return err;
12872 
12873 	err = bpf_link_update(link->fd, map->fd, NULL);
12874 	if (err < 0)
12875 		return err;
12876 
12877 	st_ops_link->map_fd = map->fd;
12878 
12879 	return 0;
12880 }
12881 
12882 typedef enum bpf_perf_event_ret (*bpf_perf_event_print_t)(struct perf_event_header *hdr,
12883 							  void *private_data);
12884 
12885 static enum bpf_perf_event_ret
12886 perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
12887 		       void **copy_mem, size_t *copy_size,
12888 		       bpf_perf_event_print_t fn, void *private_data)
12889 {
12890 	struct perf_event_mmap_page *header = mmap_mem;
12891 	__u64 data_head = ring_buffer_read_head(header);
12892 	__u64 data_tail = header->data_tail;
12893 	void *base = ((__u8 *)header) + page_size;
12894 	int ret = LIBBPF_PERF_EVENT_CONT;
12895 	struct perf_event_header *ehdr;
12896 	size_t ehdr_size;
12897 
12898 	while (data_head != data_tail) {
12899 		ehdr = base + (data_tail & (mmap_size - 1));
12900 		ehdr_size = ehdr->size;
12901 
12902 		if (((void *)ehdr) + ehdr_size > base + mmap_size) {
12903 			void *copy_start = ehdr;
12904 			size_t len_first = base + mmap_size - copy_start;
12905 			size_t len_secnd = ehdr_size - len_first;
12906 
12907 			if (*copy_size < ehdr_size) {
12908 				free(*copy_mem);
12909 				*copy_mem = malloc(ehdr_size);
12910 				if (!*copy_mem) {
12911 					*copy_size = 0;
12912 					ret = LIBBPF_PERF_EVENT_ERROR;
12913 					break;
12914 				}
12915 				*copy_size = ehdr_size;
12916 			}
12917 
12918 			memcpy(*copy_mem, copy_start, len_first);
12919 			memcpy(*copy_mem + len_first, base, len_secnd);
12920 			ehdr = *copy_mem;
12921 		}
12922 
12923 		ret = fn(ehdr, private_data);
12924 		data_tail += ehdr_size;
12925 		if (ret != LIBBPF_PERF_EVENT_CONT)
12926 			break;
12927 	}
12928 
12929 	ring_buffer_write_tail(header, data_tail);
12930 	return libbpf_err(ret);
12931 }
12932 
12933 struct perf_buffer;
12934 
12935 struct perf_buffer_params {
12936 	struct perf_event_attr *attr;
12937 	/* if event_cb is specified, it takes precendence */
12938 	perf_buffer_event_fn event_cb;
12939 	/* sample_cb and lost_cb are higher-level common-case callbacks */
12940 	perf_buffer_sample_fn sample_cb;
12941 	perf_buffer_lost_fn lost_cb;
12942 	void *ctx;
12943 	int cpu_cnt;
12944 	int *cpus;
12945 	int *map_keys;
12946 };
12947 
12948 struct perf_cpu_buf {
12949 	struct perf_buffer *pb;
12950 	void *base; /* mmap()'ed memory */
12951 	void *buf; /* for reconstructing segmented data */
12952 	size_t buf_size;
12953 	int fd;
12954 	int cpu;
12955 	int map_key;
12956 };
12957 
12958 struct perf_buffer {
12959 	perf_buffer_event_fn event_cb;
12960 	perf_buffer_sample_fn sample_cb;
12961 	perf_buffer_lost_fn lost_cb;
12962 	void *ctx; /* passed into callbacks */
12963 
12964 	size_t page_size;
12965 	size_t mmap_size;
12966 	struct perf_cpu_buf **cpu_bufs;
12967 	struct epoll_event *events;
12968 	int cpu_cnt; /* number of allocated CPU buffers */
12969 	int epoll_fd; /* perf event FD */
12970 	int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
12971 };
12972 
12973 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
12974 				      struct perf_cpu_buf *cpu_buf)
12975 {
12976 	if (!cpu_buf)
12977 		return;
12978 	if (cpu_buf->base &&
12979 	    munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
12980 		pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
12981 	if (cpu_buf->fd >= 0) {
12982 		ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
12983 		close(cpu_buf->fd);
12984 	}
12985 	free(cpu_buf->buf);
12986 	free(cpu_buf);
12987 }
12988 
12989 void perf_buffer__free(struct perf_buffer *pb)
12990 {
12991 	int i;
12992 
12993 	if (IS_ERR_OR_NULL(pb))
12994 		return;
12995 	if (pb->cpu_bufs) {
12996 		for (i = 0; i < pb->cpu_cnt; i++) {
12997 			struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
12998 
12999 			if (!cpu_buf)
13000 				continue;
13001 
13002 			bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
13003 			perf_buffer__free_cpu_buf(pb, cpu_buf);
13004 		}
13005 		free(pb->cpu_bufs);
13006 	}
13007 	if (pb->epoll_fd >= 0)
13008 		close(pb->epoll_fd);
13009 	free(pb->events);
13010 	free(pb);
13011 }
13012 
13013 static struct perf_cpu_buf *
13014 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
13015 			  int cpu, int map_key)
13016 {
13017 	struct perf_cpu_buf *cpu_buf;
13018 	char msg[STRERR_BUFSIZE];
13019 	int err;
13020 
13021 	cpu_buf = calloc(1, sizeof(*cpu_buf));
13022 	if (!cpu_buf)
13023 		return ERR_PTR(-ENOMEM);
13024 
13025 	cpu_buf->pb = pb;
13026 	cpu_buf->cpu = cpu;
13027 	cpu_buf->map_key = map_key;
13028 
13029 	cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
13030 			      -1, PERF_FLAG_FD_CLOEXEC);
13031 	if (cpu_buf->fd < 0) {
13032 		err = -errno;
13033 		pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
13034 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
13035 		goto error;
13036 	}
13037 
13038 	cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
13039 			     PROT_READ | PROT_WRITE, MAP_SHARED,
13040 			     cpu_buf->fd, 0);
13041 	if (cpu_buf->base == MAP_FAILED) {
13042 		cpu_buf->base = NULL;
13043 		err = -errno;
13044 		pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
13045 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
13046 		goto error;
13047 	}
13048 
13049 	if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
13050 		err = -errno;
13051 		pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
13052 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
13053 		goto error;
13054 	}
13055 
13056 	return cpu_buf;
13057 
13058 error:
13059 	perf_buffer__free_cpu_buf(pb, cpu_buf);
13060 	return (struct perf_cpu_buf *)ERR_PTR(err);
13061 }
13062 
13063 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
13064 					      struct perf_buffer_params *p);
13065 
13066 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
13067 				     perf_buffer_sample_fn sample_cb,
13068 				     perf_buffer_lost_fn lost_cb,
13069 				     void *ctx,
13070 				     const struct perf_buffer_opts *opts)
13071 {
13072 	const size_t attr_sz = sizeof(struct perf_event_attr);
13073 	struct perf_buffer_params p = {};
13074 	struct perf_event_attr attr;
13075 	__u32 sample_period;
13076 
13077 	if (!OPTS_VALID(opts, perf_buffer_opts))
13078 		return libbpf_err_ptr(-EINVAL);
13079 
13080 	sample_period = OPTS_GET(opts, sample_period, 1);
13081 	if (!sample_period)
13082 		sample_period = 1;
13083 
13084 	memset(&attr, 0, attr_sz);
13085 	attr.size = attr_sz;
13086 	attr.config = PERF_COUNT_SW_BPF_OUTPUT;
13087 	attr.type = PERF_TYPE_SOFTWARE;
13088 	attr.sample_type = PERF_SAMPLE_RAW;
13089 	attr.sample_period = sample_period;
13090 	attr.wakeup_events = sample_period;
13091 
13092 	p.attr = &attr;
13093 	p.sample_cb = sample_cb;
13094 	p.lost_cb = lost_cb;
13095 	p.ctx = ctx;
13096 
13097 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
13098 }
13099 
13100 struct perf_buffer *perf_buffer__new_raw(int map_fd, size_t page_cnt,
13101 					 struct perf_event_attr *attr,
13102 					 perf_buffer_event_fn event_cb, void *ctx,
13103 					 const struct perf_buffer_raw_opts *opts)
13104 {
13105 	struct perf_buffer_params p = {};
13106 
13107 	if (!attr)
13108 		return libbpf_err_ptr(-EINVAL);
13109 
13110 	if (!OPTS_VALID(opts, perf_buffer_raw_opts))
13111 		return libbpf_err_ptr(-EINVAL);
13112 
13113 	p.attr = attr;
13114 	p.event_cb = event_cb;
13115 	p.ctx = ctx;
13116 	p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
13117 	p.cpus = OPTS_GET(opts, cpus, NULL);
13118 	p.map_keys = OPTS_GET(opts, map_keys, NULL);
13119 
13120 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
13121 }
13122 
13123 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
13124 					      struct perf_buffer_params *p)
13125 {
13126 	const char *online_cpus_file = "/sys/devices/system/cpu/online";
13127 	struct bpf_map_info map;
13128 	char msg[STRERR_BUFSIZE];
13129 	struct perf_buffer *pb;
13130 	bool *online = NULL;
13131 	__u32 map_info_len;
13132 	int err, i, j, n;
13133 
13134 	if (page_cnt == 0 || (page_cnt & (page_cnt - 1))) {
13135 		pr_warn("page count should be power of two, but is %zu\n",
13136 			page_cnt);
13137 		return ERR_PTR(-EINVAL);
13138 	}
13139 
13140 	/* best-effort sanity checks */
13141 	memset(&map, 0, sizeof(map));
13142 	map_info_len = sizeof(map);
13143 	err = bpf_map_get_info_by_fd(map_fd, &map, &map_info_len);
13144 	if (err) {
13145 		err = -errno;
13146 		/* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
13147 		 * -EBADFD, -EFAULT, or -E2BIG on real error
13148 		 */
13149 		if (err != -EINVAL) {
13150 			pr_warn("failed to get map info for map FD %d: %s\n",
13151 				map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
13152 			return ERR_PTR(err);
13153 		}
13154 		pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
13155 			 map_fd);
13156 	} else {
13157 		if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
13158 			pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
13159 				map.name);
13160 			return ERR_PTR(-EINVAL);
13161 		}
13162 	}
13163 
13164 	pb = calloc(1, sizeof(*pb));
13165 	if (!pb)
13166 		return ERR_PTR(-ENOMEM);
13167 
13168 	pb->event_cb = p->event_cb;
13169 	pb->sample_cb = p->sample_cb;
13170 	pb->lost_cb = p->lost_cb;
13171 	pb->ctx = p->ctx;
13172 
13173 	pb->page_size = getpagesize();
13174 	pb->mmap_size = pb->page_size * page_cnt;
13175 	pb->map_fd = map_fd;
13176 
13177 	pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
13178 	if (pb->epoll_fd < 0) {
13179 		err = -errno;
13180 		pr_warn("failed to create epoll instance: %s\n",
13181 			libbpf_strerror_r(err, msg, sizeof(msg)));
13182 		goto error;
13183 	}
13184 
13185 	if (p->cpu_cnt > 0) {
13186 		pb->cpu_cnt = p->cpu_cnt;
13187 	} else {
13188 		pb->cpu_cnt = libbpf_num_possible_cpus();
13189 		if (pb->cpu_cnt < 0) {
13190 			err = pb->cpu_cnt;
13191 			goto error;
13192 		}
13193 		if (map.max_entries && map.max_entries < pb->cpu_cnt)
13194 			pb->cpu_cnt = map.max_entries;
13195 	}
13196 
13197 	pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
13198 	if (!pb->events) {
13199 		err = -ENOMEM;
13200 		pr_warn("failed to allocate events: out of memory\n");
13201 		goto error;
13202 	}
13203 	pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
13204 	if (!pb->cpu_bufs) {
13205 		err = -ENOMEM;
13206 		pr_warn("failed to allocate buffers: out of memory\n");
13207 		goto error;
13208 	}
13209 
13210 	err = parse_cpu_mask_file(online_cpus_file, &online, &n);
13211 	if (err) {
13212 		pr_warn("failed to get online CPU mask: %d\n", err);
13213 		goto error;
13214 	}
13215 
13216 	for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
13217 		struct perf_cpu_buf *cpu_buf;
13218 		int cpu, map_key;
13219 
13220 		cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
13221 		map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
13222 
13223 		/* in case user didn't explicitly requested particular CPUs to
13224 		 * be attached to, skip offline/not present CPUs
13225 		 */
13226 		if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
13227 			continue;
13228 
13229 		cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
13230 		if (IS_ERR(cpu_buf)) {
13231 			err = PTR_ERR(cpu_buf);
13232 			goto error;
13233 		}
13234 
13235 		pb->cpu_bufs[j] = cpu_buf;
13236 
13237 		err = bpf_map_update_elem(pb->map_fd, &map_key,
13238 					  &cpu_buf->fd, 0);
13239 		if (err) {
13240 			err = -errno;
13241 			pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
13242 				cpu, map_key, cpu_buf->fd,
13243 				libbpf_strerror_r(err, msg, sizeof(msg)));
13244 			goto error;
13245 		}
13246 
13247 		pb->events[j].events = EPOLLIN;
13248 		pb->events[j].data.ptr = cpu_buf;
13249 		if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
13250 			      &pb->events[j]) < 0) {
13251 			err = -errno;
13252 			pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
13253 				cpu, cpu_buf->fd,
13254 				libbpf_strerror_r(err, msg, sizeof(msg)));
13255 			goto error;
13256 		}
13257 		j++;
13258 	}
13259 	pb->cpu_cnt = j;
13260 	free(online);
13261 
13262 	return pb;
13263 
13264 error:
13265 	free(online);
13266 	if (pb)
13267 		perf_buffer__free(pb);
13268 	return ERR_PTR(err);
13269 }
13270 
13271 struct perf_sample_raw {
13272 	struct perf_event_header header;
13273 	uint32_t size;
13274 	char data[];
13275 };
13276 
13277 struct perf_sample_lost {
13278 	struct perf_event_header header;
13279 	uint64_t id;
13280 	uint64_t lost;
13281 	uint64_t sample_id;
13282 };
13283 
13284 static enum bpf_perf_event_ret
13285 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
13286 {
13287 	struct perf_cpu_buf *cpu_buf = ctx;
13288 	struct perf_buffer *pb = cpu_buf->pb;
13289 	void *data = e;
13290 
13291 	/* user wants full control over parsing perf event */
13292 	if (pb->event_cb)
13293 		return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
13294 
13295 	switch (e->type) {
13296 	case PERF_RECORD_SAMPLE: {
13297 		struct perf_sample_raw *s = data;
13298 
13299 		if (pb->sample_cb)
13300 			pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
13301 		break;
13302 	}
13303 	case PERF_RECORD_LOST: {
13304 		struct perf_sample_lost *s = data;
13305 
13306 		if (pb->lost_cb)
13307 			pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
13308 		break;
13309 	}
13310 	default:
13311 		pr_warn("unknown perf sample type %d\n", e->type);
13312 		return LIBBPF_PERF_EVENT_ERROR;
13313 	}
13314 	return LIBBPF_PERF_EVENT_CONT;
13315 }
13316 
13317 static int perf_buffer__process_records(struct perf_buffer *pb,
13318 					struct perf_cpu_buf *cpu_buf)
13319 {
13320 	enum bpf_perf_event_ret ret;
13321 
13322 	ret = perf_event_read_simple(cpu_buf->base, pb->mmap_size,
13323 				     pb->page_size, &cpu_buf->buf,
13324 				     &cpu_buf->buf_size,
13325 				     perf_buffer__process_record, cpu_buf);
13326 	if (ret != LIBBPF_PERF_EVENT_CONT)
13327 		return ret;
13328 	return 0;
13329 }
13330 
13331 int perf_buffer__epoll_fd(const struct perf_buffer *pb)
13332 {
13333 	return pb->epoll_fd;
13334 }
13335 
13336 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
13337 {
13338 	int i, cnt, err;
13339 
13340 	cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
13341 	if (cnt < 0)
13342 		return -errno;
13343 
13344 	for (i = 0; i < cnt; i++) {
13345 		struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
13346 
13347 		err = perf_buffer__process_records(pb, cpu_buf);
13348 		if (err) {
13349 			pr_warn("error while processing records: %d\n", err);
13350 			return libbpf_err(err);
13351 		}
13352 	}
13353 	return cnt;
13354 }
13355 
13356 /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
13357  * manager.
13358  */
13359 size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
13360 {
13361 	return pb->cpu_cnt;
13362 }
13363 
13364 /*
13365  * Return perf_event FD of a ring buffer in *buf_idx* slot of
13366  * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
13367  * select()/poll()/epoll() Linux syscalls.
13368  */
13369 int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
13370 {
13371 	struct perf_cpu_buf *cpu_buf;
13372 
13373 	if (buf_idx >= pb->cpu_cnt)
13374 		return libbpf_err(-EINVAL);
13375 
13376 	cpu_buf = pb->cpu_bufs[buf_idx];
13377 	if (!cpu_buf)
13378 		return libbpf_err(-ENOENT);
13379 
13380 	return cpu_buf->fd;
13381 }
13382 
13383 int perf_buffer__buffer(struct perf_buffer *pb, int buf_idx, void **buf, size_t *buf_size)
13384 {
13385 	struct perf_cpu_buf *cpu_buf;
13386 
13387 	if (buf_idx >= pb->cpu_cnt)
13388 		return libbpf_err(-EINVAL);
13389 
13390 	cpu_buf = pb->cpu_bufs[buf_idx];
13391 	if (!cpu_buf)
13392 		return libbpf_err(-ENOENT);
13393 
13394 	*buf = cpu_buf->base;
13395 	*buf_size = pb->mmap_size;
13396 	return 0;
13397 }
13398 
13399 /*
13400  * Consume data from perf ring buffer corresponding to slot *buf_idx* in
13401  * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
13402  * consume, do nothing and return success.
13403  * Returns:
13404  *   - 0 on success;
13405  *   - <0 on failure.
13406  */
13407 int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
13408 {
13409 	struct perf_cpu_buf *cpu_buf;
13410 
13411 	if (buf_idx >= pb->cpu_cnt)
13412 		return libbpf_err(-EINVAL);
13413 
13414 	cpu_buf = pb->cpu_bufs[buf_idx];
13415 	if (!cpu_buf)
13416 		return libbpf_err(-ENOENT);
13417 
13418 	return perf_buffer__process_records(pb, cpu_buf);
13419 }
13420 
13421 int perf_buffer__consume(struct perf_buffer *pb)
13422 {
13423 	int i, err;
13424 
13425 	for (i = 0; i < pb->cpu_cnt; i++) {
13426 		struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
13427 
13428 		if (!cpu_buf)
13429 			continue;
13430 
13431 		err = perf_buffer__process_records(pb, cpu_buf);
13432 		if (err) {
13433 			pr_warn("perf_buffer: failed to process records in buffer #%d: %d\n", i, err);
13434 			return libbpf_err(err);
13435 		}
13436 	}
13437 	return 0;
13438 }
13439 
13440 int bpf_program__set_attach_target(struct bpf_program *prog,
13441 				   int attach_prog_fd,
13442 				   const char *attach_func_name)
13443 {
13444 	int btf_obj_fd = 0, btf_id = 0, err;
13445 
13446 	if (!prog || attach_prog_fd < 0)
13447 		return libbpf_err(-EINVAL);
13448 
13449 	if (prog->obj->loaded)
13450 		return libbpf_err(-EINVAL);
13451 
13452 	if (attach_prog_fd && !attach_func_name) {
13453 		/* remember attach_prog_fd and let bpf_program__load() find
13454 		 * BTF ID during the program load
13455 		 */
13456 		prog->attach_prog_fd = attach_prog_fd;
13457 		return 0;
13458 	}
13459 
13460 	if (attach_prog_fd) {
13461 		btf_id = libbpf_find_prog_btf_id(attach_func_name,
13462 						 attach_prog_fd);
13463 		if (btf_id < 0)
13464 			return libbpf_err(btf_id);
13465 	} else {
13466 		if (!attach_func_name)
13467 			return libbpf_err(-EINVAL);
13468 
13469 		/* load btf_vmlinux, if not yet */
13470 		err = bpf_object__load_vmlinux_btf(prog->obj, true);
13471 		if (err)
13472 			return libbpf_err(err);
13473 		err = find_kernel_btf_id(prog->obj, attach_func_name,
13474 					 prog->expected_attach_type,
13475 					 &btf_obj_fd, &btf_id);
13476 		if (err)
13477 			return libbpf_err(err);
13478 	}
13479 
13480 	prog->attach_btf_id = btf_id;
13481 	prog->attach_btf_obj_fd = btf_obj_fd;
13482 	prog->attach_prog_fd = attach_prog_fd;
13483 	return 0;
13484 }
13485 
13486 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
13487 {
13488 	int err = 0, n, len, start, end = -1;
13489 	bool *tmp;
13490 
13491 	*mask = NULL;
13492 	*mask_sz = 0;
13493 
13494 	/* Each sub string separated by ',' has format \d+-\d+ or \d+ */
13495 	while (*s) {
13496 		if (*s == ',' || *s == '\n') {
13497 			s++;
13498 			continue;
13499 		}
13500 		n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
13501 		if (n <= 0 || n > 2) {
13502 			pr_warn("Failed to get CPU range %s: %d\n", s, n);
13503 			err = -EINVAL;
13504 			goto cleanup;
13505 		} else if (n == 1) {
13506 			end = start;
13507 		}
13508 		if (start < 0 || start > end) {
13509 			pr_warn("Invalid CPU range [%d,%d] in %s\n",
13510 				start, end, s);
13511 			err = -EINVAL;
13512 			goto cleanup;
13513 		}
13514 		tmp = realloc(*mask, end + 1);
13515 		if (!tmp) {
13516 			err = -ENOMEM;
13517 			goto cleanup;
13518 		}
13519 		*mask = tmp;
13520 		memset(tmp + *mask_sz, 0, start - *mask_sz);
13521 		memset(tmp + start, 1, end - start + 1);
13522 		*mask_sz = end + 1;
13523 		s += len;
13524 	}
13525 	if (!*mask_sz) {
13526 		pr_warn("Empty CPU range\n");
13527 		return -EINVAL;
13528 	}
13529 	return 0;
13530 cleanup:
13531 	free(*mask);
13532 	*mask = NULL;
13533 	return err;
13534 }
13535 
13536 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
13537 {
13538 	int fd, err = 0, len;
13539 	char buf[128];
13540 
13541 	fd = open(fcpu, O_RDONLY | O_CLOEXEC);
13542 	if (fd < 0) {
13543 		err = -errno;
13544 		pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
13545 		return err;
13546 	}
13547 	len = read(fd, buf, sizeof(buf));
13548 	close(fd);
13549 	if (len <= 0) {
13550 		err = len ? -errno : -EINVAL;
13551 		pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
13552 		return err;
13553 	}
13554 	if (len >= sizeof(buf)) {
13555 		pr_warn("CPU mask is too big in file %s\n", fcpu);
13556 		return -E2BIG;
13557 	}
13558 	buf[len] = '\0';
13559 
13560 	return parse_cpu_mask_str(buf, mask, mask_sz);
13561 }
13562 
13563 int libbpf_num_possible_cpus(void)
13564 {
13565 	static const char *fcpu = "/sys/devices/system/cpu/possible";
13566 	static int cpus;
13567 	int err, n, i, tmp_cpus;
13568 	bool *mask;
13569 
13570 	tmp_cpus = READ_ONCE(cpus);
13571 	if (tmp_cpus > 0)
13572 		return tmp_cpus;
13573 
13574 	err = parse_cpu_mask_file(fcpu, &mask, &n);
13575 	if (err)
13576 		return libbpf_err(err);
13577 
13578 	tmp_cpus = 0;
13579 	for (i = 0; i < n; i++) {
13580 		if (mask[i])
13581 			tmp_cpus++;
13582 	}
13583 	free(mask);
13584 
13585 	WRITE_ONCE(cpus, tmp_cpus);
13586 	return tmp_cpus;
13587 }
13588 
13589 static int populate_skeleton_maps(const struct bpf_object *obj,
13590 				  struct bpf_map_skeleton *maps,
13591 				  size_t map_cnt)
13592 {
13593 	int i;
13594 
13595 	for (i = 0; i < map_cnt; i++) {
13596 		struct bpf_map **map = maps[i].map;
13597 		const char *name = maps[i].name;
13598 		void **mmaped = maps[i].mmaped;
13599 
13600 		*map = bpf_object__find_map_by_name(obj, name);
13601 		if (!*map) {
13602 			pr_warn("failed to find skeleton map '%s'\n", name);
13603 			return -ESRCH;
13604 		}
13605 
13606 		/* externs shouldn't be pre-setup from user code */
13607 		if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
13608 			*mmaped = (*map)->mmaped;
13609 	}
13610 	return 0;
13611 }
13612 
13613 static int populate_skeleton_progs(const struct bpf_object *obj,
13614 				   struct bpf_prog_skeleton *progs,
13615 				   size_t prog_cnt)
13616 {
13617 	int i;
13618 
13619 	for (i = 0; i < prog_cnt; i++) {
13620 		struct bpf_program **prog = progs[i].prog;
13621 		const char *name = progs[i].name;
13622 
13623 		*prog = bpf_object__find_program_by_name(obj, name);
13624 		if (!*prog) {
13625 			pr_warn("failed to find skeleton program '%s'\n", name);
13626 			return -ESRCH;
13627 		}
13628 	}
13629 	return 0;
13630 }
13631 
13632 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
13633 			      const struct bpf_object_open_opts *opts)
13634 {
13635 	DECLARE_LIBBPF_OPTS(bpf_object_open_opts, skel_opts,
13636 		.object_name = s->name,
13637 	);
13638 	struct bpf_object *obj;
13639 	int err;
13640 
13641 	/* Attempt to preserve opts->object_name, unless overriden by user
13642 	 * explicitly. Overwriting object name for skeletons is discouraged,
13643 	 * as it breaks global data maps, because they contain object name
13644 	 * prefix as their own map name prefix. When skeleton is generated,
13645 	 * bpftool is making an assumption that this name will stay the same.
13646 	 */
13647 	if (opts) {
13648 		memcpy(&skel_opts, opts, sizeof(*opts));
13649 		if (!opts->object_name)
13650 			skel_opts.object_name = s->name;
13651 	}
13652 
13653 	obj = bpf_object__open_mem(s->data, s->data_sz, &skel_opts);
13654 	err = libbpf_get_error(obj);
13655 	if (err) {
13656 		pr_warn("failed to initialize skeleton BPF object '%s': %d\n",
13657 			s->name, err);
13658 		return libbpf_err(err);
13659 	}
13660 
13661 	*s->obj = obj;
13662 	err = populate_skeleton_maps(obj, s->maps, s->map_cnt);
13663 	if (err) {
13664 		pr_warn("failed to populate skeleton maps for '%s': %d\n", s->name, err);
13665 		return libbpf_err(err);
13666 	}
13667 
13668 	err = populate_skeleton_progs(obj, s->progs, s->prog_cnt);
13669 	if (err) {
13670 		pr_warn("failed to populate skeleton progs for '%s': %d\n", s->name, err);
13671 		return libbpf_err(err);
13672 	}
13673 
13674 	return 0;
13675 }
13676 
13677 int bpf_object__open_subskeleton(struct bpf_object_subskeleton *s)
13678 {
13679 	int err, len, var_idx, i;
13680 	const char *var_name;
13681 	const struct bpf_map *map;
13682 	struct btf *btf;
13683 	__u32 map_type_id;
13684 	const struct btf_type *map_type, *var_type;
13685 	const struct bpf_var_skeleton *var_skel;
13686 	struct btf_var_secinfo *var;
13687 
13688 	if (!s->obj)
13689 		return libbpf_err(-EINVAL);
13690 
13691 	btf = bpf_object__btf(s->obj);
13692 	if (!btf) {
13693 		pr_warn("subskeletons require BTF at runtime (object %s)\n",
13694 			bpf_object__name(s->obj));
13695 		return libbpf_err(-errno);
13696 	}
13697 
13698 	err = populate_skeleton_maps(s->obj, s->maps, s->map_cnt);
13699 	if (err) {
13700 		pr_warn("failed to populate subskeleton maps: %d\n", err);
13701 		return libbpf_err(err);
13702 	}
13703 
13704 	err = populate_skeleton_progs(s->obj, s->progs, s->prog_cnt);
13705 	if (err) {
13706 		pr_warn("failed to populate subskeleton maps: %d\n", err);
13707 		return libbpf_err(err);
13708 	}
13709 
13710 	for (var_idx = 0; var_idx < s->var_cnt; var_idx++) {
13711 		var_skel = &s->vars[var_idx];
13712 		map = *var_skel->map;
13713 		map_type_id = bpf_map__btf_value_type_id(map);
13714 		map_type = btf__type_by_id(btf, map_type_id);
13715 
13716 		if (!btf_is_datasec(map_type)) {
13717 			pr_warn("type for map '%1$s' is not a datasec: %2$s",
13718 				bpf_map__name(map),
13719 				__btf_kind_str(btf_kind(map_type)));
13720 			return libbpf_err(-EINVAL);
13721 		}
13722 
13723 		len = btf_vlen(map_type);
13724 		var = btf_var_secinfos(map_type);
13725 		for (i = 0; i < len; i++, var++) {
13726 			var_type = btf__type_by_id(btf, var->type);
13727 			var_name = btf__name_by_offset(btf, var_type->name_off);
13728 			if (strcmp(var_name, var_skel->name) == 0) {
13729 				*var_skel->addr = map->mmaped + var->offset;
13730 				break;
13731 			}
13732 		}
13733 	}
13734 	return 0;
13735 }
13736 
13737 void bpf_object__destroy_subskeleton(struct bpf_object_subskeleton *s)
13738 {
13739 	if (!s)
13740 		return;
13741 	free(s->maps);
13742 	free(s->progs);
13743 	free(s->vars);
13744 	free(s);
13745 }
13746 
13747 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
13748 {
13749 	int i, err;
13750 
13751 	err = bpf_object__load(*s->obj);
13752 	if (err) {
13753 		pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
13754 		return libbpf_err(err);
13755 	}
13756 
13757 	for (i = 0; i < s->map_cnt; i++) {
13758 		struct bpf_map *map = *s->maps[i].map;
13759 		size_t mmap_sz = bpf_map_mmap_sz(map);
13760 		int prot, map_fd = map->fd;
13761 		void **mmaped = s->maps[i].mmaped;
13762 
13763 		if (!mmaped)
13764 			continue;
13765 
13766 		if (!(map->def.map_flags & BPF_F_MMAPABLE)) {
13767 			*mmaped = NULL;
13768 			continue;
13769 		}
13770 
13771 		if (map->def.type == BPF_MAP_TYPE_ARENA) {
13772 			*mmaped = map->mmaped;
13773 			continue;
13774 		}
13775 
13776 		if (map->def.map_flags & BPF_F_RDONLY_PROG)
13777 			prot = PROT_READ;
13778 		else
13779 			prot = PROT_READ | PROT_WRITE;
13780 
13781 		/* Remap anonymous mmap()-ed "map initialization image" as
13782 		 * a BPF map-backed mmap()-ed memory, but preserving the same
13783 		 * memory address. This will cause kernel to change process'
13784 		 * page table to point to a different piece of kernel memory,
13785 		 * but from userspace point of view memory address (and its
13786 		 * contents, being identical at this point) will stay the
13787 		 * same. This mapping will be released by bpf_object__close()
13788 		 * as per normal clean up procedure, so we don't need to worry
13789 		 * about it from skeleton's clean up perspective.
13790 		 */
13791 		*mmaped = mmap(map->mmaped, mmap_sz, prot, MAP_SHARED | MAP_FIXED, map_fd, 0);
13792 		if (*mmaped == MAP_FAILED) {
13793 			err = -errno;
13794 			*mmaped = NULL;
13795 			pr_warn("failed to re-mmap() map '%s': %d\n",
13796 				 bpf_map__name(map), err);
13797 			return libbpf_err(err);
13798 		}
13799 	}
13800 
13801 	return 0;
13802 }
13803 
13804 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
13805 {
13806 	int i, err;
13807 
13808 	for (i = 0; i < s->prog_cnt; i++) {
13809 		struct bpf_program *prog = *s->progs[i].prog;
13810 		struct bpf_link **link = s->progs[i].link;
13811 
13812 		if (!prog->autoload || !prog->autoattach)
13813 			continue;
13814 
13815 		/* auto-attaching not supported for this program */
13816 		if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
13817 			continue;
13818 
13819 		/* if user already set the link manually, don't attempt auto-attach */
13820 		if (*link)
13821 			continue;
13822 
13823 		err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, link);
13824 		if (err) {
13825 			pr_warn("prog '%s': failed to auto-attach: %d\n",
13826 				bpf_program__name(prog), err);
13827 			return libbpf_err(err);
13828 		}
13829 
13830 		/* It's possible that for some SEC() definitions auto-attach
13831 		 * is supported in some cases (e.g., if definition completely
13832 		 * specifies target information), but is not in other cases.
13833 		 * SEC("uprobe") is one such case. If user specified target
13834 		 * binary and function name, such BPF program can be
13835 		 * auto-attached. But if not, it shouldn't trigger skeleton's
13836 		 * attach to fail. It should just be skipped.
13837 		 * attach_fn signals such case with returning 0 (no error) and
13838 		 * setting link to NULL.
13839 		 */
13840 	}
13841 
13842 	return 0;
13843 }
13844 
13845 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
13846 {
13847 	int i;
13848 
13849 	for (i = 0; i < s->prog_cnt; i++) {
13850 		struct bpf_link **link = s->progs[i].link;
13851 
13852 		bpf_link__destroy(*link);
13853 		*link = NULL;
13854 	}
13855 }
13856 
13857 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
13858 {
13859 	if (!s)
13860 		return;
13861 
13862 	if (s->progs)
13863 		bpf_object__detach_skeleton(s);
13864 	if (s->obj)
13865 		bpf_object__close(*s->obj);
13866 	free(s->maps);
13867 	free(s->progs);
13868 	free(s);
13869 }
13870