xref: /linux/tools/lib/bpf/libbpf.c (revision 3e64db35bc37edbe9e37aaa987df92cde12ddb6c)
1 // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
2 
3 /*
4  * Common eBPF ELF object loading operations.
5  *
6  * Copyright (C) 2013-2015 Alexei Starovoitov <ast@kernel.org>
7  * Copyright (C) 2015 Wang Nan <wangnan0@huawei.com>
8  * Copyright (C) 2015 Huawei Inc.
9  * Copyright (C) 2017 Nicira, Inc.
10  * Copyright (C) 2019 Isovalent, Inc.
11  */
12 
13 #ifndef _GNU_SOURCE
14 #define _GNU_SOURCE
15 #endif
16 #include <stdlib.h>
17 #include <stdio.h>
18 #include <stdarg.h>
19 #include <libgen.h>
20 #include <inttypes.h>
21 #include <limits.h>
22 #include <string.h>
23 #include <unistd.h>
24 #include <endian.h>
25 #include <fcntl.h>
26 #include <errno.h>
27 #include <ctype.h>
28 #include <asm/unistd.h>
29 #include <linux/err.h>
30 #include <linux/kernel.h>
31 #include <linux/bpf.h>
32 #include <linux/btf.h>
33 #include <linux/filter.h>
34 #include <linux/limits.h>
35 #include <linux/perf_event.h>
36 #include <linux/ring_buffer.h>
37 #include <sys/epoll.h>
38 #include <sys/ioctl.h>
39 #include <sys/mman.h>
40 #include <sys/stat.h>
41 #include <sys/types.h>
42 #include <sys/vfs.h>
43 #include <sys/utsname.h>
44 #include <sys/resource.h>
45 #include <libelf.h>
46 #include <gelf.h>
47 #include <zlib.h>
48 
49 #include "libbpf.h"
50 #include "bpf.h"
51 #include "btf.h"
52 #include "str_error.h"
53 #include "libbpf_internal.h"
54 #include "hashmap.h"
55 #include "bpf_gen_internal.h"
56 #include "zip.h"
57 
58 #ifndef BPF_FS_MAGIC
59 #define BPF_FS_MAGIC		0xcafe4a11
60 #endif
61 
62 #define BPF_INSN_SZ (sizeof(struct bpf_insn))
63 
64 /* vsprintf() in __base_pr() uses nonliteral format string. It may break
65  * compilation if user enables corresponding warning. Disable it explicitly.
66  */
67 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
68 
69 #define __printf(a, b)	__attribute__((format(printf, a, b)))
70 
71 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj);
72 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog);
73 
74 static const char * const attach_type_name[] = {
75 	[BPF_CGROUP_INET_INGRESS]	= "cgroup_inet_ingress",
76 	[BPF_CGROUP_INET_EGRESS]	= "cgroup_inet_egress",
77 	[BPF_CGROUP_INET_SOCK_CREATE]	= "cgroup_inet_sock_create",
78 	[BPF_CGROUP_INET_SOCK_RELEASE]	= "cgroup_inet_sock_release",
79 	[BPF_CGROUP_SOCK_OPS]		= "cgroup_sock_ops",
80 	[BPF_CGROUP_DEVICE]		= "cgroup_device",
81 	[BPF_CGROUP_INET4_BIND]		= "cgroup_inet4_bind",
82 	[BPF_CGROUP_INET6_BIND]		= "cgroup_inet6_bind",
83 	[BPF_CGROUP_INET4_CONNECT]	= "cgroup_inet4_connect",
84 	[BPF_CGROUP_INET6_CONNECT]	= "cgroup_inet6_connect",
85 	[BPF_CGROUP_UNIX_CONNECT]       = "cgroup_unix_connect",
86 	[BPF_CGROUP_INET4_POST_BIND]	= "cgroup_inet4_post_bind",
87 	[BPF_CGROUP_INET6_POST_BIND]	= "cgroup_inet6_post_bind",
88 	[BPF_CGROUP_INET4_GETPEERNAME]	= "cgroup_inet4_getpeername",
89 	[BPF_CGROUP_INET6_GETPEERNAME]	= "cgroup_inet6_getpeername",
90 	[BPF_CGROUP_UNIX_GETPEERNAME]	= "cgroup_unix_getpeername",
91 	[BPF_CGROUP_INET4_GETSOCKNAME]	= "cgroup_inet4_getsockname",
92 	[BPF_CGROUP_INET6_GETSOCKNAME]	= "cgroup_inet6_getsockname",
93 	[BPF_CGROUP_UNIX_GETSOCKNAME]	= "cgroup_unix_getsockname",
94 	[BPF_CGROUP_UDP4_SENDMSG]	= "cgroup_udp4_sendmsg",
95 	[BPF_CGROUP_UDP6_SENDMSG]	= "cgroup_udp6_sendmsg",
96 	[BPF_CGROUP_UNIX_SENDMSG]	= "cgroup_unix_sendmsg",
97 	[BPF_CGROUP_SYSCTL]		= "cgroup_sysctl",
98 	[BPF_CGROUP_UDP4_RECVMSG]	= "cgroup_udp4_recvmsg",
99 	[BPF_CGROUP_UDP6_RECVMSG]	= "cgroup_udp6_recvmsg",
100 	[BPF_CGROUP_UNIX_RECVMSG]	= "cgroup_unix_recvmsg",
101 	[BPF_CGROUP_GETSOCKOPT]		= "cgroup_getsockopt",
102 	[BPF_CGROUP_SETSOCKOPT]		= "cgroup_setsockopt",
103 	[BPF_SK_SKB_STREAM_PARSER]	= "sk_skb_stream_parser",
104 	[BPF_SK_SKB_STREAM_VERDICT]	= "sk_skb_stream_verdict",
105 	[BPF_SK_SKB_VERDICT]		= "sk_skb_verdict",
106 	[BPF_SK_MSG_VERDICT]		= "sk_msg_verdict",
107 	[BPF_LIRC_MODE2]		= "lirc_mode2",
108 	[BPF_FLOW_DISSECTOR]		= "flow_dissector",
109 	[BPF_TRACE_RAW_TP]		= "trace_raw_tp",
110 	[BPF_TRACE_FENTRY]		= "trace_fentry",
111 	[BPF_TRACE_FEXIT]		= "trace_fexit",
112 	[BPF_MODIFY_RETURN]		= "modify_return",
113 	[BPF_LSM_MAC]			= "lsm_mac",
114 	[BPF_LSM_CGROUP]		= "lsm_cgroup",
115 	[BPF_SK_LOOKUP]			= "sk_lookup",
116 	[BPF_TRACE_ITER]		= "trace_iter",
117 	[BPF_XDP_DEVMAP]		= "xdp_devmap",
118 	[BPF_XDP_CPUMAP]		= "xdp_cpumap",
119 	[BPF_XDP]			= "xdp",
120 	[BPF_SK_REUSEPORT_SELECT]	= "sk_reuseport_select",
121 	[BPF_SK_REUSEPORT_SELECT_OR_MIGRATE]	= "sk_reuseport_select_or_migrate",
122 	[BPF_PERF_EVENT]		= "perf_event",
123 	[BPF_TRACE_KPROBE_MULTI]	= "trace_kprobe_multi",
124 	[BPF_STRUCT_OPS]		= "struct_ops",
125 	[BPF_NETFILTER]			= "netfilter",
126 	[BPF_TCX_INGRESS]		= "tcx_ingress",
127 	[BPF_TCX_EGRESS]		= "tcx_egress",
128 	[BPF_TRACE_UPROBE_MULTI]	= "trace_uprobe_multi",
129 	[BPF_NETKIT_PRIMARY]		= "netkit_primary",
130 	[BPF_NETKIT_PEER]		= "netkit_peer",
131 };
132 
133 static const char * const link_type_name[] = {
134 	[BPF_LINK_TYPE_UNSPEC]			= "unspec",
135 	[BPF_LINK_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
136 	[BPF_LINK_TYPE_TRACING]			= "tracing",
137 	[BPF_LINK_TYPE_CGROUP]			= "cgroup",
138 	[BPF_LINK_TYPE_ITER]			= "iter",
139 	[BPF_LINK_TYPE_NETNS]			= "netns",
140 	[BPF_LINK_TYPE_XDP]			= "xdp",
141 	[BPF_LINK_TYPE_PERF_EVENT]		= "perf_event",
142 	[BPF_LINK_TYPE_KPROBE_MULTI]		= "kprobe_multi",
143 	[BPF_LINK_TYPE_STRUCT_OPS]		= "struct_ops",
144 	[BPF_LINK_TYPE_NETFILTER]		= "netfilter",
145 	[BPF_LINK_TYPE_TCX]			= "tcx",
146 	[BPF_LINK_TYPE_UPROBE_MULTI]		= "uprobe_multi",
147 	[BPF_LINK_TYPE_NETKIT]			= "netkit",
148 };
149 
150 static const char * const map_type_name[] = {
151 	[BPF_MAP_TYPE_UNSPEC]			= "unspec",
152 	[BPF_MAP_TYPE_HASH]			= "hash",
153 	[BPF_MAP_TYPE_ARRAY]			= "array",
154 	[BPF_MAP_TYPE_PROG_ARRAY]		= "prog_array",
155 	[BPF_MAP_TYPE_PERF_EVENT_ARRAY]		= "perf_event_array",
156 	[BPF_MAP_TYPE_PERCPU_HASH]		= "percpu_hash",
157 	[BPF_MAP_TYPE_PERCPU_ARRAY]		= "percpu_array",
158 	[BPF_MAP_TYPE_STACK_TRACE]		= "stack_trace",
159 	[BPF_MAP_TYPE_CGROUP_ARRAY]		= "cgroup_array",
160 	[BPF_MAP_TYPE_LRU_HASH]			= "lru_hash",
161 	[BPF_MAP_TYPE_LRU_PERCPU_HASH]		= "lru_percpu_hash",
162 	[BPF_MAP_TYPE_LPM_TRIE]			= "lpm_trie",
163 	[BPF_MAP_TYPE_ARRAY_OF_MAPS]		= "array_of_maps",
164 	[BPF_MAP_TYPE_HASH_OF_MAPS]		= "hash_of_maps",
165 	[BPF_MAP_TYPE_DEVMAP]			= "devmap",
166 	[BPF_MAP_TYPE_DEVMAP_HASH]		= "devmap_hash",
167 	[BPF_MAP_TYPE_SOCKMAP]			= "sockmap",
168 	[BPF_MAP_TYPE_CPUMAP]			= "cpumap",
169 	[BPF_MAP_TYPE_XSKMAP]			= "xskmap",
170 	[BPF_MAP_TYPE_SOCKHASH]			= "sockhash",
171 	[BPF_MAP_TYPE_CGROUP_STORAGE]		= "cgroup_storage",
172 	[BPF_MAP_TYPE_REUSEPORT_SOCKARRAY]	= "reuseport_sockarray",
173 	[BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE]	= "percpu_cgroup_storage",
174 	[BPF_MAP_TYPE_QUEUE]			= "queue",
175 	[BPF_MAP_TYPE_STACK]			= "stack",
176 	[BPF_MAP_TYPE_SK_STORAGE]		= "sk_storage",
177 	[BPF_MAP_TYPE_STRUCT_OPS]		= "struct_ops",
178 	[BPF_MAP_TYPE_RINGBUF]			= "ringbuf",
179 	[BPF_MAP_TYPE_INODE_STORAGE]		= "inode_storage",
180 	[BPF_MAP_TYPE_TASK_STORAGE]		= "task_storage",
181 	[BPF_MAP_TYPE_BLOOM_FILTER]		= "bloom_filter",
182 	[BPF_MAP_TYPE_USER_RINGBUF]             = "user_ringbuf",
183 	[BPF_MAP_TYPE_CGRP_STORAGE]		= "cgrp_storage",
184 };
185 
186 static const char * const prog_type_name[] = {
187 	[BPF_PROG_TYPE_UNSPEC]			= "unspec",
188 	[BPF_PROG_TYPE_SOCKET_FILTER]		= "socket_filter",
189 	[BPF_PROG_TYPE_KPROBE]			= "kprobe",
190 	[BPF_PROG_TYPE_SCHED_CLS]		= "sched_cls",
191 	[BPF_PROG_TYPE_SCHED_ACT]		= "sched_act",
192 	[BPF_PROG_TYPE_TRACEPOINT]		= "tracepoint",
193 	[BPF_PROG_TYPE_XDP]			= "xdp",
194 	[BPF_PROG_TYPE_PERF_EVENT]		= "perf_event",
195 	[BPF_PROG_TYPE_CGROUP_SKB]		= "cgroup_skb",
196 	[BPF_PROG_TYPE_CGROUP_SOCK]		= "cgroup_sock",
197 	[BPF_PROG_TYPE_LWT_IN]			= "lwt_in",
198 	[BPF_PROG_TYPE_LWT_OUT]			= "lwt_out",
199 	[BPF_PROG_TYPE_LWT_XMIT]		= "lwt_xmit",
200 	[BPF_PROG_TYPE_SOCK_OPS]		= "sock_ops",
201 	[BPF_PROG_TYPE_SK_SKB]			= "sk_skb",
202 	[BPF_PROG_TYPE_CGROUP_DEVICE]		= "cgroup_device",
203 	[BPF_PROG_TYPE_SK_MSG]			= "sk_msg",
204 	[BPF_PROG_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
205 	[BPF_PROG_TYPE_CGROUP_SOCK_ADDR]	= "cgroup_sock_addr",
206 	[BPF_PROG_TYPE_LWT_SEG6LOCAL]		= "lwt_seg6local",
207 	[BPF_PROG_TYPE_LIRC_MODE2]		= "lirc_mode2",
208 	[BPF_PROG_TYPE_SK_REUSEPORT]		= "sk_reuseport",
209 	[BPF_PROG_TYPE_FLOW_DISSECTOR]		= "flow_dissector",
210 	[BPF_PROG_TYPE_CGROUP_SYSCTL]		= "cgroup_sysctl",
211 	[BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE]	= "raw_tracepoint_writable",
212 	[BPF_PROG_TYPE_CGROUP_SOCKOPT]		= "cgroup_sockopt",
213 	[BPF_PROG_TYPE_TRACING]			= "tracing",
214 	[BPF_PROG_TYPE_STRUCT_OPS]		= "struct_ops",
215 	[BPF_PROG_TYPE_EXT]			= "ext",
216 	[BPF_PROG_TYPE_LSM]			= "lsm",
217 	[BPF_PROG_TYPE_SK_LOOKUP]		= "sk_lookup",
218 	[BPF_PROG_TYPE_SYSCALL]			= "syscall",
219 	[BPF_PROG_TYPE_NETFILTER]		= "netfilter",
220 };
221 
222 static int __base_pr(enum libbpf_print_level level, const char *format,
223 		     va_list args)
224 {
225 	if (level == LIBBPF_DEBUG)
226 		return 0;
227 
228 	return vfprintf(stderr, format, args);
229 }
230 
231 static libbpf_print_fn_t __libbpf_pr = __base_pr;
232 
233 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
234 {
235 	libbpf_print_fn_t old_print_fn;
236 
237 	old_print_fn = __atomic_exchange_n(&__libbpf_pr, fn, __ATOMIC_RELAXED);
238 
239 	return old_print_fn;
240 }
241 
242 __printf(2, 3)
243 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
244 {
245 	va_list args;
246 	int old_errno;
247 	libbpf_print_fn_t print_fn;
248 
249 	print_fn = __atomic_load_n(&__libbpf_pr, __ATOMIC_RELAXED);
250 	if (!print_fn)
251 		return;
252 
253 	old_errno = errno;
254 
255 	va_start(args, format);
256 	__libbpf_pr(level, format, args);
257 	va_end(args);
258 
259 	errno = old_errno;
260 }
261 
262 static void pr_perm_msg(int err)
263 {
264 	struct rlimit limit;
265 	char buf[100];
266 
267 	if (err != -EPERM || geteuid() != 0)
268 		return;
269 
270 	err = getrlimit(RLIMIT_MEMLOCK, &limit);
271 	if (err)
272 		return;
273 
274 	if (limit.rlim_cur == RLIM_INFINITY)
275 		return;
276 
277 	if (limit.rlim_cur < 1024)
278 		snprintf(buf, sizeof(buf), "%zu bytes", (size_t)limit.rlim_cur);
279 	else if (limit.rlim_cur < 1024*1024)
280 		snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
281 	else
282 		snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
283 
284 	pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
285 		buf);
286 }
287 
288 #define STRERR_BUFSIZE  128
289 
290 /* Copied from tools/perf/util/util.h */
291 #ifndef zfree
292 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
293 #endif
294 
295 #ifndef zclose
296 # define zclose(fd) ({			\
297 	int ___err = 0;			\
298 	if ((fd) >= 0)			\
299 		___err = close((fd));	\
300 	fd = -1;			\
301 	___err; })
302 #endif
303 
304 static inline __u64 ptr_to_u64(const void *ptr)
305 {
306 	return (__u64) (unsigned long) ptr;
307 }
308 
309 int libbpf_set_strict_mode(enum libbpf_strict_mode mode)
310 {
311 	/* as of v1.0 libbpf_set_strict_mode() is a no-op */
312 	return 0;
313 }
314 
315 __u32 libbpf_major_version(void)
316 {
317 	return LIBBPF_MAJOR_VERSION;
318 }
319 
320 __u32 libbpf_minor_version(void)
321 {
322 	return LIBBPF_MINOR_VERSION;
323 }
324 
325 const char *libbpf_version_string(void)
326 {
327 #define __S(X) #X
328 #define _S(X) __S(X)
329 	return  "v" _S(LIBBPF_MAJOR_VERSION) "." _S(LIBBPF_MINOR_VERSION);
330 #undef _S
331 #undef __S
332 }
333 
334 enum reloc_type {
335 	RELO_LD64,
336 	RELO_CALL,
337 	RELO_DATA,
338 	RELO_EXTERN_LD64,
339 	RELO_EXTERN_CALL,
340 	RELO_SUBPROG_ADDR,
341 	RELO_CORE,
342 };
343 
344 struct reloc_desc {
345 	enum reloc_type type;
346 	int insn_idx;
347 	union {
348 		const struct bpf_core_relo *core_relo; /* used when type == RELO_CORE */
349 		struct {
350 			int map_idx;
351 			int sym_off;
352 			int ext_idx;
353 		};
354 	};
355 };
356 
357 /* stored as sec_def->cookie for all libbpf-supported SEC()s */
358 enum sec_def_flags {
359 	SEC_NONE = 0,
360 	/* expected_attach_type is optional, if kernel doesn't support that */
361 	SEC_EXP_ATTACH_OPT = 1,
362 	/* legacy, only used by libbpf_get_type_names() and
363 	 * libbpf_attach_type_by_name(), not used by libbpf itself at all.
364 	 * This used to be associated with cgroup (and few other) BPF programs
365 	 * that were attachable through BPF_PROG_ATTACH command. Pretty
366 	 * meaningless nowadays, though.
367 	 */
368 	SEC_ATTACHABLE = 2,
369 	SEC_ATTACHABLE_OPT = SEC_ATTACHABLE | SEC_EXP_ATTACH_OPT,
370 	/* attachment target is specified through BTF ID in either kernel or
371 	 * other BPF program's BTF object
372 	 */
373 	SEC_ATTACH_BTF = 4,
374 	/* BPF program type allows sleeping/blocking in kernel */
375 	SEC_SLEEPABLE = 8,
376 	/* BPF program support non-linear XDP buffer */
377 	SEC_XDP_FRAGS = 16,
378 	/* Setup proper attach type for usdt probes. */
379 	SEC_USDT = 32,
380 };
381 
382 struct bpf_sec_def {
383 	char *sec;
384 	enum bpf_prog_type prog_type;
385 	enum bpf_attach_type expected_attach_type;
386 	long cookie;
387 	int handler_id;
388 
389 	libbpf_prog_setup_fn_t prog_setup_fn;
390 	libbpf_prog_prepare_load_fn_t prog_prepare_load_fn;
391 	libbpf_prog_attach_fn_t prog_attach_fn;
392 };
393 
394 /*
395  * bpf_prog should be a better name but it has been used in
396  * linux/filter.h.
397  */
398 struct bpf_program {
399 	char *name;
400 	char *sec_name;
401 	size_t sec_idx;
402 	const struct bpf_sec_def *sec_def;
403 	/* this program's instruction offset (in number of instructions)
404 	 * within its containing ELF section
405 	 */
406 	size_t sec_insn_off;
407 	/* number of original instructions in ELF section belonging to this
408 	 * program, not taking into account subprogram instructions possible
409 	 * appended later during relocation
410 	 */
411 	size_t sec_insn_cnt;
412 	/* Offset (in number of instructions) of the start of instruction
413 	 * belonging to this BPF program  within its containing main BPF
414 	 * program. For the entry-point (main) BPF program, this is always
415 	 * zero. For a sub-program, this gets reset before each of main BPF
416 	 * programs are processed and relocated and is used to determined
417 	 * whether sub-program was already appended to the main program, and
418 	 * if yes, at which instruction offset.
419 	 */
420 	size_t sub_insn_off;
421 
422 	/* instructions that belong to BPF program; insns[0] is located at
423 	 * sec_insn_off instruction within its ELF section in ELF file, so
424 	 * when mapping ELF file instruction index to the local instruction,
425 	 * one needs to subtract sec_insn_off; and vice versa.
426 	 */
427 	struct bpf_insn *insns;
428 	/* actual number of instruction in this BPF program's image; for
429 	 * entry-point BPF programs this includes the size of main program
430 	 * itself plus all the used sub-programs, appended at the end
431 	 */
432 	size_t insns_cnt;
433 
434 	struct reloc_desc *reloc_desc;
435 	int nr_reloc;
436 
437 	/* BPF verifier log settings */
438 	char *log_buf;
439 	size_t log_size;
440 	__u32 log_level;
441 
442 	struct bpf_object *obj;
443 
444 	int fd;
445 	bool autoload;
446 	bool autoattach;
447 	bool sym_global;
448 	bool mark_btf_static;
449 	enum bpf_prog_type type;
450 	enum bpf_attach_type expected_attach_type;
451 	int exception_cb_idx;
452 
453 	int prog_ifindex;
454 	__u32 attach_btf_obj_fd;
455 	__u32 attach_btf_id;
456 	__u32 attach_prog_fd;
457 
458 	void *func_info;
459 	__u32 func_info_rec_size;
460 	__u32 func_info_cnt;
461 
462 	void *line_info;
463 	__u32 line_info_rec_size;
464 	__u32 line_info_cnt;
465 	__u32 prog_flags;
466 };
467 
468 struct bpf_struct_ops {
469 	const char *tname;
470 	const struct btf_type *type;
471 	struct bpf_program **progs;
472 	__u32 *kern_func_off;
473 	/* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
474 	void *data;
475 	/* e.g. struct bpf_struct_ops_tcp_congestion_ops in
476 	 *      btf_vmlinux's format.
477 	 * struct bpf_struct_ops_tcp_congestion_ops {
478 	 *	[... some other kernel fields ...]
479 	 *	struct tcp_congestion_ops data;
480 	 * }
481 	 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
482 	 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
483 	 * from "data".
484 	 */
485 	void *kern_vdata;
486 	__u32 type_id;
487 };
488 
489 #define DATA_SEC ".data"
490 #define BSS_SEC ".bss"
491 #define RODATA_SEC ".rodata"
492 #define KCONFIG_SEC ".kconfig"
493 #define KSYMS_SEC ".ksyms"
494 #define STRUCT_OPS_SEC ".struct_ops"
495 #define STRUCT_OPS_LINK_SEC ".struct_ops.link"
496 
497 enum libbpf_map_type {
498 	LIBBPF_MAP_UNSPEC,
499 	LIBBPF_MAP_DATA,
500 	LIBBPF_MAP_BSS,
501 	LIBBPF_MAP_RODATA,
502 	LIBBPF_MAP_KCONFIG,
503 };
504 
505 struct bpf_map_def {
506 	unsigned int type;
507 	unsigned int key_size;
508 	unsigned int value_size;
509 	unsigned int max_entries;
510 	unsigned int map_flags;
511 };
512 
513 struct bpf_map {
514 	struct bpf_object *obj;
515 	char *name;
516 	/* real_name is defined for special internal maps (.rodata*,
517 	 * .data*, .bss, .kconfig) and preserves their original ELF section
518 	 * name. This is important to be able to find corresponding BTF
519 	 * DATASEC information.
520 	 */
521 	char *real_name;
522 	int fd;
523 	int sec_idx;
524 	size_t sec_offset;
525 	int map_ifindex;
526 	int inner_map_fd;
527 	struct bpf_map_def def;
528 	__u32 numa_node;
529 	__u32 btf_var_idx;
530 	__u32 btf_key_type_id;
531 	__u32 btf_value_type_id;
532 	__u32 btf_vmlinux_value_type_id;
533 	enum libbpf_map_type libbpf_type;
534 	void *mmaped;
535 	struct bpf_struct_ops *st_ops;
536 	struct bpf_map *inner_map;
537 	void **init_slots;
538 	int init_slots_sz;
539 	char *pin_path;
540 	bool pinned;
541 	bool reused;
542 	bool autocreate;
543 	__u64 map_extra;
544 };
545 
546 enum extern_type {
547 	EXT_UNKNOWN,
548 	EXT_KCFG,
549 	EXT_KSYM,
550 };
551 
552 enum kcfg_type {
553 	KCFG_UNKNOWN,
554 	KCFG_CHAR,
555 	KCFG_BOOL,
556 	KCFG_INT,
557 	KCFG_TRISTATE,
558 	KCFG_CHAR_ARR,
559 };
560 
561 struct extern_desc {
562 	enum extern_type type;
563 	int sym_idx;
564 	int btf_id;
565 	int sec_btf_id;
566 	const char *name;
567 	char *essent_name;
568 	bool is_set;
569 	bool is_weak;
570 	union {
571 		struct {
572 			enum kcfg_type type;
573 			int sz;
574 			int align;
575 			int data_off;
576 			bool is_signed;
577 		} kcfg;
578 		struct {
579 			unsigned long long addr;
580 
581 			/* target btf_id of the corresponding kernel var. */
582 			int kernel_btf_obj_fd;
583 			int kernel_btf_id;
584 
585 			/* local btf_id of the ksym extern's type. */
586 			__u32 type_id;
587 			/* BTF fd index to be patched in for insn->off, this is
588 			 * 0 for vmlinux BTF, index in obj->fd_array for module
589 			 * BTF
590 			 */
591 			__s16 btf_fd_idx;
592 		} ksym;
593 	};
594 };
595 
596 struct module_btf {
597 	struct btf *btf;
598 	char *name;
599 	__u32 id;
600 	int fd;
601 	int fd_array_idx;
602 };
603 
604 enum sec_type {
605 	SEC_UNUSED = 0,
606 	SEC_RELO,
607 	SEC_BSS,
608 	SEC_DATA,
609 	SEC_RODATA,
610 };
611 
612 struct elf_sec_desc {
613 	enum sec_type sec_type;
614 	Elf64_Shdr *shdr;
615 	Elf_Data *data;
616 };
617 
618 struct elf_state {
619 	int fd;
620 	const void *obj_buf;
621 	size_t obj_buf_sz;
622 	Elf *elf;
623 	Elf64_Ehdr *ehdr;
624 	Elf_Data *symbols;
625 	Elf_Data *st_ops_data;
626 	Elf_Data *st_ops_link_data;
627 	size_t shstrndx; /* section index for section name strings */
628 	size_t strtabidx;
629 	struct elf_sec_desc *secs;
630 	size_t sec_cnt;
631 	int btf_maps_shndx;
632 	__u32 btf_maps_sec_btf_id;
633 	int text_shndx;
634 	int symbols_shndx;
635 	int st_ops_shndx;
636 	int st_ops_link_shndx;
637 };
638 
639 struct usdt_manager;
640 
641 struct bpf_object {
642 	char name[BPF_OBJ_NAME_LEN];
643 	char license[64];
644 	__u32 kern_version;
645 
646 	struct bpf_program *programs;
647 	size_t nr_programs;
648 	struct bpf_map *maps;
649 	size_t nr_maps;
650 	size_t maps_cap;
651 
652 	char *kconfig;
653 	struct extern_desc *externs;
654 	int nr_extern;
655 	int kconfig_map_idx;
656 
657 	bool loaded;
658 	bool has_subcalls;
659 	bool has_rodata;
660 
661 	struct bpf_gen *gen_loader;
662 
663 	/* Information when doing ELF related work. Only valid if efile.elf is not NULL */
664 	struct elf_state efile;
665 
666 	struct btf *btf;
667 	struct btf_ext *btf_ext;
668 
669 	/* Parse and load BTF vmlinux if any of the programs in the object need
670 	 * it at load time.
671 	 */
672 	struct btf *btf_vmlinux;
673 	/* Path to the custom BTF to be used for BPF CO-RE relocations as an
674 	 * override for vmlinux BTF.
675 	 */
676 	char *btf_custom_path;
677 	/* vmlinux BTF override for CO-RE relocations */
678 	struct btf *btf_vmlinux_override;
679 	/* Lazily initialized kernel module BTFs */
680 	struct module_btf *btf_modules;
681 	bool btf_modules_loaded;
682 	size_t btf_module_cnt;
683 	size_t btf_module_cap;
684 
685 	/* optional log settings passed to BPF_BTF_LOAD and BPF_PROG_LOAD commands */
686 	char *log_buf;
687 	size_t log_size;
688 	__u32 log_level;
689 
690 	int *fd_array;
691 	size_t fd_array_cap;
692 	size_t fd_array_cnt;
693 
694 	struct usdt_manager *usdt_man;
695 
696 	char path[];
697 };
698 
699 static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
700 static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
701 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
702 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
703 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn);
704 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
705 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
706 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx);
707 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx);
708 
709 void bpf_program__unload(struct bpf_program *prog)
710 {
711 	if (!prog)
712 		return;
713 
714 	zclose(prog->fd);
715 
716 	zfree(&prog->func_info);
717 	zfree(&prog->line_info);
718 }
719 
720 static void bpf_program__exit(struct bpf_program *prog)
721 {
722 	if (!prog)
723 		return;
724 
725 	bpf_program__unload(prog);
726 	zfree(&prog->name);
727 	zfree(&prog->sec_name);
728 	zfree(&prog->insns);
729 	zfree(&prog->reloc_desc);
730 
731 	prog->nr_reloc = 0;
732 	prog->insns_cnt = 0;
733 	prog->sec_idx = -1;
734 }
735 
736 static bool insn_is_subprog_call(const struct bpf_insn *insn)
737 {
738 	return BPF_CLASS(insn->code) == BPF_JMP &&
739 	       BPF_OP(insn->code) == BPF_CALL &&
740 	       BPF_SRC(insn->code) == BPF_K &&
741 	       insn->src_reg == BPF_PSEUDO_CALL &&
742 	       insn->dst_reg == 0 &&
743 	       insn->off == 0;
744 }
745 
746 static bool is_call_insn(const struct bpf_insn *insn)
747 {
748 	return insn->code == (BPF_JMP | BPF_CALL);
749 }
750 
751 static bool insn_is_pseudo_func(struct bpf_insn *insn)
752 {
753 	return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
754 }
755 
756 static int
757 bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
758 		      const char *name, size_t sec_idx, const char *sec_name,
759 		      size_t sec_off, void *insn_data, size_t insn_data_sz)
760 {
761 	if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
762 		pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
763 			sec_name, name, sec_off, insn_data_sz);
764 		return -EINVAL;
765 	}
766 
767 	memset(prog, 0, sizeof(*prog));
768 	prog->obj = obj;
769 
770 	prog->sec_idx = sec_idx;
771 	prog->sec_insn_off = sec_off / BPF_INSN_SZ;
772 	prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
773 	/* insns_cnt can later be increased by appending used subprograms */
774 	prog->insns_cnt = prog->sec_insn_cnt;
775 
776 	prog->type = BPF_PROG_TYPE_UNSPEC;
777 	prog->fd = -1;
778 	prog->exception_cb_idx = -1;
779 
780 	/* libbpf's convention for SEC("?abc...") is that it's just like
781 	 * SEC("abc...") but the corresponding bpf_program starts out with
782 	 * autoload set to false.
783 	 */
784 	if (sec_name[0] == '?') {
785 		prog->autoload = false;
786 		/* from now on forget there was ? in section name */
787 		sec_name++;
788 	} else {
789 		prog->autoload = true;
790 	}
791 
792 	prog->autoattach = true;
793 
794 	/* inherit object's log_level */
795 	prog->log_level = obj->log_level;
796 
797 	prog->sec_name = strdup(sec_name);
798 	if (!prog->sec_name)
799 		goto errout;
800 
801 	prog->name = strdup(name);
802 	if (!prog->name)
803 		goto errout;
804 
805 	prog->insns = malloc(insn_data_sz);
806 	if (!prog->insns)
807 		goto errout;
808 	memcpy(prog->insns, insn_data, insn_data_sz);
809 
810 	return 0;
811 errout:
812 	pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
813 	bpf_program__exit(prog);
814 	return -ENOMEM;
815 }
816 
817 static int
818 bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
819 			 const char *sec_name, int sec_idx)
820 {
821 	Elf_Data *symbols = obj->efile.symbols;
822 	struct bpf_program *prog, *progs;
823 	void *data = sec_data->d_buf;
824 	size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
825 	int nr_progs, err, i;
826 	const char *name;
827 	Elf64_Sym *sym;
828 
829 	progs = obj->programs;
830 	nr_progs = obj->nr_programs;
831 	nr_syms = symbols->d_size / sizeof(Elf64_Sym);
832 
833 	for (i = 0; i < nr_syms; i++) {
834 		sym = elf_sym_by_idx(obj, i);
835 
836 		if (sym->st_shndx != sec_idx)
837 			continue;
838 		if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC)
839 			continue;
840 
841 		prog_sz = sym->st_size;
842 		sec_off = sym->st_value;
843 
844 		name = elf_sym_str(obj, sym->st_name);
845 		if (!name) {
846 			pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
847 				sec_name, sec_off);
848 			return -LIBBPF_ERRNO__FORMAT;
849 		}
850 
851 		if (sec_off + prog_sz > sec_sz) {
852 			pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
853 				sec_name, sec_off);
854 			return -LIBBPF_ERRNO__FORMAT;
855 		}
856 
857 		if (sec_idx != obj->efile.text_shndx && ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
858 			pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
859 			return -ENOTSUP;
860 		}
861 
862 		pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
863 			 sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
864 
865 		progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
866 		if (!progs) {
867 			/*
868 			 * In this case the original obj->programs
869 			 * is still valid, so don't need special treat for
870 			 * bpf_close_object().
871 			 */
872 			pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
873 				sec_name, name);
874 			return -ENOMEM;
875 		}
876 		obj->programs = progs;
877 
878 		prog = &progs[nr_progs];
879 
880 		err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
881 					    sec_off, data + sec_off, prog_sz);
882 		if (err)
883 			return err;
884 
885 		if (ELF64_ST_BIND(sym->st_info) != STB_LOCAL)
886 			prog->sym_global = true;
887 
888 		/* if function is a global/weak symbol, but has restricted
889 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
890 		 * as static to enable more permissive BPF verification mode
891 		 * with more outside context available to BPF verifier
892 		 */
893 		if (prog->sym_global && (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
894 		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL))
895 			prog->mark_btf_static = true;
896 
897 		nr_progs++;
898 		obj->nr_programs = nr_progs;
899 	}
900 
901 	return 0;
902 }
903 
904 static const struct btf_member *
905 find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
906 {
907 	struct btf_member *m;
908 	int i;
909 
910 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
911 		if (btf_member_bit_offset(t, i) == bit_offset)
912 			return m;
913 	}
914 
915 	return NULL;
916 }
917 
918 static const struct btf_member *
919 find_member_by_name(const struct btf *btf, const struct btf_type *t,
920 		    const char *name)
921 {
922 	struct btf_member *m;
923 	int i;
924 
925 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
926 		if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
927 			return m;
928 	}
929 
930 	return NULL;
931 }
932 
933 #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
934 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
935 				   const char *name, __u32 kind);
936 
937 static int
938 find_struct_ops_kern_types(const struct btf *btf, const char *tname,
939 			   const struct btf_type **type, __u32 *type_id,
940 			   const struct btf_type **vtype, __u32 *vtype_id,
941 			   const struct btf_member **data_member)
942 {
943 	const struct btf_type *kern_type, *kern_vtype;
944 	const struct btf_member *kern_data_member;
945 	__s32 kern_vtype_id, kern_type_id;
946 	__u32 i;
947 
948 	kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
949 	if (kern_type_id < 0) {
950 		pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n",
951 			tname);
952 		return kern_type_id;
953 	}
954 	kern_type = btf__type_by_id(btf, kern_type_id);
955 
956 	/* Find the corresponding "map_value" type that will be used
957 	 * in map_update(BPF_MAP_TYPE_STRUCT_OPS).  For example,
958 	 * find "struct bpf_struct_ops_tcp_congestion_ops" from the
959 	 * btf_vmlinux.
960 	 */
961 	kern_vtype_id = find_btf_by_prefix_kind(btf, STRUCT_OPS_VALUE_PREFIX,
962 						tname, BTF_KIND_STRUCT);
963 	if (kern_vtype_id < 0) {
964 		pr_warn("struct_ops init_kern: struct %s%s is not found in kernel BTF\n",
965 			STRUCT_OPS_VALUE_PREFIX, tname);
966 		return kern_vtype_id;
967 	}
968 	kern_vtype = btf__type_by_id(btf, kern_vtype_id);
969 
970 	/* Find "struct tcp_congestion_ops" from
971 	 * struct bpf_struct_ops_tcp_congestion_ops {
972 	 *	[ ... ]
973 	 *	struct tcp_congestion_ops data;
974 	 * }
975 	 */
976 	kern_data_member = btf_members(kern_vtype);
977 	for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
978 		if (kern_data_member->type == kern_type_id)
979 			break;
980 	}
981 	if (i == btf_vlen(kern_vtype)) {
982 		pr_warn("struct_ops init_kern: struct %s data is not found in struct %s%s\n",
983 			tname, STRUCT_OPS_VALUE_PREFIX, tname);
984 		return -EINVAL;
985 	}
986 
987 	*type = kern_type;
988 	*type_id = kern_type_id;
989 	*vtype = kern_vtype;
990 	*vtype_id = kern_vtype_id;
991 	*data_member = kern_data_member;
992 
993 	return 0;
994 }
995 
996 static bool bpf_map__is_struct_ops(const struct bpf_map *map)
997 {
998 	return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
999 }
1000 
1001 /* Init the map's fields that depend on kern_btf */
1002 static int bpf_map__init_kern_struct_ops(struct bpf_map *map,
1003 					 const struct btf *btf,
1004 					 const struct btf *kern_btf)
1005 {
1006 	const struct btf_member *member, *kern_member, *kern_data_member;
1007 	const struct btf_type *type, *kern_type, *kern_vtype;
1008 	__u32 i, kern_type_id, kern_vtype_id, kern_data_off;
1009 	struct bpf_struct_ops *st_ops;
1010 	void *data, *kern_data;
1011 	const char *tname;
1012 	int err;
1013 
1014 	st_ops = map->st_ops;
1015 	type = st_ops->type;
1016 	tname = st_ops->tname;
1017 	err = find_struct_ops_kern_types(kern_btf, tname,
1018 					 &kern_type, &kern_type_id,
1019 					 &kern_vtype, &kern_vtype_id,
1020 					 &kern_data_member);
1021 	if (err)
1022 		return err;
1023 
1024 	pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
1025 		 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
1026 
1027 	map->def.value_size = kern_vtype->size;
1028 	map->btf_vmlinux_value_type_id = kern_vtype_id;
1029 
1030 	st_ops->kern_vdata = calloc(1, kern_vtype->size);
1031 	if (!st_ops->kern_vdata)
1032 		return -ENOMEM;
1033 
1034 	data = st_ops->data;
1035 	kern_data_off = kern_data_member->offset / 8;
1036 	kern_data = st_ops->kern_vdata + kern_data_off;
1037 
1038 	member = btf_members(type);
1039 	for (i = 0; i < btf_vlen(type); i++, member++) {
1040 		const struct btf_type *mtype, *kern_mtype;
1041 		__u32 mtype_id, kern_mtype_id;
1042 		void *mdata, *kern_mdata;
1043 		__s64 msize, kern_msize;
1044 		__u32 moff, kern_moff;
1045 		__u32 kern_member_idx;
1046 		const char *mname;
1047 
1048 		mname = btf__name_by_offset(btf, member->name_off);
1049 		kern_member = find_member_by_name(kern_btf, kern_type, mname);
1050 		if (!kern_member) {
1051 			pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
1052 				map->name, mname);
1053 			return -ENOTSUP;
1054 		}
1055 
1056 		kern_member_idx = kern_member - btf_members(kern_type);
1057 		if (btf_member_bitfield_size(type, i) ||
1058 		    btf_member_bitfield_size(kern_type, kern_member_idx)) {
1059 			pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
1060 				map->name, mname);
1061 			return -ENOTSUP;
1062 		}
1063 
1064 		moff = member->offset / 8;
1065 		kern_moff = kern_member->offset / 8;
1066 
1067 		mdata = data + moff;
1068 		kern_mdata = kern_data + kern_moff;
1069 
1070 		mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
1071 		kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
1072 						    &kern_mtype_id);
1073 		if (BTF_INFO_KIND(mtype->info) !=
1074 		    BTF_INFO_KIND(kern_mtype->info)) {
1075 			pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
1076 				map->name, mname, BTF_INFO_KIND(mtype->info),
1077 				BTF_INFO_KIND(kern_mtype->info));
1078 			return -ENOTSUP;
1079 		}
1080 
1081 		if (btf_is_ptr(mtype)) {
1082 			struct bpf_program *prog;
1083 
1084 			prog = st_ops->progs[i];
1085 			if (!prog)
1086 				continue;
1087 
1088 			kern_mtype = skip_mods_and_typedefs(kern_btf,
1089 							    kern_mtype->type,
1090 							    &kern_mtype_id);
1091 
1092 			/* mtype->type must be a func_proto which was
1093 			 * guaranteed in bpf_object__collect_st_ops_relos(),
1094 			 * so only check kern_mtype for func_proto here.
1095 			 */
1096 			if (!btf_is_func_proto(kern_mtype)) {
1097 				pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
1098 					map->name, mname);
1099 				return -ENOTSUP;
1100 			}
1101 
1102 			prog->attach_btf_id = kern_type_id;
1103 			prog->expected_attach_type = kern_member_idx;
1104 
1105 			st_ops->kern_func_off[i] = kern_data_off + kern_moff;
1106 
1107 			pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
1108 				 map->name, mname, prog->name, moff,
1109 				 kern_moff);
1110 
1111 			continue;
1112 		}
1113 
1114 		msize = btf__resolve_size(btf, mtype_id);
1115 		kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
1116 		if (msize < 0 || kern_msize < 0 || msize != kern_msize) {
1117 			pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
1118 				map->name, mname, (ssize_t)msize,
1119 				(ssize_t)kern_msize);
1120 			return -ENOTSUP;
1121 		}
1122 
1123 		pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
1124 			 map->name, mname, (unsigned int)msize,
1125 			 moff, kern_moff);
1126 		memcpy(kern_mdata, mdata, msize);
1127 	}
1128 
1129 	return 0;
1130 }
1131 
1132 static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
1133 {
1134 	struct bpf_map *map;
1135 	size_t i;
1136 	int err;
1137 
1138 	for (i = 0; i < obj->nr_maps; i++) {
1139 		map = &obj->maps[i];
1140 
1141 		if (!bpf_map__is_struct_ops(map))
1142 			continue;
1143 
1144 		err = bpf_map__init_kern_struct_ops(map, obj->btf,
1145 						    obj->btf_vmlinux);
1146 		if (err)
1147 			return err;
1148 	}
1149 
1150 	return 0;
1151 }
1152 
1153 static int init_struct_ops_maps(struct bpf_object *obj, const char *sec_name,
1154 				int shndx, Elf_Data *data, __u32 map_flags)
1155 {
1156 	const struct btf_type *type, *datasec;
1157 	const struct btf_var_secinfo *vsi;
1158 	struct bpf_struct_ops *st_ops;
1159 	const char *tname, *var_name;
1160 	__s32 type_id, datasec_id;
1161 	const struct btf *btf;
1162 	struct bpf_map *map;
1163 	__u32 i;
1164 
1165 	if (shndx == -1)
1166 		return 0;
1167 
1168 	btf = obj->btf;
1169 	datasec_id = btf__find_by_name_kind(btf, sec_name,
1170 					    BTF_KIND_DATASEC);
1171 	if (datasec_id < 0) {
1172 		pr_warn("struct_ops init: DATASEC %s not found\n",
1173 			sec_name);
1174 		return -EINVAL;
1175 	}
1176 
1177 	datasec = btf__type_by_id(btf, datasec_id);
1178 	vsi = btf_var_secinfos(datasec);
1179 	for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
1180 		type = btf__type_by_id(obj->btf, vsi->type);
1181 		var_name = btf__name_by_offset(obj->btf, type->name_off);
1182 
1183 		type_id = btf__resolve_type(obj->btf, vsi->type);
1184 		if (type_id < 0) {
1185 			pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
1186 				vsi->type, sec_name);
1187 			return -EINVAL;
1188 		}
1189 
1190 		type = btf__type_by_id(obj->btf, type_id);
1191 		tname = btf__name_by_offset(obj->btf, type->name_off);
1192 		if (!tname[0]) {
1193 			pr_warn("struct_ops init: anonymous type is not supported\n");
1194 			return -ENOTSUP;
1195 		}
1196 		if (!btf_is_struct(type)) {
1197 			pr_warn("struct_ops init: %s is not a struct\n", tname);
1198 			return -EINVAL;
1199 		}
1200 
1201 		map = bpf_object__add_map(obj);
1202 		if (IS_ERR(map))
1203 			return PTR_ERR(map);
1204 
1205 		map->sec_idx = shndx;
1206 		map->sec_offset = vsi->offset;
1207 		map->name = strdup(var_name);
1208 		if (!map->name)
1209 			return -ENOMEM;
1210 
1211 		map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
1212 		map->def.key_size = sizeof(int);
1213 		map->def.value_size = type->size;
1214 		map->def.max_entries = 1;
1215 		map->def.map_flags = map_flags;
1216 
1217 		map->st_ops = calloc(1, sizeof(*map->st_ops));
1218 		if (!map->st_ops)
1219 			return -ENOMEM;
1220 		st_ops = map->st_ops;
1221 		st_ops->data = malloc(type->size);
1222 		st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1223 		st_ops->kern_func_off = malloc(btf_vlen(type) *
1224 					       sizeof(*st_ops->kern_func_off));
1225 		if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1226 			return -ENOMEM;
1227 
1228 		if (vsi->offset + type->size > data->d_size) {
1229 			pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1230 				var_name, sec_name);
1231 			return -EINVAL;
1232 		}
1233 
1234 		memcpy(st_ops->data,
1235 		       data->d_buf + vsi->offset,
1236 		       type->size);
1237 		st_ops->tname = tname;
1238 		st_ops->type = type;
1239 		st_ops->type_id = type_id;
1240 
1241 		pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
1242 			 tname, type_id, var_name, vsi->offset);
1243 	}
1244 
1245 	return 0;
1246 }
1247 
1248 static int bpf_object_init_struct_ops(struct bpf_object *obj)
1249 {
1250 	int err;
1251 
1252 	err = init_struct_ops_maps(obj, STRUCT_OPS_SEC, obj->efile.st_ops_shndx,
1253 				   obj->efile.st_ops_data, 0);
1254 	err = err ?: init_struct_ops_maps(obj, STRUCT_OPS_LINK_SEC,
1255 					  obj->efile.st_ops_link_shndx,
1256 					  obj->efile.st_ops_link_data,
1257 					  BPF_F_LINK);
1258 	return err;
1259 }
1260 
1261 static struct bpf_object *bpf_object__new(const char *path,
1262 					  const void *obj_buf,
1263 					  size_t obj_buf_sz,
1264 					  const char *obj_name)
1265 {
1266 	struct bpf_object *obj;
1267 	char *end;
1268 
1269 	obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1270 	if (!obj) {
1271 		pr_warn("alloc memory failed for %s\n", path);
1272 		return ERR_PTR(-ENOMEM);
1273 	}
1274 
1275 	strcpy(obj->path, path);
1276 	if (obj_name) {
1277 		libbpf_strlcpy(obj->name, obj_name, sizeof(obj->name));
1278 	} else {
1279 		/* Using basename() GNU version which doesn't modify arg. */
1280 		libbpf_strlcpy(obj->name, basename((void *)path), sizeof(obj->name));
1281 		end = strchr(obj->name, '.');
1282 		if (end)
1283 			*end = 0;
1284 	}
1285 
1286 	obj->efile.fd = -1;
1287 	/*
1288 	 * Caller of this function should also call
1289 	 * bpf_object__elf_finish() after data collection to return
1290 	 * obj_buf to user. If not, we should duplicate the buffer to
1291 	 * avoid user freeing them before elf finish.
1292 	 */
1293 	obj->efile.obj_buf = obj_buf;
1294 	obj->efile.obj_buf_sz = obj_buf_sz;
1295 	obj->efile.btf_maps_shndx = -1;
1296 	obj->efile.st_ops_shndx = -1;
1297 	obj->efile.st_ops_link_shndx = -1;
1298 	obj->kconfig_map_idx = -1;
1299 
1300 	obj->kern_version = get_kernel_version();
1301 	obj->loaded = false;
1302 
1303 	return obj;
1304 }
1305 
1306 static void bpf_object__elf_finish(struct bpf_object *obj)
1307 {
1308 	if (!obj->efile.elf)
1309 		return;
1310 
1311 	elf_end(obj->efile.elf);
1312 	obj->efile.elf = NULL;
1313 	obj->efile.symbols = NULL;
1314 	obj->efile.st_ops_data = NULL;
1315 	obj->efile.st_ops_link_data = NULL;
1316 
1317 	zfree(&obj->efile.secs);
1318 	obj->efile.sec_cnt = 0;
1319 	zclose(obj->efile.fd);
1320 	obj->efile.obj_buf = NULL;
1321 	obj->efile.obj_buf_sz = 0;
1322 }
1323 
1324 static int bpf_object__elf_init(struct bpf_object *obj)
1325 {
1326 	Elf64_Ehdr *ehdr;
1327 	int err = 0;
1328 	Elf *elf;
1329 
1330 	if (obj->efile.elf) {
1331 		pr_warn("elf: init internal error\n");
1332 		return -LIBBPF_ERRNO__LIBELF;
1333 	}
1334 
1335 	if (obj->efile.obj_buf_sz > 0) {
1336 		/* obj_buf should have been validated by bpf_object__open_mem(). */
1337 		elf = elf_memory((char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
1338 	} else {
1339 		obj->efile.fd = open(obj->path, O_RDONLY | O_CLOEXEC);
1340 		if (obj->efile.fd < 0) {
1341 			char errmsg[STRERR_BUFSIZE], *cp;
1342 
1343 			err = -errno;
1344 			cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
1345 			pr_warn("elf: failed to open %s: %s\n", obj->path, cp);
1346 			return err;
1347 		}
1348 
1349 		elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1350 	}
1351 
1352 	if (!elf) {
1353 		pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
1354 		err = -LIBBPF_ERRNO__LIBELF;
1355 		goto errout;
1356 	}
1357 
1358 	obj->efile.elf = elf;
1359 
1360 	if (elf_kind(elf) != ELF_K_ELF) {
1361 		err = -LIBBPF_ERRNO__FORMAT;
1362 		pr_warn("elf: '%s' is not a proper ELF object\n", obj->path);
1363 		goto errout;
1364 	}
1365 
1366 	if (gelf_getclass(elf) != ELFCLASS64) {
1367 		err = -LIBBPF_ERRNO__FORMAT;
1368 		pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path);
1369 		goto errout;
1370 	}
1371 
1372 	obj->efile.ehdr = ehdr = elf64_getehdr(elf);
1373 	if (!obj->efile.ehdr) {
1374 		pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
1375 		err = -LIBBPF_ERRNO__FORMAT;
1376 		goto errout;
1377 	}
1378 
1379 	if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
1380 		pr_warn("elf: failed to get section names section index for %s: %s\n",
1381 			obj->path, elf_errmsg(-1));
1382 		err = -LIBBPF_ERRNO__FORMAT;
1383 		goto errout;
1384 	}
1385 
1386 	/* ELF is corrupted/truncated, avoid calling elf_strptr. */
1387 	if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
1388 		pr_warn("elf: failed to get section names strings from %s: %s\n",
1389 			obj->path, elf_errmsg(-1));
1390 		err = -LIBBPF_ERRNO__FORMAT;
1391 		goto errout;
1392 	}
1393 
1394 	/* Old LLVM set e_machine to EM_NONE */
1395 	if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
1396 		pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
1397 		err = -LIBBPF_ERRNO__FORMAT;
1398 		goto errout;
1399 	}
1400 
1401 	return 0;
1402 errout:
1403 	bpf_object__elf_finish(obj);
1404 	return err;
1405 }
1406 
1407 static int bpf_object__check_endianness(struct bpf_object *obj)
1408 {
1409 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1410 	if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2LSB)
1411 		return 0;
1412 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1413 	if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2MSB)
1414 		return 0;
1415 #else
1416 # error "Unrecognized __BYTE_ORDER__"
1417 #endif
1418 	pr_warn("elf: endianness mismatch in %s.\n", obj->path);
1419 	return -LIBBPF_ERRNO__ENDIAN;
1420 }
1421 
1422 static int
1423 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1424 {
1425 	if (!data) {
1426 		pr_warn("invalid license section in %s\n", obj->path);
1427 		return -LIBBPF_ERRNO__FORMAT;
1428 	}
1429 	/* libbpf_strlcpy() only copies first N - 1 bytes, so size + 1 won't
1430 	 * go over allowed ELF data section buffer
1431 	 */
1432 	libbpf_strlcpy(obj->license, data, min(size + 1, sizeof(obj->license)));
1433 	pr_debug("license of %s is %s\n", obj->path, obj->license);
1434 	return 0;
1435 }
1436 
1437 static int
1438 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1439 {
1440 	__u32 kver;
1441 
1442 	if (!data || size != sizeof(kver)) {
1443 		pr_warn("invalid kver section in %s\n", obj->path);
1444 		return -LIBBPF_ERRNO__FORMAT;
1445 	}
1446 	memcpy(&kver, data, sizeof(kver));
1447 	obj->kern_version = kver;
1448 	pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1449 	return 0;
1450 }
1451 
1452 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1453 {
1454 	if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1455 	    type == BPF_MAP_TYPE_HASH_OF_MAPS)
1456 		return true;
1457 	return false;
1458 }
1459 
1460 static int find_elf_sec_sz(const struct bpf_object *obj, const char *name, __u32 *size)
1461 {
1462 	Elf_Data *data;
1463 	Elf_Scn *scn;
1464 
1465 	if (!name)
1466 		return -EINVAL;
1467 
1468 	scn = elf_sec_by_name(obj, name);
1469 	data = elf_sec_data(obj, scn);
1470 	if (data) {
1471 		*size = data->d_size;
1472 		return 0; /* found it */
1473 	}
1474 
1475 	return -ENOENT;
1476 }
1477 
1478 static Elf64_Sym *find_elf_var_sym(const struct bpf_object *obj, const char *name)
1479 {
1480 	Elf_Data *symbols = obj->efile.symbols;
1481 	const char *sname;
1482 	size_t si;
1483 
1484 	for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
1485 		Elf64_Sym *sym = elf_sym_by_idx(obj, si);
1486 
1487 		if (ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)
1488 			continue;
1489 
1490 		if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL &&
1491 		    ELF64_ST_BIND(sym->st_info) != STB_WEAK)
1492 			continue;
1493 
1494 		sname = elf_sym_str(obj, sym->st_name);
1495 		if (!sname) {
1496 			pr_warn("failed to get sym name string for var %s\n", name);
1497 			return ERR_PTR(-EIO);
1498 		}
1499 		if (strcmp(name, sname) == 0)
1500 			return sym;
1501 	}
1502 
1503 	return ERR_PTR(-ENOENT);
1504 }
1505 
1506 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1507 {
1508 	struct bpf_map *map;
1509 	int err;
1510 
1511 	err = libbpf_ensure_mem((void **)&obj->maps, &obj->maps_cap,
1512 				sizeof(*obj->maps), obj->nr_maps + 1);
1513 	if (err)
1514 		return ERR_PTR(err);
1515 
1516 	map = &obj->maps[obj->nr_maps++];
1517 	map->obj = obj;
1518 	map->fd = -1;
1519 	map->inner_map_fd = -1;
1520 	map->autocreate = true;
1521 
1522 	return map;
1523 }
1524 
1525 static size_t bpf_map_mmap_sz(unsigned int value_sz, unsigned int max_entries)
1526 {
1527 	const long page_sz = sysconf(_SC_PAGE_SIZE);
1528 	size_t map_sz;
1529 
1530 	map_sz = (size_t)roundup(value_sz, 8) * max_entries;
1531 	map_sz = roundup(map_sz, page_sz);
1532 	return map_sz;
1533 }
1534 
1535 static int bpf_map_mmap_resize(struct bpf_map *map, size_t old_sz, size_t new_sz)
1536 {
1537 	void *mmaped;
1538 
1539 	if (!map->mmaped)
1540 		return -EINVAL;
1541 
1542 	if (old_sz == new_sz)
1543 		return 0;
1544 
1545 	mmaped = mmap(NULL, new_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1546 	if (mmaped == MAP_FAILED)
1547 		return -errno;
1548 
1549 	memcpy(mmaped, map->mmaped, min(old_sz, new_sz));
1550 	munmap(map->mmaped, old_sz);
1551 	map->mmaped = mmaped;
1552 	return 0;
1553 }
1554 
1555 static char *internal_map_name(struct bpf_object *obj, const char *real_name)
1556 {
1557 	char map_name[BPF_OBJ_NAME_LEN], *p;
1558 	int pfx_len, sfx_len = max((size_t)7, strlen(real_name));
1559 
1560 	/* This is one of the more confusing parts of libbpf for various
1561 	 * reasons, some of which are historical. The original idea for naming
1562 	 * internal names was to include as much of BPF object name prefix as
1563 	 * possible, so that it can be distinguished from similar internal
1564 	 * maps of a different BPF object.
1565 	 * As an example, let's say we have bpf_object named 'my_object_name'
1566 	 * and internal map corresponding to '.rodata' ELF section. The final
1567 	 * map name advertised to user and to the kernel will be
1568 	 * 'my_objec.rodata', taking first 8 characters of object name and
1569 	 * entire 7 characters of '.rodata'.
1570 	 * Somewhat confusingly, if internal map ELF section name is shorter
1571 	 * than 7 characters, e.g., '.bss', we still reserve 7 characters
1572 	 * for the suffix, even though we only have 4 actual characters, and
1573 	 * resulting map will be called 'my_objec.bss', not even using all 15
1574 	 * characters allowed by the kernel. Oh well, at least the truncated
1575 	 * object name is somewhat consistent in this case. But if the map
1576 	 * name is '.kconfig', we'll still have entirety of '.kconfig' added
1577 	 * (8 chars) and thus will be left with only first 7 characters of the
1578 	 * object name ('my_obje'). Happy guessing, user, that the final map
1579 	 * name will be "my_obje.kconfig".
1580 	 * Now, with libbpf starting to support arbitrarily named .rodata.*
1581 	 * and .data.* data sections, it's possible that ELF section name is
1582 	 * longer than allowed 15 chars, so we now need to be careful to take
1583 	 * only up to 15 first characters of ELF name, taking no BPF object
1584 	 * name characters at all. So '.rodata.abracadabra' will result in
1585 	 * '.rodata.abracad' kernel and user-visible name.
1586 	 * We need to keep this convoluted logic intact for .data, .bss and
1587 	 * .rodata maps, but for new custom .data.custom and .rodata.custom
1588 	 * maps we use their ELF names as is, not prepending bpf_object name
1589 	 * in front. We still need to truncate them to 15 characters for the
1590 	 * kernel. Full name can be recovered for such maps by using DATASEC
1591 	 * BTF type associated with such map's value type, though.
1592 	 */
1593 	if (sfx_len >= BPF_OBJ_NAME_LEN)
1594 		sfx_len = BPF_OBJ_NAME_LEN - 1;
1595 
1596 	/* if there are two or more dots in map name, it's a custom dot map */
1597 	if (strchr(real_name + 1, '.') != NULL)
1598 		pfx_len = 0;
1599 	else
1600 		pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
1601 
1602 	snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1603 		 sfx_len, real_name);
1604 
1605 	/* sanitise map name to characters allowed by kernel */
1606 	for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1607 		if (!isalnum(*p) && *p != '_' && *p != '.')
1608 			*p = '_';
1609 
1610 	return strdup(map_name);
1611 }
1612 
1613 static int
1614 map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map);
1615 
1616 /* Internal BPF map is mmap()'able only if at least one of corresponding
1617  * DATASEC's VARs are to be exposed through BPF skeleton. I.e., it's a GLOBAL
1618  * variable and it's not marked as __hidden (which turns it into, effectively,
1619  * a STATIC variable).
1620  */
1621 static bool map_is_mmapable(struct bpf_object *obj, struct bpf_map *map)
1622 {
1623 	const struct btf_type *t, *vt;
1624 	struct btf_var_secinfo *vsi;
1625 	int i, n;
1626 
1627 	if (!map->btf_value_type_id)
1628 		return false;
1629 
1630 	t = btf__type_by_id(obj->btf, map->btf_value_type_id);
1631 	if (!btf_is_datasec(t))
1632 		return false;
1633 
1634 	vsi = btf_var_secinfos(t);
1635 	for (i = 0, n = btf_vlen(t); i < n; i++, vsi++) {
1636 		vt = btf__type_by_id(obj->btf, vsi->type);
1637 		if (!btf_is_var(vt))
1638 			continue;
1639 
1640 		if (btf_var(vt)->linkage != BTF_VAR_STATIC)
1641 			return true;
1642 	}
1643 
1644 	return false;
1645 }
1646 
1647 static int
1648 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
1649 			      const char *real_name, int sec_idx, void *data, size_t data_sz)
1650 {
1651 	struct bpf_map_def *def;
1652 	struct bpf_map *map;
1653 	size_t mmap_sz;
1654 	int err;
1655 
1656 	map = bpf_object__add_map(obj);
1657 	if (IS_ERR(map))
1658 		return PTR_ERR(map);
1659 
1660 	map->libbpf_type = type;
1661 	map->sec_idx = sec_idx;
1662 	map->sec_offset = 0;
1663 	map->real_name = strdup(real_name);
1664 	map->name = internal_map_name(obj, real_name);
1665 	if (!map->real_name || !map->name) {
1666 		zfree(&map->real_name);
1667 		zfree(&map->name);
1668 		return -ENOMEM;
1669 	}
1670 
1671 	def = &map->def;
1672 	def->type = BPF_MAP_TYPE_ARRAY;
1673 	def->key_size = sizeof(int);
1674 	def->value_size = data_sz;
1675 	def->max_entries = 1;
1676 	def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
1677 			 ? BPF_F_RDONLY_PROG : 0;
1678 
1679 	/* failures are fine because of maps like .rodata.str1.1 */
1680 	(void) map_fill_btf_type_info(obj, map);
1681 
1682 	if (map_is_mmapable(obj, map))
1683 		def->map_flags |= BPF_F_MMAPABLE;
1684 
1685 	pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
1686 		 map->name, map->sec_idx, map->sec_offset, def->map_flags);
1687 
1688 	mmap_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
1689 	map->mmaped = mmap(NULL, mmap_sz, PROT_READ | PROT_WRITE,
1690 			   MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1691 	if (map->mmaped == MAP_FAILED) {
1692 		err = -errno;
1693 		map->mmaped = NULL;
1694 		pr_warn("failed to alloc map '%s' content buffer: %d\n",
1695 			map->name, err);
1696 		zfree(&map->real_name);
1697 		zfree(&map->name);
1698 		return err;
1699 	}
1700 
1701 	if (data)
1702 		memcpy(map->mmaped, data, data_sz);
1703 
1704 	pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
1705 	return 0;
1706 }
1707 
1708 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
1709 {
1710 	struct elf_sec_desc *sec_desc;
1711 	const char *sec_name;
1712 	int err = 0, sec_idx;
1713 
1714 	/*
1715 	 * Populate obj->maps with libbpf internal maps.
1716 	 */
1717 	for (sec_idx = 1; sec_idx < obj->efile.sec_cnt; sec_idx++) {
1718 		sec_desc = &obj->efile.secs[sec_idx];
1719 
1720 		/* Skip recognized sections with size 0. */
1721 		if (!sec_desc->data || sec_desc->data->d_size == 0)
1722 			continue;
1723 
1724 		switch (sec_desc->sec_type) {
1725 		case SEC_DATA:
1726 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1727 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
1728 							    sec_name, sec_idx,
1729 							    sec_desc->data->d_buf,
1730 							    sec_desc->data->d_size);
1731 			break;
1732 		case SEC_RODATA:
1733 			obj->has_rodata = true;
1734 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1735 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
1736 							    sec_name, sec_idx,
1737 							    sec_desc->data->d_buf,
1738 							    sec_desc->data->d_size);
1739 			break;
1740 		case SEC_BSS:
1741 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1742 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
1743 							    sec_name, sec_idx,
1744 							    NULL,
1745 							    sec_desc->data->d_size);
1746 			break;
1747 		default:
1748 			/* skip */
1749 			break;
1750 		}
1751 		if (err)
1752 			return err;
1753 	}
1754 	return 0;
1755 }
1756 
1757 
1758 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
1759 					       const void *name)
1760 {
1761 	int i;
1762 
1763 	for (i = 0; i < obj->nr_extern; i++) {
1764 		if (strcmp(obj->externs[i].name, name) == 0)
1765 			return &obj->externs[i];
1766 	}
1767 	return NULL;
1768 }
1769 
1770 static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
1771 			      char value)
1772 {
1773 	switch (ext->kcfg.type) {
1774 	case KCFG_BOOL:
1775 		if (value == 'm') {
1776 			pr_warn("extern (kcfg) '%s': value '%c' implies tristate or char type\n",
1777 				ext->name, value);
1778 			return -EINVAL;
1779 		}
1780 		*(bool *)ext_val = value == 'y' ? true : false;
1781 		break;
1782 	case KCFG_TRISTATE:
1783 		if (value == 'y')
1784 			*(enum libbpf_tristate *)ext_val = TRI_YES;
1785 		else if (value == 'm')
1786 			*(enum libbpf_tristate *)ext_val = TRI_MODULE;
1787 		else /* value == 'n' */
1788 			*(enum libbpf_tristate *)ext_val = TRI_NO;
1789 		break;
1790 	case KCFG_CHAR:
1791 		*(char *)ext_val = value;
1792 		break;
1793 	case KCFG_UNKNOWN:
1794 	case KCFG_INT:
1795 	case KCFG_CHAR_ARR:
1796 	default:
1797 		pr_warn("extern (kcfg) '%s': value '%c' implies bool, tristate, or char type\n",
1798 			ext->name, value);
1799 		return -EINVAL;
1800 	}
1801 	ext->is_set = true;
1802 	return 0;
1803 }
1804 
1805 static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
1806 			      const char *value)
1807 {
1808 	size_t len;
1809 
1810 	if (ext->kcfg.type != KCFG_CHAR_ARR) {
1811 		pr_warn("extern (kcfg) '%s': value '%s' implies char array type\n",
1812 			ext->name, value);
1813 		return -EINVAL;
1814 	}
1815 
1816 	len = strlen(value);
1817 	if (value[len - 1] != '"') {
1818 		pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
1819 			ext->name, value);
1820 		return -EINVAL;
1821 	}
1822 
1823 	/* strip quotes */
1824 	len -= 2;
1825 	if (len >= ext->kcfg.sz) {
1826 		pr_warn("extern (kcfg) '%s': long string '%s' of (%zu bytes) truncated to %d bytes\n",
1827 			ext->name, value, len, ext->kcfg.sz - 1);
1828 		len = ext->kcfg.sz - 1;
1829 	}
1830 	memcpy(ext_val, value + 1, len);
1831 	ext_val[len] = '\0';
1832 	ext->is_set = true;
1833 	return 0;
1834 }
1835 
1836 static int parse_u64(const char *value, __u64 *res)
1837 {
1838 	char *value_end;
1839 	int err;
1840 
1841 	errno = 0;
1842 	*res = strtoull(value, &value_end, 0);
1843 	if (errno) {
1844 		err = -errno;
1845 		pr_warn("failed to parse '%s' as integer: %d\n", value, err);
1846 		return err;
1847 	}
1848 	if (*value_end) {
1849 		pr_warn("failed to parse '%s' as integer completely\n", value);
1850 		return -EINVAL;
1851 	}
1852 	return 0;
1853 }
1854 
1855 static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
1856 {
1857 	int bit_sz = ext->kcfg.sz * 8;
1858 
1859 	if (ext->kcfg.sz == 8)
1860 		return true;
1861 
1862 	/* Validate that value stored in u64 fits in integer of `ext->sz`
1863 	 * bytes size without any loss of information. If the target integer
1864 	 * is signed, we rely on the following limits of integer type of
1865 	 * Y bits and subsequent transformation:
1866 	 *
1867 	 *     -2^(Y-1) <= X           <= 2^(Y-1) - 1
1868 	 *            0 <= X + 2^(Y-1) <= 2^Y - 1
1869 	 *            0 <= X + 2^(Y-1) <  2^Y
1870 	 *
1871 	 *  For unsigned target integer, check that all the (64 - Y) bits are
1872 	 *  zero.
1873 	 */
1874 	if (ext->kcfg.is_signed)
1875 		return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
1876 	else
1877 		return (v >> bit_sz) == 0;
1878 }
1879 
1880 static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
1881 			      __u64 value)
1882 {
1883 	if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR &&
1884 	    ext->kcfg.type != KCFG_BOOL) {
1885 		pr_warn("extern (kcfg) '%s': value '%llu' implies integer, char, or boolean type\n",
1886 			ext->name, (unsigned long long)value);
1887 		return -EINVAL;
1888 	}
1889 	if (ext->kcfg.type == KCFG_BOOL && value > 1) {
1890 		pr_warn("extern (kcfg) '%s': value '%llu' isn't boolean compatible\n",
1891 			ext->name, (unsigned long long)value);
1892 		return -EINVAL;
1893 
1894 	}
1895 	if (!is_kcfg_value_in_range(ext, value)) {
1896 		pr_warn("extern (kcfg) '%s': value '%llu' doesn't fit in %d bytes\n",
1897 			ext->name, (unsigned long long)value, ext->kcfg.sz);
1898 		return -ERANGE;
1899 	}
1900 	switch (ext->kcfg.sz) {
1901 	case 1:
1902 		*(__u8 *)ext_val = value;
1903 		break;
1904 	case 2:
1905 		*(__u16 *)ext_val = value;
1906 		break;
1907 	case 4:
1908 		*(__u32 *)ext_val = value;
1909 		break;
1910 	case 8:
1911 		*(__u64 *)ext_val = value;
1912 		break;
1913 	default:
1914 		return -EINVAL;
1915 	}
1916 	ext->is_set = true;
1917 	return 0;
1918 }
1919 
1920 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
1921 					    char *buf, void *data)
1922 {
1923 	struct extern_desc *ext;
1924 	char *sep, *value;
1925 	int len, err = 0;
1926 	void *ext_val;
1927 	__u64 num;
1928 
1929 	if (!str_has_pfx(buf, "CONFIG_"))
1930 		return 0;
1931 
1932 	sep = strchr(buf, '=');
1933 	if (!sep) {
1934 		pr_warn("failed to parse '%s': no separator\n", buf);
1935 		return -EINVAL;
1936 	}
1937 
1938 	/* Trim ending '\n' */
1939 	len = strlen(buf);
1940 	if (buf[len - 1] == '\n')
1941 		buf[len - 1] = '\0';
1942 	/* Split on '=' and ensure that a value is present. */
1943 	*sep = '\0';
1944 	if (!sep[1]) {
1945 		*sep = '=';
1946 		pr_warn("failed to parse '%s': no value\n", buf);
1947 		return -EINVAL;
1948 	}
1949 
1950 	ext = find_extern_by_name(obj, buf);
1951 	if (!ext || ext->is_set)
1952 		return 0;
1953 
1954 	ext_val = data + ext->kcfg.data_off;
1955 	value = sep + 1;
1956 
1957 	switch (*value) {
1958 	case 'y': case 'n': case 'm':
1959 		err = set_kcfg_value_tri(ext, ext_val, *value);
1960 		break;
1961 	case '"':
1962 		err = set_kcfg_value_str(ext, ext_val, value);
1963 		break;
1964 	default:
1965 		/* assume integer */
1966 		err = parse_u64(value, &num);
1967 		if (err) {
1968 			pr_warn("extern (kcfg) '%s': value '%s' isn't a valid integer\n", ext->name, value);
1969 			return err;
1970 		}
1971 		if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
1972 			pr_warn("extern (kcfg) '%s': value '%s' implies integer type\n", ext->name, value);
1973 			return -EINVAL;
1974 		}
1975 		err = set_kcfg_value_num(ext, ext_val, num);
1976 		break;
1977 	}
1978 	if (err)
1979 		return err;
1980 	pr_debug("extern (kcfg) '%s': set to %s\n", ext->name, value);
1981 	return 0;
1982 }
1983 
1984 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
1985 {
1986 	char buf[PATH_MAX];
1987 	struct utsname uts;
1988 	int len, err = 0;
1989 	gzFile file;
1990 
1991 	uname(&uts);
1992 	len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
1993 	if (len < 0)
1994 		return -EINVAL;
1995 	else if (len >= PATH_MAX)
1996 		return -ENAMETOOLONG;
1997 
1998 	/* gzopen also accepts uncompressed files. */
1999 	file = gzopen(buf, "re");
2000 	if (!file)
2001 		file = gzopen("/proc/config.gz", "re");
2002 
2003 	if (!file) {
2004 		pr_warn("failed to open system Kconfig\n");
2005 		return -ENOENT;
2006 	}
2007 
2008 	while (gzgets(file, buf, sizeof(buf))) {
2009 		err = bpf_object__process_kconfig_line(obj, buf, data);
2010 		if (err) {
2011 			pr_warn("error parsing system Kconfig line '%s': %d\n",
2012 				buf, err);
2013 			goto out;
2014 		}
2015 	}
2016 
2017 out:
2018 	gzclose(file);
2019 	return err;
2020 }
2021 
2022 static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
2023 					const char *config, void *data)
2024 {
2025 	char buf[PATH_MAX];
2026 	int err = 0;
2027 	FILE *file;
2028 
2029 	file = fmemopen((void *)config, strlen(config), "r");
2030 	if (!file) {
2031 		err = -errno;
2032 		pr_warn("failed to open in-memory Kconfig: %d\n", err);
2033 		return err;
2034 	}
2035 
2036 	while (fgets(buf, sizeof(buf), file)) {
2037 		err = bpf_object__process_kconfig_line(obj, buf, data);
2038 		if (err) {
2039 			pr_warn("error parsing in-memory Kconfig line '%s': %d\n",
2040 				buf, err);
2041 			break;
2042 		}
2043 	}
2044 
2045 	fclose(file);
2046 	return err;
2047 }
2048 
2049 static int bpf_object__init_kconfig_map(struct bpf_object *obj)
2050 {
2051 	struct extern_desc *last_ext = NULL, *ext;
2052 	size_t map_sz;
2053 	int i, err;
2054 
2055 	for (i = 0; i < obj->nr_extern; i++) {
2056 		ext = &obj->externs[i];
2057 		if (ext->type == EXT_KCFG)
2058 			last_ext = ext;
2059 	}
2060 
2061 	if (!last_ext)
2062 		return 0;
2063 
2064 	map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
2065 	err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
2066 					    ".kconfig", obj->efile.symbols_shndx,
2067 					    NULL, map_sz);
2068 	if (err)
2069 		return err;
2070 
2071 	obj->kconfig_map_idx = obj->nr_maps - 1;
2072 
2073 	return 0;
2074 }
2075 
2076 const struct btf_type *
2077 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
2078 {
2079 	const struct btf_type *t = btf__type_by_id(btf, id);
2080 
2081 	if (res_id)
2082 		*res_id = id;
2083 
2084 	while (btf_is_mod(t) || btf_is_typedef(t)) {
2085 		if (res_id)
2086 			*res_id = t->type;
2087 		t = btf__type_by_id(btf, t->type);
2088 	}
2089 
2090 	return t;
2091 }
2092 
2093 static const struct btf_type *
2094 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
2095 {
2096 	const struct btf_type *t;
2097 
2098 	t = skip_mods_and_typedefs(btf, id, NULL);
2099 	if (!btf_is_ptr(t))
2100 		return NULL;
2101 
2102 	t = skip_mods_and_typedefs(btf, t->type, res_id);
2103 
2104 	return btf_is_func_proto(t) ? t : NULL;
2105 }
2106 
2107 static const char *__btf_kind_str(__u16 kind)
2108 {
2109 	switch (kind) {
2110 	case BTF_KIND_UNKN: return "void";
2111 	case BTF_KIND_INT: return "int";
2112 	case BTF_KIND_PTR: return "ptr";
2113 	case BTF_KIND_ARRAY: return "array";
2114 	case BTF_KIND_STRUCT: return "struct";
2115 	case BTF_KIND_UNION: return "union";
2116 	case BTF_KIND_ENUM: return "enum";
2117 	case BTF_KIND_FWD: return "fwd";
2118 	case BTF_KIND_TYPEDEF: return "typedef";
2119 	case BTF_KIND_VOLATILE: return "volatile";
2120 	case BTF_KIND_CONST: return "const";
2121 	case BTF_KIND_RESTRICT: return "restrict";
2122 	case BTF_KIND_FUNC: return "func";
2123 	case BTF_KIND_FUNC_PROTO: return "func_proto";
2124 	case BTF_KIND_VAR: return "var";
2125 	case BTF_KIND_DATASEC: return "datasec";
2126 	case BTF_KIND_FLOAT: return "float";
2127 	case BTF_KIND_DECL_TAG: return "decl_tag";
2128 	case BTF_KIND_TYPE_TAG: return "type_tag";
2129 	case BTF_KIND_ENUM64: return "enum64";
2130 	default: return "unknown";
2131 	}
2132 }
2133 
2134 const char *btf_kind_str(const struct btf_type *t)
2135 {
2136 	return __btf_kind_str(btf_kind(t));
2137 }
2138 
2139 /*
2140  * Fetch integer attribute of BTF map definition. Such attributes are
2141  * represented using a pointer to an array, in which dimensionality of array
2142  * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2143  * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2144  * type definition, while using only sizeof(void *) space in ELF data section.
2145  */
2146 static bool get_map_field_int(const char *map_name, const struct btf *btf,
2147 			      const struct btf_member *m, __u32 *res)
2148 {
2149 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2150 	const char *name = btf__name_by_offset(btf, m->name_off);
2151 	const struct btf_array *arr_info;
2152 	const struct btf_type *arr_t;
2153 
2154 	if (!btf_is_ptr(t)) {
2155 		pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2156 			map_name, name, btf_kind_str(t));
2157 		return false;
2158 	}
2159 
2160 	arr_t = btf__type_by_id(btf, t->type);
2161 	if (!arr_t) {
2162 		pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2163 			map_name, name, t->type);
2164 		return false;
2165 	}
2166 	if (!btf_is_array(arr_t)) {
2167 		pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2168 			map_name, name, btf_kind_str(arr_t));
2169 		return false;
2170 	}
2171 	arr_info = btf_array(arr_t);
2172 	*res = arr_info->nelems;
2173 	return true;
2174 }
2175 
2176 static int pathname_concat(char *buf, size_t buf_sz, const char *path, const char *name)
2177 {
2178 	int len;
2179 
2180 	len = snprintf(buf, buf_sz, "%s/%s", path, name);
2181 	if (len < 0)
2182 		return -EINVAL;
2183 	if (len >= buf_sz)
2184 		return -ENAMETOOLONG;
2185 
2186 	return 0;
2187 }
2188 
2189 static int build_map_pin_path(struct bpf_map *map, const char *path)
2190 {
2191 	char buf[PATH_MAX];
2192 	int err;
2193 
2194 	if (!path)
2195 		path = "/sys/fs/bpf";
2196 
2197 	err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
2198 	if (err)
2199 		return err;
2200 
2201 	return bpf_map__set_pin_path(map, buf);
2202 }
2203 
2204 /* should match definition in bpf_helpers.h */
2205 enum libbpf_pin_type {
2206 	LIBBPF_PIN_NONE,
2207 	/* PIN_BY_NAME: pin maps by name (in /sys/fs/bpf by default) */
2208 	LIBBPF_PIN_BY_NAME,
2209 };
2210 
2211 int parse_btf_map_def(const char *map_name, struct btf *btf,
2212 		      const struct btf_type *def_t, bool strict,
2213 		      struct btf_map_def *map_def, struct btf_map_def *inner_def)
2214 {
2215 	const struct btf_type *t;
2216 	const struct btf_member *m;
2217 	bool is_inner = inner_def == NULL;
2218 	int vlen, i;
2219 
2220 	vlen = btf_vlen(def_t);
2221 	m = btf_members(def_t);
2222 	for (i = 0; i < vlen; i++, m++) {
2223 		const char *name = btf__name_by_offset(btf, m->name_off);
2224 
2225 		if (!name) {
2226 			pr_warn("map '%s': invalid field #%d.\n", map_name, i);
2227 			return -EINVAL;
2228 		}
2229 		if (strcmp(name, "type") == 0) {
2230 			if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
2231 				return -EINVAL;
2232 			map_def->parts |= MAP_DEF_MAP_TYPE;
2233 		} else if (strcmp(name, "max_entries") == 0) {
2234 			if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
2235 				return -EINVAL;
2236 			map_def->parts |= MAP_DEF_MAX_ENTRIES;
2237 		} else if (strcmp(name, "map_flags") == 0) {
2238 			if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
2239 				return -EINVAL;
2240 			map_def->parts |= MAP_DEF_MAP_FLAGS;
2241 		} else if (strcmp(name, "numa_node") == 0) {
2242 			if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
2243 				return -EINVAL;
2244 			map_def->parts |= MAP_DEF_NUMA_NODE;
2245 		} else if (strcmp(name, "key_size") == 0) {
2246 			__u32 sz;
2247 
2248 			if (!get_map_field_int(map_name, btf, m, &sz))
2249 				return -EINVAL;
2250 			if (map_def->key_size && map_def->key_size != sz) {
2251 				pr_warn("map '%s': conflicting key size %u != %u.\n",
2252 					map_name, map_def->key_size, sz);
2253 				return -EINVAL;
2254 			}
2255 			map_def->key_size = sz;
2256 			map_def->parts |= MAP_DEF_KEY_SIZE;
2257 		} else if (strcmp(name, "key") == 0) {
2258 			__s64 sz;
2259 
2260 			t = btf__type_by_id(btf, m->type);
2261 			if (!t) {
2262 				pr_warn("map '%s': key type [%d] not found.\n",
2263 					map_name, m->type);
2264 				return -EINVAL;
2265 			}
2266 			if (!btf_is_ptr(t)) {
2267 				pr_warn("map '%s': key spec is not PTR: %s.\n",
2268 					map_name, btf_kind_str(t));
2269 				return -EINVAL;
2270 			}
2271 			sz = btf__resolve_size(btf, t->type);
2272 			if (sz < 0) {
2273 				pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2274 					map_name, t->type, (ssize_t)sz);
2275 				return sz;
2276 			}
2277 			if (map_def->key_size && map_def->key_size != sz) {
2278 				pr_warn("map '%s': conflicting key size %u != %zd.\n",
2279 					map_name, map_def->key_size, (ssize_t)sz);
2280 				return -EINVAL;
2281 			}
2282 			map_def->key_size = sz;
2283 			map_def->key_type_id = t->type;
2284 			map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
2285 		} else if (strcmp(name, "value_size") == 0) {
2286 			__u32 sz;
2287 
2288 			if (!get_map_field_int(map_name, btf, m, &sz))
2289 				return -EINVAL;
2290 			if (map_def->value_size && map_def->value_size != sz) {
2291 				pr_warn("map '%s': conflicting value size %u != %u.\n",
2292 					map_name, map_def->value_size, sz);
2293 				return -EINVAL;
2294 			}
2295 			map_def->value_size = sz;
2296 			map_def->parts |= MAP_DEF_VALUE_SIZE;
2297 		} else if (strcmp(name, "value") == 0) {
2298 			__s64 sz;
2299 
2300 			t = btf__type_by_id(btf, m->type);
2301 			if (!t) {
2302 				pr_warn("map '%s': value type [%d] not found.\n",
2303 					map_name, m->type);
2304 				return -EINVAL;
2305 			}
2306 			if (!btf_is_ptr(t)) {
2307 				pr_warn("map '%s': value spec is not PTR: %s.\n",
2308 					map_name, btf_kind_str(t));
2309 				return -EINVAL;
2310 			}
2311 			sz = btf__resolve_size(btf, t->type);
2312 			if (sz < 0) {
2313 				pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2314 					map_name, t->type, (ssize_t)sz);
2315 				return sz;
2316 			}
2317 			if (map_def->value_size && map_def->value_size != sz) {
2318 				pr_warn("map '%s': conflicting value size %u != %zd.\n",
2319 					map_name, map_def->value_size, (ssize_t)sz);
2320 				return -EINVAL;
2321 			}
2322 			map_def->value_size = sz;
2323 			map_def->value_type_id = t->type;
2324 			map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
2325 		}
2326 		else if (strcmp(name, "values") == 0) {
2327 			bool is_map_in_map = bpf_map_type__is_map_in_map(map_def->map_type);
2328 			bool is_prog_array = map_def->map_type == BPF_MAP_TYPE_PROG_ARRAY;
2329 			const char *desc = is_map_in_map ? "map-in-map inner" : "prog-array value";
2330 			char inner_map_name[128];
2331 			int err;
2332 
2333 			if (is_inner) {
2334 				pr_warn("map '%s': multi-level inner maps not supported.\n",
2335 					map_name);
2336 				return -ENOTSUP;
2337 			}
2338 			if (i != vlen - 1) {
2339 				pr_warn("map '%s': '%s' member should be last.\n",
2340 					map_name, name);
2341 				return -EINVAL;
2342 			}
2343 			if (!is_map_in_map && !is_prog_array) {
2344 				pr_warn("map '%s': should be map-in-map or prog-array.\n",
2345 					map_name);
2346 				return -ENOTSUP;
2347 			}
2348 			if (map_def->value_size && map_def->value_size != 4) {
2349 				pr_warn("map '%s': conflicting value size %u != 4.\n",
2350 					map_name, map_def->value_size);
2351 				return -EINVAL;
2352 			}
2353 			map_def->value_size = 4;
2354 			t = btf__type_by_id(btf, m->type);
2355 			if (!t) {
2356 				pr_warn("map '%s': %s type [%d] not found.\n",
2357 					map_name, desc, m->type);
2358 				return -EINVAL;
2359 			}
2360 			if (!btf_is_array(t) || btf_array(t)->nelems) {
2361 				pr_warn("map '%s': %s spec is not a zero-sized array.\n",
2362 					map_name, desc);
2363 				return -EINVAL;
2364 			}
2365 			t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
2366 			if (!btf_is_ptr(t)) {
2367 				pr_warn("map '%s': %s def is of unexpected kind %s.\n",
2368 					map_name, desc, btf_kind_str(t));
2369 				return -EINVAL;
2370 			}
2371 			t = skip_mods_and_typedefs(btf, t->type, NULL);
2372 			if (is_prog_array) {
2373 				if (!btf_is_func_proto(t)) {
2374 					pr_warn("map '%s': prog-array value def is of unexpected kind %s.\n",
2375 						map_name, btf_kind_str(t));
2376 					return -EINVAL;
2377 				}
2378 				continue;
2379 			}
2380 			if (!btf_is_struct(t)) {
2381 				pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2382 					map_name, btf_kind_str(t));
2383 				return -EINVAL;
2384 			}
2385 
2386 			snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2387 			err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
2388 			if (err)
2389 				return err;
2390 
2391 			map_def->parts |= MAP_DEF_INNER_MAP;
2392 		} else if (strcmp(name, "pinning") == 0) {
2393 			__u32 val;
2394 
2395 			if (is_inner) {
2396 				pr_warn("map '%s': inner def can't be pinned.\n", map_name);
2397 				return -EINVAL;
2398 			}
2399 			if (!get_map_field_int(map_name, btf, m, &val))
2400 				return -EINVAL;
2401 			if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
2402 				pr_warn("map '%s': invalid pinning value %u.\n",
2403 					map_name, val);
2404 				return -EINVAL;
2405 			}
2406 			map_def->pinning = val;
2407 			map_def->parts |= MAP_DEF_PINNING;
2408 		} else if (strcmp(name, "map_extra") == 0) {
2409 			__u32 map_extra;
2410 
2411 			if (!get_map_field_int(map_name, btf, m, &map_extra))
2412 				return -EINVAL;
2413 			map_def->map_extra = map_extra;
2414 			map_def->parts |= MAP_DEF_MAP_EXTRA;
2415 		} else {
2416 			if (strict) {
2417 				pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
2418 				return -ENOTSUP;
2419 			}
2420 			pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
2421 		}
2422 	}
2423 
2424 	if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2425 		pr_warn("map '%s': map type isn't specified.\n", map_name);
2426 		return -EINVAL;
2427 	}
2428 
2429 	return 0;
2430 }
2431 
2432 static size_t adjust_ringbuf_sz(size_t sz)
2433 {
2434 	__u32 page_sz = sysconf(_SC_PAGE_SIZE);
2435 	__u32 mul;
2436 
2437 	/* if user forgot to set any size, make sure they see error */
2438 	if (sz == 0)
2439 		return 0;
2440 	/* Kernel expects BPF_MAP_TYPE_RINGBUF's max_entries to be
2441 	 * a power-of-2 multiple of kernel's page size. If user diligently
2442 	 * satisified these conditions, pass the size through.
2443 	 */
2444 	if ((sz % page_sz) == 0 && is_pow_of_2(sz / page_sz))
2445 		return sz;
2446 
2447 	/* Otherwise find closest (page_sz * power_of_2) product bigger than
2448 	 * user-set size to satisfy both user size request and kernel
2449 	 * requirements and substitute correct max_entries for map creation.
2450 	 */
2451 	for (mul = 1; mul <= UINT_MAX / page_sz; mul <<= 1) {
2452 		if (mul * page_sz > sz)
2453 			return mul * page_sz;
2454 	}
2455 
2456 	/* if it's impossible to satisfy the conditions (i.e., user size is
2457 	 * very close to UINT_MAX but is not a power-of-2 multiple of
2458 	 * page_size) then just return original size and let kernel reject it
2459 	 */
2460 	return sz;
2461 }
2462 
2463 static bool map_is_ringbuf(const struct bpf_map *map)
2464 {
2465 	return map->def.type == BPF_MAP_TYPE_RINGBUF ||
2466 	       map->def.type == BPF_MAP_TYPE_USER_RINGBUF;
2467 }
2468 
2469 static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2470 {
2471 	map->def.type = def->map_type;
2472 	map->def.key_size = def->key_size;
2473 	map->def.value_size = def->value_size;
2474 	map->def.max_entries = def->max_entries;
2475 	map->def.map_flags = def->map_flags;
2476 	map->map_extra = def->map_extra;
2477 
2478 	map->numa_node = def->numa_node;
2479 	map->btf_key_type_id = def->key_type_id;
2480 	map->btf_value_type_id = def->value_type_id;
2481 
2482 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
2483 	if (map_is_ringbuf(map))
2484 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
2485 
2486 	if (def->parts & MAP_DEF_MAP_TYPE)
2487 		pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2488 
2489 	if (def->parts & MAP_DEF_KEY_TYPE)
2490 		pr_debug("map '%s': found key [%u], sz = %u.\n",
2491 			 map->name, def->key_type_id, def->key_size);
2492 	else if (def->parts & MAP_DEF_KEY_SIZE)
2493 		pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2494 
2495 	if (def->parts & MAP_DEF_VALUE_TYPE)
2496 		pr_debug("map '%s': found value [%u], sz = %u.\n",
2497 			 map->name, def->value_type_id, def->value_size);
2498 	else if (def->parts & MAP_DEF_VALUE_SIZE)
2499 		pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2500 
2501 	if (def->parts & MAP_DEF_MAX_ENTRIES)
2502 		pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2503 	if (def->parts & MAP_DEF_MAP_FLAGS)
2504 		pr_debug("map '%s': found map_flags = 0x%x.\n", map->name, def->map_flags);
2505 	if (def->parts & MAP_DEF_MAP_EXTRA)
2506 		pr_debug("map '%s': found map_extra = 0x%llx.\n", map->name,
2507 			 (unsigned long long)def->map_extra);
2508 	if (def->parts & MAP_DEF_PINNING)
2509 		pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2510 	if (def->parts & MAP_DEF_NUMA_NODE)
2511 		pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2512 
2513 	if (def->parts & MAP_DEF_INNER_MAP)
2514 		pr_debug("map '%s': found inner map definition.\n", map->name);
2515 }
2516 
2517 static const char *btf_var_linkage_str(__u32 linkage)
2518 {
2519 	switch (linkage) {
2520 	case BTF_VAR_STATIC: return "static";
2521 	case BTF_VAR_GLOBAL_ALLOCATED: return "global";
2522 	case BTF_VAR_GLOBAL_EXTERN: return "extern";
2523 	default: return "unknown";
2524 	}
2525 }
2526 
2527 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2528 					 const struct btf_type *sec,
2529 					 int var_idx, int sec_idx,
2530 					 const Elf_Data *data, bool strict,
2531 					 const char *pin_root_path)
2532 {
2533 	struct btf_map_def map_def = {}, inner_def = {};
2534 	const struct btf_type *var, *def;
2535 	const struct btf_var_secinfo *vi;
2536 	const struct btf_var *var_extra;
2537 	const char *map_name;
2538 	struct bpf_map *map;
2539 	int err;
2540 
2541 	vi = btf_var_secinfos(sec) + var_idx;
2542 	var = btf__type_by_id(obj->btf, vi->type);
2543 	var_extra = btf_var(var);
2544 	map_name = btf__name_by_offset(obj->btf, var->name_off);
2545 
2546 	if (map_name == NULL || map_name[0] == '\0') {
2547 		pr_warn("map #%d: empty name.\n", var_idx);
2548 		return -EINVAL;
2549 	}
2550 	if ((__u64)vi->offset + vi->size > data->d_size) {
2551 		pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2552 		return -EINVAL;
2553 	}
2554 	if (!btf_is_var(var)) {
2555 		pr_warn("map '%s': unexpected var kind %s.\n",
2556 			map_name, btf_kind_str(var));
2557 		return -EINVAL;
2558 	}
2559 	if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
2560 		pr_warn("map '%s': unsupported map linkage %s.\n",
2561 			map_name, btf_var_linkage_str(var_extra->linkage));
2562 		return -EOPNOTSUPP;
2563 	}
2564 
2565 	def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2566 	if (!btf_is_struct(def)) {
2567 		pr_warn("map '%s': unexpected def kind %s.\n",
2568 			map_name, btf_kind_str(var));
2569 		return -EINVAL;
2570 	}
2571 	if (def->size > vi->size) {
2572 		pr_warn("map '%s': invalid def size.\n", map_name);
2573 		return -EINVAL;
2574 	}
2575 
2576 	map = bpf_object__add_map(obj);
2577 	if (IS_ERR(map))
2578 		return PTR_ERR(map);
2579 	map->name = strdup(map_name);
2580 	if (!map->name) {
2581 		pr_warn("map '%s': failed to alloc map name.\n", map_name);
2582 		return -ENOMEM;
2583 	}
2584 	map->libbpf_type = LIBBPF_MAP_UNSPEC;
2585 	map->def.type = BPF_MAP_TYPE_UNSPEC;
2586 	map->sec_idx = sec_idx;
2587 	map->sec_offset = vi->offset;
2588 	map->btf_var_idx = var_idx;
2589 	pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2590 		 map_name, map->sec_idx, map->sec_offset);
2591 
2592 	err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
2593 	if (err)
2594 		return err;
2595 
2596 	fill_map_from_def(map, &map_def);
2597 
2598 	if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
2599 		err = build_map_pin_path(map, pin_root_path);
2600 		if (err) {
2601 			pr_warn("map '%s': couldn't build pin path.\n", map->name);
2602 			return err;
2603 		}
2604 	}
2605 
2606 	if (map_def.parts & MAP_DEF_INNER_MAP) {
2607 		map->inner_map = calloc(1, sizeof(*map->inner_map));
2608 		if (!map->inner_map)
2609 			return -ENOMEM;
2610 		map->inner_map->fd = -1;
2611 		map->inner_map->sec_idx = sec_idx;
2612 		map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
2613 		if (!map->inner_map->name)
2614 			return -ENOMEM;
2615 		sprintf(map->inner_map->name, "%s.inner", map_name);
2616 
2617 		fill_map_from_def(map->inner_map, &inner_def);
2618 	}
2619 
2620 	err = map_fill_btf_type_info(obj, map);
2621 	if (err)
2622 		return err;
2623 
2624 	return 0;
2625 }
2626 
2627 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
2628 					  const char *pin_root_path)
2629 {
2630 	const struct btf_type *sec = NULL;
2631 	int nr_types, i, vlen, err;
2632 	const struct btf_type *t;
2633 	const char *name;
2634 	Elf_Data *data;
2635 	Elf_Scn *scn;
2636 
2637 	if (obj->efile.btf_maps_shndx < 0)
2638 		return 0;
2639 
2640 	scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
2641 	data = elf_sec_data(obj, scn);
2642 	if (!scn || !data) {
2643 		pr_warn("elf: failed to get %s map definitions for %s\n",
2644 			MAPS_ELF_SEC, obj->path);
2645 		return -EINVAL;
2646 	}
2647 
2648 	nr_types = btf__type_cnt(obj->btf);
2649 	for (i = 1; i < nr_types; i++) {
2650 		t = btf__type_by_id(obj->btf, i);
2651 		if (!btf_is_datasec(t))
2652 			continue;
2653 		name = btf__name_by_offset(obj->btf, t->name_off);
2654 		if (strcmp(name, MAPS_ELF_SEC) == 0) {
2655 			sec = t;
2656 			obj->efile.btf_maps_sec_btf_id = i;
2657 			break;
2658 		}
2659 	}
2660 
2661 	if (!sec) {
2662 		pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
2663 		return -ENOENT;
2664 	}
2665 
2666 	vlen = btf_vlen(sec);
2667 	for (i = 0; i < vlen; i++) {
2668 		err = bpf_object__init_user_btf_map(obj, sec, i,
2669 						    obj->efile.btf_maps_shndx,
2670 						    data, strict,
2671 						    pin_root_path);
2672 		if (err)
2673 			return err;
2674 	}
2675 
2676 	return 0;
2677 }
2678 
2679 static int bpf_object__init_maps(struct bpf_object *obj,
2680 				 const struct bpf_object_open_opts *opts)
2681 {
2682 	const char *pin_root_path;
2683 	bool strict;
2684 	int err = 0;
2685 
2686 	strict = !OPTS_GET(opts, relaxed_maps, false);
2687 	pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
2688 
2689 	err = bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
2690 	err = err ?: bpf_object__init_global_data_maps(obj);
2691 	err = err ?: bpf_object__init_kconfig_map(obj);
2692 	err = err ?: bpf_object_init_struct_ops(obj);
2693 
2694 	return err;
2695 }
2696 
2697 static bool section_have_execinstr(struct bpf_object *obj, int idx)
2698 {
2699 	Elf64_Shdr *sh;
2700 
2701 	sh = elf_sec_hdr(obj, elf_sec_by_idx(obj, idx));
2702 	if (!sh)
2703 		return false;
2704 
2705 	return sh->sh_flags & SHF_EXECINSTR;
2706 }
2707 
2708 static bool btf_needs_sanitization(struct bpf_object *obj)
2709 {
2710 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2711 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2712 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2713 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2714 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2715 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2716 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
2717 
2718 	return !has_func || !has_datasec || !has_func_global || !has_float ||
2719 	       !has_decl_tag || !has_type_tag || !has_enum64;
2720 }
2721 
2722 static int bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *btf)
2723 {
2724 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2725 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2726 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2727 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2728 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2729 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2730 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
2731 	int enum64_placeholder_id = 0;
2732 	struct btf_type *t;
2733 	int i, j, vlen;
2734 
2735 	for (i = 1; i < btf__type_cnt(btf); i++) {
2736 		t = (struct btf_type *)btf__type_by_id(btf, i);
2737 
2738 		if ((!has_datasec && btf_is_var(t)) || (!has_decl_tag && btf_is_decl_tag(t))) {
2739 			/* replace VAR/DECL_TAG with INT */
2740 			t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
2741 			/*
2742 			 * using size = 1 is the safest choice, 4 will be too
2743 			 * big and cause kernel BTF validation failure if
2744 			 * original variable took less than 4 bytes
2745 			 */
2746 			t->size = 1;
2747 			*(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
2748 		} else if (!has_datasec && btf_is_datasec(t)) {
2749 			/* replace DATASEC with STRUCT */
2750 			const struct btf_var_secinfo *v = btf_var_secinfos(t);
2751 			struct btf_member *m = btf_members(t);
2752 			struct btf_type *vt;
2753 			char *name;
2754 
2755 			name = (char *)btf__name_by_offset(btf, t->name_off);
2756 			while (*name) {
2757 				if (*name == '.')
2758 					*name = '_';
2759 				name++;
2760 			}
2761 
2762 			vlen = btf_vlen(t);
2763 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
2764 			for (j = 0; j < vlen; j++, v++, m++) {
2765 				/* order of field assignments is important */
2766 				m->offset = v->offset * 8;
2767 				m->type = v->type;
2768 				/* preserve variable name as member name */
2769 				vt = (void *)btf__type_by_id(btf, v->type);
2770 				m->name_off = vt->name_off;
2771 			}
2772 		} else if (!has_func && btf_is_func_proto(t)) {
2773 			/* replace FUNC_PROTO with ENUM */
2774 			vlen = btf_vlen(t);
2775 			t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
2776 			t->size = sizeof(__u32); /* kernel enforced */
2777 		} else if (!has_func && btf_is_func(t)) {
2778 			/* replace FUNC with TYPEDEF */
2779 			t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
2780 		} else if (!has_func_global && btf_is_func(t)) {
2781 			/* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
2782 			t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
2783 		} else if (!has_float && btf_is_float(t)) {
2784 			/* replace FLOAT with an equally-sized empty STRUCT;
2785 			 * since C compilers do not accept e.g. "float" as a
2786 			 * valid struct name, make it anonymous
2787 			 */
2788 			t->name_off = 0;
2789 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
2790 		} else if (!has_type_tag && btf_is_type_tag(t)) {
2791 			/* replace TYPE_TAG with a CONST */
2792 			t->name_off = 0;
2793 			t->info = BTF_INFO_ENC(BTF_KIND_CONST, 0, 0);
2794 		} else if (!has_enum64 && btf_is_enum(t)) {
2795 			/* clear the kflag */
2796 			t->info = btf_type_info(btf_kind(t), btf_vlen(t), false);
2797 		} else if (!has_enum64 && btf_is_enum64(t)) {
2798 			/* replace ENUM64 with a union */
2799 			struct btf_member *m;
2800 
2801 			if (enum64_placeholder_id == 0) {
2802 				enum64_placeholder_id = btf__add_int(btf, "enum64_placeholder", 1, 0);
2803 				if (enum64_placeholder_id < 0)
2804 					return enum64_placeholder_id;
2805 
2806 				t = (struct btf_type *)btf__type_by_id(btf, i);
2807 			}
2808 
2809 			m = btf_members(t);
2810 			vlen = btf_vlen(t);
2811 			t->info = BTF_INFO_ENC(BTF_KIND_UNION, 0, vlen);
2812 			for (j = 0; j < vlen; j++, m++) {
2813 				m->type = enum64_placeholder_id;
2814 				m->offset = 0;
2815 			}
2816 		}
2817 	}
2818 
2819 	return 0;
2820 }
2821 
2822 static bool libbpf_needs_btf(const struct bpf_object *obj)
2823 {
2824 	return obj->efile.btf_maps_shndx >= 0 ||
2825 	       obj->efile.st_ops_shndx >= 0 ||
2826 	       obj->efile.st_ops_link_shndx >= 0 ||
2827 	       obj->nr_extern > 0;
2828 }
2829 
2830 static bool kernel_needs_btf(const struct bpf_object *obj)
2831 {
2832 	return obj->efile.st_ops_shndx >= 0 || obj->efile.st_ops_link_shndx >= 0;
2833 }
2834 
2835 static int bpf_object__init_btf(struct bpf_object *obj,
2836 				Elf_Data *btf_data,
2837 				Elf_Data *btf_ext_data)
2838 {
2839 	int err = -ENOENT;
2840 
2841 	if (btf_data) {
2842 		obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
2843 		err = libbpf_get_error(obj->btf);
2844 		if (err) {
2845 			obj->btf = NULL;
2846 			pr_warn("Error loading ELF section %s: %d.\n", BTF_ELF_SEC, err);
2847 			goto out;
2848 		}
2849 		/* enforce 8-byte pointers for BPF-targeted BTFs */
2850 		btf__set_pointer_size(obj->btf, 8);
2851 	}
2852 	if (btf_ext_data) {
2853 		struct btf_ext_info *ext_segs[3];
2854 		int seg_num, sec_num;
2855 
2856 		if (!obj->btf) {
2857 			pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
2858 				 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
2859 			goto out;
2860 		}
2861 		obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
2862 		err = libbpf_get_error(obj->btf_ext);
2863 		if (err) {
2864 			pr_warn("Error loading ELF section %s: %d. Ignored and continue.\n",
2865 				BTF_EXT_ELF_SEC, err);
2866 			obj->btf_ext = NULL;
2867 			goto out;
2868 		}
2869 
2870 		/* setup .BTF.ext to ELF section mapping */
2871 		ext_segs[0] = &obj->btf_ext->func_info;
2872 		ext_segs[1] = &obj->btf_ext->line_info;
2873 		ext_segs[2] = &obj->btf_ext->core_relo_info;
2874 		for (seg_num = 0; seg_num < ARRAY_SIZE(ext_segs); seg_num++) {
2875 			struct btf_ext_info *seg = ext_segs[seg_num];
2876 			const struct btf_ext_info_sec *sec;
2877 			const char *sec_name;
2878 			Elf_Scn *scn;
2879 
2880 			if (seg->sec_cnt == 0)
2881 				continue;
2882 
2883 			seg->sec_idxs = calloc(seg->sec_cnt, sizeof(*seg->sec_idxs));
2884 			if (!seg->sec_idxs) {
2885 				err = -ENOMEM;
2886 				goto out;
2887 			}
2888 
2889 			sec_num = 0;
2890 			for_each_btf_ext_sec(seg, sec) {
2891 				/* preventively increment index to avoid doing
2892 				 * this before every continue below
2893 				 */
2894 				sec_num++;
2895 
2896 				sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
2897 				if (str_is_empty(sec_name))
2898 					continue;
2899 				scn = elf_sec_by_name(obj, sec_name);
2900 				if (!scn)
2901 					continue;
2902 
2903 				seg->sec_idxs[sec_num - 1] = elf_ndxscn(scn);
2904 			}
2905 		}
2906 	}
2907 out:
2908 	if (err && libbpf_needs_btf(obj)) {
2909 		pr_warn("BTF is required, but is missing or corrupted.\n");
2910 		return err;
2911 	}
2912 	return 0;
2913 }
2914 
2915 static int compare_vsi_off(const void *_a, const void *_b)
2916 {
2917 	const struct btf_var_secinfo *a = _a;
2918 	const struct btf_var_secinfo *b = _b;
2919 
2920 	return a->offset - b->offset;
2921 }
2922 
2923 static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
2924 			     struct btf_type *t)
2925 {
2926 	__u32 size = 0, i, vars = btf_vlen(t);
2927 	const char *sec_name = btf__name_by_offset(btf, t->name_off);
2928 	struct btf_var_secinfo *vsi;
2929 	bool fixup_offsets = false;
2930 	int err;
2931 
2932 	if (!sec_name) {
2933 		pr_debug("No name found in string section for DATASEC kind.\n");
2934 		return -ENOENT;
2935 	}
2936 
2937 	/* Extern-backing datasecs (.ksyms, .kconfig) have their size and
2938 	 * variable offsets set at the previous step. Further, not every
2939 	 * extern BTF VAR has corresponding ELF symbol preserved, so we skip
2940 	 * all fixups altogether for such sections and go straight to sorting
2941 	 * VARs within their DATASEC.
2942 	 */
2943 	if (strcmp(sec_name, KCONFIG_SEC) == 0 || strcmp(sec_name, KSYMS_SEC) == 0)
2944 		goto sort_vars;
2945 
2946 	/* Clang leaves DATASEC size and VAR offsets as zeroes, so we need to
2947 	 * fix this up. But BPF static linker already fixes this up and fills
2948 	 * all the sizes and offsets during static linking. So this step has
2949 	 * to be optional. But the STV_HIDDEN handling is non-optional for any
2950 	 * non-extern DATASEC, so the variable fixup loop below handles both
2951 	 * functions at the same time, paying the cost of BTF VAR <-> ELF
2952 	 * symbol matching just once.
2953 	 */
2954 	if (t->size == 0) {
2955 		err = find_elf_sec_sz(obj, sec_name, &size);
2956 		if (err || !size) {
2957 			pr_debug("sec '%s': failed to determine size from ELF: size %u, err %d\n",
2958 				 sec_name, size, err);
2959 			return -ENOENT;
2960 		}
2961 
2962 		t->size = size;
2963 		fixup_offsets = true;
2964 	}
2965 
2966 	for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
2967 		const struct btf_type *t_var;
2968 		struct btf_var *var;
2969 		const char *var_name;
2970 		Elf64_Sym *sym;
2971 
2972 		t_var = btf__type_by_id(btf, vsi->type);
2973 		if (!t_var || !btf_is_var(t_var)) {
2974 			pr_debug("sec '%s': unexpected non-VAR type found\n", sec_name);
2975 			return -EINVAL;
2976 		}
2977 
2978 		var = btf_var(t_var);
2979 		if (var->linkage == BTF_VAR_STATIC || var->linkage == BTF_VAR_GLOBAL_EXTERN)
2980 			continue;
2981 
2982 		var_name = btf__name_by_offset(btf, t_var->name_off);
2983 		if (!var_name) {
2984 			pr_debug("sec '%s': failed to find name of DATASEC's member #%d\n",
2985 				 sec_name, i);
2986 			return -ENOENT;
2987 		}
2988 
2989 		sym = find_elf_var_sym(obj, var_name);
2990 		if (IS_ERR(sym)) {
2991 			pr_debug("sec '%s': failed to find ELF symbol for VAR '%s'\n",
2992 				 sec_name, var_name);
2993 			return -ENOENT;
2994 		}
2995 
2996 		if (fixup_offsets)
2997 			vsi->offset = sym->st_value;
2998 
2999 		/* if variable is a global/weak symbol, but has restricted
3000 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF VAR
3001 		 * as static. This follows similar logic for functions (BPF
3002 		 * subprogs) and influences libbpf's further decisions about
3003 		 * whether to make global data BPF array maps as
3004 		 * BPF_F_MMAPABLE.
3005 		 */
3006 		if (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
3007 		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL)
3008 			var->linkage = BTF_VAR_STATIC;
3009 	}
3010 
3011 sort_vars:
3012 	qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
3013 	return 0;
3014 }
3015 
3016 static int bpf_object_fixup_btf(struct bpf_object *obj)
3017 {
3018 	int i, n, err = 0;
3019 
3020 	if (!obj->btf)
3021 		return 0;
3022 
3023 	n = btf__type_cnt(obj->btf);
3024 	for (i = 1; i < n; i++) {
3025 		struct btf_type *t = btf_type_by_id(obj->btf, i);
3026 
3027 		/* Loader needs to fix up some of the things compiler
3028 		 * couldn't get its hands on while emitting BTF. This
3029 		 * is section size and global variable offset. We use
3030 		 * the info from the ELF itself for this purpose.
3031 		 */
3032 		if (btf_is_datasec(t)) {
3033 			err = btf_fixup_datasec(obj, obj->btf, t);
3034 			if (err)
3035 				return err;
3036 		}
3037 	}
3038 
3039 	return 0;
3040 }
3041 
3042 static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
3043 {
3044 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
3045 	    prog->type == BPF_PROG_TYPE_LSM)
3046 		return true;
3047 
3048 	/* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
3049 	 * also need vmlinux BTF
3050 	 */
3051 	if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
3052 		return true;
3053 
3054 	return false;
3055 }
3056 
3057 static bool map_needs_vmlinux_btf(struct bpf_map *map)
3058 {
3059 	return bpf_map__is_struct_ops(map);
3060 }
3061 
3062 static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
3063 {
3064 	struct bpf_program *prog;
3065 	struct bpf_map *map;
3066 	int i;
3067 
3068 	/* CO-RE relocations need kernel BTF, only when btf_custom_path
3069 	 * is not specified
3070 	 */
3071 	if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
3072 		return true;
3073 
3074 	/* Support for typed ksyms needs kernel BTF */
3075 	for (i = 0; i < obj->nr_extern; i++) {
3076 		const struct extern_desc *ext;
3077 
3078 		ext = &obj->externs[i];
3079 		if (ext->type == EXT_KSYM && ext->ksym.type_id)
3080 			return true;
3081 	}
3082 
3083 	bpf_object__for_each_program(prog, obj) {
3084 		if (!prog->autoload)
3085 			continue;
3086 		if (prog_needs_vmlinux_btf(prog))
3087 			return true;
3088 	}
3089 
3090 	bpf_object__for_each_map(map, obj) {
3091 		if (map_needs_vmlinux_btf(map))
3092 			return true;
3093 	}
3094 
3095 	return false;
3096 }
3097 
3098 static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
3099 {
3100 	int err;
3101 
3102 	/* btf_vmlinux could be loaded earlier */
3103 	if (obj->btf_vmlinux || obj->gen_loader)
3104 		return 0;
3105 
3106 	if (!force && !obj_needs_vmlinux_btf(obj))
3107 		return 0;
3108 
3109 	obj->btf_vmlinux = btf__load_vmlinux_btf();
3110 	err = libbpf_get_error(obj->btf_vmlinux);
3111 	if (err) {
3112 		pr_warn("Error loading vmlinux BTF: %d\n", err);
3113 		obj->btf_vmlinux = NULL;
3114 		return err;
3115 	}
3116 	return 0;
3117 }
3118 
3119 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
3120 {
3121 	struct btf *kern_btf = obj->btf;
3122 	bool btf_mandatory, sanitize;
3123 	int i, err = 0;
3124 
3125 	if (!obj->btf)
3126 		return 0;
3127 
3128 	if (!kernel_supports(obj, FEAT_BTF)) {
3129 		if (kernel_needs_btf(obj)) {
3130 			err = -EOPNOTSUPP;
3131 			goto report;
3132 		}
3133 		pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
3134 		return 0;
3135 	}
3136 
3137 	/* Even though some subprogs are global/weak, user might prefer more
3138 	 * permissive BPF verification process that BPF verifier performs for
3139 	 * static functions, taking into account more context from the caller
3140 	 * functions. In such case, they need to mark such subprogs with
3141 	 * __attribute__((visibility("hidden"))) and libbpf will adjust
3142 	 * corresponding FUNC BTF type to be marked as static and trigger more
3143 	 * involved BPF verification process.
3144 	 */
3145 	for (i = 0; i < obj->nr_programs; i++) {
3146 		struct bpf_program *prog = &obj->programs[i];
3147 		struct btf_type *t;
3148 		const char *name;
3149 		int j, n;
3150 
3151 		if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
3152 			continue;
3153 
3154 		n = btf__type_cnt(obj->btf);
3155 		for (j = 1; j < n; j++) {
3156 			t = btf_type_by_id(obj->btf, j);
3157 			if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
3158 				continue;
3159 
3160 			name = btf__str_by_offset(obj->btf, t->name_off);
3161 			if (strcmp(name, prog->name) != 0)
3162 				continue;
3163 
3164 			t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
3165 			break;
3166 		}
3167 	}
3168 
3169 	if (!kernel_supports(obj, FEAT_BTF_DECL_TAG))
3170 		goto skip_exception_cb;
3171 	for (i = 0; i < obj->nr_programs; i++) {
3172 		struct bpf_program *prog = &obj->programs[i];
3173 		int j, k, n;
3174 
3175 		if (prog_is_subprog(obj, prog))
3176 			continue;
3177 		n = btf__type_cnt(obj->btf);
3178 		for (j = 1; j < n; j++) {
3179 			const char *str = "exception_callback:", *name;
3180 			size_t len = strlen(str);
3181 			struct btf_type *t;
3182 
3183 			t = btf_type_by_id(obj->btf, j);
3184 			if (!btf_is_decl_tag(t) || btf_decl_tag(t)->component_idx != -1)
3185 				continue;
3186 
3187 			name = btf__str_by_offset(obj->btf, t->name_off);
3188 			if (strncmp(name, str, len))
3189 				continue;
3190 
3191 			t = btf_type_by_id(obj->btf, t->type);
3192 			if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
3193 				pr_warn("prog '%s': exception_callback:<value> decl tag not applied to the main program\n",
3194 					prog->name);
3195 				return -EINVAL;
3196 			}
3197 			if (strcmp(prog->name, btf__str_by_offset(obj->btf, t->name_off)))
3198 				continue;
3199 			/* Multiple callbacks are specified for the same prog,
3200 			 * the verifier will eventually return an error for this
3201 			 * case, hence simply skip appending a subprog.
3202 			 */
3203 			if (prog->exception_cb_idx >= 0) {
3204 				prog->exception_cb_idx = -1;
3205 				break;
3206 			}
3207 
3208 			name += len;
3209 			if (str_is_empty(name)) {
3210 				pr_warn("prog '%s': exception_callback:<value> decl tag contains empty value\n",
3211 					prog->name);
3212 				return -EINVAL;
3213 			}
3214 
3215 			for (k = 0; k < obj->nr_programs; k++) {
3216 				struct bpf_program *subprog = &obj->programs[k];
3217 
3218 				if (!prog_is_subprog(obj, subprog))
3219 					continue;
3220 				if (strcmp(name, subprog->name))
3221 					continue;
3222 				/* Enforce non-hidden, as from verifier point of
3223 				 * view it expects global functions, whereas the
3224 				 * mark_btf_static fixes up linkage as static.
3225 				 */
3226 				if (!subprog->sym_global || subprog->mark_btf_static) {
3227 					pr_warn("prog '%s': exception callback %s must be a global non-hidden function\n",
3228 						prog->name, subprog->name);
3229 					return -EINVAL;
3230 				}
3231 				/* Let's see if we already saw a static exception callback with the same name */
3232 				if (prog->exception_cb_idx >= 0) {
3233 					pr_warn("prog '%s': multiple subprogs with same name as exception callback '%s'\n",
3234 					        prog->name, subprog->name);
3235 					return -EINVAL;
3236 				}
3237 				prog->exception_cb_idx = k;
3238 				break;
3239 			}
3240 
3241 			if (prog->exception_cb_idx >= 0)
3242 				continue;
3243 			pr_warn("prog '%s': cannot find exception callback '%s'\n", prog->name, name);
3244 			return -ENOENT;
3245 		}
3246 	}
3247 skip_exception_cb:
3248 
3249 	sanitize = btf_needs_sanitization(obj);
3250 	if (sanitize) {
3251 		const void *raw_data;
3252 		__u32 sz;
3253 
3254 		/* clone BTF to sanitize a copy and leave the original intact */
3255 		raw_data = btf__raw_data(obj->btf, &sz);
3256 		kern_btf = btf__new(raw_data, sz);
3257 		err = libbpf_get_error(kern_btf);
3258 		if (err)
3259 			return err;
3260 
3261 		/* enforce 8-byte pointers for BPF-targeted BTFs */
3262 		btf__set_pointer_size(obj->btf, 8);
3263 		err = bpf_object__sanitize_btf(obj, kern_btf);
3264 		if (err)
3265 			return err;
3266 	}
3267 
3268 	if (obj->gen_loader) {
3269 		__u32 raw_size = 0;
3270 		const void *raw_data = btf__raw_data(kern_btf, &raw_size);
3271 
3272 		if (!raw_data)
3273 			return -ENOMEM;
3274 		bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
3275 		/* Pretend to have valid FD to pass various fd >= 0 checks.
3276 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
3277 		 */
3278 		btf__set_fd(kern_btf, 0);
3279 	} else {
3280 		/* currently BPF_BTF_LOAD only supports log_level 1 */
3281 		err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
3282 					   obj->log_level ? 1 : 0);
3283 	}
3284 	if (sanitize) {
3285 		if (!err) {
3286 			/* move fd to libbpf's BTF */
3287 			btf__set_fd(obj->btf, btf__fd(kern_btf));
3288 			btf__set_fd(kern_btf, -1);
3289 		}
3290 		btf__free(kern_btf);
3291 	}
3292 report:
3293 	if (err) {
3294 		btf_mandatory = kernel_needs_btf(obj);
3295 		pr_warn("Error loading .BTF into kernel: %d. %s\n", err,
3296 			btf_mandatory ? "BTF is mandatory, can't proceed."
3297 				      : "BTF is optional, ignoring.");
3298 		if (!btf_mandatory)
3299 			err = 0;
3300 	}
3301 	return err;
3302 }
3303 
3304 static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
3305 {
3306 	const char *name;
3307 
3308 	name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
3309 	if (!name) {
3310 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3311 			off, obj->path, elf_errmsg(-1));
3312 		return NULL;
3313 	}
3314 
3315 	return name;
3316 }
3317 
3318 static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
3319 {
3320 	const char *name;
3321 
3322 	name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
3323 	if (!name) {
3324 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3325 			off, obj->path, elf_errmsg(-1));
3326 		return NULL;
3327 	}
3328 
3329 	return name;
3330 }
3331 
3332 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
3333 {
3334 	Elf_Scn *scn;
3335 
3336 	scn = elf_getscn(obj->efile.elf, idx);
3337 	if (!scn) {
3338 		pr_warn("elf: failed to get section(%zu) from %s: %s\n",
3339 			idx, obj->path, elf_errmsg(-1));
3340 		return NULL;
3341 	}
3342 	return scn;
3343 }
3344 
3345 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
3346 {
3347 	Elf_Scn *scn = NULL;
3348 	Elf *elf = obj->efile.elf;
3349 	const char *sec_name;
3350 
3351 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3352 		sec_name = elf_sec_name(obj, scn);
3353 		if (!sec_name)
3354 			return NULL;
3355 
3356 		if (strcmp(sec_name, name) != 0)
3357 			continue;
3358 
3359 		return scn;
3360 	}
3361 	return NULL;
3362 }
3363 
3364 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn)
3365 {
3366 	Elf64_Shdr *shdr;
3367 
3368 	if (!scn)
3369 		return NULL;
3370 
3371 	shdr = elf64_getshdr(scn);
3372 	if (!shdr) {
3373 		pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
3374 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3375 		return NULL;
3376 	}
3377 
3378 	return shdr;
3379 }
3380 
3381 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
3382 {
3383 	const char *name;
3384 	Elf64_Shdr *sh;
3385 
3386 	if (!scn)
3387 		return NULL;
3388 
3389 	sh = elf_sec_hdr(obj, scn);
3390 	if (!sh)
3391 		return NULL;
3392 
3393 	name = elf_sec_str(obj, sh->sh_name);
3394 	if (!name) {
3395 		pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
3396 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3397 		return NULL;
3398 	}
3399 
3400 	return name;
3401 }
3402 
3403 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
3404 {
3405 	Elf_Data *data;
3406 
3407 	if (!scn)
3408 		return NULL;
3409 
3410 	data = elf_getdata(scn, 0);
3411 	if (!data) {
3412 		pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
3413 			elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
3414 			obj->path, elf_errmsg(-1));
3415 		return NULL;
3416 	}
3417 
3418 	return data;
3419 }
3420 
3421 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx)
3422 {
3423 	if (idx >= obj->efile.symbols->d_size / sizeof(Elf64_Sym))
3424 		return NULL;
3425 
3426 	return (Elf64_Sym *)obj->efile.symbols->d_buf + idx;
3427 }
3428 
3429 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx)
3430 {
3431 	if (idx >= data->d_size / sizeof(Elf64_Rel))
3432 		return NULL;
3433 
3434 	return (Elf64_Rel *)data->d_buf + idx;
3435 }
3436 
3437 static bool is_sec_name_dwarf(const char *name)
3438 {
3439 	/* approximation, but the actual list is too long */
3440 	return str_has_pfx(name, ".debug_");
3441 }
3442 
3443 static bool ignore_elf_section(Elf64_Shdr *hdr, const char *name)
3444 {
3445 	/* no special handling of .strtab */
3446 	if (hdr->sh_type == SHT_STRTAB)
3447 		return true;
3448 
3449 	/* ignore .llvm_addrsig section as well */
3450 	if (hdr->sh_type == SHT_LLVM_ADDRSIG)
3451 		return true;
3452 
3453 	/* no subprograms will lead to an empty .text section, ignore it */
3454 	if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
3455 	    strcmp(name, ".text") == 0)
3456 		return true;
3457 
3458 	/* DWARF sections */
3459 	if (is_sec_name_dwarf(name))
3460 		return true;
3461 
3462 	if (str_has_pfx(name, ".rel")) {
3463 		name += sizeof(".rel") - 1;
3464 		/* DWARF section relocations */
3465 		if (is_sec_name_dwarf(name))
3466 			return true;
3467 
3468 		/* .BTF and .BTF.ext don't need relocations */
3469 		if (strcmp(name, BTF_ELF_SEC) == 0 ||
3470 		    strcmp(name, BTF_EXT_ELF_SEC) == 0)
3471 			return true;
3472 	}
3473 
3474 	return false;
3475 }
3476 
3477 static int cmp_progs(const void *_a, const void *_b)
3478 {
3479 	const struct bpf_program *a = _a;
3480 	const struct bpf_program *b = _b;
3481 
3482 	if (a->sec_idx != b->sec_idx)
3483 		return a->sec_idx < b->sec_idx ? -1 : 1;
3484 
3485 	/* sec_insn_off can't be the same within the section */
3486 	return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
3487 }
3488 
3489 static int bpf_object__elf_collect(struct bpf_object *obj)
3490 {
3491 	struct elf_sec_desc *sec_desc;
3492 	Elf *elf = obj->efile.elf;
3493 	Elf_Data *btf_ext_data = NULL;
3494 	Elf_Data *btf_data = NULL;
3495 	int idx = 0, err = 0;
3496 	const char *name;
3497 	Elf_Data *data;
3498 	Elf_Scn *scn;
3499 	Elf64_Shdr *sh;
3500 
3501 	/* ELF section indices are 0-based, but sec #0 is special "invalid"
3502 	 * section. Since section count retrieved by elf_getshdrnum() does
3503 	 * include sec #0, it is already the necessary size of an array to keep
3504 	 * all the sections.
3505 	 */
3506 	if (elf_getshdrnum(obj->efile.elf, &obj->efile.sec_cnt)) {
3507 		pr_warn("elf: failed to get the number of sections for %s: %s\n",
3508 			obj->path, elf_errmsg(-1));
3509 		return -LIBBPF_ERRNO__FORMAT;
3510 	}
3511 	obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs));
3512 	if (!obj->efile.secs)
3513 		return -ENOMEM;
3514 
3515 	/* a bunch of ELF parsing functionality depends on processing symbols,
3516 	 * so do the first pass and find the symbol table
3517 	 */
3518 	scn = NULL;
3519 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3520 		sh = elf_sec_hdr(obj, scn);
3521 		if (!sh)
3522 			return -LIBBPF_ERRNO__FORMAT;
3523 
3524 		if (sh->sh_type == SHT_SYMTAB) {
3525 			if (obj->efile.symbols) {
3526 				pr_warn("elf: multiple symbol tables in %s\n", obj->path);
3527 				return -LIBBPF_ERRNO__FORMAT;
3528 			}
3529 
3530 			data = elf_sec_data(obj, scn);
3531 			if (!data)
3532 				return -LIBBPF_ERRNO__FORMAT;
3533 
3534 			idx = elf_ndxscn(scn);
3535 
3536 			obj->efile.symbols = data;
3537 			obj->efile.symbols_shndx = idx;
3538 			obj->efile.strtabidx = sh->sh_link;
3539 		}
3540 	}
3541 
3542 	if (!obj->efile.symbols) {
3543 		pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
3544 			obj->path);
3545 		return -ENOENT;
3546 	}
3547 
3548 	scn = NULL;
3549 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3550 		idx = elf_ndxscn(scn);
3551 		sec_desc = &obj->efile.secs[idx];
3552 
3553 		sh = elf_sec_hdr(obj, scn);
3554 		if (!sh)
3555 			return -LIBBPF_ERRNO__FORMAT;
3556 
3557 		name = elf_sec_str(obj, sh->sh_name);
3558 		if (!name)
3559 			return -LIBBPF_ERRNO__FORMAT;
3560 
3561 		if (ignore_elf_section(sh, name))
3562 			continue;
3563 
3564 		data = elf_sec_data(obj, scn);
3565 		if (!data)
3566 			return -LIBBPF_ERRNO__FORMAT;
3567 
3568 		pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
3569 			 idx, name, (unsigned long)data->d_size,
3570 			 (int)sh->sh_link, (unsigned long)sh->sh_flags,
3571 			 (int)sh->sh_type);
3572 
3573 		if (strcmp(name, "license") == 0) {
3574 			err = bpf_object__init_license(obj, data->d_buf, data->d_size);
3575 			if (err)
3576 				return err;
3577 		} else if (strcmp(name, "version") == 0) {
3578 			err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
3579 			if (err)
3580 				return err;
3581 		} else if (strcmp(name, "maps") == 0) {
3582 			pr_warn("elf: legacy map definitions in 'maps' section are not supported by libbpf v1.0+\n");
3583 			return -ENOTSUP;
3584 		} else if (strcmp(name, MAPS_ELF_SEC) == 0) {
3585 			obj->efile.btf_maps_shndx = idx;
3586 		} else if (strcmp(name, BTF_ELF_SEC) == 0) {
3587 			if (sh->sh_type != SHT_PROGBITS)
3588 				return -LIBBPF_ERRNO__FORMAT;
3589 			btf_data = data;
3590 		} else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
3591 			if (sh->sh_type != SHT_PROGBITS)
3592 				return -LIBBPF_ERRNO__FORMAT;
3593 			btf_ext_data = data;
3594 		} else if (sh->sh_type == SHT_SYMTAB) {
3595 			/* already processed during the first pass above */
3596 		} else if (sh->sh_type == SHT_PROGBITS && data->d_size > 0) {
3597 			if (sh->sh_flags & SHF_EXECINSTR) {
3598 				if (strcmp(name, ".text") == 0)
3599 					obj->efile.text_shndx = idx;
3600 				err = bpf_object__add_programs(obj, data, name, idx);
3601 				if (err)
3602 					return err;
3603 			} else if (strcmp(name, DATA_SEC) == 0 ||
3604 				   str_has_pfx(name, DATA_SEC ".")) {
3605 				sec_desc->sec_type = SEC_DATA;
3606 				sec_desc->shdr = sh;
3607 				sec_desc->data = data;
3608 			} else if (strcmp(name, RODATA_SEC) == 0 ||
3609 				   str_has_pfx(name, RODATA_SEC ".")) {
3610 				sec_desc->sec_type = SEC_RODATA;
3611 				sec_desc->shdr = sh;
3612 				sec_desc->data = data;
3613 			} else if (strcmp(name, STRUCT_OPS_SEC) == 0) {
3614 				obj->efile.st_ops_data = data;
3615 				obj->efile.st_ops_shndx = idx;
3616 			} else if (strcmp(name, STRUCT_OPS_LINK_SEC) == 0) {
3617 				obj->efile.st_ops_link_data = data;
3618 				obj->efile.st_ops_link_shndx = idx;
3619 			} else {
3620 				pr_info("elf: skipping unrecognized data section(%d) %s\n",
3621 					idx, name);
3622 			}
3623 		} else if (sh->sh_type == SHT_REL) {
3624 			int targ_sec_idx = sh->sh_info; /* points to other section */
3625 
3626 			if (sh->sh_entsize != sizeof(Elf64_Rel) ||
3627 			    targ_sec_idx >= obj->efile.sec_cnt)
3628 				return -LIBBPF_ERRNO__FORMAT;
3629 
3630 			/* Only do relo for section with exec instructions */
3631 			if (!section_have_execinstr(obj, targ_sec_idx) &&
3632 			    strcmp(name, ".rel" STRUCT_OPS_SEC) &&
3633 			    strcmp(name, ".rel" STRUCT_OPS_LINK_SEC) &&
3634 			    strcmp(name, ".rel" MAPS_ELF_SEC)) {
3635 				pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
3636 					idx, name, targ_sec_idx,
3637 					elf_sec_name(obj, elf_sec_by_idx(obj, targ_sec_idx)) ?: "<?>");
3638 				continue;
3639 			}
3640 
3641 			sec_desc->sec_type = SEC_RELO;
3642 			sec_desc->shdr = sh;
3643 			sec_desc->data = data;
3644 		} else if (sh->sh_type == SHT_NOBITS && (strcmp(name, BSS_SEC) == 0 ||
3645 							 str_has_pfx(name, BSS_SEC "."))) {
3646 			sec_desc->sec_type = SEC_BSS;
3647 			sec_desc->shdr = sh;
3648 			sec_desc->data = data;
3649 		} else {
3650 			pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
3651 				(size_t)sh->sh_size);
3652 		}
3653 	}
3654 
3655 	if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
3656 		pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
3657 		return -LIBBPF_ERRNO__FORMAT;
3658 	}
3659 
3660 	/* sort BPF programs by section name and in-section instruction offset
3661 	 * for faster search
3662 	 */
3663 	if (obj->nr_programs)
3664 		qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
3665 
3666 	return bpf_object__init_btf(obj, btf_data, btf_ext_data);
3667 }
3668 
3669 static bool sym_is_extern(const Elf64_Sym *sym)
3670 {
3671 	int bind = ELF64_ST_BIND(sym->st_info);
3672 	/* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
3673 	return sym->st_shndx == SHN_UNDEF &&
3674 	       (bind == STB_GLOBAL || bind == STB_WEAK) &&
3675 	       ELF64_ST_TYPE(sym->st_info) == STT_NOTYPE;
3676 }
3677 
3678 static bool sym_is_subprog(const Elf64_Sym *sym, int text_shndx)
3679 {
3680 	int bind = ELF64_ST_BIND(sym->st_info);
3681 	int type = ELF64_ST_TYPE(sym->st_info);
3682 
3683 	/* in .text section */
3684 	if (sym->st_shndx != text_shndx)
3685 		return false;
3686 
3687 	/* local function */
3688 	if (bind == STB_LOCAL && type == STT_SECTION)
3689 		return true;
3690 
3691 	/* global function */
3692 	return bind == STB_GLOBAL && type == STT_FUNC;
3693 }
3694 
3695 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
3696 {
3697 	const struct btf_type *t;
3698 	const char *tname;
3699 	int i, n;
3700 
3701 	if (!btf)
3702 		return -ESRCH;
3703 
3704 	n = btf__type_cnt(btf);
3705 	for (i = 1; i < n; i++) {
3706 		t = btf__type_by_id(btf, i);
3707 
3708 		if (!btf_is_var(t) && !btf_is_func(t))
3709 			continue;
3710 
3711 		tname = btf__name_by_offset(btf, t->name_off);
3712 		if (strcmp(tname, ext_name))
3713 			continue;
3714 
3715 		if (btf_is_var(t) &&
3716 		    btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
3717 			return -EINVAL;
3718 
3719 		if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
3720 			return -EINVAL;
3721 
3722 		return i;
3723 	}
3724 
3725 	return -ENOENT;
3726 }
3727 
3728 static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
3729 	const struct btf_var_secinfo *vs;
3730 	const struct btf_type *t;
3731 	int i, j, n;
3732 
3733 	if (!btf)
3734 		return -ESRCH;
3735 
3736 	n = btf__type_cnt(btf);
3737 	for (i = 1; i < n; i++) {
3738 		t = btf__type_by_id(btf, i);
3739 
3740 		if (!btf_is_datasec(t))
3741 			continue;
3742 
3743 		vs = btf_var_secinfos(t);
3744 		for (j = 0; j < btf_vlen(t); j++, vs++) {
3745 			if (vs->type == ext_btf_id)
3746 				return i;
3747 		}
3748 	}
3749 
3750 	return -ENOENT;
3751 }
3752 
3753 static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
3754 				     bool *is_signed)
3755 {
3756 	const struct btf_type *t;
3757 	const char *name;
3758 
3759 	t = skip_mods_and_typedefs(btf, id, NULL);
3760 	name = btf__name_by_offset(btf, t->name_off);
3761 
3762 	if (is_signed)
3763 		*is_signed = false;
3764 	switch (btf_kind(t)) {
3765 	case BTF_KIND_INT: {
3766 		int enc = btf_int_encoding(t);
3767 
3768 		if (enc & BTF_INT_BOOL)
3769 			return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
3770 		if (is_signed)
3771 			*is_signed = enc & BTF_INT_SIGNED;
3772 		if (t->size == 1)
3773 			return KCFG_CHAR;
3774 		if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
3775 			return KCFG_UNKNOWN;
3776 		return KCFG_INT;
3777 	}
3778 	case BTF_KIND_ENUM:
3779 		if (t->size != 4)
3780 			return KCFG_UNKNOWN;
3781 		if (strcmp(name, "libbpf_tristate"))
3782 			return KCFG_UNKNOWN;
3783 		return KCFG_TRISTATE;
3784 	case BTF_KIND_ENUM64:
3785 		if (strcmp(name, "libbpf_tristate"))
3786 			return KCFG_UNKNOWN;
3787 		return KCFG_TRISTATE;
3788 	case BTF_KIND_ARRAY:
3789 		if (btf_array(t)->nelems == 0)
3790 			return KCFG_UNKNOWN;
3791 		if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
3792 			return KCFG_UNKNOWN;
3793 		return KCFG_CHAR_ARR;
3794 	default:
3795 		return KCFG_UNKNOWN;
3796 	}
3797 }
3798 
3799 static int cmp_externs(const void *_a, const void *_b)
3800 {
3801 	const struct extern_desc *a = _a;
3802 	const struct extern_desc *b = _b;
3803 
3804 	if (a->type != b->type)
3805 		return a->type < b->type ? -1 : 1;
3806 
3807 	if (a->type == EXT_KCFG) {
3808 		/* descending order by alignment requirements */
3809 		if (a->kcfg.align != b->kcfg.align)
3810 			return a->kcfg.align > b->kcfg.align ? -1 : 1;
3811 		/* ascending order by size, within same alignment class */
3812 		if (a->kcfg.sz != b->kcfg.sz)
3813 			return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
3814 	}
3815 
3816 	/* resolve ties by name */
3817 	return strcmp(a->name, b->name);
3818 }
3819 
3820 static int find_int_btf_id(const struct btf *btf)
3821 {
3822 	const struct btf_type *t;
3823 	int i, n;
3824 
3825 	n = btf__type_cnt(btf);
3826 	for (i = 1; i < n; i++) {
3827 		t = btf__type_by_id(btf, i);
3828 
3829 		if (btf_is_int(t) && btf_int_bits(t) == 32)
3830 			return i;
3831 	}
3832 
3833 	return 0;
3834 }
3835 
3836 static int add_dummy_ksym_var(struct btf *btf)
3837 {
3838 	int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
3839 	const struct btf_var_secinfo *vs;
3840 	const struct btf_type *sec;
3841 
3842 	if (!btf)
3843 		return 0;
3844 
3845 	sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
3846 					    BTF_KIND_DATASEC);
3847 	if (sec_btf_id < 0)
3848 		return 0;
3849 
3850 	sec = btf__type_by_id(btf, sec_btf_id);
3851 	vs = btf_var_secinfos(sec);
3852 	for (i = 0; i < btf_vlen(sec); i++, vs++) {
3853 		const struct btf_type *vt;
3854 
3855 		vt = btf__type_by_id(btf, vs->type);
3856 		if (btf_is_func(vt))
3857 			break;
3858 	}
3859 
3860 	/* No func in ksyms sec.  No need to add dummy var. */
3861 	if (i == btf_vlen(sec))
3862 		return 0;
3863 
3864 	int_btf_id = find_int_btf_id(btf);
3865 	dummy_var_btf_id = btf__add_var(btf,
3866 					"dummy_ksym",
3867 					BTF_VAR_GLOBAL_ALLOCATED,
3868 					int_btf_id);
3869 	if (dummy_var_btf_id < 0)
3870 		pr_warn("cannot create a dummy_ksym var\n");
3871 
3872 	return dummy_var_btf_id;
3873 }
3874 
3875 static int bpf_object__collect_externs(struct bpf_object *obj)
3876 {
3877 	struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
3878 	const struct btf_type *t;
3879 	struct extern_desc *ext;
3880 	int i, n, off, dummy_var_btf_id;
3881 	const char *ext_name, *sec_name;
3882 	size_t ext_essent_len;
3883 	Elf_Scn *scn;
3884 	Elf64_Shdr *sh;
3885 
3886 	if (!obj->efile.symbols)
3887 		return 0;
3888 
3889 	scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
3890 	sh = elf_sec_hdr(obj, scn);
3891 	if (!sh || sh->sh_entsize != sizeof(Elf64_Sym))
3892 		return -LIBBPF_ERRNO__FORMAT;
3893 
3894 	dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
3895 	if (dummy_var_btf_id < 0)
3896 		return dummy_var_btf_id;
3897 
3898 	n = sh->sh_size / sh->sh_entsize;
3899 	pr_debug("looking for externs among %d symbols...\n", n);
3900 
3901 	for (i = 0; i < n; i++) {
3902 		Elf64_Sym *sym = elf_sym_by_idx(obj, i);
3903 
3904 		if (!sym)
3905 			return -LIBBPF_ERRNO__FORMAT;
3906 		if (!sym_is_extern(sym))
3907 			continue;
3908 		ext_name = elf_sym_str(obj, sym->st_name);
3909 		if (!ext_name || !ext_name[0])
3910 			continue;
3911 
3912 		ext = obj->externs;
3913 		ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
3914 		if (!ext)
3915 			return -ENOMEM;
3916 		obj->externs = ext;
3917 		ext = &ext[obj->nr_extern];
3918 		memset(ext, 0, sizeof(*ext));
3919 		obj->nr_extern++;
3920 
3921 		ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
3922 		if (ext->btf_id <= 0) {
3923 			pr_warn("failed to find BTF for extern '%s': %d\n",
3924 				ext_name, ext->btf_id);
3925 			return ext->btf_id;
3926 		}
3927 		t = btf__type_by_id(obj->btf, ext->btf_id);
3928 		ext->name = btf__name_by_offset(obj->btf, t->name_off);
3929 		ext->sym_idx = i;
3930 		ext->is_weak = ELF64_ST_BIND(sym->st_info) == STB_WEAK;
3931 
3932 		ext_essent_len = bpf_core_essential_name_len(ext->name);
3933 		ext->essent_name = NULL;
3934 		if (ext_essent_len != strlen(ext->name)) {
3935 			ext->essent_name = strndup(ext->name, ext_essent_len);
3936 			if (!ext->essent_name)
3937 				return -ENOMEM;
3938 		}
3939 
3940 		ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
3941 		if (ext->sec_btf_id <= 0) {
3942 			pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
3943 				ext_name, ext->btf_id, ext->sec_btf_id);
3944 			return ext->sec_btf_id;
3945 		}
3946 		sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
3947 		sec_name = btf__name_by_offset(obj->btf, sec->name_off);
3948 
3949 		if (strcmp(sec_name, KCONFIG_SEC) == 0) {
3950 			if (btf_is_func(t)) {
3951 				pr_warn("extern function %s is unsupported under %s section\n",
3952 					ext->name, KCONFIG_SEC);
3953 				return -ENOTSUP;
3954 			}
3955 			kcfg_sec = sec;
3956 			ext->type = EXT_KCFG;
3957 			ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
3958 			if (ext->kcfg.sz <= 0) {
3959 				pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
3960 					ext_name, ext->kcfg.sz);
3961 				return ext->kcfg.sz;
3962 			}
3963 			ext->kcfg.align = btf__align_of(obj->btf, t->type);
3964 			if (ext->kcfg.align <= 0) {
3965 				pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
3966 					ext_name, ext->kcfg.align);
3967 				return -EINVAL;
3968 			}
3969 			ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
3970 							&ext->kcfg.is_signed);
3971 			if (ext->kcfg.type == KCFG_UNKNOWN) {
3972 				pr_warn("extern (kcfg) '%s': type is unsupported\n", ext_name);
3973 				return -ENOTSUP;
3974 			}
3975 		} else if (strcmp(sec_name, KSYMS_SEC) == 0) {
3976 			ksym_sec = sec;
3977 			ext->type = EXT_KSYM;
3978 			skip_mods_and_typedefs(obj->btf, t->type,
3979 					       &ext->ksym.type_id);
3980 		} else {
3981 			pr_warn("unrecognized extern section '%s'\n", sec_name);
3982 			return -ENOTSUP;
3983 		}
3984 	}
3985 	pr_debug("collected %d externs total\n", obj->nr_extern);
3986 
3987 	if (!obj->nr_extern)
3988 		return 0;
3989 
3990 	/* sort externs by type, for kcfg ones also by (align, size, name) */
3991 	qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
3992 
3993 	/* for .ksyms section, we need to turn all externs into allocated
3994 	 * variables in BTF to pass kernel verification; we do this by
3995 	 * pretending that each extern is a 8-byte variable
3996 	 */
3997 	if (ksym_sec) {
3998 		/* find existing 4-byte integer type in BTF to use for fake
3999 		 * extern variables in DATASEC
4000 		 */
4001 		int int_btf_id = find_int_btf_id(obj->btf);
4002 		/* For extern function, a dummy_var added earlier
4003 		 * will be used to replace the vs->type and
4004 		 * its name string will be used to refill
4005 		 * the missing param's name.
4006 		 */
4007 		const struct btf_type *dummy_var;
4008 
4009 		dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
4010 		for (i = 0; i < obj->nr_extern; i++) {
4011 			ext = &obj->externs[i];
4012 			if (ext->type != EXT_KSYM)
4013 				continue;
4014 			pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
4015 				 i, ext->sym_idx, ext->name);
4016 		}
4017 
4018 		sec = ksym_sec;
4019 		n = btf_vlen(sec);
4020 		for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
4021 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4022 			struct btf_type *vt;
4023 
4024 			vt = (void *)btf__type_by_id(obj->btf, vs->type);
4025 			ext_name = btf__name_by_offset(obj->btf, vt->name_off);
4026 			ext = find_extern_by_name(obj, ext_name);
4027 			if (!ext) {
4028 				pr_warn("failed to find extern definition for BTF %s '%s'\n",
4029 					btf_kind_str(vt), ext_name);
4030 				return -ESRCH;
4031 			}
4032 			if (btf_is_func(vt)) {
4033 				const struct btf_type *func_proto;
4034 				struct btf_param *param;
4035 				int j;
4036 
4037 				func_proto = btf__type_by_id(obj->btf,
4038 							     vt->type);
4039 				param = btf_params(func_proto);
4040 				/* Reuse the dummy_var string if the
4041 				 * func proto does not have param name.
4042 				 */
4043 				for (j = 0; j < btf_vlen(func_proto); j++)
4044 					if (param[j].type && !param[j].name_off)
4045 						param[j].name_off =
4046 							dummy_var->name_off;
4047 				vs->type = dummy_var_btf_id;
4048 				vt->info &= ~0xffff;
4049 				vt->info |= BTF_FUNC_GLOBAL;
4050 			} else {
4051 				btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4052 				vt->type = int_btf_id;
4053 			}
4054 			vs->offset = off;
4055 			vs->size = sizeof(int);
4056 		}
4057 		sec->size = off;
4058 	}
4059 
4060 	if (kcfg_sec) {
4061 		sec = kcfg_sec;
4062 		/* for kcfg externs calculate their offsets within a .kconfig map */
4063 		off = 0;
4064 		for (i = 0; i < obj->nr_extern; i++) {
4065 			ext = &obj->externs[i];
4066 			if (ext->type != EXT_KCFG)
4067 				continue;
4068 
4069 			ext->kcfg.data_off = roundup(off, ext->kcfg.align);
4070 			off = ext->kcfg.data_off + ext->kcfg.sz;
4071 			pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
4072 				 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
4073 		}
4074 		sec->size = off;
4075 		n = btf_vlen(sec);
4076 		for (i = 0; i < n; i++) {
4077 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4078 
4079 			t = btf__type_by_id(obj->btf, vs->type);
4080 			ext_name = btf__name_by_offset(obj->btf, t->name_off);
4081 			ext = find_extern_by_name(obj, ext_name);
4082 			if (!ext) {
4083 				pr_warn("failed to find extern definition for BTF var '%s'\n",
4084 					ext_name);
4085 				return -ESRCH;
4086 			}
4087 			btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4088 			vs->offset = ext->kcfg.data_off;
4089 		}
4090 	}
4091 	return 0;
4092 }
4093 
4094 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog)
4095 {
4096 	return prog->sec_idx == obj->efile.text_shndx && obj->nr_programs > 1;
4097 }
4098 
4099 struct bpf_program *
4100 bpf_object__find_program_by_name(const struct bpf_object *obj,
4101 				 const char *name)
4102 {
4103 	struct bpf_program *prog;
4104 
4105 	bpf_object__for_each_program(prog, obj) {
4106 		if (prog_is_subprog(obj, prog))
4107 			continue;
4108 		if (!strcmp(prog->name, name))
4109 			return prog;
4110 	}
4111 	return errno = ENOENT, NULL;
4112 }
4113 
4114 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
4115 				      int shndx)
4116 {
4117 	switch (obj->efile.secs[shndx].sec_type) {
4118 	case SEC_BSS:
4119 	case SEC_DATA:
4120 	case SEC_RODATA:
4121 		return true;
4122 	default:
4123 		return false;
4124 	}
4125 }
4126 
4127 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
4128 				      int shndx)
4129 {
4130 	return shndx == obj->efile.btf_maps_shndx;
4131 }
4132 
4133 static enum libbpf_map_type
4134 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
4135 {
4136 	if (shndx == obj->efile.symbols_shndx)
4137 		return LIBBPF_MAP_KCONFIG;
4138 
4139 	switch (obj->efile.secs[shndx].sec_type) {
4140 	case SEC_BSS:
4141 		return LIBBPF_MAP_BSS;
4142 	case SEC_DATA:
4143 		return LIBBPF_MAP_DATA;
4144 	case SEC_RODATA:
4145 		return LIBBPF_MAP_RODATA;
4146 	default:
4147 		return LIBBPF_MAP_UNSPEC;
4148 	}
4149 }
4150 
4151 static int bpf_program__record_reloc(struct bpf_program *prog,
4152 				     struct reloc_desc *reloc_desc,
4153 				     __u32 insn_idx, const char *sym_name,
4154 				     const Elf64_Sym *sym, const Elf64_Rel *rel)
4155 {
4156 	struct bpf_insn *insn = &prog->insns[insn_idx];
4157 	size_t map_idx, nr_maps = prog->obj->nr_maps;
4158 	struct bpf_object *obj = prog->obj;
4159 	__u32 shdr_idx = sym->st_shndx;
4160 	enum libbpf_map_type type;
4161 	const char *sym_sec_name;
4162 	struct bpf_map *map;
4163 
4164 	if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
4165 		pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n",
4166 			prog->name, sym_name, insn_idx, insn->code);
4167 		return -LIBBPF_ERRNO__RELOC;
4168 	}
4169 
4170 	if (sym_is_extern(sym)) {
4171 		int sym_idx = ELF64_R_SYM(rel->r_info);
4172 		int i, n = obj->nr_extern;
4173 		struct extern_desc *ext;
4174 
4175 		for (i = 0; i < n; i++) {
4176 			ext = &obj->externs[i];
4177 			if (ext->sym_idx == sym_idx)
4178 				break;
4179 		}
4180 		if (i >= n) {
4181 			pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
4182 				prog->name, sym_name, sym_idx);
4183 			return -LIBBPF_ERRNO__RELOC;
4184 		}
4185 		pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
4186 			 prog->name, i, ext->name, ext->sym_idx, insn_idx);
4187 		if (insn->code == (BPF_JMP | BPF_CALL))
4188 			reloc_desc->type = RELO_EXTERN_CALL;
4189 		else
4190 			reloc_desc->type = RELO_EXTERN_LD64;
4191 		reloc_desc->insn_idx = insn_idx;
4192 		reloc_desc->ext_idx = i;
4193 		return 0;
4194 	}
4195 
4196 	/* sub-program call relocation */
4197 	if (is_call_insn(insn)) {
4198 		if (insn->src_reg != BPF_PSEUDO_CALL) {
4199 			pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
4200 			return -LIBBPF_ERRNO__RELOC;
4201 		}
4202 		/* text_shndx can be 0, if no default "main" program exists */
4203 		if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
4204 			sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4205 			pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
4206 				prog->name, sym_name, sym_sec_name);
4207 			return -LIBBPF_ERRNO__RELOC;
4208 		}
4209 		if (sym->st_value % BPF_INSN_SZ) {
4210 			pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
4211 				prog->name, sym_name, (size_t)sym->st_value);
4212 			return -LIBBPF_ERRNO__RELOC;
4213 		}
4214 		reloc_desc->type = RELO_CALL;
4215 		reloc_desc->insn_idx = insn_idx;
4216 		reloc_desc->sym_off = sym->st_value;
4217 		return 0;
4218 	}
4219 
4220 	if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
4221 		pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
4222 			prog->name, sym_name, shdr_idx);
4223 		return -LIBBPF_ERRNO__RELOC;
4224 	}
4225 
4226 	/* loading subprog addresses */
4227 	if (sym_is_subprog(sym, obj->efile.text_shndx)) {
4228 		/* global_func: sym->st_value = offset in the section, insn->imm = 0.
4229 		 * local_func: sym->st_value = 0, insn->imm = offset in the section.
4230 		 */
4231 		if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
4232 			pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
4233 				prog->name, sym_name, (size_t)sym->st_value, insn->imm);
4234 			return -LIBBPF_ERRNO__RELOC;
4235 		}
4236 
4237 		reloc_desc->type = RELO_SUBPROG_ADDR;
4238 		reloc_desc->insn_idx = insn_idx;
4239 		reloc_desc->sym_off = sym->st_value;
4240 		return 0;
4241 	}
4242 
4243 	type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
4244 	sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4245 
4246 	/* generic map reference relocation */
4247 	if (type == LIBBPF_MAP_UNSPEC) {
4248 		if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
4249 			pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
4250 				prog->name, sym_name, sym_sec_name);
4251 			return -LIBBPF_ERRNO__RELOC;
4252 		}
4253 		for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4254 			map = &obj->maps[map_idx];
4255 			if (map->libbpf_type != type ||
4256 			    map->sec_idx != sym->st_shndx ||
4257 			    map->sec_offset != sym->st_value)
4258 				continue;
4259 			pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n",
4260 				 prog->name, map_idx, map->name, map->sec_idx,
4261 				 map->sec_offset, insn_idx);
4262 			break;
4263 		}
4264 		if (map_idx >= nr_maps) {
4265 			pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
4266 				prog->name, sym_sec_name, (size_t)sym->st_value);
4267 			return -LIBBPF_ERRNO__RELOC;
4268 		}
4269 		reloc_desc->type = RELO_LD64;
4270 		reloc_desc->insn_idx = insn_idx;
4271 		reloc_desc->map_idx = map_idx;
4272 		reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
4273 		return 0;
4274 	}
4275 
4276 	/* global data map relocation */
4277 	if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
4278 		pr_warn("prog '%s': bad data relo against section '%s'\n",
4279 			prog->name, sym_sec_name);
4280 		return -LIBBPF_ERRNO__RELOC;
4281 	}
4282 	for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4283 		map = &obj->maps[map_idx];
4284 		if (map->libbpf_type != type || map->sec_idx != sym->st_shndx)
4285 			continue;
4286 		pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n",
4287 			 prog->name, map_idx, map->name, map->sec_idx,
4288 			 map->sec_offset, insn_idx);
4289 		break;
4290 	}
4291 	if (map_idx >= nr_maps) {
4292 		pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
4293 			prog->name, sym_sec_name);
4294 		return -LIBBPF_ERRNO__RELOC;
4295 	}
4296 
4297 	reloc_desc->type = RELO_DATA;
4298 	reloc_desc->insn_idx = insn_idx;
4299 	reloc_desc->map_idx = map_idx;
4300 	reloc_desc->sym_off = sym->st_value;
4301 	return 0;
4302 }
4303 
4304 static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
4305 {
4306 	return insn_idx >= prog->sec_insn_off &&
4307 	       insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
4308 }
4309 
4310 static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
4311 						 size_t sec_idx, size_t insn_idx)
4312 {
4313 	int l = 0, r = obj->nr_programs - 1, m;
4314 	struct bpf_program *prog;
4315 
4316 	if (!obj->nr_programs)
4317 		return NULL;
4318 
4319 	while (l < r) {
4320 		m = l + (r - l + 1) / 2;
4321 		prog = &obj->programs[m];
4322 
4323 		if (prog->sec_idx < sec_idx ||
4324 		    (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
4325 			l = m;
4326 		else
4327 			r = m - 1;
4328 	}
4329 	/* matching program could be at index l, but it still might be the
4330 	 * wrong one, so we need to double check conditions for the last time
4331 	 */
4332 	prog = &obj->programs[l];
4333 	if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
4334 		return prog;
4335 	return NULL;
4336 }
4337 
4338 static int
4339 bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
4340 {
4341 	const char *relo_sec_name, *sec_name;
4342 	size_t sec_idx = shdr->sh_info, sym_idx;
4343 	struct bpf_program *prog;
4344 	struct reloc_desc *relos;
4345 	int err, i, nrels;
4346 	const char *sym_name;
4347 	__u32 insn_idx;
4348 	Elf_Scn *scn;
4349 	Elf_Data *scn_data;
4350 	Elf64_Sym *sym;
4351 	Elf64_Rel *rel;
4352 
4353 	if (sec_idx >= obj->efile.sec_cnt)
4354 		return -EINVAL;
4355 
4356 	scn = elf_sec_by_idx(obj, sec_idx);
4357 	scn_data = elf_sec_data(obj, scn);
4358 	if (!scn_data)
4359 		return -LIBBPF_ERRNO__FORMAT;
4360 
4361 	relo_sec_name = elf_sec_str(obj, shdr->sh_name);
4362 	sec_name = elf_sec_name(obj, scn);
4363 	if (!relo_sec_name || !sec_name)
4364 		return -EINVAL;
4365 
4366 	pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
4367 		 relo_sec_name, sec_idx, sec_name);
4368 	nrels = shdr->sh_size / shdr->sh_entsize;
4369 
4370 	for (i = 0; i < nrels; i++) {
4371 		rel = elf_rel_by_idx(data, i);
4372 		if (!rel) {
4373 			pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
4374 			return -LIBBPF_ERRNO__FORMAT;
4375 		}
4376 
4377 		sym_idx = ELF64_R_SYM(rel->r_info);
4378 		sym = elf_sym_by_idx(obj, sym_idx);
4379 		if (!sym) {
4380 			pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
4381 				relo_sec_name, sym_idx, i);
4382 			return -LIBBPF_ERRNO__FORMAT;
4383 		}
4384 
4385 		if (sym->st_shndx >= obj->efile.sec_cnt) {
4386 			pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
4387 				relo_sec_name, sym_idx, (size_t)sym->st_shndx, i);
4388 			return -LIBBPF_ERRNO__FORMAT;
4389 		}
4390 
4391 		if (rel->r_offset % BPF_INSN_SZ || rel->r_offset >= scn_data->d_size) {
4392 			pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
4393 				relo_sec_name, (size_t)rel->r_offset, i);
4394 			return -LIBBPF_ERRNO__FORMAT;
4395 		}
4396 
4397 		insn_idx = rel->r_offset / BPF_INSN_SZ;
4398 		/* relocations against static functions are recorded as
4399 		 * relocations against the section that contains a function;
4400 		 * in such case, symbol will be STT_SECTION and sym.st_name
4401 		 * will point to empty string (0), so fetch section name
4402 		 * instead
4403 		 */
4404 		if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
4405 			sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx));
4406 		else
4407 			sym_name = elf_sym_str(obj, sym->st_name);
4408 		sym_name = sym_name ?: "<?";
4409 
4410 		pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
4411 			 relo_sec_name, i, insn_idx, sym_name);
4412 
4413 		prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
4414 		if (!prog) {
4415 			pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
4416 				relo_sec_name, i, sec_name, insn_idx);
4417 			continue;
4418 		}
4419 
4420 		relos = libbpf_reallocarray(prog->reloc_desc,
4421 					    prog->nr_reloc + 1, sizeof(*relos));
4422 		if (!relos)
4423 			return -ENOMEM;
4424 		prog->reloc_desc = relos;
4425 
4426 		/* adjust insn_idx to local BPF program frame of reference */
4427 		insn_idx -= prog->sec_insn_off;
4428 		err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
4429 						insn_idx, sym_name, sym, rel);
4430 		if (err)
4431 			return err;
4432 
4433 		prog->nr_reloc++;
4434 	}
4435 	return 0;
4436 }
4437 
4438 static int map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map)
4439 {
4440 	int id;
4441 
4442 	if (!obj->btf)
4443 		return -ENOENT;
4444 
4445 	/* if it's BTF-defined map, we don't need to search for type IDs.
4446 	 * For struct_ops map, it does not need btf_key_type_id and
4447 	 * btf_value_type_id.
4448 	 */
4449 	if (map->sec_idx == obj->efile.btf_maps_shndx || bpf_map__is_struct_ops(map))
4450 		return 0;
4451 
4452 	/*
4453 	 * LLVM annotates global data differently in BTF, that is,
4454 	 * only as '.data', '.bss' or '.rodata'.
4455 	 */
4456 	if (!bpf_map__is_internal(map))
4457 		return -ENOENT;
4458 
4459 	id = btf__find_by_name(obj->btf, map->real_name);
4460 	if (id < 0)
4461 		return id;
4462 
4463 	map->btf_key_type_id = 0;
4464 	map->btf_value_type_id = id;
4465 	return 0;
4466 }
4467 
4468 static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
4469 {
4470 	char file[PATH_MAX], buff[4096];
4471 	FILE *fp;
4472 	__u32 val;
4473 	int err;
4474 
4475 	snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
4476 	memset(info, 0, sizeof(*info));
4477 
4478 	fp = fopen(file, "re");
4479 	if (!fp) {
4480 		err = -errno;
4481 		pr_warn("failed to open %s: %d. No procfs support?\n", file,
4482 			err);
4483 		return err;
4484 	}
4485 
4486 	while (fgets(buff, sizeof(buff), fp)) {
4487 		if (sscanf(buff, "map_type:\t%u", &val) == 1)
4488 			info->type = val;
4489 		else if (sscanf(buff, "key_size:\t%u", &val) == 1)
4490 			info->key_size = val;
4491 		else if (sscanf(buff, "value_size:\t%u", &val) == 1)
4492 			info->value_size = val;
4493 		else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
4494 			info->max_entries = val;
4495 		else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
4496 			info->map_flags = val;
4497 	}
4498 
4499 	fclose(fp);
4500 
4501 	return 0;
4502 }
4503 
4504 bool bpf_map__autocreate(const struct bpf_map *map)
4505 {
4506 	return map->autocreate;
4507 }
4508 
4509 int bpf_map__set_autocreate(struct bpf_map *map, bool autocreate)
4510 {
4511 	if (map->obj->loaded)
4512 		return libbpf_err(-EBUSY);
4513 
4514 	map->autocreate = autocreate;
4515 	return 0;
4516 }
4517 
4518 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
4519 {
4520 	struct bpf_map_info info;
4521 	__u32 len = sizeof(info), name_len;
4522 	int new_fd, err;
4523 	char *new_name;
4524 
4525 	memset(&info, 0, len);
4526 	err = bpf_map_get_info_by_fd(fd, &info, &len);
4527 	if (err && errno == EINVAL)
4528 		err = bpf_get_map_info_from_fdinfo(fd, &info);
4529 	if (err)
4530 		return libbpf_err(err);
4531 
4532 	name_len = strlen(info.name);
4533 	if (name_len == BPF_OBJ_NAME_LEN - 1 && strncmp(map->name, info.name, name_len) == 0)
4534 		new_name = strdup(map->name);
4535 	else
4536 		new_name = strdup(info.name);
4537 
4538 	if (!new_name)
4539 		return libbpf_err(-errno);
4540 
4541 	/*
4542 	 * Like dup(), but make sure new FD is >= 3 and has O_CLOEXEC set.
4543 	 * This is similar to what we do in ensure_good_fd(), but without
4544 	 * closing original FD.
4545 	 */
4546 	new_fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
4547 	if (new_fd < 0) {
4548 		err = -errno;
4549 		goto err_free_new_name;
4550 	}
4551 
4552 	err = zclose(map->fd);
4553 	if (err) {
4554 		err = -errno;
4555 		goto err_close_new_fd;
4556 	}
4557 	free(map->name);
4558 
4559 	map->fd = new_fd;
4560 	map->name = new_name;
4561 	map->def.type = info.type;
4562 	map->def.key_size = info.key_size;
4563 	map->def.value_size = info.value_size;
4564 	map->def.max_entries = info.max_entries;
4565 	map->def.map_flags = info.map_flags;
4566 	map->btf_key_type_id = info.btf_key_type_id;
4567 	map->btf_value_type_id = info.btf_value_type_id;
4568 	map->reused = true;
4569 	map->map_extra = info.map_extra;
4570 
4571 	return 0;
4572 
4573 err_close_new_fd:
4574 	close(new_fd);
4575 err_free_new_name:
4576 	free(new_name);
4577 	return libbpf_err(err);
4578 }
4579 
4580 __u32 bpf_map__max_entries(const struct bpf_map *map)
4581 {
4582 	return map->def.max_entries;
4583 }
4584 
4585 struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
4586 {
4587 	if (!bpf_map_type__is_map_in_map(map->def.type))
4588 		return errno = EINVAL, NULL;
4589 
4590 	return map->inner_map;
4591 }
4592 
4593 int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
4594 {
4595 	if (map->obj->loaded)
4596 		return libbpf_err(-EBUSY);
4597 
4598 	map->def.max_entries = max_entries;
4599 
4600 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
4601 	if (map_is_ringbuf(map))
4602 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
4603 
4604 	return 0;
4605 }
4606 
4607 static int
4608 bpf_object__probe_loading(struct bpf_object *obj)
4609 {
4610 	char *cp, errmsg[STRERR_BUFSIZE];
4611 	struct bpf_insn insns[] = {
4612 		BPF_MOV64_IMM(BPF_REG_0, 0),
4613 		BPF_EXIT_INSN(),
4614 	};
4615 	int ret, insn_cnt = ARRAY_SIZE(insns);
4616 
4617 	if (obj->gen_loader)
4618 		return 0;
4619 
4620 	ret = bump_rlimit_memlock();
4621 	if (ret)
4622 		pr_warn("Failed to bump RLIMIT_MEMLOCK (err = %d), you might need to do it explicitly!\n", ret);
4623 
4624 	/* make sure basic loading works */
4625 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4626 	if (ret < 0)
4627 		ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
4628 	if (ret < 0) {
4629 		ret = errno;
4630 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4631 		pr_warn("Error in %s():%s(%d). Couldn't load trivial BPF "
4632 			"program. Make sure your kernel supports BPF "
4633 			"(CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is "
4634 			"set to big enough value.\n", __func__, cp, ret);
4635 		return -ret;
4636 	}
4637 	close(ret);
4638 
4639 	return 0;
4640 }
4641 
4642 static int probe_fd(int fd)
4643 {
4644 	if (fd >= 0)
4645 		close(fd);
4646 	return fd >= 0;
4647 }
4648 
4649 static int probe_kern_prog_name(void)
4650 {
4651 	const size_t attr_sz = offsetofend(union bpf_attr, prog_name);
4652 	struct bpf_insn insns[] = {
4653 		BPF_MOV64_IMM(BPF_REG_0, 0),
4654 		BPF_EXIT_INSN(),
4655 	};
4656 	union bpf_attr attr;
4657 	int ret;
4658 
4659 	memset(&attr, 0, attr_sz);
4660 	attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
4661 	attr.license = ptr_to_u64("GPL");
4662 	attr.insns = ptr_to_u64(insns);
4663 	attr.insn_cnt = (__u32)ARRAY_SIZE(insns);
4664 	libbpf_strlcpy(attr.prog_name, "libbpf_nametest", sizeof(attr.prog_name));
4665 
4666 	/* make sure loading with name works */
4667 	ret = sys_bpf_prog_load(&attr, attr_sz, PROG_LOAD_ATTEMPTS);
4668 	return probe_fd(ret);
4669 }
4670 
4671 static int probe_kern_global_data(void)
4672 {
4673 	char *cp, errmsg[STRERR_BUFSIZE];
4674 	struct bpf_insn insns[] = {
4675 		BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
4676 		BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
4677 		BPF_MOV64_IMM(BPF_REG_0, 0),
4678 		BPF_EXIT_INSN(),
4679 	};
4680 	int ret, map, insn_cnt = ARRAY_SIZE(insns);
4681 
4682 	map = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_global", sizeof(int), 32, 1, NULL);
4683 	if (map < 0) {
4684 		ret = -errno;
4685 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4686 		pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4687 			__func__, cp, -ret);
4688 		return ret;
4689 	}
4690 
4691 	insns[0].imm = map;
4692 
4693 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4694 	close(map);
4695 	return probe_fd(ret);
4696 }
4697 
4698 static int probe_kern_btf(void)
4699 {
4700 	static const char strs[] = "\0int";
4701 	__u32 types[] = {
4702 		/* int */
4703 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4704 	};
4705 
4706 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4707 					     strs, sizeof(strs)));
4708 }
4709 
4710 static int probe_kern_btf_func(void)
4711 {
4712 	static const char strs[] = "\0int\0x\0a";
4713 	/* void x(int a) {} */
4714 	__u32 types[] = {
4715 		/* int */
4716 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4717 		/* FUNC_PROTO */                                /* [2] */
4718 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4719 		BTF_PARAM_ENC(7, 1),
4720 		/* FUNC x */                                    /* [3] */
4721 		BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
4722 	};
4723 
4724 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4725 					     strs, sizeof(strs)));
4726 }
4727 
4728 static int probe_kern_btf_func_global(void)
4729 {
4730 	static const char strs[] = "\0int\0x\0a";
4731 	/* static void x(int a) {} */
4732 	__u32 types[] = {
4733 		/* int */
4734 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4735 		/* FUNC_PROTO */                                /* [2] */
4736 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4737 		BTF_PARAM_ENC(7, 1),
4738 		/* FUNC x BTF_FUNC_GLOBAL */                    /* [3] */
4739 		BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, BTF_FUNC_GLOBAL), 2),
4740 	};
4741 
4742 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4743 					     strs, sizeof(strs)));
4744 }
4745 
4746 static int probe_kern_btf_datasec(void)
4747 {
4748 	static const char strs[] = "\0x\0.data";
4749 	/* static int a; */
4750 	__u32 types[] = {
4751 		/* int */
4752 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4753 		/* VAR x */                                     /* [2] */
4754 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4755 		BTF_VAR_STATIC,
4756 		/* DATASEC val */                               /* [3] */
4757 		BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
4758 		BTF_VAR_SECINFO_ENC(2, 0, 4),
4759 	};
4760 
4761 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4762 					     strs, sizeof(strs)));
4763 }
4764 
4765 static int probe_kern_btf_float(void)
4766 {
4767 	static const char strs[] = "\0float";
4768 	__u32 types[] = {
4769 		/* float */
4770 		BTF_TYPE_FLOAT_ENC(1, 4),
4771 	};
4772 
4773 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4774 					     strs, sizeof(strs)));
4775 }
4776 
4777 static int probe_kern_btf_decl_tag(void)
4778 {
4779 	static const char strs[] = "\0tag";
4780 	__u32 types[] = {
4781 		/* int */
4782 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4783 		/* VAR x */                                     /* [2] */
4784 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4785 		BTF_VAR_STATIC,
4786 		/* attr */
4787 		BTF_TYPE_DECL_TAG_ENC(1, 2, -1),
4788 	};
4789 
4790 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4791 					     strs, sizeof(strs)));
4792 }
4793 
4794 static int probe_kern_btf_type_tag(void)
4795 {
4796 	static const char strs[] = "\0tag";
4797 	__u32 types[] = {
4798 		/* int */
4799 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),		/* [1] */
4800 		/* attr */
4801 		BTF_TYPE_TYPE_TAG_ENC(1, 1),				/* [2] */
4802 		/* ptr */
4803 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_PTR, 0, 0), 2),	/* [3] */
4804 	};
4805 
4806 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4807 					     strs, sizeof(strs)));
4808 }
4809 
4810 static int probe_kern_array_mmap(void)
4811 {
4812 	LIBBPF_OPTS(bpf_map_create_opts, opts, .map_flags = BPF_F_MMAPABLE);
4813 	int fd;
4814 
4815 	fd = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_mmap", sizeof(int), sizeof(int), 1, &opts);
4816 	return probe_fd(fd);
4817 }
4818 
4819 static int probe_kern_exp_attach_type(void)
4820 {
4821 	LIBBPF_OPTS(bpf_prog_load_opts, opts, .expected_attach_type = BPF_CGROUP_INET_SOCK_CREATE);
4822 	struct bpf_insn insns[] = {
4823 		BPF_MOV64_IMM(BPF_REG_0, 0),
4824 		BPF_EXIT_INSN(),
4825 	};
4826 	int fd, insn_cnt = ARRAY_SIZE(insns);
4827 
4828 	/* use any valid combination of program type and (optional)
4829 	 * non-zero expected attach type (i.e., not a BPF_CGROUP_INET_INGRESS)
4830 	 * to see if kernel supports expected_attach_type field for
4831 	 * BPF_PROG_LOAD command
4832 	 */
4833 	fd = bpf_prog_load(BPF_PROG_TYPE_CGROUP_SOCK, NULL, "GPL", insns, insn_cnt, &opts);
4834 	return probe_fd(fd);
4835 }
4836 
4837 static int probe_kern_probe_read_kernel(void)
4838 {
4839 	struct bpf_insn insns[] = {
4840 		BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),	/* r1 = r10 (fp) */
4841 		BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -8),	/* r1 += -8 */
4842 		BPF_MOV64_IMM(BPF_REG_2, 8),		/* r2 = 8 */
4843 		BPF_MOV64_IMM(BPF_REG_3, 0),		/* r3 = 0 */
4844 		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_probe_read_kernel),
4845 		BPF_EXIT_INSN(),
4846 	};
4847 	int fd, insn_cnt = ARRAY_SIZE(insns);
4848 
4849 	fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
4850 	return probe_fd(fd);
4851 }
4852 
4853 static int probe_prog_bind_map(void)
4854 {
4855 	char *cp, errmsg[STRERR_BUFSIZE];
4856 	struct bpf_insn insns[] = {
4857 		BPF_MOV64_IMM(BPF_REG_0, 0),
4858 		BPF_EXIT_INSN(),
4859 	};
4860 	int ret, map, prog, insn_cnt = ARRAY_SIZE(insns);
4861 
4862 	map = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_det_bind", sizeof(int), 32, 1, NULL);
4863 	if (map < 0) {
4864 		ret = -errno;
4865 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4866 		pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4867 			__func__, cp, -ret);
4868 		return ret;
4869 	}
4870 
4871 	prog = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4872 	if (prog < 0) {
4873 		close(map);
4874 		return 0;
4875 	}
4876 
4877 	ret = bpf_prog_bind_map(prog, map, NULL);
4878 
4879 	close(map);
4880 	close(prog);
4881 
4882 	return ret >= 0;
4883 }
4884 
4885 static int probe_module_btf(void)
4886 {
4887 	static const char strs[] = "\0int";
4888 	__u32 types[] = {
4889 		/* int */
4890 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4891 	};
4892 	struct bpf_btf_info info;
4893 	__u32 len = sizeof(info);
4894 	char name[16];
4895 	int fd, err;
4896 
4897 	fd = libbpf__load_raw_btf((char *)types, sizeof(types), strs, sizeof(strs));
4898 	if (fd < 0)
4899 		return 0; /* BTF not supported at all */
4900 
4901 	memset(&info, 0, sizeof(info));
4902 	info.name = ptr_to_u64(name);
4903 	info.name_len = sizeof(name);
4904 
4905 	/* check that BPF_OBJ_GET_INFO_BY_FD supports specifying name pointer;
4906 	 * kernel's module BTF support coincides with support for
4907 	 * name/name_len fields in struct bpf_btf_info.
4908 	 */
4909 	err = bpf_btf_get_info_by_fd(fd, &info, &len);
4910 	close(fd);
4911 	return !err;
4912 }
4913 
4914 static int probe_perf_link(void)
4915 {
4916 	struct bpf_insn insns[] = {
4917 		BPF_MOV64_IMM(BPF_REG_0, 0),
4918 		BPF_EXIT_INSN(),
4919 	};
4920 	int prog_fd, link_fd, err;
4921 
4922 	prog_fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL",
4923 				insns, ARRAY_SIZE(insns), NULL);
4924 	if (prog_fd < 0)
4925 		return -errno;
4926 
4927 	/* use invalid perf_event FD to get EBADF, if link is supported;
4928 	 * otherwise EINVAL should be returned
4929 	 */
4930 	link_fd = bpf_link_create(prog_fd, -1, BPF_PERF_EVENT, NULL);
4931 	err = -errno; /* close() can clobber errno */
4932 
4933 	if (link_fd >= 0)
4934 		close(link_fd);
4935 	close(prog_fd);
4936 
4937 	return link_fd < 0 && err == -EBADF;
4938 }
4939 
4940 static int probe_uprobe_multi_link(void)
4941 {
4942 	LIBBPF_OPTS(bpf_prog_load_opts, load_opts,
4943 		.expected_attach_type = BPF_TRACE_UPROBE_MULTI,
4944 	);
4945 	LIBBPF_OPTS(bpf_link_create_opts, link_opts);
4946 	struct bpf_insn insns[] = {
4947 		BPF_MOV64_IMM(BPF_REG_0, 0),
4948 		BPF_EXIT_INSN(),
4949 	};
4950 	int prog_fd, link_fd, err;
4951 	unsigned long offset = 0;
4952 
4953 	prog_fd = bpf_prog_load(BPF_PROG_TYPE_KPROBE, NULL, "GPL",
4954 				insns, ARRAY_SIZE(insns), &load_opts);
4955 	if (prog_fd < 0)
4956 		return -errno;
4957 
4958 	/* Creating uprobe in '/' binary should fail with -EBADF. */
4959 	link_opts.uprobe_multi.path = "/";
4960 	link_opts.uprobe_multi.offsets = &offset;
4961 	link_opts.uprobe_multi.cnt = 1;
4962 
4963 	link_fd = bpf_link_create(prog_fd, -1, BPF_TRACE_UPROBE_MULTI, &link_opts);
4964 	err = -errno; /* close() can clobber errno */
4965 
4966 	if (link_fd >= 0)
4967 		close(link_fd);
4968 	close(prog_fd);
4969 
4970 	return link_fd < 0 && err == -EBADF;
4971 }
4972 
4973 static int probe_kern_bpf_cookie(void)
4974 {
4975 	struct bpf_insn insns[] = {
4976 		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_get_attach_cookie),
4977 		BPF_EXIT_INSN(),
4978 	};
4979 	int ret, insn_cnt = ARRAY_SIZE(insns);
4980 
4981 	ret = bpf_prog_load(BPF_PROG_TYPE_KPROBE, NULL, "GPL", insns, insn_cnt, NULL);
4982 	return probe_fd(ret);
4983 }
4984 
4985 static int probe_kern_btf_enum64(void)
4986 {
4987 	static const char strs[] = "\0enum64";
4988 	__u32 types[] = {
4989 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_ENUM64, 0, 0), 8),
4990 	};
4991 
4992 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4993 					     strs, sizeof(strs)));
4994 }
4995 
4996 static int probe_kern_syscall_wrapper(void);
4997 
4998 enum kern_feature_result {
4999 	FEAT_UNKNOWN = 0,
5000 	FEAT_SUPPORTED = 1,
5001 	FEAT_MISSING = 2,
5002 };
5003 
5004 typedef int (*feature_probe_fn)(void);
5005 
5006 static struct kern_feature_desc {
5007 	const char *desc;
5008 	feature_probe_fn probe;
5009 	enum kern_feature_result res;
5010 } feature_probes[__FEAT_CNT] = {
5011 	[FEAT_PROG_NAME] = {
5012 		"BPF program name", probe_kern_prog_name,
5013 	},
5014 	[FEAT_GLOBAL_DATA] = {
5015 		"global variables", probe_kern_global_data,
5016 	},
5017 	[FEAT_BTF] = {
5018 		"minimal BTF", probe_kern_btf,
5019 	},
5020 	[FEAT_BTF_FUNC] = {
5021 		"BTF functions", probe_kern_btf_func,
5022 	},
5023 	[FEAT_BTF_GLOBAL_FUNC] = {
5024 		"BTF global function", probe_kern_btf_func_global,
5025 	},
5026 	[FEAT_BTF_DATASEC] = {
5027 		"BTF data section and variable", probe_kern_btf_datasec,
5028 	},
5029 	[FEAT_ARRAY_MMAP] = {
5030 		"ARRAY map mmap()", probe_kern_array_mmap,
5031 	},
5032 	[FEAT_EXP_ATTACH_TYPE] = {
5033 		"BPF_PROG_LOAD expected_attach_type attribute",
5034 		probe_kern_exp_attach_type,
5035 	},
5036 	[FEAT_PROBE_READ_KERN] = {
5037 		"bpf_probe_read_kernel() helper", probe_kern_probe_read_kernel,
5038 	},
5039 	[FEAT_PROG_BIND_MAP] = {
5040 		"BPF_PROG_BIND_MAP support", probe_prog_bind_map,
5041 	},
5042 	[FEAT_MODULE_BTF] = {
5043 		"module BTF support", probe_module_btf,
5044 	},
5045 	[FEAT_BTF_FLOAT] = {
5046 		"BTF_KIND_FLOAT support", probe_kern_btf_float,
5047 	},
5048 	[FEAT_PERF_LINK] = {
5049 		"BPF perf link support", probe_perf_link,
5050 	},
5051 	[FEAT_BTF_DECL_TAG] = {
5052 		"BTF_KIND_DECL_TAG support", probe_kern_btf_decl_tag,
5053 	},
5054 	[FEAT_BTF_TYPE_TAG] = {
5055 		"BTF_KIND_TYPE_TAG support", probe_kern_btf_type_tag,
5056 	},
5057 	[FEAT_MEMCG_ACCOUNT] = {
5058 		"memcg-based memory accounting", probe_memcg_account,
5059 	},
5060 	[FEAT_BPF_COOKIE] = {
5061 		"BPF cookie support", probe_kern_bpf_cookie,
5062 	},
5063 	[FEAT_BTF_ENUM64] = {
5064 		"BTF_KIND_ENUM64 support", probe_kern_btf_enum64,
5065 	},
5066 	[FEAT_SYSCALL_WRAPPER] = {
5067 		"Kernel using syscall wrapper", probe_kern_syscall_wrapper,
5068 	},
5069 	[FEAT_UPROBE_MULTI_LINK] = {
5070 		"BPF multi-uprobe link support", probe_uprobe_multi_link,
5071 	},
5072 };
5073 
5074 bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
5075 {
5076 	struct kern_feature_desc *feat = &feature_probes[feat_id];
5077 	int ret;
5078 
5079 	if (obj && obj->gen_loader)
5080 		/* To generate loader program assume the latest kernel
5081 		 * to avoid doing extra prog_load, map_create syscalls.
5082 		 */
5083 		return true;
5084 
5085 	if (READ_ONCE(feat->res) == FEAT_UNKNOWN) {
5086 		ret = feat->probe();
5087 		if (ret > 0) {
5088 			WRITE_ONCE(feat->res, FEAT_SUPPORTED);
5089 		} else if (ret == 0) {
5090 			WRITE_ONCE(feat->res, FEAT_MISSING);
5091 		} else {
5092 			pr_warn("Detection of kernel %s support failed: %d\n", feat->desc, ret);
5093 			WRITE_ONCE(feat->res, FEAT_MISSING);
5094 		}
5095 	}
5096 
5097 	return READ_ONCE(feat->res) == FEAT_SUPPORTED;
5098 }
5099 
5100 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
5101 {
5102 	struct bpf_map_info map_info;
5103 	char msg[STRERR_BUFSIZE];
5104 	__u32 map_info_len = sizeof(map_info);
5105 	int err;
5106 
5107 	memset(&map_info, 0, map_info_len);
5108 	err = bpf_map_get_info_by_fd(map_fd, &map_info, &map_info_len);
5109 	if (err && errno == EINVAL)
5110 		err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
5111 	if (err) {
5112 		pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
5113 			libbpf_strerror_r(errno, msg, sizeof(msg)));
5114 		return false;
5115 	}
5116 
5117 	return (map_info.type == map->def.type &&
5118 		map_info.key_size == map->def.key_size &&
5119 		map_info.value_size == map->def.value_size &&
5120 		map_info.max_entries == map->def.max_entries &&
5121 		map_info.map_flags == map->def.map_flags &&
5122 		map_info.map_extra == map->map_extra);
5123 }
5124 
5125 static int
5126 bpf_object__reuse_map(struct bpf_map *map)
5127 {
5128 	char *cp, errmsg[STRERR_BUFSIZE];
5129 	int err, pin_fd;
5130 
5131 	pin_fd = bpf_obj_get(map->pin_path);
5132 	if (pin_fd < 0) {
5133 		err = -errno;
5134 		if (err == -ENOENT) {
5135 			pr_debug("found no pinned map to reuse at '%s'\n",
5136 				 map->pin_path);
5137 			return 0;
5138 		}
5139 
5140 		cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
5141 		pr_warn("couldn't retrieve pinned map '%s': %s\n",
5142 			map->pin_path, cp);
5143 		return err;
5144 	}
5145 
5146 	if (!map_is_reuse_compat(map, pin_fd)) {
5147 		pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
5148 			map->pin_path);
5149 		close(pin_fd);
5150 		return -EINVAL;
5151 	}
5152 
5153 	err = bpf_map__reuse_fd(map, pin_fd);
5154 	close(pin_fd);
5155 	if (err)
5156 		return err;
5157 
5158 	map->pinned = true;
5159 	pr_debug("reused pinned map at '%s'\n", map->pin_path);
5160 
5161 	return 0;
5162 }
5163 
5164 static int
5165 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
5166 {
5167 	enum libbpf_map_type map_type = map->libbpf_type;
5168 	char *cp, errmsg[STRERR_BUFSIZE];
5169 	int err, zero = 0;
5170 
5171 	if (obj->gen_loader) {
5172 		bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
5173 					 map->mmaped, map->def.value_size);
5174 		if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
5175 			bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
5176 		return 0;
5177 	}
5178 	err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
5179 	if (err) {
5180 		err = -errno;
5181 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5182 		pr_warn("Error setting initial map(%s) contents: %s\n",
5183 			map->name, cp);
5184 		return err;
5185 	}
5186 
5187 	/* Freeze .rodata and .kconfig map as read-only from syscall side. */
5188 	if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
5189 		err = bpf_map_freeze(map->fd);
5190 		if (err) {
5191 			err = -errno;
5192 			cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5193 			pr_warn("Error freezing map(%s) as read-only: %s\n",
5194 				map->name, cp);
5195 			return err;
5196 		}
5197 	}
5198 	return 0;
5199 }
5200 
5201 static void bpf_map__destroy(struct bpf_map *map);
5202 
5203 static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
5204 {
5205 	LIBBPF_OPTS(bpf_map_create_opts, create_attr);
5206 	struct bpf_map_def *def = &map->def;
5207 	const char *map_name = NULL;
5208 	int err = 0;
5209 
5210 	if (kernel_supports(obj, FEAT_PROG_NAME))
5211 		map_name = map->name;
5212 	create_attr.map_ifindex = map->map_ifindex;
5213 	create_attr.map_flags = def->map_flags;
5214 	create_attr.numa_node = map->numa_node;
5215 	create_attr.map_extra = map->map_extra;
5216 
5217 	if (bpf_map__is_struct_ops(map))
5218 		create_attr.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
5219 
5220 	if (obj->btf && btf__fd(obj->btf) >= 0) {
5221 		create_attr.btf_fd = btf__fd(obj->btf);
5222 		create_attr.btf_key_type_id = map->btf_key_type_id;
5223 		create_attr.btf_value_type_id = map->btf_value_type_id;
5224 	}
5225 
5226 	if (bpf_map_type__is_map_in_map(def->type)) {
5227 		if (map->inner_map) {
5228 			err = bpf_object__create_map(obj, map->inner_map, true);
5229 			if (err) {
5230 				pr_warn("map '%s': failed to create inner map: %d\n",
5231 					map->name, err);
5232 				return err;
5233 			}
5234 			map->inner_map_fd = bpf_map__fd(map->inner_map);
5235 		}
5236 		if (map->inner_map_fd >= 0)
5237 			create_attr.inner_map_fd = map->inner_map_fd;
5238 	}
5239 
5240 	switch (def->type) {
5241 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5242 	case BPF_MAP_TYPE_CGROUP_ARRAY:
5243 	case BPF_MAP_TYPE_STACK_TRACE:
5244 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5245 	case BPF_MAP_TYPE_HASH_OF_MAPS:
5246 	case BPF_MAP_TYPE_DEVMAP:
5247 	case BPF_MAP_TYPE_DEVMAP_HASH:
5248 	case BPF_MAP_TYPE_CPUMAP:
5249 	case BPF_MAP_TYPE_XSKMAP:
5250 	case BPF_MAP_TYPE_SOCKMAP:
5251 	case BPF_MAP_TYPE_SOCKHASH:
5252 	case BPF_MAP_TYPE_QUEUE:
5253 	case BPF_MAP_TYPE_STACK:
5254 		create_attr.btf_fd = 0;
5255 		create_attr.btf_key_type_id = 0;
5256 		create_attr.btf_value_type_id = 0;
5257 		map->btf_key_type_id = 0;
5258 		map->btf_value_type_id = 0;
5259 	default:
5260 		break;
5261 	}
5262 
5263 	if (obj->gen_loader) {
5264 		bpf_gen__map_create(obj->gen_loader, def->type, map_name,
5265 				    def->key_size, def->value_size, def->max_entries,
5266 				    &create_attr, is_inner ? -1 : map - obj->maps);
5267 		/* Pretend to have valid FD to pass various fd >= 0 checks.
5268 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
5269 		 */
5270 		map->fd = 0;
5271 	} else {
5272 		map->fd = bpf_map_create(def->type, map_name,
5273 					 def->key_size, def->value_size,
5274 					 def->max_entries, &create_attr);
5275 	}
5276 	if (map->fd < 0 && (create_attr.btf_key_type_id ||
5277 			    create_attr.btf_value_type_id)) {
5278 		char *cp, errmsg[STRERR_BUFSIZE];
5279 
5280 		err = -errno;
5281 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5282 		pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
5283 			map->name, cp, err);
5284 		create_attr.btf_fd = 0;
5285 		create_attr.btf_key_type_id = 0;
5286 		create_attr.btf_value_type_id = 0;
5287 		map->btf_key_type_id = 0;
5288 		map->btf_value_type_id = 0;
5289 		map->fd = bpf_map_create(def->type, map_name,
5290 					 def->key_size, def->value_size,
5291 					 def->max_entries, &create_attr);
5292 	}
5293 
5294 	err = map->fd < 0 ? -errno : 0;
5295 
5296 	if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
5297 		if (obj->gen_loader)
5298 			map->inner_map->fd = -1;
5299 		bpf_map__destroy(map->inner_map);
5300 		zfree(&map->inner_map);
5301 	}
5302 
5303 	return err;
5304 }
5305 
5306 static int init_map_in_map_slots(struct bpf_object *obj, struct bpf_map *map)
5307 {
5308 	const struct bpf_map *targ_map;
5309 	unsigned int i;
5310 	int fd, err = 0;
5311 
5312 	for (i = 0; i < map->init_slots_sz; i++) {
5313 		if (!map->init_slots[i])
5314 			continue;
5315 
5316 		targ_map = map->init_slots[i];
5317 		fd = bpf_map__fd(targ_map);
5318 
5319 		if (obj->gen_loader) {
5320 			bpf_gen__populate_outer_map(obj->gen_loader,
5321 						    map - obj->maps, i,
5322 						    targ_map - obj->maps);
5323 		} else {
5324 			err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5325 		}
5326 		if (err) {
5327 			err = -errno;
5328 			pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %d\n",
5329 				map->name, i, targ_map->name, fd, err);
5330 			return err;
5331 		}
5332 		pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
5333 			 map->name, i, targ_map->name, fd);
5334 	}
5335 
5336 	zfree(&map->init_slots);
5337 	map->init_slots_sz = 0;
5338 
5339 	return 0;
5340 }
5341 
5342 static int init_prog_array_slots(struct bpf_object *obj, struct bpf_map *map)
5343 {
5344 	const struct bpf_program *targ_prog;
5345 	unsigned int i;
5346 	int fd, err;
5347 
5348 	if (obj->gen_loader)
5349 		return -ENOTSUP;
5350 
5351 	for (i = 0; i < map->init_slots_sz; i++) {
5352 		if (!map->init_slots[i])
5353 			continue;
5354 
5355 		targ_prog = map->init_slots[i];
5356 		fd = bpf_program__fd(targ_prog);
5357 
5358 		err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5359 		if (err) {
5360 			err = -errno;
5361 			pr_warn("map '%s': failed to initialize slot [%d] to prog '%s' fd=%d: %d\n",
5362 				map->name, i, targ_prog->name, fd, err);
5363 			return err;
5364 		}
5365 		pr_debug("map '%s': slot [%d] set to prog '%s' fd=%d\n",
5366 			 map->name, i, targ_prog->name, fd);
5367 	}
5368 
5369 	zfree(&map->init_slots);
5370 	map->init_slots_sz = 0;
5371 
5372 	return 0;
5373 }
5374 
5375 static int bpf_object_init_prog_arrays(struct bpf_object *obj)
5376 {
5377 	struct bpf_map *map;
5378 	int i, err;
5379 
5380 	for (i = 0; i < obj->nr_maps; i++) {
5381 		map = &obj->maps[i];
5382 
5383 		if (!map->init_slots_sz || map->def.type != BPF_MAP_TYPE_PROG_ARRAY)
5384 			continue;
5385 
5386 		err = init_prog_array_slots(obj, map);
5387 		if (err < 0) {
5388 			zclose(map->fd);
5389 			return err;
5390 		}
5391 	}
5392 	return 0;
5393 }
5394 
5395 static int map_set_def_max_entries(struct bpf_map *map)
5396 {
5397 	if (map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !map->def.max_entries) {
5398 		int nr_cpus;
5399 
5400 		nr_cpus = libbpf_num_possible_cpus();
5401 		if (nr_cpus < 0) {
5402 			pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
5403 				map->name, nr_cpus);
5404 			return nr_cpus;
5405 		}
5406 		pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
5407 		map->def.max_entries = nr_cpus;
5408 	}
5409 
5410 	return 0;
5411 }
5412 
5413 static int
5414 bpf_object__create_maps(struct bpf_object *obj)
5415 {
5416 	struct bpf_map *map;
5417 	char *cp, errmsg[STRERR_BUFSIZE];
5418 	unsigned int i, j;
5419 	int err;
5420 	bool retried;
5421 
5422 	for (i = 0; i < obj->nr_maps; i++) {
5423 		map = &obj->maps[i];
5424 
5425 		/* To support old kernels, we skip creating global data maps
5426 		 * (.rodata, .data, .kconfig, etc); later on, during program
5427 		 * loading, if we detect that at least one of the to-be-loaded
5428 		 * programs is referencing any global data map, we'll error
5429 		 * out with program name and relocation index logged.
5430 		 * This approach allows to accommodate Clang emitting
5431 		 * unnecessary .rodata.str1.1 sections for string literals,
5432 		 * but also it allows to have CO-RE applications that use
5433 		 * global variables in some of BPF programs, but not others.
5434 		 * If those global variable-using programs are not loaded at
5435 		 * runtime due to bpf_program__set_autoload(prog, false),
5436 		 * bpf_object loading will succeed just fine even on old
5437 		 * kernels.
5438 		 */
5439 		if (bpf_map__is_internal(map) && !kernel_supports(obj, FEAT_GLOBAL_DATA))
5440 			map->autocreate = false;
5441 
5442 		if (!map->autocreate) {
5443 			pr_debug("map '%s': skipped auto-creating...\n", map->name);
5444 			continue;
5445 		}
5446 
5447 		err = map_set_def_max_entries(map);
5448 		if (err)
5449 			goto err_out;
5450 
5451 		retried = false;
5452 retry:
5453 		if (map->pin_path) {
5454 			err = bpf_object__reuse_map(map);
5455 			if (err) {
5456 				pr_warn("map '%s': error reusing pinned map\n",
5457 					map->name);
5458 				goto err_out;
5459 			}
5460 			if (retried && map->fd < 0) {
5461 				pr_warn("map '%s': cannot find pinned map\n",
5462 					map->name);
5463 				err = -ENOENT;
5464 				goto err_out;
5465 			}
5466 		}
5467 
5468 		if (map->fd >= 0) {
5469 			pr_debug("map '%s': skipping creation (preset fd=%d)\n",
5470 				 map->name, map->fd);
5471 		} else {
5472 			err = bpf_object__create_map(obj, map, false);
5473 			if (err)
5474 				goto err_out;
5475 
5476 			pr_debug("map '%s': created successfully, fd=%d\n",
5477 				 map->name, map->fd);
5478 
5479 			if (bpf_map__is_internal(map)) {
5480 				err = bpf_object__populate_internal_map(obj, map);
5481 				if (err < 0) {
5482 					zclose(map->fd);
5483 					goto err_out;
5484 				}
5485 			}
5486 
5487 			if (map->init_slots_sz && map->def.type != BPF_MAP_TYPE_PROG_ARRAY) {
5488 				err = init_map_in_map_slots(obj, map);
5489 				if (err < 0) {
5490 					zclose(map->fd);
5491 					goto err_out;
5492 				}
5493 			}
5494 		}
5495 
5496 		if (map->pin_path && !map->pinned) {
5497 			err = bpf_map__pin(map, NULL);
5498 			if (err) {
5499 				zclose(map->fd);
5500 				if (!retried && err == -EEXIST) {
5501 					retried = true;
5502 					goto retry;
5503 				}
5504 				pr_warn("map '%s': failed to auto-pin at '%s': %d\n",
5505 					map->name, map->pin_path, err);
5506 				goto err_out;
5507 			}
5508 		}
5509 	}
5510 
5511 	return 0;
5512 
5513 err_out:
5514 	cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5515 	pr_warn("map '%s': failed to create: %s(%d)\n", map->name, cp, err);
5516 	pr_perm_msg(err);
5517 	for (j = 0; j < i; j++)
5518 		zclose(obj->maps[j].fd);
5519 	return err;
5520 }
5521 
5522 static bool bpf_core_is_flavor_sep(const char *s)
5523 {
5524 	/* check X___Y name pattern, where X and Y are not underscores */
5525 	return s[0] != '_' &&				      /* X */
5526 	       s[1] == '_' && s[2] == '_' && s[3] == '_' &&   /* ___ */
5527 	       s[4] != '_';				      /* Y */
5528 }
5529 
5530 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
5531  * before last triple underscore. Struct name part after last triple
5532  * underscore is ignored by BPF CO-RE relocation during relocation matching.
5533  */
5534 size_t bpf_core_essential_name_len(const char *name)
5535 {
5536 	size_t n = strlen(name);
5537 	int i;
5538 
5539 	for (i = n - 5; i >= 0; i--) {
5540 		if (bpf_core_is_flavor_sep(name + i))
5541 			return i + 1;
5542 	}
5543 	return n;
5544 }
5545 
5546 void bpf_core_free_cands(struct bpf_core_cand_list *cands)
5547 {
5548 	if (!cands)
5549 		return;
5550 
5551 	free(cands->cands);
5552 	free(cands);
5553 }
5554 
5555 int bpf_core_add_cands(struct bpf_core_cand *local_cand,
5556 		       size_t local_essent_len,
5557 		       const struct btf *targ_btf,
5558 		       const char *targ_btf_name,
5559 		       int targ_start_id,
5560 		       struct bpf_core_cand_list *cands)
5561 {
5562 	struct bpf_core_cand *new_cands, *cand;
5563 	const struct btf_type *t, *local_t;
5564 	const char *targ_name, *local_name;
5565 	size_t targ_essent_len;
5566 	int n, i;
5567 
5568 	local_t = btf__type_by_id(local_cand->btf, local_cand->id);
5569 	local_name = btf__str_by_offset(local_cand->btf, local_t->name_off);
5570 
5571 	n = btf__type_cnt(targ_btf);
5572 	for (i = targ_start_id; i < n; i++) {
5573 		t = btf__type_by_id(targ_btf, i);
5574 		if (!btf_kind_core_compat(t, local_t))
5575 			continue;
5576 
5577 		targ_name = btf__name_by_offset(targ_btf, t->name_off);
5578 		if (str_is_empty(targ_name))
5579 			continue;
5580 
5581 		targ_essent_len = bpf_core_essential_name_len(targ_name);
5582 		if (targ_essent_len != local_essent_len)
5583 			continue;
5584 
5585 		if (strncmp(local_name, targ_name, local_essent_len) != 0)
5586 			continue;
5587 
5588 		pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s in [%s]\n",
5589 			 local_cand->id, btf_kind_str(local_t),
5590 			 local_name, i, btf_kind_str(t), targ_name,
5591 			 targ_btf_name);
5592 		new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
5593 					      sizeof(*cands->cands));
5594 		if (!new_cands)
5595 			return -ENOMEM;
5596 
5597 		cand = &new_cands[cands->len];
5598 		cand->btf = targ_btf;
5599 		cand->id = i;
5600 
5601 		cands->cands = new_cands;
5602 		cands->len++;
5603 	}
5604 	return 0;
5605 }
5606 
5607 static int load_module_btfs(struct bpf_object *obj)
5608 {
5609 	struct bpf_btf_info info;
5610 	struct module_btf *mod_btf;
5611 	struct btf *btf;
5612 	char name[64];
5613 	__u32 id = 0, len;
5614 	int err, fd;
5615 
5616 	if (obj->btf_modules_loaded)
5617 		return 0;
5618 
5619 	if (obj->gen_loader)
5620 		return 0;
5621 
5622 	/* don't do this again, even if we find no module BTFs */
5623 	obj->btf_modules_loaded = true;
5624 
5625 	/* kernel too old to support module BTFs */
5626 	if (!kernel_supports(obj, FEAT_MODULE_BTF))
5627 		return 0;
5628 
5629 	while (true) {
5630 		err = bpf_btf_get_next_id(id, &id);
5631 		if (err && errno == ENOENT)
5632 			return 0;
5633 		if (err && errno == EPERM) {
5634 			pr_debug("skipping module BTFs loading, missing privileges\n");
5635 			return 0;
5636 		}
5637 		if (err) {
5638 			err = -errno;
5639 			pr_warn("failed to iterate BTF objects: %d\n", err);
5640 			return err;
5641 		}
5642 
5643 		fd = bpf_btf_get_fd_by_id(id);
5644 		if (fd < 0) {
5645 			if (errno == ENOENT)
5646 				continue; /* expected race: BTF was unloaded */
5647 			err = -errno;
5648 			pr_warn("failed to get BTF object #%d FD: %d\n", id, err);
5649 			return err;
5650 		}
5651 
5652 		len = sizeof(info);
5653 		memset(&info, 0, sizeof(info));
5654 		info.name = ptr_to_u64(name);
5655 		info.name_len = sizeof(name);
5656 
5657 		err = bpf_btf_get_info_by_fd(fd, &info, &len);
5658 		if (err) {
5659 			err = -errno;
5660 			pr_warn("failed to get BTF object #%d info: %d\n", id, err);
5661 			goto err_out;
5662 		}
5663 
5664 		/* ignore non-module BTFs */
5665 		if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
5666 			close(fd);
5667 			continue;
5668 		}
5669 
5670 		btf = btf_get_from_fd(fd, obj->btf_vmlinux);
5671 		err = libbpf_get_error(btf);
5672 		if (err) {
5673 			pr_warn("failed to load module [%s]'s BTF object #%d: %d\n",
5674 				name, id, err);
5675 			goto err_out;
5676 		}
5677 
5678 		err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
5679 					sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
5680 		if (err)
5681 			goto err_out;
5682 
5683 		mod_btf = &obj->btf_modules[obj->btf_module_cnt++];
5684 
5685 		mod_btf->btf = btf;
5686 		mod_btf->id = id;
5687 		mod_btf->fd = fd;
5688 		mod_btf->name = strdup(name);
5689 		if (!mod_btf->name) {
5690 			err = -ENOMEM;
5691 			goto err_out;
5692 		}
5693 		continue;
5694 
5695 err_out:
5696 		close(fd);
5697 		return err;
5698 	}
5699 
5700 	return 0;
5701 }
5702 
5703 static struct bpf_core_cand_list *
5704 bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
5705 {
5706 	struct bpf_core_cand local_cand = {};
5707 	struct bpf_core_cand_list *cands;
5708 	const struct btf *main_btf;
5709 	const struct btf_type *local_t;
5710 	const char *local_name;
5711 	size_t local_essent_len;
5712 	int err, i;
5713 
5714 	local_cand.btf = local_btf;
5715 	local_cand.id = local_type_id;
5716 	local_t = btf__type_by_id(local_btf, local_type_id);
5717 	if (!local_t)
5718 		return ERR_PTR(-EINVAL);
5719 
5720 	local_name = btf__name_by_offset(local_btf, local_t->name_off);
5721 	if (str_is_empty(local_name))
5722 		return ERR_PTR(-EINVAL);
5723 	local_essent_len = bpf_core_essential_name_len(local_name);
5724 
5725 	cands = calloc(1, sizeof(*cands));
5726 	if (!cands)
5727 		return ERR_PTR(-ENOMEM);
5728 
5729 	/* Attempt to find target candidates in vmlinux BTF first */
5730 	main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
5731 	err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
5732 	if (err)
5733 		goto err_out;
5734 
5735 	/* if vmlinux BTF has any candidate, don't got for module BTFs */
5736 	if (cands->len)
5737 		return cands;
5738 
5739 	/* if vmlinux BTF was overridden, don't attempt to load module BTFs */
5740 	if (obj->btf_vmlinux_override)
5741 		return cands;
5742 
5743 	/* now look through module BTFs, trying to still find candidates */
5744 	err = load_module_btfs(obj);
5745 	if (err)
5746 		goto err_out;
5747 
5748 	for (i = 0; i < obj->btf_module_cnt; i++) {
5749 		err = bpf_core_add_cands(&local_cand, local_essent_len,
5750 					 obj->btf_modules[i].btf,
5751 					 obj->btf_modules[i].name,
5752 					 btf__type_cnt(obj->btf_vmlinux),
5753 					 cands);
5754 		if (err)
5755 			goto err_out;
5756 	}
5757 
5758 	return cands;
5759 err_out:
5760 	bpf_core_free_cands(cands);
5761 	return ERR_PTR(err);
5762 }
5763 
5764 /* Check local and target types for compatibility. This check is used for
5765  * type-based CO-RE relocations and follow slightly different rules than
5766  * field-based relocations. This function assumes that root types were already
5767  * checked for name match. Beyond that initial root-level name check, names
5768  * are completely ignored. Compatibility rules are as follows:
5769  *   - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
5770  *     kind should match for local and target types (i.e., STRUCT is not
5771  *     compatible with UNION);
5772  *   - for ENUMs, the size is ignored;
5773  *   - for INT, size and signedness are ignored;
5774  *   - for ARRAY, dimensionality is ignored, element types are checked for
5775  *     compatibility recursively;
5776  *   - CONST/VOLATILE/RESTRICT modifiers are ignored;
5777  *   - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
5778  *   - FUNC_PROTOs are compatible if they have compatible signature: same
5779  *     number of input args and compatible return and argument types.
5780  * These rules are not set in stone and probably will be adjusted as we get
5781  * more experience with using BPF CO-RE relocations.
5782  */
5783 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
5784 			      const struct btf *targ_btf, __u32 targ_id)
5785 {
5786 	return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id, 32);
5787 }
5788 
5789 int bpf_core_types_match(const struct btf *local_btf, __u32 local_id,
5790 			 const struct btf *targ_btf, __u32 targ_id)
5791 {
5792 	return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false, 32);
5793 }
5794 
5795 static size_t bpf_core_hash_fn(const long key, void *ctx)
5796 {
5797 	return key;
5798 }
5799 
5800 static bool bpf_core_equal_fn(const long k1, const long k2, void *ctx)
5801 {
5802 	return k1 == k2;
5803 }
5804 
5805 static int record_relo_core(struct bpf_program *prog,
5806 			    const struct bpf_core_relo *core_relo, int insn_idx)
5807 {
5808 	struct reloc_desc *relos, *relo;
5809 
5810 	relos = libbpf_reallocarray(prog->reloc_desc,
5811 				    prog->nr_reloc + 1, sizeof(*relos));
5812 	if (!relos)
5813 		return -ENOMEM;
5814 	relo = &relos[prog->nr_reloc];
5815 	relo->type = RELO_CORE;
5816 	relo->insn_idx = insn_idx;
5817 	relo->core_relo = core_relo;
5818 	prog->reloc_desc = relos;
5819 	prog->nr_reloc++;
5820 	return 0;
5821 }
5822 
5823 static const struct bpf_core_relo *find_relo_core(struct bpf_program *prog, int insn_idx)
5824 {
5825 	struct reloc_desc *relo;
5826 	int i;
5827 
5828 	for (i = 0; i < prog->nr_reloc; i++) {
5829 		relo = &prog->reloc_desc[i];
5830 		if (relo->type != RELO_CORE || relo->insn_idx != insn_idx)
5831 			continue;
5832 
5833 		return relo->core_relo;
5834 	}
5835 
5836 	return NULL;
5837 }
5838 
5839 static int bpf_core_resolve_relo(struct bpf_program *prog,
5840 				 const struct bpf_core_relo *relo,
5841 				 int relo_idx,
5842 				 const struct btf *local_btf,
5843 				 struct hashmap *cand_cache,
5844 				 struct bpf_core_relo_res *targ_res)
5845 {
5846 	struct bpf_core_spec specs_scratch[3] = {};
5847 	struct bpf_core_cand_list *cands = NULL;
5848 	const char *prog_name = prog->name;
5849 	const struct btf_type *local_type;
5850 	const char *local_name;
5851 	__u32 local_id = relo->type_id;
5852 	int err;
5853 
5854 	local_type = btf__type_by_id(local_btf, local_id);
5855 	if (!local_type)
5856 		return -EINVAL;
5857 
5858 	local_name = btf__name_by_offset(local_btf, local_type->name_off);
5859 	if (!local_name)
5860 		return -EINVAL;
5861 
5862 	if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
5863 	    !hashmap__find(cand_cache, local_id, &cands)) {
5864 		cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
5865 		if (IS_ERR(cands)) {
5866 			pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n",
5867 				prog_name, relo_idx, local_id, btf_kind_str(local_type),
5868 				local_name, PTR_ERR(cands));
5869 			return PTR_ERR(cands);
5870 		}
5871 		err = hashmap__set(cand_cache, local_id, cands, NULL, NULL);
5872 		if (err) {
5873 			bpf_core_free_cands(cands);
5874 			return err;
5875 		}
5876 	}
5877 
5878 	return bpf_core_calc_relo_insn(prog_name, relo, relo_idx, local_btf, cands, specs_scratch,
5879 				       targ_res);
5880 }
5881 
5882 static int
5883 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
5884 {
5885 	const struct btf_ext_info_sec *sec;
5886 	struct bpf_core_relo_res targ_res;
5887 	const struct bpf_core_relo *rec;
5888 	const struct btf_ext_info *seg;
5889 	struct hashmap_entry *entry;
5890 	struct hashmap *cand_cache = NULL;
5891 	struct bpf_program *prog;
5892 	struct bpf_insn *insn;
5893 	const char *sec_name;
5894 	int i, err = 0, insn_idx, sec_idx, sec_num;
5895 
5896 	if (obj->btf_ext->core_relo_info.len == 0)
5897 		return 0;
5898 
5899 	if (targ_btf_path) {
5900 		obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
5901 		err = libbpf_get_error(obj->btf_vmlinux_override);
5902 		if (err) {
5903 			pr_warn("failed to parse target BTF: %d\n", err);
5904 			return err;
5905 		}
5906 	}
5907 
5908 	cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
5909 	if (IS_ERR(cand_cache)) {
5910 		err = PTR_ERR(cand_cache);
5911 		goto out;
5912 	}
5913 
5914 	seg = &obj->btf_ext->core_relo_info;
5915 	sec_num = 0;
5916 	for_each_btf_ext_sec(seg, sec) {
5917 		sec_idx = seg->sec_idxs[sec_num];
5918 		sec_num++;
5919 
5920 		sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
5921 		if (str_is_empty(sec_name)) {
5922 			err = -EINVAL;
5923 			goto out;
5924 		}
5925 
5926 		pr_debug("sec '%s': found %d CO-RE relocations\n", sec_name, sec->num_info);
5927 
5928 		for_each_btf_ext_rec(seg, sec, i, rec) {
5929 			if (rec->insn_off % BPF_INSN_SZ)
5930 				return -EINVAL;
5931 			insn_idx = rec->insn_off / BPF_INSN_SZ;
5932 			prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
5933 			if (!prog) {
5934 				/* When __weak subprog is "overridden" by another instance
5935 				 * of the subprog from a different object file, linker still
5936 				 * appends all the .BTF.ext info that used to belong to that
5937 				 * eliminated subprogram.
5938 				 * This is similar to what x86-64 linker does for relocations.
5939 				 * So just ignore such relocations just like we ignore
5940 				 * subprog instructions when discovering subprograms.
5941 				 */
5942 				pr_debug("sec '%s': skipping CO-RE relocation #%d for insn #%d belonging to eliminated weak subprogram\n",
5943 					 sec_name, i, insn_idx);
5944 				continue;
5945 			}
5946 			/* no need to apply CO-RE relocation if the program is
5947 			 * not going to be loaded
5948 			 */
5949 			if (!prog->autoload)
5950 				continue;
5951 
5952 			/* adjust insn_idx from section frame of reference to the local
5953 			 * program's frame of reference; (sub-)program code is not yet
5954 			 * relocated, so it's enough to just subtract in-section offset
5955 			 */
5956 			insn_idx = insn_idx - prog->sec_insn_off;
5957 			if (insn_idx >= prog->insns_cnt)
5958 				return -EINVAL;
5959 			insn = &prog->insns[insn_idx];
5960 
5961 			err = record_relo_core(prog, rec, insn_idx);
5962 			if (err) {
5963 				pr_warn("prog '%s': relo #%d: failed to record relocation: %d\n",
5964 					prog->name, i, err);
5965 				goto out;
5966 			}
5967 
5968 			if (prog->obj->gen_loader)
5969 				continue;
5970 
5971 			err = bpf_core_resolve_relo(prog, rec, i, obj->btf, cand_cache, &targ_res);
5972 			if (err) {
5973 				pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
5974 					prog->name, i, err);
5975 				goto out;
5976 			}
5977 
5978 			err = bpf_core_patch_insn(prog->name, insn, insn_idx, rec, i, &targ_res);
5979 			if (err) {
5980 				pr_warn("prog '%s': relo #%d: failed to patch insn #%u: %d\n",
5981 					prog->name, i, insn_idx, err);
5982 				goto out;
5983 			}
5984 		}
5985 	}
5986 
5987 out:
5988 	/* obj->btf_vmlinux and module BTFs are freed after object load */
5989 	btf__free(obj->btf_vmlinux_override);
5990 	obj->btf_vmlinux_override = NULL;
5991 
5992 	if (!IS_ERR_OR_NULL(cand_cache)) {
5993 		hashmap__for_each_entry(cand_cache, entry, i) {
5994 			bpf_core_free_cands(entry->pvalue);
5995 		}
5996 		hashmap__free(cand_cache);
5997 	}
5998 	return err;
5999 }
6000 
6001 /* base map load ldimm64 special constant, used also for log fixup logic */
6002 #define POISON_LDIMM64_MAP_BASE 2001000000
6003 #define POISON_LDIMM64_MAP_PFX "200100"
6004 
6005 static void poison_map_ldimm64(struct bpf_program *prog, int relo_idx,
6006 			       int insn_idx, struct bpf_insn *insn,
6007 			       int map_idx, const struct bpf_map *map)
6008 {
6009 	int i;
6010 
6011 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that loads map #%d '%s'\n",
6012 		 prog->name, relo_idx, insn_idx, map_idx, map->name);
6013 
6014 	/* we turn single ldimm64 into two identical invalid calls */
6015 	for (i = 0; i < 2; i++) {
6016 		insn->code = BPF_JMP | BPF_CALL;
6017 		insn->dst_reg = 0;
6018 		insn->src_reg = 0;
6019 		insn->off = 0;
6020 		/* if this instruction is reachable (not a dead code),
6021 		 * verifier will complain with something like:
6022 		 * invalid func unknown#2001000123
6023 		 * where lower 123 is map index into obj->maps[] array
6024 		 */
6025 		insn->imm = POISON_LDIMM64_MAP_BASE + map_idx;
6026 
6027 		insn++;
6028 	}
6029 }
6030 
6031 /* unresolved kfunc call special constant, used also for log fixup logic */
6032 #define POISON_CALL_KFUNC_BASE 2002000000
6033 #define POISON_CALL_KFUNC_PFX "2002"
6034 
6035 static void poison_kfunc_call(struct bpf_program *prog, int relo_idx,
6036 			      int insn_idx, struct bpf_insn *insn,
6037 			      int ext_idx, const struct extern_desc *ext)
6038 {
6039 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that calls kfunc '%s'\n",
6040 		 prog->name, relo_idx, insn_idx, ext->name);
6041 
6042 	/* we turn kfunc call into invalid helper call with identifiable constant */
6043 	insn->code = BPF_JMP | BPF_CALL;
6044 	insn->dst_reg = 0;
6045 	insn->src_reg = 0;
6046 	insn->off = 0;
6047 	/* if this instruction is reachable (not a dead code),
6048 	 * verifier will complain with something like:
6049 	 * invalid func unknown#2001000123
6050 	 * where lower 123 is extern index into obj->externs[] array
6051 	 */
6052 	insn->imm = POISON_CALL_KFUNC_BASE + ext_idx;
6053 }
6054 
6055 /* Relocate data references within program code:
6056  *  - map references;
6057  *  - global variable references;
6058  *  - extern references.
6059  */
6060 static int
6061 bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
6062 {
6063 	int i;
6064 
6065 	for (i = 0; i < prog->nr_reloc; i++) {
6066 		struct reloc_desc *relo = &prog->reloc_desc[i];
6067 		struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6068 		const struct bpf_map *map;
6069 		struct extern_desc *ext;
6070 
6071 		switch (relo->type) {
6072 		case RELO_LD64:
6073 			map = &obj->maps[relo->map_idx];
6074 			if (obj->gen_loader) {
6075 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
6076 				insn[0].imm = relo->map_idx;
6077 			} else if (map->autocreate) {
6078 				insn[0].src_reg = BPF_PSEUDO_MAP_FD;
6079 				insn[0].imm = map->fd;
6080 			} else {
6081 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6082 						   relo->map_idx, map);
6083 			}
6084 			break;
6085 		case RELO_DATA:
6086 			map = &obj->maps[relo->map_idx];
6087 			insn[1].imm = insn[0].imm + relo->sym_off;
6088 			if (obj->gen_loader) {
6089 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6090 				insn[0].imm = relo->map_idx;
6091 			} else if (map->autocreate) {
6092 				insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6093 				insn[0].imm = map->fd;
6094 			} else {
6095 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6096 						   relo->map_idx, map);
6097 			}
6098 			break;
6099 		case RELO_EXTERN_LD64:
6100 			ext = &obj->externs[relo->ext_idx];
6101 			if (ext->type == EXT_KCFG) {
6102 				if (obj->gen_loader) {
6103 					insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6104 					insn[0].imm = obj->kconfig_map_idx;
6105 				} else {
6106 					insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6107 					insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
6108 				}
6109 				insn[1].imm = ext->kcfg.data_off;
6110 			} else /* EXT_KSYM */ {
6111 				if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
6112 					insn[0].src_reg = BPF_PSEUDO_BTF_ID;
6113 					insn[0].imm = ext->ksym.kernel_btf_id;
6114 					insn[1].imm = ext->ksym.kernel_btf_obj_fd;
6115 				} else { /* typeless ksyms or unresolved typed ksyms */
6116 					insn[0].imm = (__u32)ext->ksym.addr;
6117 					insn[1].imm = ext->ksym.addr >> 32;
6118 				}
6119 			}
6120 			break;
6121 		case RELO_EXTERN_CALL:
6122 			ext = &obj->externs[relo->ext_idx];
6123 			insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
6124 			if (ext->is_set) {
6125 				insn[0].imm = ext->ksym.kernel_btf_id;
6126 				insn[0].off = ext->ksym.btf_fd_idx;
6127 			} else { /* unresolved weak kfunc call */
6128 				poison_kfunc_call(prog, i, relo->insn_idx, insn,
6129 						  relo->ext_idx, ext);
6130 			}
6131 			break;
6132 		case RELO_SUBPROG_ADDR:
6133 			if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
6134 				pr_warn("prog '%s': relo #%d: bad insn\n",
6135 					prog->name, i);
6136 				return -EINVAL;
6137 			}
6138 			/* handled already */
6139 			break;
6140 		case RELO_CALL:
6141 			/* handled already */
6142 			break;
6143 		case RELO_CORE:
6144 			/* will be handled by bpf_program_record_relos() */
6145 			break;
6146 		default:
6147 			pr_warn("prog '%s': relo #%d: bad relo type %d\n",
6148 				prog->name, i, relo->type);
6149 			return -EINVAL;
6150 		}
6151 	}
6152 
6153 	return 0;
6154 }
6155 
6156 static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
6157 				    const struct bpf_program *prog,
6158 				    const struct btf_ext_info *ext_info,
6159 				    void **prog_info, __u32 *prog_rec_cnt,
6160 				    __u32 *prog_rec_sz)
6161 {
6162 	void *copy_start = NULL, *copy_end = NULL;
6163 	void *rec, *rec_end, *new_prog_info;
6164 	const struct btf_ext_info_sec *sec;
6165 	size_t old_sz, new_sz;
6166 	int i, sec_num, sec_idx, off_adj;
6167 
6168 	sec_num = 0;
6169 	for_each_btf_ext_sec(ext_info, sec) {
6170 		sec_idx = ext_info->sec_idxs[sec_num];
6171 		sec_num++;
6172 		if (prog->sec_idx != sec_idx)
6173 			continue;
6174 
6175 		for_each_btf_ext_rec(ext_info, sec, i, rec) {
6176 			__u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
6177 
6178 			if (insn_off < prog->sec_insn_off)
6179 				continue;
6180 			if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
6181 				break;
6182 
6183 			if (!copy_start)
6184 				copy_start = rec;
6185 			copy_end = rec + ext_info->rec_size;
6186 		}
6187 
6188 		if (!copy_start)
6189 			return -ENOENT;
6190 
6191 		/* append func/line info of a given (sub-)program to the main
6192 		 * program func/line info
6193 		 */
6194 		old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
6195 		new_sz = old_sz + (copy_end - copy_start);
6196 		new_prog_info = realloc(*prog_info, new_sz);
6197 		if (!new_prog_info)
6198 			return -ENOMEM;
6199 		*prog_info = new_prog_info;
6200 		*prog_rec_cnt = new_sz / ext_info->rec_size;
6201 		memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
6202 
6203 		/* Kernel instruction offsets are in units of 8-byte
6204 		 * instructions, while .BTF.ext instruction offsets generated
6205 		 * by Clang are in units of bytes. So convert Clang offsets
6206 		 * into kernel offsets and adjust offset according to program
6207 		 * relocated position.
6208 		 */
6209 		off_adj = prog->sub_insn_off - prog->sec_insn_off;
6210 		rec = new_prog_info + old_sz;
6211 		rec_end = new_prog_info + new_sz;
6212 		for (; rec < rec_end; rec += ext_info->rec_size) {
6213 			__u32 *insn_off = rec;
6214 
6215 			*insn_off = *insn_off / BPF_INSN_SZ + off_adj;
6216 		}
6217 		*prog_rec_sz = ext_info->rec_size;
6218 		return 0;
6219 	}
6220 
6221 	return -ENOENT;
6222 }
6223 
6224 static int
6225 reloc_prog_func_and_line_info(const struct bpf_object *obj,
6226 			      struct bpf_program *main_prog,
6227 			      const struct bpf_program *prog)
6228 {
6229 	int err;
6230 
6231 	/* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
6232 	 * supprot func/line info
6233 	 */
6234 	if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
6235 		return 0;
6236 
6237 	/* only attempt func info relocation if main program's func_info
6238 	 * relocation was successful
6239 	 */
6240 	if (main_prog != prog && !main_prog->func_info)
6241 		goto line_info;
6242 
6243 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
6244 				       &main_prog->func_info,
6245 				       &main_prog->func_info_cnt,
6246 				       &main_prog->func_info_rec_size);
6247 	if (err) {
6248 		if (err != -ENOENT) {
6249 			pr_warn("prog '%s': error relocating .BTF.ext function info: %d\n",
6250 				prog->name, err);
6251 			return err;
6252 		}
6253 		if (main_prog->func_info) {
6254 			/*
6255 			 * Some info has already been found but has problem
6256 			 * in the last btf_ext reloc. Must have to error out.
6257 			 */
6258 			pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
6259 			return err;
6260 		}
6261 		/* Have problem loading the very first info. Ignore the rest. */
6262 		pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
6263 			prog->name);
6264 	}
6265 
6266 line_info:
6267 	/* don't relocate line info if main program's relocation failed */
6268 	if (main_prog != prog && !main_prog->line_info)
6269 		return 0;
6270 
6271 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
6272 				       &main_prog->line_info,
6273 				       &main_prog->line_info_cnt,
6274 				       &main_prog->line_info_rec_size);
6275 	if (err) {
6276 		if (err != -ENOENT) {
6277 			pr_warn("prog '%s': error relocating .BTF.ext line info: %d\n",
6278 				prog->name, err);
6279 			return err;
6280 		}
6281 		if (main_prog->line_info) {
6282 			/*
6283 			 * Some info has already been found but has problem
6284 			 * in the last btf_ext reloc. Must have to error out.
6285 			 */
6286 			pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
6287 			return err;
6288 		}
6289 		/* Have problem loading the very first info. Ignore the rest. */
6290 		pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
6291 			prog->name);
6292 	}
6293 	return 0;
6294 }
6295 
6296 static int cmp_relo_by_insn_idx(const void *key, const void *elem)
6297 {
6298 	size_t insn_idx = *(const size_t *)key;
6299 	const struct reloc_desc *relo = elem;
6300 
6301 	if (insn_idx == relo->insn_idx)
6302 		return 0;
6303 	return insn_idx < relo->insn_idx ? -1 : 1;
6304 }
6305 
6306 static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
6307 {
6308 	if (!prog->nr_reloc)
6309 		return NULL;
6310 	return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
6311 		       sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
6312 }
6313 
6314 static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
6315 {
6316 	int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
6317 	struct reloc_desc *relos;
6318 	int i;
6319 
6320 	if (main_prog == subprog)
6321 		return 0;
6322 	relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
6323 	/* if new count is zero, reallocarray can return a valid NULL result;
6324 	 * in this case the previous pointer will be freed, so we *have to*
6325 	 * reassign old pointer to the new value (even if it's NULL)
6326 	 */
6327 	if (!relos && new_cnt)
6328 		return -ENOMEM;
6329 	if (subprog->nr_reloc)
6330 		memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
6331 		       sizeof(*relos) * subprog->nr_reloc);
6332 
6333 	for (i = main_prog->nr_reloc; i < new_cnt; i++)
6334 		relos[i].insn_idx += subprog->sub_insn_off;
6335 	/* After insn_idx adjustment the 'relos' array is still sorted
6336 	 * by insn_idx and doesn't break bsearch.
6337 	 */
6338 	main_prog->reloc_desc = relos;
6339 	main_prog->nr_reloc = new_cnt;
6340 	return 0;
6341 }
6342 
6343 static int
6344 bpf_object__append_subprog_code(struct bpf_object *obj, struct bpf_program *main_prog,
6345 				struct bpf_program *subprog)
6346 {
6347        struct bpf_insn *insns;
6348        size_t new_cnt;
6349        int err;
6350 
6351        subprog->sub_insn_off = main_prog->insns_cnt;
6352 
6353        new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
6354        insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
6355        if (!insns) {
6356                pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
6357                return -ENOMEM;
6358        }
6359        main_prog->insns = insns;
6360        main_prog->insns_cnt = new_cnt;
6361 
6362        memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
6363               subprog->insns_cnt * sizeof(*insns));
6364 
6365        pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
6366                 main_prog->name, subprog->insns_cnt, subprog->name);
6367 
6368        /* The subprog insns are now appended. Append its relos too. */
6369        err = append_subprog_relos(main_prog, subprog);
6370        if (err)
6371                return err;
6372        return 0;
6373 }
6374 
6375 static int
6376 bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
6377 		       struct bpf_program *prog)
6378 {
6379 	size_t sub_insn_idx, insn_idx;
6380 	struct bpf_program *subprog;
6381 	struct reloc_desc *relo;
6382 	struct bpf_insn *insn;
6383 	int err;
6384 
6385 	err = reloc_prog_func_and_line_info(obj, main_prog, prog);
6386 	if (err)
6387 		return err;
6388 
6389 	for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
6390 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6391 		if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
6392 			continue;
6393 
6394 		relo = find_prog_insn_relo(prog, insn_idx);
6395 		if (relo && relo->type == RELO_EXTERN_CALL)
6396 			/* kfunc relocations will be handled later
6397 			 * in bpf_object__relocate_data()
6398 			 */
6399 			continue;
6400 		if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
6401 			pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
6402 				prog->name, insn_idx, relo->type);
6403 			return -LIBBPF_ERRNO__RELOC;
6404 		}
6405 		if (relo) {
6406 			/* sub-program instruction index is a combination of
6407 			 * an offset of a symbol pointed to by relocation and
6408 			 * call instruction's imm field; for global functions,
6409 			 * call always has imm = -1, but for static functions
6410 			 * relocation is against STT_SECTION and insn->imm
6411 			 * points to a start of a static function
6412 			 *
6413 			 * for subprog addr relocation, the relo->sym_off + insn->imm is
6414 			 * the byte offset in the corresponding section.
6415 			 */
6416 			if (relo->type == RELO_CALL)
6417 				sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
6418 			else
6419 				sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
6420 		} else if (insn_is_pseudo_func(insn)) {
6421 			/*
6422 			 * RELO_SUBPROG_ADDR relo is always emitted even if both
6423 			 * functions are in the same section, so it shouldn't reach here.
6424 			 */
6425 			pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
6426 				prog->name, insn_idx);
6427 			return -LIBBPF_ERRNO__RELOC;
6428 		} else {
6429 			/* if subprogram call is to a static function within
6430 			 * the same ELF section, there won't be any relocation
6431 			 * emitted, but it also means there is no additional
6432 			 * offset necessary, insns->imm is relative to
6433 			 * instruction's original position within the section
6434 			 */
6435 			sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
6436 		}
6437 
6438 		/* we enforce that sub-programs should be in .text section */
6439 		subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
6440 		if (!subprog) {
6441 			pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
6442 				prog->name);
6443 			return -LIBBPF_ERRNO__RELOC;
6444 		}
6445 
6446 		/* if it's the first call instruction calling into this
6447 		 * subprogram (meaning this subprog hasn't been processed
6448 		 * yet) within the context of current main program:
6449 		 *   - append it at the end of main program's instructions blog;
6450 		 *   - process is recursively, while current program is put on hold;
6451 		 *   - if that subprogram calls some other not yet processes
6452 		 *   subprogram, same thing will happen recursively until
6453 		 *   there are no more unprocesses subprograms left to append
6454 		 *   and relocate.
6455 		 */
6456 		if (subprog->sub_insn_off == 0) {
6457 			err = bpf_object__append_subprog_code(obj, main_prog, subprog);
6458 			if (err)
6459 				return err;
6460 			err = bpf_object__reloc_code(obj, main_prog, subprog);
6461 			if (err)
6462 				return err;
6463 		}
6464 
6465 		/* main_prog->insns memory could have been re-allocated, so
6466 		 * calculate pointer again
6467 		 */
6468 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6469 		/* calculate correct instruction position within current main
6470 		 * prog; each main prog can have a different set of
6471 		 * subprograms appended (potentially in different order as
6472 		 * well), so position of any subprog can be different for
6473 		 * different main programs
6474 		 */
6475 		insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
6476 
6477 		pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
6478 			 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
6479 	}
6480 
6481 	return 0;
6482 }
6483 
6484 /*
6485  * Relocate sub-program calls.
6486  *
6487  * Algorithm operates as follows. Each entry-point BPF program (referred to as
6488  * main prog) is processed separately. For each subprog (non-entry functions,
6489  * that can be called from either entry progs or other subprogs) gets their
6490  * sub_insn_off reset to zero. This serves as indicator that this subprogram
6491  * hasn't been yet appended and relocated within current main prog. Once its
6492  * relocated, sub_insn_off will point at the position within current main prog
6493  * where given subprog was appended. This will further be used to relocate all
6494  * the call instructions jumping into this subprog.
6495  *
6496  * We start with main program and process all call instructions. If the call
6497  * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
6498  * is zero), subprog instructions are appended at the end of main program's
6499  * instruction array. Then main program is "put on hold" while we recursively
6500  * process newly appended subprogram. If that subprogram calls into another
6501  * subprogram that hasn't been appended, new subprogram is appended again to
6502  * the *main* prog's instructions (subprog's instructions are always left
6503  * untouched, as they need to be in unmodified state for subsequent main progs
6504  * and subprog instructions are always sent only as part of a main prog) and
6505  * the process continues recursively. Once all the subprogs called from a main
6506  * prog or any of its subprogs are appended (and relocated), all their
6507  * positions within finalized instructions array are known, so it's easy to
6508  * rewrite call instructions with correct relative offsets, corresponding to
6509  * desired target subprog.
6510  *
6511  * Its important to realize that some subprogs might not be called from some
6512  * main prog and any of its called/used subprogs. Those will keep their
6513  * subprog->sub_insn_off as zero at all times and won't be appended to current
6514  * main prog and won't be relocated within the context of current main prog.
6515  * They might still be used from other main progs later.
6516  *
6517  * Visually this process can be shown as below. Suppose we have two main
6518  * programs mainA and mainB and BPF object contains three subprogs: subA,
6519  * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
6520  * subC both call subB:
6521  *
6522  *        +--------+ +-------+
6523  *        |        v v       |
6524  *     +--+---+ +--+-+-+ +---+--+
6525  *     | subA | | subB | | subC |
6526  *     +--+---+ +------+ +---+--+
6527  *        ^                  ^
6528  *        |                  |
6529  *    +---+-------+   +------+----+
6530  *    |   mainA   |   |   mainB   |
6531  *    +-----------+   +-----------+
6532  *
6533  * We'll start relocating mainA, will find subA, append it and start
6534  * processing sub A recursively:
6535  *
6536  *    +-----------+------+
6537  *    |   mainA   | subA |
6538  *    +-----------+------+
6539  *
6540  * At this point we notice that subB is used from subA, so we append it and
6541  * relocate (there are no further subcalls from subB):
6542  *
6543  *    +-----------+------+------+
6544  *    |   mainA   | subA | subB |
6545  *    +-----------+------+------+
6546  *
6547  * At this point, we relocate subA calls, then go one level up and finish with
6548  * relocatin mainA calls. mainA is done.
6549  *
6550  * For mainB process is similar but results in different order. We start with
6551  * mainB and skip subA and subB, as mainB never calls them (at least
6552  * directly), but we see subC is needed, so we append and start processing it:
6553  *
6554  *    +-----------+------+
6555  *    |   mainB   | subC |
6556  *    +-----------+------+
6557  * Now we see subC needs subB, so we go back to it, append and relocate it:
6558  *
6559  *    +-----------+------+------+
6560  *    |   mainB   | subC | subB |
6561  *    +-----------+------+------+
6562  *
6563  * At this point we unwind recursion, relocate calls in subC, then in mainB.
6564  */
6565 static int
6566 bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
6567 {
6568 	struct bpf_program *subprog;
6569 	int i, err;
6570 
6571 	/* mark all subprogs as not relocated (yet) within the context of
6572 	 * current main program
6573 	 */
6574 	for (i = 0; i < obj->nr_programs; i++) {
6575 		subprog = &obj->programs[i];
6576 		if (!prog_is_subprog(obj, subprog))
6577 			continue;
6578 
6579 		subprog->sub_insn_off = 0;
6580 	}
6581 
6582 	err = bpf_object__reloc_code(obj, prog, prog);
6583 	if (err)
6584 		return err;
6585 
6586 	return 0;
6587 }
6588 
6589 static void
6590 bpf_object__free_relocs(struct bpf_object *obj)
6591 {
6592 	struct bpf_program *prog;
6593 	int i;
6594 
6595 	/* free up relocation descriptors */
6596 	for (i = 0; i < obj->nr_programs; i++) {
6597 		prog = &obj->programs[i];
6598 		zfree(&prog->reloc_desc);
6599 		prog->nr_reloc = 0;
6600 	}
6601 }
6602 
6603 static int cmp_relocs(const void *_a, const void *_b)
6604 {
6605 	const struct reloc_desc *a = _a;
6606 	const struct reloc_desc *b = _b;
6607 
6608 	if (a->insn_idx != b->insn_idx)
6609 		return a->insn_idx < b->insn_idx ? -1 : 1;
6610 
6611 	/* no two relocations should have the same insn_idx, but ... */
6612 	if (a->type != b->type)
6613 		return a->type < b->type ? -1 : 1;
6614 
6615 	return 0;
6616 }
6617 
6618 static void bpf_object__sort_relos(struct bpf_object *obj)
6619 {
6620 	int i;
6621 
6622 	for (i = 0; i < obj->nr_programs; i++) {
6623 		struct bpf_program *p = &obj->programs[i];
6624 
6625 		if (!p->nr_reloc)
6626 			continue;
6627 
6628 		qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
6629 	}
6630 }
6631 
6632 static int
6633 bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
6634 {
6635 	struct bpf_program *prog;
6636 	size_t i, j;
6637 	int err;
6638 
6639 	if (obj->btf_ext) {
6640 		err = bpf_object__relocate_core(obj, targ_btf_path);
6641 		if (err) {
6642 			pr_warn("failed to perform CO-RE relocations: %d\n",
6643 				err);
6644 			return err;
6645 		}
6646 		bpf_object__sort_relos(obj);
6647 	}
6648 
6649 	/* Before relocating calls pre-process relocations and mark
6650 	 * few ld_imm64 instructions that points to subprogs.
6651 	 * Otherwise bpf_object__reloc_code() later would have to consider
6652 	 * all ld_imm64 insns as relocation candidates. That would
6653 	 * reduce relocation speed, since amount of find_prog_insn_relo()
6654 	 * would increase and most of them will fail to find a relo.
6655 	 */
6656 	for (i = 0; i < obj->nr_programs; i++) {
6657 		prog = &obj->programs[i];
6658 		for (j = 0; j < prog->nr_reloc; j++) {
6659 			struct reloc_desc *relo = &prog->reloc_desc[j];
6660 			struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6661 
6662 			/* mark the insn, so it's recognized by insn_is_pseudo_func() */
6663 			if (relo->type == RELO_SUBPROG_ADDR)
6664 				insn[0].src_reg = BPF_PSEUDO_FUNC;
6665 		}
6666 	}
6667 
6668 	/* relocate subprogram calls and append used subprograms to main
6669 	 * programs; each copy of subprogram code needs to be relocated
6670 	 * differently for each main program, because its code location might
6671 	 * have changed.
6672 	 * Append subprog relos to main programs to allow data relos to be
6673 	 * processed after text is completely relocated.
6674 	 */
6675 	for (i = 0; i < obj->nr_programs; i++) {
6676 		prog = &obj->programs[i];
6677 		/* sub-program's sub-calls are relocated within the context of
6678 		 * its main program only
6679 		 */
6680 		if (prog_is_subprog(obj, prog))
6681 			continue;
6682 		if (!prog->autoload)
6683 			continue;
6684 
6685 		err = bpf_object__relocate_calls(obj, prog);
6686 		if (err) {
6687 			pr_warn("prog '%s': failed to relocate calls: %d\n",
6688 				prog->name, err);
6689 			return err;
6690 		}
6691 
6692 		/* Now, also append exception callback if it has not been done already. */
6693 		if (prog->exception_cb_idx >= 0) {
6694 			struct bpf_program *subprog = &obj->programs[prog->exception_cb_idx];
6695 
6696 			/* Calling exception callback directly is disallowed, which the
6697 			 * verifier will reject later. In case it was processed already,
6698 			 * we can skip this step, otherwise for all other valid cases we
6699 			 * have to append exception callback now.
6700 			 */
6701 			if (subprog->sub_insn_off == 0) {
6702 				err = bpf_object__append_subprog_code(obj, prog, subprog);
6703 				if (err)
6704 					return err;
6705 				err = bpf_object__reloc_code(obj, prog, subprog);
6706 				if (err)
6707 					return err;
6708 			}
6709 		}
6710 	}
6711 	/* Process data relos for main programs */
6712 	for (i = 0; i < obj->nr_programs; i++) {
6713 		prog = &obj->programs[i];
6714 		if (prog_is_subprog(obj, prog))
6715 			continue;
6716 		if (!prog->autoload)
6717 			continue;
6718 		err = bpf_object__relocate_data(obj, prog);
6719 		if (err) {
6720 			pr_warn("prog '%s': failed to relocate data references: %d\n",
6721 				prog->name, err);
6722 			return err;
6723 		}
6724 	}
6725 
6726 	return 0;
6727 }
6728 
6729 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
6730 					    Elf64_Shdr *shdr, Elf_Data *data);
6731 
6732 static int bpf_object__collect_map_relos(struct bpf_object *obj,
6733 					 Elf64_Shdr *shdr, Elf_Data *data)
6734 {
6735 	const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
6736 	int i, j, nrels, new_sz;
6737 	const struct btf_var_secinfo *vi = NULL;
6738 	const struct btf_type *sec, *var, *def;
6739 	struct bpf_map *map = NULL, *targ_map = NULL;
6740 	struct bpf_program *targ_prog = NULL;
6741 	bool is_prog_array, is_map_in_map;
6742 	const struct btf_member *member;
6743 	const char *name, *mname, *type;
6744 	unsigned int moff;
6745 	Elf64_Sym *sym;
6746 	Elf64_Rel *rel;
6747 	void *tmp;
6748 
6749 	if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
6750 		return -EINVAL;
6751 	sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
6752 	if (!sec)
6753 		return -EINVAL;
6754 
6755 	nrels = shdr->sh_size / shdr->sh_entsize;
6756 	for (i = 0; i < nrels; i++) {
6757 		rel = elf_rel_by_idx(data, i);
6758 		if (!rel) {
6759 			pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
6760 			return -LIBBPF_ERRNO__FORMAT;
6761 		}
6762 
6763 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
6764 		if (!sym) {
6765 			pr_warn(".maps relo #%d: symbol %zx not found\n",
6766 				i, (size_t)ELF64_R_SYM(rel->r_info));
6767 			return -LIBBPF_ERRNO__FORMAT;
6768 		}
6769 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
6770 
6771 		pr_debug(".maps relo #%d: for %zd value %zd rel->r_offset %zu name %d ('%s')\n",
6772 			 i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
6773 			 (size_t)rel->r_offset, sym->st_name, name);
6774 
6775 		for (j = 0; j < obj->nr_maps; j++) {
6776 			map = &obj->maps[j];
6777 			if (map->sec_idx != obj->efile.btf_maps_shndx)
6778 				continue;
6779 
6780 			vi = btf_var_secinfos(sec) + map->btf_var_idx;
6781 			if (vi->offset <= rel->r_offset &&
6782 			    rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size)
6783 				break;
6784 		}
6785 		if (j == obj->nr_maps) {
6786 			pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
6787 				i, name, (size_t)rel->r_offset);
6788 			return -EINVAL;
6789 		}
6790 
6791 		is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
6792 		is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
6793 		type = is_map_in_map ? "map" : "prog";
6794 		if (is_map_in_map) {
6795 			if (sym->st_shndx != obj->efile.btf_maps_shndx) {
6796 				pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
6797 					i, name);
6798 				return -LIBBPF_ERRNO__RELOC;
6799 			}
6800 			if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
6801 			    map->def.key_size != sizeof(int)) {
6802 				pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
6803 					i, map->name, sizeof(int));
6804 				return -EINVAL;
6805 			}
6806 			targ_map = bpf_object__find_map_by_name(obj, name);
6807 			if (!targ_map) {
6808 				pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
6809 					i, name);
6810 				return -ESRCH;
6811 			}
6812 		} else if (is_prog_array) {
6813 			targ_prog = bpf_object__find_program_by_name(obj, name);
6814 			if (!targ_prog) {
6815 				pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
6816 					i, name);
6817 				return -ESRCH;
6818 			}
6819 			if (targ_prog->sec_idx != sym->st_shndx ||
6820 			    targ_prog->sec_insn_off * 8 != sym->st_value ||
6821 			    prog_is_subprog(obj, targ_prog)) {
6822 				pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
6823 					i, name);
6824 				return -LIBBPF_ERRNO__RELOC;
6825 			}
6826 		} else {
6827 			return -EINVAL;
6828 		}
6829 
6830 		var = btf__type_by_id(obj->btf, vi->type);
6831 		def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
6832 		if (btf_vlen(def) == 0)
6833 			return -EINVAL;
6834 		member = btf_members(def) + btf_vlen(def) - 1;
6835 		mname = btf__name_by_offset(obj->btf, member->name_off);
6836 		if (strcmp(mname, "values"))
6837 			return -EINVAL;
6838 
6839 		moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
6840 		if (rel->r_offset - vi->offset < moff)
6841 			return -EINVAL;
6842 
6843 		moff = rel->r_offset - vi->offset - moff;
6844 		/* here we use BPF pointer size, which is always 64 bit, as we
6845 		 * are parsing ELF that was built for BPF target
6846 		 */
6847 		if (moff % bpf_ptr_sz)
6848 			return -EINVAL;
6849 		moff /= bpf_ptr_sz;
6850 		if (moff >= map->init_slots_sz) {
6851 			new_sz = moff + 1;
6852 			tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
6853 			if (!tmp)
6854 				return -ENOMEM;
6855 			map->init_slots = tmp;
6856 			memset(map->init_slots + map->init_slots_sz, 0,
6857 			       (new_sz - map->init_slots_sz) * host_ptr_sz);
6858 			map->init_slots_sz = new_sz;
6859 		}
6860 		map->init_slots[moff] = is_map_in_map ? (void *)targ_map : (void *)targ_prog;
6861 
6862 		pr_debug(".maps relo #%d: map '%s' slot [%d] points to %s '%s'\n",
6863 			 i, map->name, moff, type, name);
6864 	}
6865 
6866 	return 0;
6867 }
6868 
6869 static int bpf_object__collect_relos(struct bpf_object *obj)
6870 {
6871 	int i, err;
6872 
6873 	for (i = 0; i < obj->efile.sec_cnt; i++) {
6874 		struct elf_sec_desc *sec_desc = &obj->efile.secs[i];
6875 		Elf64_Shdr *shdr;
6876 		Elf_Data *data;
6877 		int idx;
6878 
6879 		if (sec_desc->sec_type != SEC_RELO)
6880 			continue;
6881 
6882 		shdr = sec_desc->shdr;
6883 		data = sec_desc->data;
6884 		idx = shdr->sh_info;
6885 
6886 		if (shdr->sh_type != SHT_REL) {
6887 			pr_warn("internal error at %d\n", __LINE__);
6888 			return -LIBBPF_ERRNO__INTERNAL;
6889 		}
6890 
6891 		if (idx == obj->efile.st_ops_shndx || idx == obj->efile.st_ops_link_shndx)
6892 			err = bpf_object__collect_st_ops_relos(obj, shdr, data);
6893 		else if (idx == obj->efile.btf_maps_shndx)
6894 			err = bpf_object__collect_map_relos(obj, shdr, data);
6895 		else
6896 			err = bpf_object__collect_prog_relos(obj, shdr, data);
6897 		if (err)
6898 			return err;
6899 	}
6900 
6901 	bpf_object__sort_relos(obj);
6902 	return 0;
6903 }
6904 
6905 static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
6906 {
6907 	if (BPF_CLASS(insn->code) == BPF_JMP &&
6908 	    BPF_OP(insn->code) == BPF_CALL &&
6909 	    BPF_SRC(insn->code) == BPF_K &&
6910 	    insn->src_reg == 0 &&
6911 	    insn->dst_reg == 0) {
6912 		    *func_id = insn->imm;
6913 		    return true;
6914 	}
6915 	return false;
6916 }
6917 
6918 static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
6919 {
6920 	struct bpf_insn *insn = prog->insns;
6921 	enum bpf_func_id func_id;
6922 	int i;
6923 
6924 	if (obj->gen_loader)
6925 		return 0;
6926 
6927 	for (i = 0; i < prog->insns_cnt; i++, insn++) {
6928 		if (!insn_is_helper_call(insn, &func_id))
6929 			continue;
6930 
6931 		/* on kernels that don't yet support
6932 		 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
6933 		 * to bpf_probe_read() which works well for old kernels
6934 		 */
6935 		switch (func_id) {
6936 		case BPF_FUNC_probe_read_kernel:
6937 		case BPF_FUNC_probe_read_user:
6938 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6939 				insn->imm = BPF_FUNC_probe_read;
6940 			break;
6941 		case BPF_FUNC_probe_read_kernel_str:
6942 		case BPF_FUNC_probe_read_user_str:
6943 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6944 				insn->imm = BPF_FUNC_probe_read_str;
6945 			break;
6946 		default:
6947 			break;
6948 		}
6949 	}
6950 	return 0;
6951 }
6952 
6953 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
6954 				     int *btf_obj_fd, int *btf_type_id);
6955 
6956 /* this is called as prog->sec_def->prog_prepare_load_fn for libbpf-supported sec_defs */
6957 static int libbpf_prepare_prog_load(struct bpf_program *prog,
6958 				    struct bpf_prog_load_opts *opts, long cookie)
6959 {
6960 	enum sec_def_flags def = cookie;
6961 
6962 	/* old kernels might not support specifying expected_attach_type */
6963 	if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
6964 		opts->expected_attach_type = 0;
6965 
6966 	if (def & SEC_SLEEPABLE)
6967 		opts->prog_flags |= BPF_F_SLEEPABLE;
6968 
6969 	if (prog->type == BPF_PROG_TYPE_XDP && (def & SEC_XDP_FRAGS))
6970 		opts->prog_flags |= BPF_F_XDP_HAS_FRAGS;
6971 
6972 	/* special check for usdt to use uprobe_multi link */
6973 	if ((def & SEC_USDT) && kernel_supports(prog->obj, FEAT_UPROBE_MULTI_LINK))
6974 		prog->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
6975 
6976 	if ((def & SEC_ATTACH_BTF) && !prog->attach_btf_id) {
6977 		int btf_obj_fd = 0, btf_type_id = 0, err;
6978 		const char *attach_name;
6979 
6980 		attach_name = strchr(prog->sec_name, '/');
6981 		if (!attach_name) {
6982 			/* if BPF program is annotated with just SEC("fentry")
6983 			 * (or similar) without declaratively specifying
6984 			 * target, then it is expected that target will be
6985 			 * specified with bpf_program__set_attach_target() at
6986 			 * runtime before BPF object load step. If not, then
6987 			 * there is nothing to load into the kernel as BPF
6988 			 * verifier won't be able to validate BPF program
6989 			 * correctness anyways.
6990 			 */
6991 			pr_warn("prog '%s': no BTF-based attach target is specified, use bpf_program__set_attach_target()\n",
6992 				prog->name);
6993 			return -EINVAL;
6994 		}
6995 		attach_name++; /* skip over / */
6996 
6997 		err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
6998 		if (err)
6999 			return err;
7000 
7001 		/* cache resolved BTF FD and BTF type ID in the prog */
7002 		prog->attach_btf_obj_fd = btf_obj_fd;
7003 		prog->attach_btf_id = btf_type_id;
7004 
7005 		/* but by now libbpf common logic is not utilizing
7006 		 * prog->atach_btf_obj_fd/prog->attach_btf_id anymore because
7007 		 * this callback is called after opts were populated by
7008 		 * libbpf, so this callback has to update opts explicitly here
7009 		 */
7010 		opts->attach_btf_obj_fd = btf_obj_fd;
7011 		opts->attach_btf_id = btf_type_id;
7012 	}
7013 	return 0;
7014 }
7015 
7016 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz);
7017 
7018 static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
7019 				struct bpf_insn *insns, int insns_cnt,
7020 				const char *license, __u32 kern_version, int *prog_fd)
7021 {
7022 	LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
7023 	const char *prog_name = NULL;
7024 	char *cp, errmsg[STRERR_BUFSIZE];
7025 	size_t log_buf_size = 0;
7026 	char *log_buf = NULL, *tmp;
7027 	int btf_fd, ret, err;
7028 	bool own_log_buf = true;
7029 	__u32 log_level = prog->log_level;
7030 
7031 	if (prog->type == BPF_PROG_TYPE_UNSPEC) {
7032 		/*
7033 		 * The program type must be set.  Most likely we couldn't find a proper
7034 		 * section definition at load time, and thus we didn't infer the type.
7035 		 */
7036 		pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
7037 			prog->name, prog->sec_name);
7038 		return -EINVAL;
7039 	}
7040 
7041 	if (!insns || !insns_cnt)
7042 		return -EINVAL;
7043 
7044 	if (kernel_supports(obj, FEAT_PROG_NAME))
7045 		prog_name = prog->name;
7046 	load_attr.attach_prog_fd = prog->attach_prog_fd;
7047 	load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
7048 	load_attr.attach_btf_id = prog->attach_btf_id;
7049 	load_attr.kern_version = kern_version;
7050 	load_attr.prog_ifindex = prog->prog_ifindex;
7051 
7052 	/* specify func_info/line_info only if kernel supports them */
7053 	btf_fd = bpf_object__btf_fd(obj);
7054 	if (btf_fd >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
7055 		load_attr.prog_btf_fd = btf_fd;
7056 		load_attr.func_info = prog->func_info;
7057 		load_attr.func_info_rec_size = prog->func_info_rec_size;
7058 		load_attr.func_info_cnt = prog->func_info_cnt;
7059 		load_attr.line_info = prog->line_info;
7060 		load_attr.line_info_rec_size = prog->line_info_rec_size;
7061 		load_attr.line_info_cnt = prog->line_info_cnt;
7062 	}
7063 	load_attr.log_level = log_level;
7064 	load_attr.prog_flags = prog->prog_flags;
7065 	load_attr.fd_array = obj->fd_array;
7066 
7067 	/* adjust load_attr if sec_def provides custom preload callback */
7068 	if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
7069 		err = prog->sec_def->prog_prepare_load_fn(prog, &load_attr, prog->sec_def->cookie);
7070 		if (err < 0) {
7071 			pr_warn("prog '%s': failed to prepare load attributes: %d\n",
7072 				prog->name, err);
7073 			return err;
7074 		}
7075 		insns = prog->insns;
7076 		insns_cnt = prog->insns_cnt;
7077 	}
7078 
7079 	/* allow prog_prepare_load_fn to change expected_attach_type */
7080 	load_attr.expected_attach_type = prog->expected_attach_type;
7081 
7082 	if (obj->gen_loader) {
7083 		bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
7084 				   license, insns, insns_cnt, &load_attr,
7085 				   prog - obj->programs);
7086 		*prog_fd = -1;
7087 		return 0;
7088 	}
7089 
7090 retry_load:
7091 	/* if log_level is zero, we don't request logs initially even if
7092 	 * custom log_buf is specified; if the program load fails, then we'll
7093 	 * bump log_level to 1 and use either custom log_buf or we'll allocate
7094 	 * our own and retry the load to get details on what failed
7095 	 */
7096 	if (log_level) {
7097 		if (prog->log_buf) {
7098 			log_buf = prog->log_buf;
7099 			log_buf_size = prog->log_size;
7100 			own_log_buf = false;
7101 		} else if (obj->log_buf) {
7102 			log_buf = obj->log_buf;
7103 			log_buf_size = obj->log_size;
7104 			own_log_buf = false;
7105 		} else {
7106 			log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
7107 			tmp = realloc(log_buf, log_buf_size);
7108 			if (!tmp) {
7109 				ret = -ENOMEM;
7110 				goto out;
7111 			}
7112 			log_buf = tmp;
7113 			log_buf[0] = '\0';
7114 			own_log_buf = true;
7115 		}
7116 	}
7117 
7118 	load_attr.log_buf = log_buf;
7119 	load_attr.log_size = log_buf_size;
7120 	load_attr.log_level = log_level;
7121 
7122 	ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
7123 	if (ret >= 0) {
7124 		if (log_level && own_log_buf) {
7125 			pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
7126 				 prog->name, log_buf);
7127 		}
7128 
7129 		if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
7130 			struct bpf_map *map;
7131 			int i;
7132 
7133 			for (i = 0; i < obj->nr_maps; i++) {
7134 				map = &prog->obj->maps[i];
7135 				if (map->libbpf_type != LIBBPF_MAP_RODATA)
7136 					continue;
7137 
7138 				if (bpf_prog_bind_map(ret, bpf_map__fd(map), NULL)) {
7139 					cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
7140 					pr_warn("prog '%s': failed to bind map '%s': %s\n",
7141 						prog->name, map->real_name, cp);
7142 					/* Don't fail hard if can't bind rodata. */
7143 				}
7144 			}
7145 		}
7146 
7147 		*prog_fd = ret;
7148 		ret = 0;
7149 		goto out;
7150 	}
7151 
7152 	if (log_level == 0) {
7153 		log_level = 1;
7154 		goto retry_load;
7155 	}
7156 	/* On ENOSPC, increase log buffer size and retry, unless custom
7157 	 * log_buf is specified.
7158 	 * Be careful to not overflow u32, though. Kernel's log buf size limit
7159 	 * isn't part of UAPI so it can always be bumped to full 4GB. So don't
7160 	 * multiply by 2 unless we are sure we'll fit within 32 bits.
7161 	 * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
7162 	 */
7163 	if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
7164 		goto retry_load;
7165 
7166 	ret = -errno;
7167 
7168 	/* post-process verifier log to improve error descriptions */
7169 	fixup_verifier_log(prog, log_buf, log_buf_size);
7170 
7171 	cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
7172 	pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, cp);
7173 	pr_perm_msg(ret);
7174 
7175 	if (own_log_buf && log_buf && log_buf[0] != '\0') {
7176 		pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
7177 			prog->name, log_buf);
7178 	}
7179 
7180 out:
7181 	if (own_log_buf)
7182 		free(log_buf);
7183 	return ret;
7184 }
7185 
7186 static char *find_prev_line(char *buf, char *cur)
7187 {
7188 	char *p;
7189 
7190 	if (cur == buf) /* end of a log buf */
7191 		return NULL;
7192 
7193 	p = cur - 1;
7194 	while (p - 1 >= buf && *(p - 1) != '\n')
7195 		p--;
7196 
7197 	return p;
7198 }
7199 
7200 static void patch_log(char *buf, size_t buf_sz, size_t log_sz,
7201 		      char *orig, size_t orig_sz, const char *patch)
7202 {
7203 	/* size of the remaining log content to the right from the to-be-replaced part */
7204 	size_t rem_sz = (buf + log_sz) - (orig + orig_sz);
7205 	size_t patch_sz = strlen(patch);
7206 
7207 	if (patch_sz != orig_sz) {
7208 		/* If patch line(s) are longer than original piece of verifier log,
7209 		 * shift log contents by (patch_sz - orig_sz) bytes to the right
7210 		 * starting from after to-be-replaced part of the log.
7211 		 *
7212 		 * If patch line(s) are shorter than original piece of verifier log,
7213 		 * shift log contents by (orig_sz - patch_sz) bytes to the left
7214 		 * starting from after to-be-replaced part of the log
7215 		 *
7216 		 * We need to be careful about not overflowing available
7217 		 * buf_sz capacity. If that's the case, we'll truncate the end
7218 		 * of the original log, as necessary.
7219 		 */
7220 		if (patch_sz > orig_sz) {
7221 			if (orig + patch_sz >= buf + buf_sz) {
7222 				/* patch is big enough to cover remaining space completely */
7223 				patch_sz -= (orig + patch_sz) - (buf + buf_sz) + 1;
7224 				rem_sz = 0;
7225 			} else if (patch_sz - orig_sz > buf_sz - log_sz) {
7226 				/* patch causes part of remaining log to be truncated */
7227 				rem_sz -= (patch_sz - orig_sz) - (buf_sz - log_sz);
7228 			}
7229 		}
7230 		/* shift remaining log to the right by calculated amount */
7231 		memmove(orig + patch_sz, orig + orig_sz, rem_sz);
7232 	}
7233 
7234 	memcpy(orig, patch, patch_sz);
7235 }
7236 
7237 static void fixup_log_failed_core_relo(struct bpf_program *prog,
7238 				       char *buf, size_t buf_sz, size_t log_sz,
7239 				       char *line1, char *line2, char *line3)
7240 {
7241 	/* Expected log for failed and not properly guarded CO-RE relocation:
7242 	 * line1 -> 123: (85) call unknown#195896080
7243 	 * line2 -> invalid func unknown#195896080
7244 	 * line3 -> <anything else or end of buffer>
7245 	 *
7246 	 * "123" is the index of the instruction that was poisoned. We extract
7247 	 * instruction index to find corresponding CO-RE relocation and
7248 	 * replace this part of the log with more relevant information about
7249 	 * failed CO-RE relocation.
7250 	 */
7251 	const struct bpf_core_relo *relo;
7252 	struct bpf_core_spec spec;
7253 	char patch[512], spec_buf[256];
7254 	int insn_idx, err, spec_len;
7255 
7256 	if (sscanf(line1, "%d: (%*d) call unknown#195896080\n", &insn_idx) != 1)
7257 		return;
7258 
7259 	relo = find_relo_core(prog, insn_idx);
7260 	if (!relo)
7261 		return;
7262 
7263 	err = bpf_core_parse_spec(prog->name, prog->obj->btf, relo, &spec);
7264 	if (err)
7265 		return;
7266 
7267 	spec_len = bpf_core_format_spec(spec_buf, sizeof(spec_buf), &spec);
7268 	snprintf(patch, sizeof(patch),
7269 		 "%d: <invalid CO-RE relocation>\n"
7270 		 "failed to resolve CO-RE relocation %s%s\n",
7271 		 insn_idx, spec_buf, spec_len >= sizeof(spec_buf) ? "..." : "");
7272 
7273 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7274 }
7275 
7276 static void fixup_log_missing_map_load(struct bpf_program *prog,
7277 				       char *buf, size_t buf_sz, size_t log_sz,
7278 				       char *line1, char *line2, char *line3)
7279 {
7280 	/* Expected log for failed and not properly guarded map reference:
7281 	 * line1 -> 123: (85) call unknown#2001000345
7282 	 * line2 -> invalid func unknown#2001000345
7283 	 * line3 -> <anything else or end of buffer>
7284 	 *
7285 	 * "123" is the index of the instruction that was poisoned.
7286 	 * "345" in "2001000345" is a map index in obj->maps to fetch map name.
7287 	 */
7288 	struct bpf_object *obj = prog->obj;
7289 	const struct bpf_map *map;
7290 	int insn_idx, map_idx;
7291 	char patch[128];
7292 
7293 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &map_idx) != 2)
7294 		return;
7295 
7296 	map_idx -= POISON_LDIMM64_MAP_BASE;
7297 	if (map_idx < 0 || map_idx >= obj->nr_maps)
7298 		return;
7299 	map = &obj->maps[map_idx];
7300 
7301 	snprintf(patch, sizeof(patch),
7302 		 "%d: <invalid BPF map reference>\n"
7303 		 "BPF map '%s' is referenced but wasn't created\n",
7304 		 insn_idx, map->name);
7305 
7306 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7307 }
7308 
7309 static void fixup_log_missing_kfunc_call(struct bpf_program *prog,
7310 					 char *buf, size_t buf_sz, size_t log_sz,
7311 					 char *line1, char *line2, char *line3)
7312 {
7313 	/* Expected log for failed and not properly guarded kfunc call:
7314 	 * line1 -> 123: (85) call unknown#2002000345
7315 	 * line2 -> invalid func unknown#2002000345
7316 	 * line3 -> <anything else or end of buffer>
7317 	 *
7318 	 * "123" is the index of the instruction that was poisoned.
7319 	 * "345" in "2002000345" is an extern index in obj->externs to fetch kfunc name.
7320 	 */
7321 	struct bpf_object *obj = prog->obj;
7322 	const struct extern_desc *ext;
7323 	int insn_idx, ext_idx;
7324 	char patch[128];
7325 
7326 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &ext_idx) != 2)
7327 		return;
7328 
7329 	ext_idx -= POISON_CALL_KFUNC_BASE;
7330 	if (ext_idx < 0 || ext_idx >= obj->nr_extern)
7331 		return;
7332 	ext = &obj->externs[ext_idx];
7333 
7334 	snprintf(patch, sizeof(patch),
7335 		 "%d: <invalid kfunc call>\n"
7336 		 "kfunc '%s' is referenced but wasn't resolved\n",
7337 		 insn_idx, ext->name);
7338 
7339 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7340 }
7341 
7342 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz)
7343 {
7344 	/* look for familiar error patterns in last N lines of the log */
7345 	const size_t max_last_line_cnt = 10;
7346 	char *prev_line, *cur_line, *next_line;
7347 	size_t log_sz;
7348 	int i;
7349 
7350 	if (!buf)
7351 		return;
7352 
7353 	log_sz = strlen(buf) + 1;
7354 	next_line = buf + log_sz - 1;
7355 
7356 	for (i = 0; i < max_last_line_cnt; i++, next_line = cur_line) {
7357 		cur_line = find_prev_line(buf, next_line);
7358 		if (!cur_line)
7359 			return;
7360 
7361 		if (str_has_pfx(cur_line, "invalid func unknown#195896080\n")) {
7362 			prev_line = find_prev_line(buf, cur_line);
7363 			if (!prev_line)
7364 				continue;
7365 
7366 			/* failed CO-RE relocation case */
7367 			fixup_log_failed_core_relo(prog, buf, buf_sz, log_sz,
7368 						   prev_line, cur_line, next_line);
7369 			return;
7370 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_LDIMM64_MAP_PFX)) {
7371 			prev_line = find_prev_line(buf, cur_line);
7372 			if (!prev_line)
7373 				continue;
7374 
7375 			/* reference to uncreated BPF map */
7376 			fixup_log_missing_map_load(prog, buf, buf_sz, log_sz,
7377 						   prev_line, cur_line, next_line);
7378 			return;
7379 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_CALL_KFUNC_PFX)) {
7380 			prev_line = find_prev_line(buf, cur_line);
7381 			if (!prev_line)
7382 				continue;
7383 
7384 			/* reference to unresolved kfunc */
7385 			fixup_log_missing_kfunc_call(prog, buf, buf_sz, log_sz,
7386 						     prev_line, cur_line, next_line);
7387 			return;
7388 		}
7389 	}
7390 }
7391 
7392 static int bpf_program_record_relos(struct bpf_program *prog)
7393 {
7394 	struct bpf_object *obj = prog->obj;
7395 	int i;
7396 
7397 	for (i = 0; i < prog->nr_reloc; i++) {
7398 		struct reloc_desc *relo = &prog->reloc_desc[i];
7399 		struct extern_desc *ext = &obj->externs[relo->ext_idx];
7400 		int kind;
7401 
7402 		switch (relo->type) {
7403 		case RELO_EXTERN_LD64:
7404 			if (ext->type != EXT_KSYM)
7405 				continue;
7406 			kind = btf_is_var(btf__type_by_id(obj->btf, ext->btf_id)) ?
7407 				BTF_KIND_VAR : BTF_KIND_FUNC;
7408 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7409 					       ext->is_weak, !ext->ksym.type_id,
7410 					       true, kind, relo->insn_idx);
7411 			break;
7412 		case RELO_EXTERN_CALL:
7413 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7414 					       ext->is_weak, false, false, BTF_KIND_FUNC,
7415 					       relo->insn_idx);
7416 			break;
7417 		case RELO_CORE: {
7418 			struct bpf_core_relo cr = {
7419 				.insn_off = relo->insn_idx * 8,
7420 				.type_id = relo->core_relo->type_id,
7421 				.access_str_off = relo->core_relo->access_str_off,
7422 				.kind = relo->core_relo->kind,
7423 			};
7424 
7425 			bpf_gen__record_relo_core(obj->gen_loader, &cr);
7426 			break;
7427 		}
7428 		default:
7429 			continue;
7430 		}
7431 	}
7432 	return 0;
7433 }
7434 
7435 static int
7436 bpf_object__load_progs(struct bpf_object *obj, int log_level)
7437 {
7438 	struct bpf_program *prog;
7439 	size_t i;
7440 	int err;
7441 
7442 	for (i = 0; i < obj->nr_programs; i++) {
7443 		prog = &obj->programs[i];
7444 		err = bpf_object__sanitize_prog(obj, prog);
7445 		if (err)
7446 			return err;
7447 	}
7448 
7449 	for (i = 0; i < obj->nr_programs; i++) {
7450 		prog = &obj->programs[i];
7451 		if (prog_is_subprog(obj, prog))
7452 			continue;
7453 		if (!prog->autoload) {
7454 			pr_debug("prog '%s': skipped loading\n", prog->name);
7455 			continue;
7456 		}
7457 		prog->log_level |= log_level;
7458 
7459 		if (obj->gen_loader)
7460 			bpf_program_record_relos(prog);
7461 
7462 		err = bpf_object_load_prog(obj, prog, prog->insns, prog->insns_cnt,
7463 					   obj->license, obj->kern_version, &prog->fd);
7464 		if (err) {
7465 			pr_warn("prog '%s': failed to load: %d\n", prog->name, err);
7466 			return err;
7467 		}
7468 	}
7469 
7470 	bpf_object__free_relocs(obj);
7471 	return 0;
7472 }
7473 
7474 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
7475 
7476 static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
7477 {
7478 	struct bpf_program *prog;
7479 	int err;
7480 
7481 	bpf_object__for_each_program(prog, obj) {
7482 		prog->sec_def = find_sec_def(prog->sec_name);
7483 		if (!prog->sec_def) {
7484 			/* couldn't guess, but user might manually specify */
7485 			pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
7486 				prog->name, prog->sec_name);
7487 			continue;
7488 		}
7489 
7490 		prog->type = prog->sec_def->prog_type;
7491 		prog->expected_attach_type = prog->sec_def->expected_attach_type;
7492 
7493 		/* sec_def can have custom callback which should be called
7494 		 * after bpf_program is initialized to adjust its properties
7495 		 */
7496 		if (prog->sec_def->prog_setup_fn) {
7497 			err = prog->sec_def->prog_setup_fn(prog, prog->sec_def->cookie);
7498 			if (err < 0) {
7499 				pr_warn("prog '%s': failed to initialize: %d\n",
7500 					prog->name, err);
7501 				return err;
7502 			}
7503 		}
7504 	}
7505 
7506 	return 0;
7507 }
7508 
7509 static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
7510 					  const struct bpf_object_open_opts *opts)
7511 {
7512 	const char *obj_name, *kconfig, *btf_tmp_path;
7513 	struct bpf_object *obj;
7514 	char tmp_name[64];
7515 	int err;
7516 	char *log_buf;
7517 	size_t log_size;
7518 	__u32 log_level;
7519 
7520 	if (elf_version(EV_CURRENT) == EV_NONE) {
7521 		pr_warn("failed to init libelf for %s\n",
7522 			path ? : "(mem buf)");
7523 		return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
7524 	}
7525 
7526 	if (!OPTS_VALID(opts, bpf_object_open_opts))
7527 		return ERR_PTR(-EINVAL);
7528 
7529 	obj_name = OPTS_GET(opts, object_name, NULL);
7530 	if (obj_buf) {
7531 		if (!obj_name) {
7532 			snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
7533 				 (unsigned long)obj_buf,
7534 				 (unsigned long)obj_buf_sz);
7535 			obj_name = tmp_name;
7536 		}
7537 		path = obj_name;
7538 		pr_debug("loading object '%s' from buffer\n", obj_name);
7539 	}
7540 
7541 	log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
7542 	log_size = OPTS_GET(opts, kernel_log_size, 0);
7543 	log_level = OPTS_GET(opts, kernel_log_level, 0);
7544 	if (log_size > UINT_MAX)
7545 		return ERR_PTR(-EINVAL);
7546 	if (log_size && !log_buf)
7547 		return ERR_PTR(-EINVAL);
7548 
7549 	obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
7550 	if (IS_ERR(obj))
7551 		return obj;
7552 
7553 	obj->log_buf = log_buf;
7554 	obj->log_size = log_size;
7555 	obj->log_level = log_level;
7556 
7557 	btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
7558 	if (btf_tmp_path) {
7559 		if (strlen(btf_tmp_path) >= PATH_MAX) {
7560 			err = -ENAMETOOLONG;
7561 			goto out;
7562 		}
7563 		obj->btf_custom_path = strdup(btf_tmp_path);
7564 		if (!obj->btf_custom_path) {
7565 			err = -ENOMEM;
7566 			goto out;
7567 		}
7568 	}
7569 
7570 	kconfig = OPTS_GET(opts, kconfig, NULL);
7571 	if (kconfig) {
7572 		obj->kconfig = strdup(kconfig);
7573 		if (!obj->kconfig) {
7574 			err = -ENOMEM;
7575 			goto out;
7576 		}
7577 	}
7578 
7579 	err = bpf_object__elf_init(obj);
7580 	err = err ? : bpf_object__check_endianness(obj);
7581 	err = err ? : bpf_object__elf_collect(obj);
7582 	err = err ? : bpf_object__collect_externs(obj);
7583 	err = err ? : bpf_object_fixup_btf(obj);
7584 	err = err ? : bpf_object__init_maps(obj, opts);
7585 	err = err ? : bpf_object_init_progs(obj, opts);
7586 	err = err ? : bpf_object__collect_relos(obj);
7587 	if (err)
7588 		goto out;
7589 
7590 	bpf_object__elf_finish(obj);
7591 
7592 	return obj;
7593 out:
7594 	bpf_object__close(obj);
7595 	return ERR_PTR(err);
7596 }
7597 
7598 struct bpf_object *
7599 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
7600 {
7601 	if (!path)
7602 		return libbpf_err_ptr(-EINVAL);
7603 
7604 	pr_debug("loading %s\n", path);
7605 
7606 	return libbpf_ptr(bpf_object_open(path, NULL, 0, opts));
7607 }
7608 
7609 struct bpf_object *bpf_object__open(const char *path)
7610 {
7611 	return bpf_object__open_file(path, NULL);
7612 }
7613 
7614 struct bpf_object *
7615 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
7616 		     const struct bpf_object_open_opts *opts)
7617 {
7618 	if (!obj_buf || obj_buf_sz == 0)
7619 		return libbpf_err_ptr(-EINVAL);
7620 
7621 	return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, opts));
7622 }
7623 
7624 static int bpf_object_unload(struct bpf_object *obj)
7625 {
7626 	size_t i;
7627 
7628 	if (!obj)
7629 		return libbpf_err(-EINVAL);
7630 
7631 	for (i = 0; i < obj->nr_maps; i++) {
7632 		zclose(obj->maps[i].fd);
7633 		if (obj->maps[i].st_ops)
7634 			zfree(&obj->maps[i].st_ops->kern_vdata);
7635 	}
7636 
7637 	for (i = 0; i < obj->nr_programs; i++)
7638 		bpf_program__unload(&obj->programs[i]);
7639 
7640 	return 0;
7641 }
7642 
7643 static int bpf_object__sanitize_maps(struct bpf_object *obj)
7644 {
7645 	struct bpf_map *m;
7646 
7647 	bpf_object__for_each_map(m, obj) {
7648 		if (!bpf_map__is_internal(m))
7649 			continue;
7650 		if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
7651 			m->def.map_flags &= ~BPF_F_MMAPABLE;
7652 	}
7653 
7654 	return 0;
7655 }
7656 
7657 int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
7658 {
7659 	char sym_type, sym_name[500];
7660 	unsigned long long sym_addr;
7661 	int ret, err = 0;
7662 	FILE *f;
7663 
7664 	f = fopen("/proc/kallsyms", "re");
7665 	if (!f) {
7666 		err = -errno;
7667 		pr_warn("failed to open /proc/kallsyms: %d\n", err);
7668 		return err;
7669 	}
7670 
7671 	while (true) {
7672 		ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
7673 			     &sym_addr, &sym_type, sym_name);
7674 		if (ret == EOF && feof(f))
7675 			break;
7676 		if (ret != 3) {
7677 			pr_warn("failed to read kallsyms entry: %d\n", ret);
7678 			err = -EINVAL;
7679 			break;
7680 		}
7681 
7682 		err = cb(sym_addr, sym_type, sym_name, ctx);
7683 		if (err)
7684 			break;
7685 	}
7686 
7687 	fclose(f);
7688 	return err;
7689 }
7690 
7691 static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
7692 		       const char *sym_name, void *ctx)
7693 {
7694 	struct bpf_object *obj = ctx;
7695 	const struct btf_type *t;
7696 	struct extern_desc *ext;
7697 
7698 	ext = find_extern_by_name(obj, sym_name);
7699 	if (!ext || ext->type != EXT_KSYM)
7700 		return 0;
7701 
7702 	t = btf__type_by_id(obj->btf, ext->btf_id);
7703 	if (!btf_is_var(t))
7704 		return 0;
7705 
7706 	if (ext->is_set && ext->ksym.addr != sym_addr) {
7707 		pr_warn("extern (ksym) '%s': resolution is ambiguous: 0x%llx or 0x%llx\n",
7708 			sym_name, ext->ksym.addr, sym_addr);
7709 		return -EINVAL;
7710 	}
7711 	if (!ext->is_set) {
7712 		ext->is_set = true;
7713 		ext->ksym.addr = sym_addr;
7714 		pr_debug("extern (ksym) '%s': set to 0x%llx\n", sym_name, sym_addr);
7715 	}
7716 	return 0;
7717 }
7718 
7719 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
7720 {
7721 	return libbpf_kallsyms_parse(kallsyms_cb, obj);
7722 }
7723 
7724 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
7725 			    __u16 kind, struct btf **res_btf,
7726 			    struct module_btf **res_mod_btf)
7727 {
7728 	struct module_btf *mod_btf;
7729 	struct btf *btf;
7730 	int i, id, err;
7731 
7732 	btf = obj->btf_vmlinux;
7733 	mod_btf = NULL;
7734 	id = btf__find_by_name_kind(btf, ksym_name, kind);
7735 
7736 	if (id == -ENOENT) {
7737 		err = load_module_btfs(obj);
7738 		if (err)
7739 			return err;
7740 
7741 		for (i = 0; i < obj->btf_module_cnt; i++) {
7742 			/* we assume module_btf's BTF FD is always >0 */
7743 			mod_btf = &obj->btf_modules[i];
7744 			btf = mod_btf->btf;
7745 			id = btf__find_by_name_kind_own(btf, ksym_name, kind);
7746 			if (id != -ENOENT)
7747 				break;
7748 		}
7749 	}
7750 	if (id <= 0)
7751 		return -ESRCH;
7752 
7753 	*res_btf = btf;
7754 	*res_mod_btf = mod_btf;
7755 	return id;
7756 }
7757 
7758 static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
7759 					       struct extern_desc *ext)
7760 {
7761 	const struct btf_type *targ_var, *targ_type;
7762 	__u32 targ_type_id, local_type_id;
7763 	struct module_btf *mod_btf = NULL;
7764 	const char *targ_var_name;
7765 	struct btf *btf = NULL;
7766 	int id, err;
7767 
7768 	id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
7769 	if (id < 0) {
7770 		if (id == -ESRCH && ext->is_weak)
7771 			return 0;
7772 		pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
7773 			ext->name);
7774 		return id;
7775 	}
7776 
7777 	/* find local type_id */
7778 	local_type_id = ext->ksym.type_id;
7779 
7780 	/* find target type_id */
7781 	targ_var = btf__type_by_id(btf, id);
7782 	targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
7783 	targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
7784 
7785 	err = bpf_core_types_are_compat(obj->btf, local_type_id,
7786 					btf, targ_type_id);
7787 	if (err <= 0) {
7788 		const struct btf_type *local_type;
7789 		const char *targ_name, *local_name;
7790 
7791 		local_type = btf__type_by_id(obj->btf, local_type_id);
7792 		local_name = btf__name_by_offset(obj->btf, local_type->name_off);
7793 		targ_name = btf__name_by_offset(btf, targ_type->name_off);
7794 
7795 		pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
7796 			ext->name, local_type_id,
7797 			btf_kind_str(local_type), local_name, targ_type_id,
7798 			btf_kind_str(targ_type), targ_name);
7799 		return -EINVAL;
7800 	}
7801 
7802 	ext->is_set = true;
7803 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
7804 	ext->ksym.kernel_btf_id = id;
7805 	pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
7806 		 ext->name, id, btf_kind_str(targ_var), targ_var_name);
7807 
7808 	return 0;
7809 }
7810 
7811 static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
7812 						struct extern_desc *ext)
7813 {
7814 	int local_func_proto_id, kfunc_proto_id, kfunc_id;
7815 	struct module_btf *mod_btf = NULL;
7816 	const struct btf_type *kern_func;
7817 	struct btf *kern_btf = NULL;
7818 	int ret;
7819 
7820 	local_func_proto_id = ext->ksym.type_id;
7821 
7822 	kfunc_id = find_ksym_btf_id(obj, ext->essent_name ?: ext->name, BTF_KIND_FUNC, &kern_btf,
7823 				    &mod_btf);
7824 	if (kfunc_id < 0) {
7825 		if (kfunc_id == -ESRCH && ext->is_weak)
7826 			return 0;
7827 		pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
7828 			ext->name);
7829 		return kfunc_id;
7830 	}
7831 
7832 	kern_func = btf__type_by_id(kern_btf, kfunc_id);
7833 	kfunc_proto_id = kern_func->type;
7834 
7835 	ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
7836 					kern_btf, kfunc_proto_id);
7837 	if (ret <= 0) {
7838 		if (ext->is_weak)
7839 			return 0;
7840 
7841 		pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with %s [%d]\n",
7842 			ext->name, local_func_proto_id,
7843 			mod_btf ? mod_btf->name : "vmlinux", kfunc_proto_id);
7844 		return -EINVAL;
7845 	}
7846 
7847 	/* set index for module BTF fd in fd_array, if unset */
7848 	if (mod_btf && !mod_btf->fd_array_idx) {
7849 		/* insn->off is s16 */
7850 		if (obj->fd_array_cnt == INT16_MAX) {
7851 			pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
7852 				ext->name, mod_btf->fd_array_idx);
7853 			return -E2BIG;
7854 		}
7855 		/* Cannot use index 0 for module BTF fd */
7856 		if (!obj->fd_array_cnt)
7857 			obj->fd_array_cnt = 1;
7858 
7859 		ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
7860 					obj->fd_array_cnt + 1);
7861 		if (ret)
7862 			return ret;
7863 		mod_btf->fd_array_idx = obj->fd_array_cnt;
7864 		/* we assume module BTF FD is always >0 */
7865 		obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
7866 	}
7867 
7868 	ext->is_set = true;
7869 	ext->ksym.kernel_btf_id = kfunc_id;
7870 	ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
7871 	/* Also set kernel_btf_obj_fd to make sure that bpf_object__relocate_data()
7872 	 * populates FD into ld_imm64 insn when it's used to point to kfunc.
7873 	 * {kernel_btf_id, btf_fd_idx} -> fixup bpf_call.
7874 	 * {kernel_btf_id, kernel_btf_obj_fd} -> fixup ld_imm64.
7875 	 */
7876 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
7877 	pr_debug("extern (func ksym) '%s': resolved to %s [%d]\n",
7878 		 ext->name, mod_btf ? mod_btf->name : "vmlinux", kfunc_id);
7879 
7880 	return 0;
7881 }
7882 
7883 static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
7884 {
7885 	const struct btf_type *t;
7886 	struct extern_desc *ext;
7887 	int i, err;
7888 
7889 	for (i = 0; i < obj->nr_extern; i++) {
7890 		ext = &obj->externs[i];
7891 		if (ext->type != EXT_KSYM || !ext->ksym.type_id)
7892 			continue;
7893 
7894 		if (obj->gen_loader) {
7895 			ext->is_set = true;
7896 			ext->ksym.kernel_btf_obj_fd = 0;
7897 			ext->ksym.kernel_btf_id = 0;
7898 			continue;
7899 		}
7900 		t = btf__type_by_id(obj->btf, ext->btf_id);
7901 		if (btf_is_var(t))
7902 			err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
7903 		else
7904 			err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
7905 		if (err)
7906 			return err;
7907 	}
7908 	return 0;
7909 }
7910 
7911 static int bpf_object__resolve_externs(struct bpf_object *obj,
7912 				       const char *extra_kconfig)
7913 {
7914 	bool need_config = false, need_kallsyms = false;
7915 	bool need_vmlinux_btf = false;
7916 	struct extern_desc *ext;
7917 	void *kcfg_data = NULL;
7918 	int err, i;
7919 
7920 	if (obj->nr_extern == 0)
7921 		return 0;
7922 
7923 	if (obj->kconfig_map_idx >= 0)
7924 		kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
7925 
7926 	for (i = 0; i < obj->nr_extern; i++) {
7927 		ext = &obj->externs[i];
7928 
7929 		if (ext->type == EXT_KSYM) {
7930 			if (ext->ksym.type_id)
7931 				need_vmlinux_btf = true;
7932 			else
7933 				need_kallsyms = true;
7934 			continue;
7935 		} else if (ext->type == EXT_KCFG) {
7936 			void *ext_ptr = kcfg_data + ext->kcfg.data_off;
7937 			__u64 value = 0;
7938 
7939 			/* Kconfig externs need actual /proc/config.gz */
7940 			if (str_has_pfx(ext->name, "CONFIG_")) {
7941 				need_config = true;
7942 				continue;
7943 			}
7944 
7945 			/* Virtual kcfg externs are customly handled by libbpf */
7946 			if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
7947 				value = get_kernel_version();
7948 				if (!value) {
7949 					pr_warn("extern (kcfg) '%s': failed to get kernel version\n", ext->name);
7950 					return -EINVAL;
7951 				}
7952 			} else if (strcmp(ext->name, "LINUX_HAS_BPF_COOKIE") == 0) {
7953 				value = kernel_supports(obj, FEAT_BPF_COOKIE);
7954 			} else if (strcmp(ext->name, "LINUX_HAS_SYSCALL_WRAPPER") == 0) {
7955 				value = kernel_supports(obj, FEAT_SYSCALL_WRAPPER);
7956 			} else if (!str_has_pfx(ext->name, "LINUX_") || !ext->is_weak) {
7957 				/* Currently libbpf supports only CONFIG_ and LINUX_ prefixed
7958 				 * __kconfig externs, where LINUX_ ones are virtual and filled out
7959 				 * customly by libbpf (their values don't come from Kconfig).
7960 				 * If LINUX_xxx variable is not recognized by libbpf, but is marked
7961 				 * __weak, it defaults to zero value, just like for CONFIG_xxx
7962 				 * externs.
7963 				 */
7964 				pr_warn("extern (kcfg) '%s': unrecognized virtual extern\n", ext->name);
7965 				return -EINVAL;
7966 			}
7967 
7968 			err = set_kcfg_value_num(ext, ext_ptr, value);
7969 			if (err)
7970 				return err;
7971 			pr_debug("extern (kcfg) '%s': set to 0x%llx\n",
7972 				 ext->name, (long long)value);
7973 		} else {
7974 			pr_warn("extern '%s': unrecognized extern kind\n", ext->name);
7975 			return -EINVAL;
7976 		}
7977 	}
7978 	if (need_config && extra_kconfig) {
7979 		err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
7980 		if (err)
7981 			return -EINVAL;
7982 		need_config = false;
7983 		for (i = 0; i < obj->nr_extern; i++) {
7984 			ext = &obj->externs[i];
7985 			if (ext->type == EXT_KCFG && !ext->is_set) {
7986 				need_config = true;
7987 				break;
7988 			}
7989 		}
7990 	}
7991 	if (need_config) {
7992 		err = bpf_object__read_kconfig_file(obj, kcfg_data);
7993 		if (err)
7994 			return -EINVAL;
7995 	}
7996 	if (need_kallsyms) {
7997 		err = bpf_object__read_kallsyms_file(obj);
7998 		if (err)
7999 			return -EINVAL;
8000 	}
8001 	if (need_vmlinux_btf) {
8002 		err = bpf_object__resolve_ksyms_btf_id(obj);
8003 		if (err)
8004 			return -EINVAL;
8005 	}
8006 	for (i = 0; i < obj->nr_extern; i++) {
8007 		ext = &obj->externs[i];
8008 
8009 		if (!ext->is_set && !ext->is_weak) {
8010 			pr_warn("extern '%s' (strong): not resolved\n", ext->name);
8011 			return -ESRCH;
8012 		} else if (!ext->is_set) {
8013 			pr_debug("extern '%s' (weak): not resolved, defaulting to zero\n",
8014 				 ext->name);
8015 		}
8016 	}
8017 
8018 	return 0;
8019 }
8020 
8021 static void bpf_map_prepare_vdata(const struct bpf_map *map)
8022 {
8023 	struct bpf_struct_ops *st_ops;
8024 	__u32 i;
8025 
8026 	st_ops = map->st_ops;
8027 	for (i = 0; i < btf_vlen(st_ops->type); i++) {
8028 		struct bpf_program *prog = st_ops->progs[i];
8029 		void *kern_data;
8030 		int prog_fd;
8031 
8032 		if (!prog)
8033 			continue;
8034 
8035 		prog_fd = bpf_program__fd(prog);
8036 		kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
8037 		*(unsigned long *)kern_data = prog_fd;
8038 	}
8039 }
8040 
8041 static int bpf_object_prepare_struct_ops(struct bpf_object *obj)
8042 {
8043 	int i;
8044 
8045 	for (i = 0; i < obj->nr_maps; i++)
8046 		if (bpf_map__is_struct_ops(&obj->maps[i]))
8047 			bpf_map_prepare_vdata(&obj->maps[i]);
8048 
8049 	return 0;
8050 }
8051 
8052 static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
8053 {
8054 	int err, i;
8055 
8056 	if (!obj)
8057 		return libbpf_err(-EINVAL);
8058 
8059 	if (obj->loaded) {
8060 		pr_warn("object '%s': load can't be attempted twice\n", obj->name);
8061 		return libbpf_err(-EINVAL);
8062 	}
8063 
8064 	if (obj->gen_loader)
8065 		bpf_gen__init(obj->gen_loader, extra_log_level, obj->nr_programs, obj->nr_maps);
8066 
8067 	err = bpf_object__probe_loading(obj);
8068 	err = err ? : bpf_object__load_vmlinux_btf(obj, false);
8069 	err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
8070 	err = err ? : bpf_object__sanitize_and_load_btf(obj);
8071 	err = err ? : bpf_object__sanitize_maps(obj);
8072 	err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
8073 	err = err ? : bpf_object__create_maps(obj);
8074 	err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
8075 	err = err ? : bpf_object__load_progs(obj, extra_log_level);
8076 	err = err ? : bpf_object_init_prog_arrays(obj);
8077 	err = err ? : bpf_object_prepare_struct_ops(obj);
8078 
8079 	if (obj->gen_loader) {
8080 		/* reset FDs */
8081 		if (obj->btf)
8082 			btf__set_fd(obj->btf, -1);
8083 		for (i = 0; i < obj->nr_maps; i++)
8084 			obj->maps[i].fd = -1;
8085 		if (!err)
8086 			err = bpf_gen__finish(obj->gen_loader, obj->nr_programs, obj->nr_maps);
8087 	}
8088 
8089 	/* clean up fd_array */
8090 	zfree(&obj->fd_array);
8091 
8092 	/* clean up module BTFs */
8093 	for (i = 0; i < obj->btf_module_cnt; i++) {
8094 		close(obj->btf_modules[i].fd);
8095 		btf__free(obj->btf_modules[i].btf);
8096 		free(obj->btf_modules[i].name);
8097 	}
8098 	free(obj->btf_modules);
8099 
8100 	/* clean up vmlinux BTF */
8101 	btf__free(obj->btf_vmlinux);
8102 	obj->btf_vmlinux = NULL;
8103 
8104 	obj->loaded = true; /* doesn't matter if successfully or not */
8105 
8106 	if (err)
8107 		goto out;
8108 
8109 	return 0;
8110 out:
8111 	/* unpin any maps that were auto-pinned during load */
8112 	for (i = 0; i < obj->nr_maps; i++)
8113 		if (obj->maps[i].pinned && !obj->maps[i].reused)
8114 			bpf_map__unpin(&obj->maps[i], NULL);
8115 
8116 	bpf_object_unload(obj);
8117 	pr_warn("failed to load object '%s'\n", obj->path);
8118 	return libbpf_err(err);
8119 }
8120 
8121 int bpf_object__load(struct bpf_object *obj)
8122 {
8123 	return bpf_object_load(obj, 0, NULL);
8124 }
8125 
8126 static int make_parent_dir(const char *path)
8127 {
8128 	char *cp, errmsg[STRERR_BUFSIZE];
8129 	char *dname, *dir;
8130 	int err = 0;
8131 
8132 	dname = strdup(path);
8133 	if (dname == NULL)
8134 		return -ENOMEM;
8135 
8136 	dir = dirname(dname);
8137 	if (mkdir(dir, 0700) && errno != EEXIST)
8138 		err = -errno;
8139 
8140 	free(dname);
8141 	if (err) {
8142 		cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
8143 		pr_warn("failed to mkdir %s: %s\n", path, cp);
8144 	}
8145 	return err;
8146 }
8147 
8148 static int check_path(const char *path)
8149 {
8150 	char *cp, errmsg[STRERR_BUFSIZE];
8151 	struct statfs st_fs;
8152 	char *dname, *dir;
8153 	int err = 0;
8154 
8155 	if (path == NULL)
8156 		return -EINVAL;
8157 
8158 	dname = strdup(path);
8159 	if (dname == NULL)
8160 		return -ENOMEM;
8161 
8162 	dir = dirname(dname);
8163 	if (statfs(dir, &st_fs)) {
8164 		cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
8165 		pr_warn("failed to statfs %s: %s\n", dir, cp);
8166 		err = -errno;
8167 	}
8168 	free(dname);
8169 
8170 	if (!err && st_fs.f_type != BPF_FS_MAGIC) {
8171 		pr_warn("specified path %s is not on BPF FS\n", path);
8172 		err = -EINVAL;
8173 	}
8174 
8175 	return err;
8176 }
8177 
8178 int bpf_program__pin(struct bpf_program *prog, const char *path)
8179 {
8180 	char *cp, errmsg[STRERR_BUFSIZE];
8181 	int err;
8182 
8183 	if (prog->fd < 0) {
8184 		pr_warn("prog '%s': can't pin program that wasn't loaded\n", prog->name);
8185 		return libbpf_err(-EINVAL);
8186 	}
8187 
8188 	err = make_parent_dir(path);
8189 	if (err)
8190 		return libbpf_err(err);
8191 
8192 	err = check_path(path);
8193 	if (err)
8194 		return libbpf_err(err);
8195 
8196 	if (bpf_obj_pin(prog->fd, path)) {
8197 		err = -errno;
8198 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
8199 		pr_warn("prog '%s': failed to pin at '%s': %s\n", prog->name, path, cp);
8200 		return libbpf_err(err);
8201 	}
8202 
8203 	pr_debug("prog '%s': pinned at '%s'\n", prog->name, path);
8204 	return 0;
8205 }
8206 
8207 int bpf_program__unpin(struct bpf_program *prog, const char *path)
8208 {
8209 	int err;
8210 
8211 	if (prog->fd < 0) {
8212 		pr_warn("prog '%s': can't unpin program that wasn't loaded\n", prog->name);
8213 		return libbpf_err(-EINVAL);
8214 	}
8215 
8216 	err = check_path(path);
8217 	if (err)
8218 		return libbpf_err(err);
8219 
8220 	err = unlink(path);
8221 	if (err)
8222 		return libbpf_err(-errno);
8223 
8224 	pr_debug("prog '%s': unpinned from '%s'\n", prog->name, path);
8225 	return 0;
8226 }
8227 
8228 int bpf_map__pin(struct bpf_map *map, const char *path)
8229 {
8230 	char *cp, errmsg[STRERR_BUFSIZE];
8231 	int err;
8232 
8233 	if (map == NULL) {
8234 		pr_warn("invalid map pointer\n");
8235 		return libbpf_err(-EINVAL);
8236 	}
8237 
8238 	if (map->pin_path) {
8239 		if (path && strcmp(path, map->pin_path)) {
8240 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8241 				bpf_map__name(map), map->pin_path, path);
8242 			return libbpf_err(-EINVAL);
8243 		} else if (map->pinned) {
8244 			pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
8245 				 bpf_map__name(map), map->pin_path);
8246 			return 0;
8247 		}
8248 	} else {
8249 		if (!path) {
8250 			pr_warn("missing a path to pin map '%s' at\n",
8251 				bpf_map__name(map));
8252 			return libbpf_err(-EINVAL);
8253 		} else if (map->pinned) {
8254 			pr_warn("map '%s' already pinned\n", bpf_map__name(map));
8255 			return libbpf_err(-EEXIST);
8256 		}
8257 
8258 		map->pin_path = strdup(path);
8259 		if (!map->pin_path) {
8260 			err = -errno;
8261 			goto out_err;
8262 		}
8263 	}
8264 
8265 	err = make_parent_dir(map->pin_path);
8266 	if (err)
8267 		return libbpf_err(err);
8268 
8269 	err = check_path(map->pin_path);
8270 	if (err)
8271 		return libbpf_err(err);
8272 
8273 	if (bpf_obj_pin(map->fd, map->pin_path)) {
8274 		err = -errno;
8275 		goto out_err;
8276 	}
8277 
8278 	map->pinned = true;
8279 	pr_debug("pinned map '%s'\n", map->pin_path);
8280 
8281 	return 0;
8282 
8283 out_err:
8284 	cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
8285 	pr_warn("failed to pin map: %s\n", cp);
8286 	return libbpf_err(err);
8287 }
8288 
8289 int bpf_map__unpin(struct bpf_map *map, const char *path)
8290 {
8291 	int err;
8292 
8293 	if (map == NULL) {
8294 		pr_warn("invalid map pointer\n");
8295 		return libbpf_err(-EINVAL);
8296 	}
8297 
8298 	if (map->pin_path) {
8299 		if (path && strcmp(path, map->pin_path)) {
8300 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8301 				bpf_map__name(map), map->pin_path, path);
8302 			return libbpf_err(-EINVAL);
8303 		}
8304 		path = map->pin_path;
8305 	} else if (!path) {
8306 		pr_warn("no path to unpin map '%s' from\n",
8307 			bpf_map__name(map));
8308 		return libbpf_err(-EINVAL);
8309 	}
8310 
8311 	err = check_path(path);
8312 	if (err)
8313 		return libbpf_err(err);
8314 
8315 	err = unlink(path);
8316 	if (err != 0)
8317 		return libbpf_err(-errno);
8318 
8319 	map->pinned = false;
8320 	pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
8321 
8322 	return 0;
8323 }
8324 
8325 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
8326 {
8327 	char *new = NULL;
8328 
8329 	if (path) {
8330 		new = strdup(path);
8331 		if (!new)
8332 			return libbpf_err(-errno);
8333 	}
8334 
8335 	free(map->pin_path);
8336 	map->pin_path = new;
8337 	return 0;
8338 }
8339 
8340 __alias(bpf_map__pin_path)
8341 const char *bpf_map__get_pin_path(const struct bpf_map *map);
8342 
8343 const char *bpf_map__pin_path(const struct bpf_map *map)
8344 {
8345 	return map->pin_path;
8346 }
8347 
8348 bool bpf_map__is_pinned(const struct bpf_map *map)
8349 {
8350 	return map->pinned;
8351 }
8352 
8353 static void sanitize_pin_path(char *s)
8354 {
8355 	/* bpffs disallows periods in path names */
8356 	while (*s) {
8357 		if (*s == '.')
8358 			*s = '_';
8359 		s++;
8360 	}
8361 }
8362 
8363 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
8364 {
8365 	struct bpf_map *map;
8366 	int err;
8367 
8368 	if (!obj)
8369 		return libbpf_err(-ENOENT);
8370 
8371 	if (!obj->loaded) {
8372 		pr_warn("object not yet loaded; load it first\n");
8373 		return libbpf_err(-ENOENT);
8374 	}
8375 
8376 	bpf_object__for_each_map(map, obj) {
8377 		char *pin_path = NULL;
8378 		char buf[PATH_MAX];
8379 
8380 		if (!map->autocreate)
8381 			continue;
8382 
8383 		if (path) {
8384 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8385 			if (err)
8386 				goto err_unpin_maps;
8387 			sanitize_pin_path(buf);
8388 			pin_path = buf;
8389 		} else if (!map->pin_path) {
8390 			continue;
8391 		}
8392 
8393 		err = bpf_map__pin(map, pin_path);
8394 		if (err)
8395 			goto err_unpin_maps;
8396 	}
8397 
8398 	return 0;
8399 
8400 err_unpin_maps:
8401 	while ((map = bpf_object__prev_map(obj, map))) {
8402 		if (!map->pin_path)
8403 			continue;
8404 
8405 		bpf_map__unpin(map, NULL);
8406 	}
8407 
8408 	return libbpf_err(err);
8409 }
8410 
8411 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
8412 {
8413 	struct bpf_map *map;
8414 	int err;
8415 
8416 	if (!obj)
8417 		return libbpf_err(-ENOENT);
8418 
8419 	bpf_object__for_each_map(map, obj) {
8420 		char *pin_path = NULL;
8421 		char buf[PATH_MAX];
8422 
8423 		if (path) {
8424 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8425 			if (err)
8426 				return libbpf_err(err);
8427 			sanitize_pin_path(buf);
8428 			pin_path = buf;
8429 		} else if (!map->pin_path) {
8430 			continue;
8431 		}
8432 
8433 		err = bpf_map__unpin(map, pin_path);
8434 		if (err)
8435 			return libbpf_err(err);
8436 	}
8437 
8438 	return 0;
8439 }
8440 
8441 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
8442 {
8443 	struct bpf_program *prog;
8444 	char buf[PATH_MAX];
8445 	int err;
8446 
8447 	if (!obj)
8448 		return libbpf_err(-ENOENT);
8449 
8450 	if (!obj->loaded) {
8451 		pr_warn("object not yet loaded; load it first\n");
8452 		return libbpf_err(-ENOENT);
8453 	}
8454 
8455 	bpf_object__for_each_program(prog, obj) {
8456 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
8457 		if (err)
8458 			goto err_unpin_programs;
8459 
8460 		err = bpf_program__pin(prog, buf);
8461 		if (err)
8462 			goto err_unpin_programs;
8463 	}
8464 
8465 	return 0;
8466 
8467 err_unpin_programs:
8468 	while ((prog = bpf_object__prev_program(obj, prog))) {
8469 		if (pathname_concat(buf, sizeof(buf), path, prog->name))
8470 			continue;
8471 
8472 		bpf_program__unpin(prog, buf);
8473 	}
8474 
8475 	return libbpf_err(err);
8476 }
8477 
8478 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
8479 {
8480 	struct bpf_program *prog;
8481 	int err;
8482 
8483 	if (!obj)
8484 		return libbpf_err(-ENOENT);
8485 
8486 	bpf_object__for_each_program(prog, obj) {
8487 		char buf[PATH_MAX];
8488 
8489 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
8490 		if (err)
8491 			return libbpf_err(err);
8492 
8493 		err = bpf_program__unpin(prog, buf);
8494 		if (err)
8495 			return libbpf_err(err);
8496 	}
8497 
8498 	return 0;
8499 }
8500 
8501 int bpf_object__pin(struct bpf_object *obj, const char *path)
8502 {
8503 	int err;
8504 
8505 	err = bpf_object__pin_maps(obj, path);
8506 	if (err)
8507 		return libbpf_err(err);
8508 
8509 	err = bpf_object__pin_programs(obj, path);
8510 	if (err) {
8511 		bpf_object__unpin_maps(obj, path);
8512 		return libbpf_err(err);
8513 	}
8514 
8515 	return 0;
8516 }
8517 
8518 int bpf_object__unpin(struct bpf_object *obj, const char *path)
8519 {
8520 	int err;
8521 
8522 	err = bpf_object__unpin_programs(obj, path);
8523 	if (err)
8524 		return libbpf_err(err);
8525 
8526 	err = bpf_object__unpin_maps(obj, path);
8527 	if (err)
8528 		return libbpf_err(err);
8529 
8530 	return 0;
8531 }
8532 
8533 static void bpf_map__destroy(struct bpf_map *map)
8534 {
8535 	if (map->inner_map) {
8536 		bpf_map__destroy(map->inner_map);
8537 		zfree(&map->inner_map);
8538 	}
8539 
8540 	zfree(&map->init_slots);
8541 	map->init_slots_sz = 0;
8542 
8543 	if (map->mmaped) {
8544 		size_t mmap_sz;
8545 
8546 		mmap_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
8547 		munmap(map->mmaped, mmap_sz);
8548 		map->mmaped = NULL;
8549 	}
8550 
8551 	if (map->st_ops) {
8552 		zfree(&map->st_ops->data);
8553 		zfree(&map->st_ops->progs);
8554 		zfree(&map->st_ops->kern_func_off);
8555 		zfree(&map->st_ops);
8556 	}
8557 
8558 	zfree(&map->name);
8559 	zfree(&map->real_name);
8560 	zfree(&map->pin_path);
8561 
8562 	if (map->fd >= 0)
8563 		zclose(map->fd);
8564 }
8565 
8566 void bpf_object__close(struct bpf_object *obj)
8567 {
8568 	size_t i;
8569 
8570 	if (IS_ERR_OR_NULL(obj))
8571 		return;
8572 
8573 	usdt_manager_free(obj->usdt_man);
8574 	obj->usdt_man = NULL;
8575 
8576 	bpf_gen__free(obj->gen_loader);
8577 	bpf_object__elf_finish(obj);
8578 	bpf_object_unload(obj);
8579 	btf__free(obj->btf);
8580 	btf__free(obj->btf_vmlinux);
8581 	btf_ext__free(obj->btf_ext);
8582 
8583 	for (i = 0; i < obj->nr_maps; i++)
8584 		bpf_map__destroy(&obj->maps[i]);
8585 
8586 	zfree(&obj->btf_custom_path);
8587 	zfree(&obj->kconfig);
8588 
8589 	for (i = 0; i < obj->nr_extern; i++)
8590 		zfree(&obj->externs[i].essent_name);
8591 
8592 	zfree(&obj->externs);
8593 	obj->nr_extern = 0;
8594 
8595 	zfree(&obj->maps);
8596 	obj->nr_maps = 0;
8597 
8598 	if (obj->programs && obj->nr_programs) {
8599 		for (i = 0; i < obj->nr_programs; i++)
8600 			bpf_program__exit(&obj->programs[i]);
8601 	}
8602 	zfree(&obj->programs);
8603 
8604 	free(obj);
8605 }
8606 
8607 const char *bpf_object__name(const struct bpf_object *obj)
8608 {
8609 	return obj ? obj->name : libbpf_err_ptr(-EINVAL);
8610 }
8611 
8612 unsigned int bpf_object__kversion(const struct bpf_object *obj)
8613 {
8614 	return obj ? obj->kern_version : 0;
8615 }
8616 
8617 struct btf *bpf_object__btf(const struct bpf_object *obj)
8618 {
8619 	return obj ? obj->btf : NULL;
8620 }
8621 
8622 int bpf_object__btf_fd(const struct bpf_object *obj)
8623 {
8624 	return obj->btf ? btf__fd(obj->btf) : -1;
8625 }
8626 
8627 int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
8628 {
8629 	if (obj->loaded)
8630 		return libbpf_err(-EINVAL);
8631 
8632 	obj->kern_version = kern_version;
8633 
8634 	return 0;
8635 }
8636 
8637 int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
8638 {
8639 	struct bpf_gen *gen;
8640 
8641 	if (!opts)
8642 		return -EFAULT;
8643 	if (!OPTS_VALID(opts, gen_loader_opts))
8644 		return -EINVAL;
8645 	gen = calloc(sizeof(*gen), 1);
8646 	if (!gen)
8647 		return -ENOMEM;
8648 	gen->opts = opts;
8649 	obj->gen_loader = gen;
8650 	return 0;
8651 }
8652 
8653 static struct bpf_program *
8654 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
8655 		    bool forward)
8656 {
8657 	size_t nr_programs = obj->nr_programs;
8658 	ssize_t idx;
8659 
8660 	if (!nr_programs)
8661 		return NULL;
8662 
8663 	if (!p)
8664 		/* Iter from the beginning */
8665 		return forward ? &obj->programs[0] :
8666 			&obj->programs[nr_programs - 1];
8667 
8668 	if (p->obj != obj) {
8669 		pr_warn("error: program handler doesn't match object\n");
8670 		return errno = EINVAL, NULL;
8671 	}
8672 
8673 	idx = (p - obj->programs) + (forward ? 1 : -1);
8674 	if (idx >= obj->nr_programs || idx < 0)
8675 		return NULL;
8676 	return &obj->programs[idx];
8677 }
8678 
8679 struct bpf_program *
8680 bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
8681 {
8682 	struct bpf_program *prog = prev;
8683 
8684 	do {
8685 		prog = __bpf_program__iter(prog, obj, true);
8686 	} while (prog && prog_is_subprog(obj, prog));
8687 
8688 	return prog;
8689 }
8690 
8691 struct bpf_program *
8692 bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
8693 {
8694 	struct bpf_program *prog = next;
8695 
8696 	do {
8697 		prog = __bpf_program__iter(prog, obj, false);
8698 	} while (prog && prog_is_subprog(obj, prog));
8699 
8700 	return prog;
8701 }
8702 
8703 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
8704 {
8705 	prog->prog_ifindex = ifindex;
8706 }
8707 
8708 const char *bpf_program__name(const struct bpf_program *prog)
8709 {
8710 	return prog->name;
8711 }
8712 
8713 const char *bpf_program__section_name(const struct bpf_program *prog)
8714 {
8715 	return prog->sec_name;
8716 }
8717 
8718 bool bpf_program__autoload(const struct bpf_program *prog)
8719 {
8720 	return prog->autoload;
8721 }
8722 
8723 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
8724 {
8725 	if (prog->obj->loaded)
8726 		return libbpf_err(-EINVAL);
8727 
8728 	prog->autoload = autoload;
8729 	return 0;
8730 }
8731 
8732 bool bpf_program__autoattach(const struct bpf_program *prog)
8733 {
8734 	return prog->autoattach;
8735 }
8736 
8737 void bpf_program__set_autoattach(struct bpf_program *prog, bool autoattach)
8738 {
8739 	prog->autoattach = autoattach;
8740 }
8741 
8742 const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
8743 {
8744 	return prog->insns;
8745 }
8746 
8747 size_t bpf_program__insn_cnt(const struct bpf_program *prog)
8748 {
8749 	return prog->insns_cnt;
8750 }
8751 
8752 int bpf_program__set_insns(struct bpf_program *prog,
8753 			   struct bpf_insn *new_insns, size_t new_insn_cnt)
8754 {
8755 	struct bpf_insn *insns;
8756 
8757 	if (prog->obj->loaded)
8758 		return -EBUSY;
8759 
8760 	insns = libbpf_reallocarray(prog->insns, new_insn_cnt, sizeof(*insns));
8761 	/* NULL is a valid return from reallocarray if the new count is zero */
8762 	if (!insns && new_insn_cnt) {
8763 		pr_warn("prog '%s': failed to realloc prog code\n", prog->name);
8764 		return -ENOMEM;
8765 	}
8766 	memcpy(insns, new_insns, new_insn_cnt * sizeof(*insns));
8767 
8768 	prog->insns = insns;
8769 	prog->insns_cnt = new_insn_cnt;
8770 	return 0;
8771 }
8772 
8773 int bpf_program__fd(const struct bpf_program *prog)
8774 {
8775 	if (!prog)
8776 		return libbpf_err(-EINVAL);
8777 
8778 	if (prog->fd < 0)
8779 		return libbpf_err(-ENOENT);
8780 
8781 	return prog->fd;
8782 }
8783 
8784 __alias(bpf_program__type)
8785 enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog);
8786 
8787 enum bpf_prog_type bpf_program__type(const struct bpf_program *prog)
8788 {
8789 	return prog->type;
8790 }
8791 
8792 static size_t custom_sec_def_cnt;
8793 static struct bpf_sec_def *custom_sec_defs;
8794 static struct bpf_sec_def custom_fallback_def;
8795 static bool has_custom_fallback_def;
8796 static int last_custom_sec_def_handler_id;
8797 
8798 int bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
8799 {
8800 	if (prog->obj->loaded)
8801 		return libbpf_err(-EBUSY);
8802 
8803 	/* if type is not changed, do nothing */
8804 	if (prog->type == type)
8805 		return 0;
8806 
8807 	prog->type = type;
8808 
8809 	/* If a program type was changed, we need to reset associated SEC()
8810 	 * handler, as it will be invalid now. The only exception is a generic
8811 	 * fallback handler, which by definition is program type-agnostic and
8812 	 * is a catch-all custom handler, optionally set by the application,
8813 	 * so should be able to handle any type of BPF program.
8814 	 */
8815 	if (prog->sec_def != &custom_fallback_def)
8816 		prog->sec_def = NULL;
8817 	return 0;
8818 }
8819 
8820 __alias(bpf_program__expected_attach_type)
8821 enum bpf_attach_type bpf_program__get_expected_attach_type(const struct bpf_program *prog);
8822 
8823 enum bpf_attach_type bpf_program__expected_attach_type(const struct bpf_program *prog)
8824 {
8825 	return prog->expected_attach_type;
8826 }
8827 
8828 int bpf_program__set_expected_attach_type(struct bpf_program *prog,
8829 					   enum bpf_attach_type type)
8830 {
8831 	if (prog->obj->loaded)
8832 		return libbpf_err(-EBUSY);
8833 
8834 	prog->expected_attach_type = type;
8835 	return 0;
8836 }
8837 
8838 __u32 bpf_program__flags(const struct bpf_program *prog)
8839 {
8840 	return prog->prog_flags;
8841 }
8842 
8843 int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
8844 {
8845 	if (prog->obj->loaded)
8846 		return libbpf_err(-EBUSY);
8847 
8848 	prog->prog_flags = flags;
8849 	return 0;
8850 }
8851 
8852 __u32 bpf_program__log_level(const struct bpf_program *prog)
8853 {
8854 	return prog->log_level;
8855 }
8856 
8857 int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
8858 {
8859 	if (prog->obj->loaded)
8860 		return libbpf_err(-EBUSY);
8861 
8862 	prog->log_level = log_level;
8863 	return 0;
8864 }
8865 
8866 const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
8867 {
8868 	*log_size = prog->log_size;
8869 	return prog->log_buf;
8870 }
8871 
8872 int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
8873 {
8874 	if (log_size && !log_buf)
8875 		return -EINVAL;
8876 	if (prog->log_size > UINT_MAX)
8877 		return -EINVAL;
8878 	if (prog->obj->loaded)
8879 		return -EBUSY;
8880 
8881 	prog->log_buf = log_buf;
8882 	prog->log_size = log_size;
8883 	return 0;
8884 }
8885 
8886 #define SEC_DEF(sec_pfx, ptype, atype, flags, ...) {			    \
8887 	.sec = (char *)sec_pfx,						    \
8888 	.prog_type = BPF_PROG_TYPE_##ptype,				    \
8889 	.expected_attach_type = atype,					    \
8890 	.cookie = (long)(flags),					    \
8891 	.prog_prepare_load_fn = libbpf_prepare_prog_load,		    \
8892 	__VA_ARGS__							    \
8893 }
8894 
8895 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8896 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8897 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8898 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8899 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8900 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8901 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8902 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8903 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8904 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8905 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8906 
8907 static const struct bpf_sec_def section_defs[] = {
8908 	SEC_DEF("socket",		SOCKET_FILTER, 0, SEC_NONE),
8909 	SEC_DEF("sk_reuseport/migrate",	SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE),
8910 	SEC_DEF("sk_reuseport",		SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE),
8911 	SEC_DEF("kprobe+",		KPROBE,	0, SEC_NONE, attach_kprobe),
8912 	SEC_DEF("uprobe+",		KPROBE,	0, SEC_NONE, attach_uprobe),
8913 	SEC_DEF("uprobe.s+",		KPROBE,	0, SEC_SLEEPABLE, attach_uprobe),
8914 	SEC_DEF("kretprobe+",		KPROBE, 0, SEC_NONE, attach_kprobe),
8915 	SEC_DEF("uretprobe+",		KPROBE, 0, SEC_NONE, attach_uprobe),
8916 	SEC_DEF("uretprobe.s+",		KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
8917 	SEC_DEF("kprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
8918 	SEC_DEF("kretprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
8919 	SEC_DEF("uprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
8920 	SEC_DEF("uretprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
8921 	SEC_DEF("uprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
8922 	SEC_DEF("uretprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
8923 	SEC_DEF("ksyscall+",		KPROBE,	0, SEC_NONE, attach_ksyscall),
8924 	SEC_DEF("kretsyscall+",		KPROBE, 0, SEC_NONE, attach_ksyscall),
8925 	SEC_DEF("usdt+",		KPROBE,	0, SEC_USDT, attach_usdt),
8926 	SEC_DEF("usdt.s+",		KPROBE,	0, SEC_USDT | SEC_SLEEPABLE, attach_usdt),
8927 	SEC_DEF("tc/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE), /* alias for tcx */
8928 	SEC_DEF("tc/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),  /* alias for tcx */
8929 	SEC_DEF("tcx/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE),
8930 	SEC_DEF("tcx/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),
8931 	SEC_DEF("tc",			SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
8932 	SEC_DEF("classifier",		SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
8933 	SEC_DEF("action",		SCHED_ACT, 0, SEC_NONE), /* deprecated / legacy, use tcx */
8934 	SEC_DEF("netkit/primary",	SCHED_CLS, BPF_NETKIT_PRIMARY, SEC_NONE),
8935 	SEC_DEF("netkit/peer",		SCHED_CLS, BPF_NETKIT_PEER, SEC_NONE),
8936 	SEC_DEF("tracepoint+",		TRACEPOINT, 0, SEC_NONE, attach_tp),
8937 	SEC_DEF("tp+",			TRACEPOINT, 0, SEC_NONE, attach_tp),
8938 	SEC_DEF("raw_tracepoint+",	RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
8939 	SEC_DEF("raw_tp+",		RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
8940 	SEC_DEF("raw_tracepoint.w+",	RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
8941 	SEC_DEF("raw_tp.w+",		RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
8942 	SEC_DEF("tp_btf+",		TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
8943 	SEC_DEF("fentry+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
8944 	SEC_DEF("fmod_ret+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
8945 	SEC_DEF("fexit+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
8946 	SEC_DEF("fentry.s+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8947 	SEC_DEF("fmod_ret.s+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8948 	SEC_DEF("fexit.s+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8949 	SEC_DEF("freplace+",		EXT, 0, SEC_ATTACH_BTF, attach_trace),
8950 	SEC_DEF("lsm+",			LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
8951 	SEC_DEF("lsm.s+",		LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
8952 	SEC_DEF("lsm_cgroup+",		LSM, BPF_LSM_CGROUP, SEC_ATTACH_BTF),
8953 	SEC_DEF("iter+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
8954 	SEC_DEF("iter.s+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_iter),
8955 	SEC_DEF("syscall",		SYSCALL, 0, SEC_SLEEPABLE),
8956 	SEC_DEF("xdp.frags/devmap",	XDP, BPF_XDP_DEVMAP, SEC_XDP_FRAGS),
8957 	SEC_DEF("xdp/devmap",		XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
8958 	SEC_DEF("xdp.frags/cpumap",	XDP, BPF_XDP_CPUMAP, SEC_XDP_FRAGS),
8959 	SEC_DEF("xdp/cpumap",		XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
8960 	SEC_DEF("xdp.frags",		XDP, BPF_XDP, SEC_XDP_FRAGS),
8961 	SEC_DEF("xdp",			XDP, BPF_XDP, SEC_ATTACHABLE_OPT),
8962 	SEC_DEF("perf_event",		PERF_EVENT, 0, SEC_NONE),
8963 	SEC_DEF("lwt_in",		LWT_IN, 0, SEC_NONE),
8964 	SEC_DEF("lwt_out",		LWT_OUT, 0, SEC_NONE),
8965 	SEC_DEF("lwt_xmit",		LWT_XMIT, 0, SEC_NONE),
8966 	SEC_DEF("lwt_seg6local",	LWT_SEG6LOCAL, 0, SEC_NONE),
8967 	SEC_DEF("sockops",		SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT),
8968 	SEC_DEF("sk_skb/stream_parser",	SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT),
8969 	SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT),
8970 	SEC_DEF("sk_skb",		SK_SKB, 0, SEC_NONE),
8971 	SEC_DEF("sk_msg",		SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT),
8972 	SEC_DEF("lirc_mode2",		LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT),
8973 	SEC_DEF("flow_dissector",	FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT),
8974 	SEC_DEF("cgroup_skb/ingress",	CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT),
8975 	SEC_DEF("cgroup_skb/egress",	CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT),
8976 	SEC_DEF("cgroup/skb",		CGROUP_SKB, 0, SEC_NONE),
8977 	SEC_DEF("cgroup/sock_create",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE),
8978 	SEC_DEF("cgroup/sock_release",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE),
8979 	SEC_DEF("cgroup/sock",		CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT),
8980 	SEC_DEF("cgroup/post_bind4",	CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE),
8981 	SEC_DEF("cgroup/post_bind6",	CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE),
8982 	SEC_DEF("cgroup/bind4",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE),
8983 	SEC_DEF("cgroup/bind6",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE),
8984 	SEC_DEF("cgroup/connect4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE),
8985 	SEC_DEF("cgroup/connect6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE),
8986 	SEC_DEF("cgroup/connect_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_CONNECT, SEC_ATTACHABLE),
8987 	SEC_DEF("cgroup/sendmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE),
8988 	SEC_DEF("cgroup/sendmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE),
8989 	SEC_DEF("cgroup/sendmsg_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_SENDMSG, SEC_ATTACHABLE),
8990 	SEC_DEF("cgroup/recvmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE),
8991 	SEC_DEF("cgroup/recvmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE),
8992 	SEC_DEF("cgroup/recvmsg_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_RECVMSG, SEC_ATTACHABLE),
8993 	SEC_DEF("cgroup/getpeername4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE),
8994 	SEC_DEF("cgroup/getpeername6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE),
8995 	SEC_DEF("cgroup/getpeername_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETPEERNAME, SEC_ATTACHABLE),
8996 	SEC_DEF("cgroup/getsockname4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE),
8997 	SEC_DEF("cgroup/getsockname6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE),
8998 	SEC_DEF("cgroup/getsockname_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETSOCKNAME, SEC_ATTACHABLE),
8999 	SEC_DEF("cgroup/sysctl",	CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE),
9000 	SEC_DEF("cgroup/getsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE),
9001 	SEC_DEF("cgroup/setsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE),
9002 	SEC_DEF("cgroup/dev",		CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT),
9003 	SEC_DEF("struct_ops+",		STRUCT_OPS, 0, SEC_NONE),
9004 	SEC_DEF("struct_ops.s+",	STRUCT_OPS, 0, SEC_SLEEPABLE),
9005 	SEC_DEF("sk_lookup",		SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE),
9006 	SEC_DEF("netfilter",		NETFILTER, BPF_NETFILTER, SEC_NONE),
9007 };
9008 
9009 int libbpf_register_prog_handler(const char *sec,
9010 				 enum bpf_prog_type prog_type,
9011 				 enum bpf_attach_type exp_attach_type,
9012 				 const struct libbpf_prog_handler_opts *opts)
9013 {
9014 	struct bpf_sec_def *sec_def;
9015 
9016 	if (!OPTS_VALID(opts, libbpf_prog_handler_opts))
9017 		return libbpf_err(-EINVAL);
9018 
9019 	if (last_custom_sec_def_handler_id == INT_MAX) /* prevent overflow */
9020 		return libbpf_err(-E2BIG);
9021 
9022 	if (sec) {
9023 		sec_def = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt + 1,
9024 					      sizeof(*sec_def));
9025 		if (!sec_def)
9026 			return libbpf_err(-ENOMEM);
9027 
9028 		custom_sec_defs = sec_def;
9029 		sec_def = &custom_sec_defs[custom_sec_def_cnt];
9030 	} else {
9031 		if (has_custom_fallback_def)
9032 			return libbpf_err(-EBUSY);
9033 
9034 		sec_def = &custom_fallback_def;
9035 	}
9036 
9037 	sec_def->sec = sec ? strdup(sec) : NULL;
9038 	if (sec && !sec_def->sec)
9039 		return libbpf_err(-ENOMEM);
9040 
9041 	sec_def->prog_type = prog_type;
9042 	sec_def->expected_attach_type = exp_attach_type;
9043 	sec_def->cookie = OPTS_GET(opts, cookie, 0);
9044 
9045 	sec_def->prog_setup_fn = OPTS_GET(opts, prog_setup_fn, NULL);
9046 	sec_def->prog_prepare_load_fn = OPTS_GET(opts, prog_prepare_load_fn, NULL);
9047 	sec_def->prog_attach_fn = OPTS_GET(opts, prog_attach_fn, NULL);
9048 
9049 	sec_def->handler_id = ++last_custom_sec_def_handler_id;
9050 
9051 	if (sec)
9052 		custom_sec_def_cnt++;
9053 	else
9054 		has_custom_fallback_def = true;
9055 
9056 	return sec_def->handler_id;
9057 }
9058 
9059 int libbpf_unregister_prog_handler(int handler_id)
9060 {
9061 	struct bpf_sec_def *sec_defs;
9062 	int i;
9063 
9064 	if (handler_id <= 0)
9065 		return libbpf_err(-EINVAL);
9066 
9067 	if (has_custom_fallback_def && custom_fallback_def.handler_id == handler_id) {
9068 		memset(&custom_fallback_def, 0, sizeof(custom_fallback_def));
9069 		has_custom_fallback_def = false;
9070 		return 0;
9071 	}
9072 
9073 	for (i = 0; i < custom_sec_def_cnt; i++) {
9074 		if (custom_sec_defs[i].handler_id == handler_id)
9075 			break;
9076 	}
9077 
9078 	if (i == custom_sec_def_cnt)
9079 		return libbpf_err(-ENOENT);
9080 
9081 	free(custom_sec_defs[i].sec);
9082 	for (i = i + 1; i < custom_sec_def_cnt; i++)
9083 		custom_sec_defs[i - 1] = custom_sec_defs[i];
9084 	custom_sec_def_cnt--;
9085 
9086 	/* try to shrink the array, but it's ok if we couldn't */
9087 	sec_defs = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt, sizeof(*sec_defs));
9088 	/* if new count is zero, reallocarray can return a valid NULL result;
9089 	 * in this case the previous pointer will be freed, so we *have to*
9090 	 * reassign old pointer to the new value (even if it's NULL)
9091 	 */
9092 	if (sec_defs || custom_sec_def_cnt == 0)
9093 		custom_sec_defs = sec_defs;
9094 
9095 	return 0;
9096 }
9097 
9098 static bool sec_def_matches(const struct bpf_sec_def *sec_def, const char *sec_name)
9099 {
9100 	size_t len = strlen(sec_def->sec);
9101 
9102 	/* "type/" always has to have proper SEC("type/extras") form */
9103 	if (sec_def->sec[len - 1] == '/') {
9104 		if (str_has_pfx(sec_name, sec_def->sec))
9105 			return true;
9106 		return false;
9107 	}
9108 
9109 	/* "type+" means it can be either exact SEC("type") or
9110 	 * well-formed SEC("type/extras") with proper '/' separator
9111 	 */
9112 	if (sec_def->sec[len - 1] == '+') {
9113 		len--;
9114 		/* not even a prefix */
9115 		if (strncmp(sec_name, sec_def->sec, len) != 0)
9116 			return false;
9117 		/* exact match or has '/' separator */
9118 		if (sec_name[len] == '\0' || sec_name[len] == '/')
9119 			return true;
9120 		return false;
9121 	}
9122 
9123 	return strcmp(sec_name, sec_def->sec) == 0;
9124 }
9125 
9126 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
9127 {
9128 	const struct bpf_sec_def *sec_def;
9129 	int i, n;
9130 
9131 	n = custom_sec_def_cnt;
9132 	for (i = 0; i < n; i++) {
9133 		sec_def = &custom_sec_defs[i];
9134 		if (sec_def_matches(sec_def, sec_name))
9135 			return sec_def;
9136 	}
9137 
9138 	n = ARRAY_SIZE(section_defs);
9139 	for (i = 0; i < n; i++) {
9140 		sec_def = &section_defs[i];
9141 		if (sec_def_matches(sec_def, sec_name))
9142 			return sec_def;
9143 	}
9144 
9145 	if (has_custom_fallback_def)
9146 		return &custom_fallback_def;
9147 
9148 	return NULL;
9149 }
9150 
9151 #define MAX_TYPE_NAME_SIZE 32
9152 
9153 static char *libbpf_get_type_names(bool attach_type)
9154 {
9155 	int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
9156 	char *buf;
9157 
9158 	buf = malloc(len);
9159 	if (!buf)
9160 		return NULL;
9161 
9162 	buf[0] = '\0';
9163 	/* Forge string buf with all available names */
9164 	for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
9165 		const struct bpf_sec_def *sec_def = &section_defs[i];
9166 
9167 		if (attach_type) {
9168 			if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
9169 				continue;
9170 
9171 			if (!(sec_def->cookie & SEC_ATTACHABLE))
9172 				continue;
9173 		}
9174 
9175 		if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
9176 			free(buf);
9177 			return NULL;
9178 		}
9179 		strcat(buf, " ");
9180 		strcat(buf, section_defs[i].sec);
9181 	}
9182 
9183 	return buf;
9184 }
9185 
9186 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
9187 			     enum bpf_attach_type *expected_attach_type)
9188 {
9189 	const struct bpf_sec_def *sec_def;
9190 	char *type_names;
9191 
9192 	if (!name)
9193 		return libbpf_err(-EINVAL);
9194 
9195 	sec_def = find_sec_def(name);
9196 	if (sec_def) {
9197 		*prog_type = sec_def->prog_type;
9198 		*expected_attach_type = sec_def->expected_attach_type;
9199 		return 0;
9200 	}
9201 
9202 	pr_debug("failed to guess program type from ELF section '%s'\n", name);
9203 	type_names = libbpf_get_type_names(false);
9204 	if (type_names != NULL) {
9205 		pr_debug("supported section(type) names are:%s\n", type_names);
9206 		free(type_names);
9207 	}
9208 
9209 	return libbpf_err(-ESRCH);
9210 }
9211 
9212 const char *libbpf_bpf_attach_type_str(enum bpf_attach_type t)
9213 {
9214 	if (t < 0 || t >= ARRAY_SIZE(attach_type_name))
9215 		return NULL;
9216 
9217 	return attach_type_name[t];
9218 }
9219 
9220 const char *libbpf_bpf_link_type_str(enum bpf_link_type t)
9221 {
9222 	if (t < 0 || t >= ARRAY_SIZE(link_type_name))
9223 		return NULL;
9224 
9225 	return link_type_name[t];
9226 }
9227 
9228 const char *libbpf_bpf_map_type_str(enum bpf_map_type t)
9229 {
9230 	if (t < 0 || t >= ARRAY_SIZE(map_type_name))
9231 		return NULL;
9232 
9233 	return map_type_name[t];
9234 }
9235 
9236 const char *libbpf_bpf_prog_type_str(enum bpf_prog_type t)
9237 {
9238 	if (t < 0 || t >= ARRAY_SIZE(prog_type_name))
9239 		return NULL;
9240 
9241 	return prog_type_name[t];
9242 }
9243 
9244 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
9245 						     int sec_idx,
9246 						     size_t offset)
9247 {
9248 	struct bpf_map *map;
9249 	size_t i;
9250 
9251 	for (i = 0; i < obj->nr_maps; i++) {
9252 		map = &obj->maps[i];
9253 		if (!bpf_map__is_struct_ops(map))
9254 			continue;
9255 		if (map->sec_idx == sec_idx &&
9256 		    map->sec_offset <= offset &&
9257 		    offset - map->sec_offset < map->def.value_size)
9258 			return map;
9259 	}
9260 
9261 	return NULL;
9262 }
9263 
9264 /* Collect the reloc from ELF and populate the st_ops->progs[] */
9265 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
9266 					    Elf64_Shdr *shdr, Elf_Data *data)
9267 {
9268 	const struct btf_member *member;
9269 	struct bpf_struct_ops *st_ops;
9270 	struct bpf_program *prog;
9271 	unsigned int shdr_idx;
9272 	const struct btf *btf;
9273 	struct bpf_map *map;
9274 	unsigned int moff, insn_idx;
9275 	const char *name;
9276 	__u32 member_idx;
9277 	Elf64_Sym *sym;
9278 	Elf64_Rel *rel;
9279 	int i, nrels;
9280 
9281 	btf = obj->btf;
9282 	nrels = shdr->sh_size / shdr->sh_entsize;
9283 	for (i = 0; i < nrels; i++) {
9284 		rel = elf_rel_by_idx(data, i);
9285 		if (!rel) {
9286 			pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
9287 			return -LIBBPF_ERRNO__FORMAT;
9288 		}
9289 
9290 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
9291 		if (!sym) {
9292 			pr_warn("struct_ops reloc: symbol %zx not found\n",
9293 				(size_t)ELF64_R_SYM(rel->r_info));
9294 			return -LIBBPF_ERRNO__FORMAT;
9295 		}
9296 
9297 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
9298 		map = find_struct_ops_map_by_offset(obj, shdr->sh_info, rel->r_offset);
9299 		if (!map) {
9300 			pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
9301 				(size_t)rel->r_offset);
9302 			return -EINVAL;
9303 		}
9304 
9305 		moff = rel->r_offset - map->sec_offset;
9306 		shdr_idx = sym->st_shndx;
9307 		st_ops = map->st_ops;
9308 		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",
9309 			 map->name,
9310 			 (long long)(rel->r_info >> 32),
9311 			 (long long)sym->st_value,
9312 			 shdr_idx, (size_t)rel->r_offset,
9313 			 map->sec_offset, sym->st_name, name);
9314 
9315 		if (shdr_idx >= SHN_LORESERVE) {
9316 			pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
9317 				map->name, (size_t)rel->r_offset, shdr_idx);
9318 			return -LIBBPF_ERRNO__RELOC;
9319 		}
9320 		if (sym->st_value % BPF_INSN_SZ) {
9321 			pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
9322 				map->name, (unsigned long long)sym->st_value);
9323 			return -LIBBPF_ERRNO__FORMAT;
9324 		}
9325 		insn_idx = sym->st_value / BPF_INSN_SZ;
9326 
9327 		member = find_member_by_offset(st_ops->type, moff * 8);
9328 		if (!member) {
9329 			pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
9330 				map->name, moff);
9331 			return -EINVAL;
9332 		}
9333 		member_idx = member - btf_members(st_ops->type);
9334 		name = btf__name_by_offset(btf, member->name_off);
9335 
9336 		if (!resolve_func_ptr(btf, member->type, NULL)) {
9337 			pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
9338 				map->name, name);
9339 			return -EINVAL;
9340 		}
9341 
9342 		prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
9343 		if (!prog) {
9344 			pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
9345 				map->name, shdr_idx, name);
9346 			return -EINVAL;
9347 		}
9348 
9349 		/* prevent the use of BPF prog with invalid type */
9350 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
9351 			pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
9352 				map->name, prog->name);
9353 			return -EINVAL;
9354 		}
9355 
9356 		/* if we haven't yet processed this BPF program, record proper
9357 		 * attach_btf_id and member_idx
9358 		 */
9359 		if (!prog->attach_btf_id) {
9360 			prog->attach_btf_id = st_ops->type_id;
9361 			prog->expected_attach_type = member_idx;
9362 		}
9363 
9364 		/* struct_ops BPF prog can be re-used between multiple
9365 		 * .struct_ops & .struct_ops.link as long as it's the
9366 		 * same struct_ops struct definition and the same
9367 		 * function pointer field
9368 		 */
9369 		if (prog->attach_btf_id != st_ops->type_id ||
9370 		    prog->expected_attach_type != member_idx) {
9371 			pr_warn("struct_ops reloc %s: cannot use prog %s in sec %s with type %u attach_btf_id %u expected_attach_type %u for func ptr %s\n",
9372 				map->name, prog->name, prog->sec_name, prog->type,
9373 				prog->attach_btf_id, prog->expected_attach_type, name);
9374 			return -EINVAL;
9375 		}
9376 
9377 		st_ops->progs[member_idx] = prog;
9378 	}
9379 
9380 	return 0;
9381 }
9382 
9383 #define BTF_TRACE_PREFIX "btf_trace_"
9384 #define BTF_LSM_PREFIX "bpf_lsm_"
9385 #define BTF_ITER_PREFIX "bpf_iter_"
9386 #define BTF_MAX_NAME_SIZE 128
9387 
9388 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
9389 				const char **prefix, int *kind)
9390 {
9391 	switch (attach_type) {
9392 	case BPF_TRACE_RAW_TP:
9393 		*prefix = BTF_TRACE_PREFIX;
9394 		*kind = BTF_KIND_TYPEDEF;
9395 		break;
9396 	case BPF_LSM_MAC:
9397 	case BPF_LSM_CGROUP:
9398 		*prefix = BTF_LSM_PREFIX;
9399 		*kind = BTF_KIND_FUNC;
9400 		break;
9401 	case BPF_TRACE_ITER:
9402 		*prefix = BTF_ITER_PREFIX;
9403 		*kind = BTF_KIND_FUNC;
9404 		break;
9405 	default:
9406 		*prefix = "";
9407 		*kind = BTF_KIND_FUNC;
9408 	}
9409 }
9410 
9411 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
9412 				   const char *name, __u32 kind)
9413 {
9414 	char btf_type_name[BTF_MAX_NAME_SIZE];
9415 	int ret;
9416 
9417 	ret = snprintf(btf_type_name, sizeof(btf_type_name),
9418 		       "%s%s", prefix, name);
9419 	/* snprintf returns the number of characters written excluding the
9420 	 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
9421 	 * indicates truncation.
9422 	 */
9423 	if (ret < 0 || ret >= sizeof(btf_type_name))
9424 		return -ENAMETOOLONG;
9425 	return btf__find_by_name_kind(btf, btf_type_name, kind);
9426 }
9427 
9428 static inline int find_attach_btf_id(struct btf *btf, const char *name,
9429 				     enum bpf_attach_type attach_type)
9430 {
9431 	const char *prefix;
9432 	int kind;
9433 
9434 	btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
9435 	return find_btf_by_prefix_kind(btf, prefix, name, kind);
9436 }
9437 
9438 int libbpf_find_vmlinux_btf_id(const char *name,
9439 			       enum bpf_attach_type attach_type)
9440 {
9441 	struct btf *btf;
9442 	int err;
9443 
9444 	btf = btf__load_vmlinux_btf();
9445 	err = libbpf_get_error(btf);
9446 	if (err) {
9447 		pr_warn("vmlinux BTF is not found\n");
9448 		return libbpf_err(err);
9449 	}
9450 
9451 	err = find_attach_btf_id(btf, name, attach_type);
9452 	if (err <= 0)
9453 		pr_warn("%s is not found in vmlinux BTF\n", name);
9454 
9455 	btf__free(btf);
9456 	return libbpf_err(err);
9457 }
9458 
9459 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
9460 {
9461 	struct bpf_prog_info info;
9462 	__u32 info_len = sizeof(info);
9463 	struct btf *btf;
9464 	int err;
9465 
9466 	memset(&info, 0, info_len);
9467 	err = bpf_prog_get_info_by_fd(attach_prog_fd, &info, &info_len);
9468 	if (err) {
9469 		pr_warn("failed bpf_prog_get_info_by_fd for FD %d: %d\n",
9470 			attach_prog_fd, err);
9471 		return err;
9472 	}
9473 
9474 	err = -EINVAL;
9475 	if (!info.btf_id) {
9476 		pr_warn("The target program doesn't have BTF\n");
9477 		goto out;
9478 	}
9479 	btf = btf__load_from_kernel_by_id(info.btf_id);
9480 	err = libbpf_get_error(btf);
9481 	if (err) {
9482 		pr_warn("Failed to get BTF %d of the program: %d\n", info.btf_id, err);
9483 		goto out;
9484 	}
9485 	err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
9486 	btf__free(btf);
9487 	if (err <= 0) {
9488 		pr_warn("%s is not found in prog's BTF\n", name);
9489 		goto out;
9490 	}
9491 out:
9492 	return err;
9493 }
9494 
9495 static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
9496 			      enum bpf_attach_type attach_type,
9497 			      int *btf_obj_fd, int *btf_type_id)
9498 {
9499 	int ret, i;
9500 
9501 	ret = find_attach_btf_id(obj->btf_vmlinux, attach_name, attach_type);
9502 	if (ret > 0) {
9503 		*btf_obj_fd = 0; /* vmlinux BTF */
9504 		*btf_type_id = ret;
9505 		return 0;
9506 	}
9507 	if (ret != -ENOENT)
9508 		return ret;
9509 
9510 	ret = load_module_btfs(obj);
9511 	if (ret)
9512 		return ret;
9513 
9514 	for (i = 0; i < obj->btf_module_cnt; i++) {
9515 		const struct module_btf *mod = &obj->btf_modules[i];
9516 
9517 		ret = find_attach_btf_id(mod->btf, attach_name, attach_type);
9518 		if (ret > 0) {
9519 			*btf_obj_fd = mod->fd;
9520 			*btf_type_id = ret;
9521 			return 0;
9522 		}
9523 		if (ret == -ENOENT)
9524 			continue;
9525 
9526 		return ret;
9527 	}
9528 
9529 	return -ESRCH;
9530 }
9531 
9532 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
9533 				     int *btf_obj_fd, int *btf_type_id)
9534 {
9535 	enum bpf_attach_type attach_type = prog->expected_attach_type;
9536 	__u32 attach_prog_fd = prog->attach_prog_fd;
9537 	int err = 0;
9538 
9539 	/* BPF program's BTF ID */
9540 	if (prog->type == BPF_PROG_TYPE_EXT || attach_prog_fd) {
9541 		if (!attach_prog_fd) {
9542 			pr_warn("prog '%s': attach program FD is not set\n", prog->name);
9543 			return -EINVAL;
9544 		}
9545 		err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd);
9546 		if (err < 0) {
9547 			pr_warn("prog '%s': failed to find BPF program (FD %d) BTF ID for '%s': %d\n",
9548 				 prog->name, attach_prog_fd, attach_name, err);
9549 			return err;
9550 		}
9551 		*btf_obj_fd = 0;
9552 		*btf_type_id = err;
9553 		return 0;
9554 	}
9555 
9556 	/* kernel/module BTF ID */
9557 	if (prog->obj->gen_loader) {
9558 		bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
9559 		*btf_obj_fd = 0;
9560 		*btf_type_id = 1;
9561 	} else {
9562 		err = find_kernel_btf_id(prog->obj, attach_name, attach_type, btf_obj_fd, btf_type_id);
9563 	}
9564 	if (err) {
9565 		pr_warn("prog '%s': failed to find kernel BTF type ID of '%s': %d\n",
9566 			prog->name, attach_name, err);
9567 		return err;
9568 	}
9569 	return 0;
9570 }
9571 
9572 int libbpf_attach_type_by_name(const char *name,
9573 			       enum bpf_attach_type *attach_type)
9574 {
9575 	char *type_names;
9576 	const struct bpf_sec_def *sec_def;
9577 
9578 	if (!name)
9579 		return libbpf_err(-EINVAL);
9580 
9581 	sec_def = find_sec_def(name);
9582 	if (!sec_def) {
9583 		pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
9584 		type_names = libbpf_get_type_names(true);
9585 		if (type_names != NULL) {
9586 			pr_debug("attachable section(type) names are:%s\n", type_names);
9587 			free(type_names);
9588 		}
9589 
9590 		return libbpf_err(-EINVAL);
9591 	}
9592 
9593 	if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
9594 		return libbpf_err(-EINVAL);
9595 	if (!(sec_def->cookie & SEC_ATTACHABLE))
9596 		return libbpf_err(-EINVAL);
9597 
9598 	*attach_type = sec_def->expected_attach_type;
9599 	return 0;
9600 }
9601 
9602 int bpf_map__fd(const struct bpf_map *map)
9603 {
9604 	return map ? map->fd : libbpf_err(-EINVAL);
9605 }
9606 
9607 static bool map_uses_real_name(const struct bpf_map *map)
9608 {
9609 	/* Since libbpf started to support custom .data.* and .rodata.* maps,
9610 	 * their user-visible name differs from kernel-visible name. Users see
9611 	 * such map's corresponding ELF section name as a map name.
9612 	 * This check distinguishes .data/.rodata from .data.* and .rodata.*
9613 	 * maps to know which name has to be returned to the user.
9614 	 */
9615 	if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
9616 		return true;
9617 	if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
9618 		return true;
9619 	return false;
9620 }
9621 
9622 const char *bpf_map__name(const struct bpf_map *map)
9623 {
9624 	if (!map)
9625 		return NULL;
9626 
9627 	if (map_uses_real_name(map))
9628 		return map->real_name;
9629 
9630 	return map->name;
9631 }
9632 
9633 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
9634 {
9635 	return map->def.type;
9636 }
9637 
9638 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
9639 {
9640 	if (map->fd >= 0)
9641 		return libbpf_err(-EBUSY);
9642 	map->def.type = type;
9643 	return 0;
9644 }
9645 
9646 __u32 bpf_map__map_flags(const struct bpf_map *map)
9647 {
9648 	return map->def.map_flags;
9649 }
9650 
9651 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
9652 {
9653 	if (map->fd >= 0)
9654 		return libbpf_err(-EBUSY);
9655 	map->def.map_flags = flags;
9656 	return 0;
9657 }
9658 
9659 __u64 bpf_map__map_extra(const struct bpf_map *map)
9660 {
9661 	return map->map_extra;
9662 }
9663 
9664 int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
9665 {
9666 	if (map->fd >= 0)
9667 		return libbpf_err(-EBUSY);
9668 	map->map_extra = map_extra;
9669 	return 0;
9670 }
9671 
9672 __u32 bpf_map__numa_node(const struct bpf_map *map)
9673 {
9674 	return map->numa_node;
9675 }
9676 
9677 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
9678 {
9679 	if (map->fd >= 0)
9680 		return libbpf_err(-EBUSY);
9681 	map->numa_node = numa_node;
9682 	return 0;
9683 }
9684 
9685 __u32 bpf_map__key_size(const struct bpf_map *map)
9686 {
9687 	return map->def.key_size;
9688 }
9689 
9690 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
9691 {
9692 	if (map->fd >= 0)
9693 		return libbpf_err(-EBUSY);
9694 	map->def.key_size = size;
9695 	return 0;
9696 }
9697 
9698 __u32 bpf_map__value_size(const struct bpf_map *map)
9699 {
9700 	return map->def.value_size;
9701 }
9702 
9703 static int map_btf_datasec_resize(struct bpf_map *map, __u32 size)
9704 {
9705 	struct btf *btf;
9706 	struct btf_type *datasec_type, *var_type;
9707 	struct btf_var_secinfo *var;
9708 	const struct btf_type *array_type;
9709 	const struct btf_array *array;
9710 	int vlen, element_sz, new_array_id;
9711 	__u32 nr_elements;
9712 
9713 	/* check btf existence */
9714 	btf = bpf_object__btf(map->obj);
9715 	if (!btf)
9716 		return -ENOENT;
9717 
9718 	/* verify map is datasec */
9719 	datasec_type = btf_type_by_id(btf, bpf_map__btf_value_type_id(map));
9720 	if (!btf_is_datasec(datasec_type)) {
9721 		pr_warn("map '%s': cannot be resized, map value type is not a datasec\n",
9722 			bpf_map__name(map));
9723 		return -EINVAL;
9724 	}
9725 
9726 	/* verify datasec has at least one var */
9727 	vlen = btf_vlen(datasec_type);
9728 	if (vlen == 0) {
9729 		pr_warn("map '%s': cannot be resized, map value datasec is empty\n",
9730 			bpf_map__name(map));
9731 		return -EINVAL;
9732 	}
9733 
9734 	/* verify last var in the datasec is an array */
9735 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
9736 	var_type = btf_type_by_id(btf, var->type);
9737 	array_type = skip_mods_and_typedefs(btf, var_type->type, NULL);
9738 	if (!btf_is_array(array_type)) {
9739 		pr_warn("map '%s': cannot be resized, last var must be an array\n",
9740 			bpf_map__name(map));
9741 		return -EINVAL;
9742 	}
9743 
9744 	/* verify request size aligns with array */
9745 	array = btf_array(array_type);
9746 	element_sz = btf__resolve_size(btf, array->type);
9747 	if (element_sz <= 0 || (size - var->offset) % element_sz != 0) {
9748 		pr_warn("map '%s': cannot be resized, element size (%d) doesn't align with new total size (%u)\n",
9749 			bpf_map__name(map), element_sz, size);
9750 		return -EINVAL;
9751 	}
9752 
9753 	/* create a new array based on the existing array, but with new length */
9754 	nr_elements = (size - var->offset) / element_sz;
9755 	new_array_id = btf__add_array(btf, array->index_type, array->type, nr_elements);
9756 	if (new_array_id < 0)
9757 		return new_array_id;
9758 
9759 	/* adding a new btf type invalidates existing pointers to btf objects,
9760 	 * so refresh pointers before proceeding
9761 	 */
9762 	datasec_type = btf_type_by_id(btf, map->btf_value_type_id);
9763 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
9764 	var_type = btf_type_by_id(btf, var->type);
9765 
9766 	/* finally update btf info */
9767 	datasec_type->size = size;
9768 	var->size = size - var->offset;
9769 	var_type->type = new_array_id;
9770 
9771 	return 0;
9772 }
9773 
9774 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
9775 {
9776 	if (map->fd >= 0)
9777 		return libbpf_err(-EBUSY);
9778 
9779 	if (map->mmaped) {
9780 		int err;
9781 		size_t mmap_old_sz, mmap_new_sz;
9782 
9783 		mmap_old_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
9784 		mmap_new_sz = bpf_map_mmap_sz(size, map->def.max_entries);
9785 		err = bpf_map_mmap_resize(map, mmap_old_sz, mmap_new_sz);
9786 		if (err) {
9787 			pr_warn("map '%s': failed to resize memory-mapped region: %d\n",
9788 				bpf_map__name(map), err);
9789 			return err;
9790 		}
9791 		err = map_btf_datasec_resize(map, size);
9792 		if (err && err != -ENOENT) {
9793 			pr_warn("map '%s': failed to adjust resized BTF, clearing BTF key/value info: %d\n",
9794 				bpf_map__name(map), err);
9795 			map->btf_value_type_id = 0;
9796 			map->btf_key_type_id = 0;
9797 		}
9798 	}
9799 
9800 	map->def.value_size = size;
9801 	return 0;
9802 }
9803 
9804 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
9805 {
9806 	return map ? map->btf_key_type_id : 0;
9807 }
9808 
9809 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
9810 {
9811 	return map ? map->btf_value_type_id : 0;
9812 }
9813 
9814 int bpf_map__set_initial_value(struct bpf_map *map,
9815 			       const void *data, size_t size)
9816 {
9817 	if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG ||
9818 	    size != map->def.value_size || map->fd >= 0)
9819 		return libbpf_err(-EINVAL);
9820 
9821 	memcpy(map->mmaped, data, size);
9822 	return 0;
9823 }
9824 
9825 void *bpf_map__initial_value(struct bpf_map *map, size_t *psize)
9826 {
9827 	if (!map->mmaped)
9828 		return NULL;
9829 	*psize = map->def.value_size;
9830 	return map->mmaped;
9831 }
9832 
9833 bool bpf_map__is_internal(const struct bpf_map *map)
9834 {
9835 	return map->libbpf_type != LIBBPF_MAP_UNSPEC;
9836 }
9837 
9838 __u32 bpf_map__ifindex(const struct bpf_map *map)
9839 {
9840 	return map->map_ifindex;
9841 }
9842 
9843 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
9844 {
9845 	if (map->fd >= 0)
9846 		return libbpf_err(-EBUSY);
9847 	map->map_ifindex = ifindex;
9848 	return 0;
9849 }
9850 
9851 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
9852 {
9853 	if (!bpf_map_type__is_map_in_map(map->def.type)) {
9854 		pr_warn("error: unsupported map type\n");
9855 		return libbpf_err(-EINVAL);
9856 	}
9857 	if (map->inner_map_fd != -1) {
9858 		pr_warn("error: inner_map_fd already specified\n");
9859 		return libbpf_err(-EINVAL);
9860 	}
9861 	if (map->inner_map) {
9862 		bpf_map__destroy(map->inner_map);
9863 		zfree(&map->inner_map);
9864 	}
9865 	map->inner_map_fd = fd;
9866 	return 0;
9867 }
9868 
9869 static struct bpf_map *
9870 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
9871 {
9872 	ssize_t idx;
9873 	struct bpf_map *s, *e;
9874 
9875 	if (!obj || !obj->maps)
9876 		return errno = EINVAL, NULL;
9877 
9878 	s = obj->maps;
9879 	e = obj->maps + obj->nr_maps;
9880 
9881 	if ((m < s) || (m >= e)) {
9882 		pr_warn("error in %s: map handler doesn't belong to object\n",
9883 			 __func__);
9884 		return errno = EINVAL, NULL;
9885 	}
9886 
9887 	idx = (m - obj->maps) + i;
9888 	if (idx >= obj->nr_maps || idx < 0)
9889 		return NULL;
9890 	return &obj->maps[idx];
9891 }
9892 
9893 struct bpf_map *
9894 bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
9895 {
9896 	if (prev == NULL)
9897 		return obj->maps;
9898 
9899 	return __bpf_map__iter(prev, obj, 1);
9900 }
9901 
9902 struct bpf_map *
9903 bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
9904 {
9905 	if (next == NULL) {
9906 		if (!obj->nr_maps)
9907 			return NULL;
9908 		return obj->maps + obj->nr_maps - 1;
9909 	}
9910 
9911 	return __bpf_map__iter(next, obj, -1);
9912 }
9913 
9914 struct bpf_map *
9915 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
9916 {
9917 	struct bpf_map *pos;
9918 
9919 	bpf_object__for_each_map(pos, obj) {
9920 		/* if it's a special internal map name (which always starts
9921 		 * with dot) then check if that special name matches the
9922 		 * real map name (ELF section name)
9923 		 */
9924 		if (name[0] == '.') {
9925 			if (pos->real_name && strcmp(pos->real_name, name) == 0)
9926 				return pos;
9927 			continue;
9928 		}
9929 		/* otherwise map name has to be an exact match */
9930 		if (map_uses_real_name(pos)) {
9931 			if (strcmp(pos->real_name, name) == 0)
9932 				return pos;
9933 			continue;
9934 		}
9935 		if (strcmp(pos->name, name) == 0)
9936 			return pos;
9937 	}
9938 	return errno = ENOENT, NULL;
9939 }
9940 
9941 int
9942 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
9943 {
9944 	return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
9945 }
9946 
9947 static int validate_map_op(const struct bpf_map *map, size_t key_sz,
9948 			   size_t value_sz, bool check_value_sz)
9949 {
9950 	if (map->fd <= 0)
9951 		return -ENOENT;
9952 
9953 	if (map->def.key_size != key_sz) {
9954 		pr_warn("map '%s': unexpected key size %zu provided, expected %u\n",
9955 			map->name, key_sz, map->def.key_size);
9956 		return -EINVAL;
9957 	}
9958 
9959 	if (!check_value_sz)
9960 		return 0;
9961 
9962 	switch (map->def.type) {
9963 	case BPF_MAP_TYPE_PERCPU_ARRAY:
9964 	case BPF_MAP_TYPE_PERCPU_HASH:
9965 	case BPF_MAP_TYPE_LRU_PERCPU_HASH:
9966 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: {
9967 		int num_cpu = libbpf_num_possible_cpus();
9968 		size_t elem_sz = roundup(map->def.value_size, 8);
9969 
9970 		if (value_sz != num_cpu * elem_sz) {
9971 			pr_warn("map '%s': unexpected value size %zu provided for per-CPU map, expected %d * %zu = %zd\n",
9972 				map->name, value_sz, num_cpu, elem_sz, num_cpu * elem_sz);
9973 			return -EINVAL;
9974 		}
9975 		break;
9976 	}
9977 	default:
9978 		if (map->def.value_size != value_sz) {
9979 			pr_warn("map '%s': unexpected value size %zu provided, expected %u\n",
9980 				map->name, value_sz, map->def.value_size);
9981 			return -EINVAL;
9982 		}
9983 		break;
9984 	}
9985 	return 0;
9986 }
9987 
9988 int bpf_map__lookup_elem(const struct bpf_map *map,
9989 			 const void *key, size_t key_sz,
9990 			 void *value, size_t value_sz, __u64 flags)
9991 {
9992 	int err;
9993 
9994 	err = validate_map_op(map, key_sz, value_sz, true);
9995 	if (err)
9996 		return libbpf_err(err);
9997 
9998 	return bpf_map_lookup_elem_flags(map->fd, key, value, flags);
9999 }
10000 
10001 int bpf_map__update_elem(const struct bpf_map *map,
10002 			 const void *key, size_t key_sz,
10003 			 const void *value, size_t value_sz, __u64 flags)
10004 {
10005 	int err;
10006 
10007 	err = validate_map_op(map, key_sz, value_sz, true);
10008 	if (err)
10009 		return libbpf_err(err);
10010 
10011 	return bpf_map_update_elem(map->fd, key, value, flags);
10012 }
10013 
10014 int bpf_map__delete_elem(const struct bpf_map *map,
10015 			 const void *key, size_t key_sz, __u64 flags)
10016 {
10017 	int err;
10018 
10019 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
10020 	if (err)
10021 		return libbpf_err(err);
10022 
10023 	return bpf_map_delete_elem_flags(map->fd, key, flags);
10024 }
10025 
10026 int bpf_map__lookup_and_delete_elem(const struct bpf_map *map,
10027 				    const void *key, size_t key_sz,
10028 				    void *value, size_t value_sz, __u64 flags)
10029 {
10030 	int err;
10031 
10032 	err = validate_map_op(map, key_sz, value_sz, true);
10033 	if (err)
10034 		return libbpf_err(err);
10035 
10036 	return bpf_map_lookup_and_delete_elem_flags(map->fd, key, value, flags);
10037 }
10038 
10039 int bpf_map__get_next_key(const struct bpf_map *map,
10040 			  const void *cur_key, void *next_key, size_t key_sz)
10041 {
10042 	int err;
10043 
10044 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
10045 	if (err)
10046 		return libbpf_err(err);
10047 
10048 	return bpf_map_get_next_key(map->fd, cur_key, next_key);
10049 }
10050 
10051 long libbpf_get_error(const void *ptr)
10052 {
10053 	if (!IS_ERR_OR_NULL(ptr))
10054 		return 0;
10055 
10056 	if (IS_ERR(ptr))
10057 		errno = -PTR_ERR(ptr);
10058 
10059 	/* If ptr == NULL, then errno should be already set by the failing
10060 	 * API, because libbpf never returns NULL on success and it now always
10061 	 * sets errno on error. So no extra errno handling for ptr == NULL
10062 	 * case.
10063 	 */
10064 	return -errno;
10065 }
10066 
10067 /* Replace link's underlying BPF program with the new one */
10068 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
10069 {
10070 	int ret;
10071 
10072 	ret = bpf_link_update(bpf_link__fd(link), bpf_program__fd(prog), NULL);
10073 	return libbpf_err_errno(ret);
10074 }
10075 
10076 /* Release "ownership" of underlying BPF resource (typically, BPF program
10077  * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
10078  * link, when destructed through bpf_link__destroy() call won't attempt to
10079  * detach/unregisted that BPF resource. This is useful in situations where,
10080  * say, attached BPF program has to outlive userspace program that attached it
10081  * in the system. Depending on type of BPF program, though, there might be
10082  * additional steps (like pinning BPF program in BPF FS) necessary to ensure
10083  * exit of userspace program doesn't trigger automatic detachment and clean up
10084  * inside the kernel.
10085  */
10086 void bpf_link__disconnect(struct bpf_link *link)
10087 {
10088 	link->disconnected = true;
10089 }
10090 
10091 int bpf_link__destroy(struct bpf_link *link)
10092 {
10093 	int err = 0;
10094 
10095 	if (IS_ERR_OR_NULL(link))
10096 		return 0;
10097 
10098 	if (!link->disconnected && link->detach)
10099 		err = link->detach(link);
10100 	if (link->pin_path)
10101 		free(link->pin_path);
10102 	if (link->dealloc)
10103 		link->dealloc(link);
10104 	else
10105 		free(link);
10106 
10107 	return libbpf_err(err);
10108 }
10109 
10110 int bpf_link__fd(const struct bpf_link *link)
10111 {
10112 	return link->fd;
10113 }
10114 
10115 const char *bpf_link__pin_path(const struct bpf_link *link)
10116 {
10117 	return link->pin_path;
10118 }
10119 
10120 static int bpf_link__detach_fd(struct bpf_link *link)
10121 {
10122 	return libbpf_err_errno(close(link->fd));
10123 }
10124 
10125 struct bpf_link *bpf_link__open(const char *path)
10126 {
10127 	struct bpf_link *link;
10128 	int fd;
10129 
10130 	fd = bpf_obj_get(path);
10131 	if (fd < 0) {
10132 		fd = -errno;
10133 		pr_warn("failed to open link at %s: %d\n", path, fd);
10134 		return libbpf_err_ptr(fd);
10135 	}
10136 
10137 	link = calloc(1, sizeof(*link));
10138 	if (!link) {
10139 		close(fd);
10140 		return libbpf_err_ptr(-ENOMEM);
10141 	}
10142 	link->detach = &bpf_link__detach_fd;
10143 	link->fd = fd;
10144 
10145 	link->pin_path = strdup(path);
10146 	if (!link->pin_path) {
10147 		bpf_link__destroy(link);
10148 		return libbpf_err_ptr(-ENOMEM);
10149 	}
10150 
10151 	return link;
10152 }
10153 
10154 int bpf_link__detach(struct bpf_link *link)
10155 {
10156 	return bpf_link_detach(link->fd) ? -errno : 0;
10157 }
10158 
10159 int bpf_link__pin(struct bpf_link *link, const char *path)
10160 {
10161 	int err;
10162 
10163 	if (link->pin_path)
10164 		return libbpf_err(-EBUSY);
10165 	err = make_parent_dir(path);
10166 	if (err)
10167 		return libbpf_err(err);
10168 	err = check_path(path);
10169 	if (err)
10170 		return libbpf_err(err);
10171 
10172 	link->pin_path = strdup(path);
10173 	if (!link->pin_path)
10174 		return libbpf_err(-ENOMEM);
10175 
10176 	if (bpf_obj_pin(link->fd, link->pin_path)) {
10177 		err = -errno;
10178 		zfree(&link->pin_path);
10179 		return libbpf_err(err);
10180 	}
10181 
10182 	pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
10183 	return 0;
10184 }
10185 
10186 int bpf_link__unpin(struct bpf_link *link)
10187 {
10188 	int err;
10189 
10190 	if (!link->pin_path)
10191 		return libbpf_err(-EINVAL);
10192 
10193 	err = unlink(link->pin_path);
10194 	if (err != 0)
10195 		return -errno;
10196 
10197 	pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
10198 	zfree(&link->pin_path);
10199 	return 0;
10200 }
10201 
10202 struct bpf_link_perf {
10203 	struct bpf_link link;
10204 	int perf_event_fd;
10205 	/* legacy kprobe support: keep track of probe identifier and type */
10206 	char *legacy_probe_name;
10207 	bool legacy_is_kprobe;
10208 	bool legacy_is_retprobe;
10209 };
10210 
10211 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
10212 static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
10213 
10214 static int bpf_link_perf_detach(struct bpf_link *link)
10215 {
10216 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10217 	int err = 0;
10218 
10219 	if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
10220 		err = -errno;
10221 
10222 	if (perf_link->perf_event_fd != link->fd)
10223 		close(perf_link->perf_event_fd);
10224 	close(link->fd);
10225 
10226 	/* legacy uprobe/kprobe needs to be removed after perf event fd closure */
10227 	if (perf_link->legacy_probe_name) {
10228 		if (perf_link->legacy_is_kprobe) {
10229 			err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
10230 							 perf_link->legacy_is_retprobe);
10231 		} else {
10232 			err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
10233 							 perf_link->legacy_is_retprobe);
10234 		}
10235 	}
10236 
10237 	return err;
10238 }
10239 
10240 static void bpf_link_perf_dealloc(struct bpf_link *link)
10241 {
10242 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10243 
10244 	free(perf_link->legacy_probe_name);
10245 	free(perf_link);
10246 }
10247 
10248 struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
10249 						     const struct bpf_perf_event_opts *opts)
10250 {
10251 	char errmsg[STRERR_BUFSIZE];
10252 	struct bpf_link_perf *link;
10253 	int prog_fd, link_fd = -1, err;
10254 	bool force_ioctl_attach;
10255 
10256 	if (!OPTS_VALID(opts, bpf_perf_event_opts))
10257 		return libbpf_err_ptr(-EINVAL);
10258 
10259 	if (pfd < 0) {
10260 		pr_warn("prog '%s': invalid perf event FD %d\n",
10261 			prog->name, pfd);
10262 		return libbpf_err_ptr(-EINVAL);
10263 	}
10264 	prog_fd = bpf_program__fd(prog);
10265 	if (prog_fd < 0) {
10266 		pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
10267 			prog->name);
10268 		return libbpf_err_ptr(-EINVAL);
10269 	}
10270 
10271 	link = calloc(1, sizeof(*link));
10272 	if (!link)
10273 		return libbpf_err_ptr(-ENOMEM);
10274 	link->link.detach = &bpf_link_perf_detach;
10275 	link->link.dealloc = &bpf_link_perf_dealloc;
10276 	link->perf_event_fd = pfd;
10277 
10278 	force_ioctl_attach = OPTS_GET(opts, force_ioctl_attach, false);
10279 	if (kernel_supports(prog->obj, FEAT_PERF_LINK) && !force_ioctl_attach) {
10280 		DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
10281 			.perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
10282 
10283 		link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
10284 		if (link_fd < 0) {
10285 			err = -errno;
10286 			pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %d (%s)\n",
10287 				prog->name, pfd,
10288 				err, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10289 			goto err_out;
10290 		}
10291 		link->link.fd = link_fd;
10292 	} else {
10293 		if (OPTS_GET(opts, bpf_cookie, 0)) {
10294 			pr_warn("prog '%s': user context value is not supported\n", prog->name);
10295 			err = -EOPNOTSUPP;
10296 			goto err_out;
10297 		}
10298 
10299 		if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
10300 			err = -errno;
10301 			pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
10302 				prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10303 			if (err == -EPROTO)
10304 				pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
10305 					prog->name, pfd);
10306 			goto err_out;
10307 		}
10308 		link->link.fd = pfd;
10309 	}
10310 	if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
10311 		err = -errno;
10312 		pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
10313 			prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10314 		goto err_out;
10315 	}
10316 
10317 	return &link->link;
10318 err_out:
10319 	if (link_fd >= 0)
10320 		close(link_fd);
10321 	free(link);
10322 	return libbpf_err_ptr(err);
10323 }
10324 
10325 struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
10326 {
10327 	return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
10328 }
10329 
10330 /*
10331  * this function is expected to parse integer in the range of [0, 2^31-1] from
10332  * given file using scanf format string fmt. If actual parsed value is
10333  * negative, the result might be indistinguishable from error
10334  */
10335 static int parse_uint_from_file(const char *file, const char *fmt)
10336 {
10337 	char buf[STRERR_BUFSIZE];
10338 	int err, ret;
10339 	FILE *f;
10340 
10341 	f = fopen(file, "re");
10342 	if (!f) {
10343 		err = -errno;
10344 		pr_debug("failed to open '%s': %s\n", file,
10345 			 libbpf_strerror_r(err, buf, sizeof(buf)));
10346 		return err;
10347 	}
10348 	err = fscanf(f, fmt, &ret);
10349 	if (err != 1) {
10350 		err = err == EOF ? -EIO : -errno;
10351 		pr_debug("failed to parse '%s': %s\n", file,
10352 			libbpf_strerror_r(err, buf, sizeof(buf)));
10353 		fclose(f);
10354 		return err;
10355 	}
10356 	fclose(f);
10357 	return ret;
10358 }
10359 
10360 static int determine_kprobe_perf_type(void)
10361 {
10362 	const char *file = "/sys/bus/event_source/devices/kprobe/type";
10363 
10364 	return parse_uint_from_file(file, "%d\n");
10365 }
10366 
10367 static int determine_uprobe_perf_type(void)
10368 {
10369 	const char *file = "/sys/bus/event_source/devices/uprobe/type";
10370 
10371 	return parse_uint_from_file(file, "%d\n");
10372 }
10373 
10374 static int determine_kprobe_retprobe_bit(void)
10375 {
10376 	const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
10377 
10378 	return parse_uint_from_file(file, "config:%d\n");
10379 }
10380 
10381 static int determine_uprobe_retprobe_bit(void)
10382 {
10383 	const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
10384 
10385 	return parse_uint_from_file(file, "config:%d\n");
10386 }
10387 
10388 #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
10389 #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
10390 
10391 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
10392 				 uint64_t offset, int pid, size_t ref_ctr_off)
10393 {
10394 	const size_t attr_sz = sizeof(struct perf_event_attr);
10395 	struct perf_event_attr attr;
10396 	char errmsg[STRERR_BUFSIZE];
10397 	int type, pfd;
10398 
10399 	if ((__u64)ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
10400 		return -EINVAL;
10401 
10402 	memset(&attr, 0, attr_sz);
10403 
10404 	type = uprobe ? determine_uprobe_perf_type()
10405 		      : determine_kprobe_perf_type();
10406 	if (type < 0) {
10407 		pr_warn("failed to determine %s perf type: %s\n",
10408 			uprobe ? "uprobe" : "kprobe",
10409 			libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
10410 		return type;
10411 	}
10412 	if (retprobe) {
10413 		int bit = uprobe ? determine_uprobe_retprobe_bit()
10414 				 : determine_kprobe_retprobe_bit();
10415 
10416 		if (bit < 0) {
10417 			pr_warn("failed to determine %s retprobe bit: %s\n",
10418 				uprobe ? "uprobe" : "kprobe",
10419 				libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
10420 			return bit;
10421 		}
10422 		attr.config |= 1 << bit;
10423 	}
10424 	attr.size = attr_sz;
10425 	attr.type = type;
10426 	attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
10427 	attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
10428 	attr.config2 = offset;		 /* kprobe_addr or probe_offset */
10429 
10430 	/* pid filter is meaningful only for uprobes */
10431 	pfd = syscall(__NR_perf_event_open, &attr,
10432 		      pid < 0 ? -1 : pid /* pid */,
10433 		      pid == -1 ? 0 : -1 /* cpu */,
10434 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
10435 	return pfd >= 0 ? pfd : -errno;
10436 }
10437 
10438 static int append_to_file(const char *file, const char *fmt, ...)
10439 {
10440 	int fd, n, err = 0;
10441 	va_list ap;
10442 	char buf[1024];
10443 
10444 	va_start(ap, fmt);
10445 	n = vsnprintf(buf, sizeof(buf), fmt, ap);
10446 	va_end(ap);
10447 
10448 	if (n < 0 || n >= sizeof(buf))
10449 		return -EINVAL;
10450 
10451 	fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
10452 	if (fd < 0)
10453 		return -errno;
10454 
10455 	if (write(fd, buf, n) < 0)
10456 		err = -errno;
10457 
10458 	close(fd);
10459 	return err;
10460 }
10461 
10462 #define DEBUGFS "/sys/kernel/debug/tracing"
10463 #define TRACEFS "/sys/kernel/tracing"
10464 
10465 static bool use_debugfs(void)
10466 {
10467 	static int has_debugfs = -1;
10468 
10469 	if (has_debugfs < 0)
10470 		has_debugfs = faccessat(AT_FDCWD, DEBUGFS, F_OK, AT_EACCESS) == 0;
10471 
10472 	return has_debugfs == 1;
10473 }
10474 
10475 static const char *tracefs_path(void)
10476 {
10477 	return use_debugfs() ? DEBUGFS : TRACEFS;
10478 }
10479 
10480 static const char *tracefs_kprobe_events(void)
10481 {
10482 	return use_debugfs() ? DEBUGFS"/kprobe_events" : TRACEFS"/kprobe_events";
10483 }
10484 
10485 static const char *tracefs_uprobe_events(void)
10486 {
10487 	return use_debugfs() ? DEBUGFS"/uprobe_events" : TRACEFS"/uprobe_events";
10488 }
10489 
10490 static const char *tracefs_available_filter_functions(void)
10491 {
10492 	return use_debugfs() ? DEBUGFS"/available_filter_functions"
10493 			     : TRACEFS"/available_filter_functions";
10494 }
10495 
10496 static const char *tracefs_available_filter_functions_addrs(void)
10497 {
10498 	return use_debugfs() ? DEBUGFS"/available_filter_functions_addrs"
10499 			     : TRACEFS"/available_filter_functions_addrs";
10500 }
10501 
10502 static void gen_kprobe_legacy_event_name(char *buf, size_t buf_sz,
10503 					 const char *kfunc_name, size_t offset)
10504 {
10505 	static int index = 0;
10506 	int i;
10507 
10508 	snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx_%d", getpid(), kfunc_name, offset,
10509 		 __sync_fetch_and_add(&index, 1));
10510 
10511 	/* sanitize binary_path in the probe name */
10512 	for (i = 0; buf[i]; i++) {
10513 		if (!isalnum(buf[i]))
10514 			buf[i] = '_';
10515 	}
10516 }
10517 
10518 static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
10519 				   const char *kfunc_name, size_t offset)
10520 {
10521 	return append_to_file(tracefs_kprobe_events(), "%c:%s/%s %s+0x%zx",
10522 			      retprobe ? 'r' : 'p',
10523 			      retprobe ? "kretprobes" : "kprobes",
10524 			      probe_name, kfunc_name, offset);
10525 }
10526 
10527 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
10528 {
10529 	return append_to_file(tracefs_kprobe_events(), "-:%s/%s",
10530 			      retprobe ? "kretprobes" : "kprobes", probe_name);
10531 }
10532 
10533 static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
10534 {
10535 	char file[256];
10536 
10537 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
10538 		 tracefs_path(), retprobe ? "kretprobes" : "kprobes", probe_name);
10539 
10540 	return parse_uint_from_file(file, "%d\n");
10541 }
10542 
10543 static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
10544 					 const char *kfunc_name, size_t offset, int pid)
10545 {
10546 	const size_t attr_sz = sizeof(struct perf_event_attr);
10547 	struct perf_event_attr attr;
10548 	char errmsg[STRERR_BUFSIZE];
10549 	int type, pfd, err;
10550 
10551 	err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
10552 	if (err < 0) {
10553 		pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
10554 			kfunc_name, offset,
10555 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10556 		return err;
10557 	}
10558 	type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
10559 	if (type < 0) {
10560 		err = type;
10561 		pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
10562 			kfunc_name, offset,
10563 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10564 		goto err_clean_legacy;
10565 	}
10566 
10567 	memset(&attr, 0, attr_sz);
10568 	attr.size = attr_sz;
10569 	attr.config = type;
10570 	attr.type = PERF_TYPE_TRACEPOINT;
10571 
10572 	pfd = syscall(__NR_perf_event_open, &attr,
10573 		      pid < 0 ? -1 : pid, /* pid */
10574 		      pid == -1 ? 0 : -1, /* cpu */
10575 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
10576 	if (pfd < 0) {
10577 		err = -errno;
10578 		pr_warn("legacy kprobe perf_event_open() failed: %s\n",
10579 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10580 		goto err_clean_legacy;
10581 	}
10582 	return pfd;
10583 
10584 err_clean_legacy:
10585 	/* Clear the newly added legacy kprobe_event */
10586 	remove_kprobe_event_legacy(probe_name, retprobe);
10587 	return err;
10588 }
10589 
10590 static const char *arch_specific_syscall_pfx(void)
10591 {
10592 #if defined(__x86_64__)
10593 	return "x64";
10594 #elif defined(__i386__)
10595 	return "ia32";
10596 #elif defined(__s390x__)
10597 	return "s390x";
10598 #elif defined(__s390__)
10599 	return "s390";
10600 #elif defined(__arm__)
10601 	return "arm";
10602 #elif defined(__aarch64__)
10603 	return "arm64";
10604 #elif defined(__mips__)
10605 	return "mips";
10606 #elif defined(__riscv)
10607 	return "riscv";
10608 #elif defined(__powerpc__)
10609 	return "powerpc";
10610 #elif defined(__powerpc64__)
10611 	return "powerpc64";
10612 #else
10613 	return NULL;
10614 #endif
10615 }
10616 
10617 static int probe_kern_syscall_wrapper(void)
10618 {
10619 	char syscall_name[64];
10620 	const char *ksys_pfx;
10621 
10622 	ksys_pfx = arch_specific_syscall_pfx();
10623 	if (!ksys_pfx)
10624 		return 0;
10625 
10626 	snprintf(syscall_name, sizeof(syscall_name), "__%s_sys_bpf", ksys_pfx);
10627 
10628 	if (determine_kprobe_perf_type() >= 0) {
10629 		int pfd;
10630 
10631 		pfd = perf_event_open_probe(false, false, syscall_name, 0, getpid(), 0);
10632 		if (pfd >= 0)
10633 			close(pfd);
10634 
10635 		return pfd >= 0 ? 1 : 0;
10636 	} else { /* legacy mode */
10637 		char probe_name[128];
10638 
10639 		gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name), syscall_name, 0);
10640 		if (add_kprobe_event_legacy(probe_name, false, syscall_name, 0) < 0)
10641 			return 0;
10642 
10643 		(void)remove_kprobe_event_legacy(probe_name, false);
10644 		return 1;
10645 	}
10646 }
10647 
10648 struct bpf_link *
10649 bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
10650 				const char *func_name,
10651 				const struct bpf_kprobe_opts *opts)
10652 {
10653 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
10654 	enum probe_attach_mode attach_mode;
10655 	char errmsg[STRERR_BUFSIZE];
10656 	char *legacy_probe = NULL;
10657 	struct bpf_link *link;
10658 	size_t offset;
10659 	bool retprobe, legacy;
10660 	int pfd, err;
10661 
10662 	if (!OPTS_VALID(opts, bpf_kprobe_opts))
10663 		return libbpf_err_ptr(-EINVAL);
10664 
10665 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
10666 	retprobe = OPTS_GET(opts, retprobe, false);
10667 	offset = OPTS_GET(opts, offset, 0);
10668 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10669 
10670 	legacy = determine_kprobe_perf_type() < 0;
10671 	switch (attach_mode) {
10672 	case PROBE_ATTACH_MODE_LEGACY:
10673 		legacy = true;
10674 		pe_opts.force_ioctl_attach = true;
10675 		break;
10676 	case PROBE_ATTACH_MODE_PERF:
10677 		if (legacy)
10678 			return libbpf_err_ptr(-ENOTSUP);
10679 		pe_opts.force_ioctl_attach = true;
10680 		break;
10681 	case PROBE_ATTACH_MODE_LINK:
10682 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
10683 			return libbpf_err_ptr(-ENOTSUP);
10684 		break;
10685 	case PROBE_ATTACH_MODE_DEFAULT:
10686 		break;
10687 	default:
10688 		return libbpf_err_ptr(-EINVAL);
10689 	}
10690 
10691 	if (!legacy) {
10692 		pfd = perf_event_open_probe(false /* uprobe */, retprobe,
10693 					    func_name, offset,
10694 					    -1 /* pid */, 0 /* ref_ctr_off */);
10695 	} else {
10696 		char probe_name[256];
10697 
10698 		gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name),
10699 					     func_name, offset);
10700 
10701 		legacy_probe = strdup(probe_name);
10702 		if (!legacy_probe)
10703 			return libbpf_err_ptr(-ENOMEM);
10704 
10705 		pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
10706 						    offset, -1 /* pid */);
10707 	}
10708 	if (pfd < 0) {
10709 		err = -errno;
10710 		pr_warn("prog '%s': failed to create %s '%s+0x%zx' perf event: %s\n",
10711 			prog->name, retprobe ? "kretprobe" : "kprobe",
10712 			func_name, offset,
10713 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10714 		goto err_out;
10715 	}
10716 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
10717 	err = libbpf_get_error(link);
10718 	if (err) {
10719 		close(pfd);
10720 		pr_warn("prog '%s': failed to attach to %s '%s+0x%zx': %s\n",
10721 			prog->name, retprobe ? "kretprobe" : "kprobe",
10722 			func_name, offset,
10723 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10724 		goto err_clean_legacy;
10725 	}
10726 	if (legacy) {
10727 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10728 
10729 		perf_link->legacy_probe_name = legacy_probe;
10730 		perf_link->legacy_is_kprobe = true;
10731 		perf_link->legacy_is_retprobe = retprobe;
10732 	}
10733 
10734 	return link;
10735 
10736 err_clean_legacy:
10737 	if (legacy)
10738 		remove_kprobe_event_legacy(legacy_probe, retprobe);
10739 err_out:
10740 	free(legacy_probe);
10741 	return libbpf_err_ptr(err);
10742 }
10743 
10744 struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
10745 					    bool retprobe,
10746 					    const char *func_name)
10747 {
10748 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
10749 		.retprobe = retprobe,
10750 	);
10751 
10752 	return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
10753 }
10754 
10755 struct bpf_link *bpf_program__attach_ksyscall(const struct bpf_program *prog,
10756 					      const char *syscall_name,
10757 					      const struct bpf_ksyscall_opts *opts)
10758 {
10759 	LIBBPF_OPTS(bpf_kprobe_opts, kprobe_opts);
10760 	char func_name[128];
10761 
10762 	if (!OPTS_VALID(opts, bpf_ksyscall_opts))
10763 		return libbpf_err_ptr(-EINVAL);
10764 
10765 	if (kernel_supports(prog->obj, FEAT_SYSCALL_WRAPPER)) {
10766 		/* arch_specific_syscall_pfx() should never return NULL here
10767 		 * because it is guarded by kernel_supports(). However, since
10768 		 * compiler does not know that we have an explicit conditional
10769 		 * as well.
10770 		 */
10771 		snprintf(func_name, sizeof(func_name), "__%s_sys_%s",
10772 			 arch_specific_syscall_pfx() ? : "", syscall_name);
10773 	} else {
10774 		snprintf(func_name, sizeof(func_name), "__se_sys_%s", syscall_name);
10775 	}
10776 
10777 	kprobe_opts.retprobe = OPTS_GET(opts, retprobe, false);
10778 	kprobe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10779 
10780 	return bpf_program__attach_kprobe_opts(prog, func_name, &kprobe_opts);
10781 }
10782 
10783 /* Adapted from perf/util/string.c */
10784 bool glob_match(const char *str, const char *pat)
10785 {
10786 	while (*str && *pat && *pat != '*') {
10787 		if (*pat == '?') {      /* Matches any single character */
10788 			str++;
10789 			pat++;
10790 			continue;
10791 		}
10792 		if (*str != *pat)
10793 			return false;
10794 		str++;
10795 		pat++;
10796 	}
10797 	/* Check wild card */
10798 	if (*pat == '*') {
10799 		while (*pat == '*')
10800 			pat++;
10801 		if (!*pat) /* Tail wild card matches all */
10802 			return true;
10803 		while (*str)
10804 			if (glob_match(str++, pat))
10805 				return true;
10806 	}
10807 	return !*str && !*pat;
10808 }
10809 
10810 struct kprobe_multi_resolve {
10811 	const char *pattern;
10812 	unsigned long *addrs;
10813 	size_t cap;
10814 	size_t cnt;
10815 };
10816 
10817 struct avail_kallsyms_data {
10818 	char **syms;
10819 	size_t cnt;
10820 	struct kprobe_multi_resolve *res;
10821 };
10822 
10823 static int avail_func_cmp(const void *a, const void *b)
10824 {
10825 	return strcmp(*(const char **)a, *(const char **)b);
10826 }
10827 
10828 static int avail_kallsyms_cb(unsigned long long sym_addr, char sym_type,
10829 			     const char *sym_name, void *ctx)
10830 {
10831 	struct avail_kallsyms_data *data = ctx;
10832 	struct kprobe_multi_resolve *res = data->res;
10833 	int err;
10834 
10835 	if (!bsearch(&sym_name, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp))
10836 		return 0;
10837 
10838 	err = libbpf_ensure_mem((void **)&res->addrs, &res->cap, sizeof(*res->addrs), res->cnt + 1);
10839 	if (err)
10840 		return err;
10841 
10842 	res->addrs[res->cnt++] = (unsigned long)sym_addr;
10843 	return 0;
10844 }
10845 
10846 static int libbpf_available_kallsyms_parse(struct kprobe_multi_resolve *res)
10847 {
10848 	const char *available_functions_file = tracefs_available_filter_functions();
10849 	struct avail_kallsyms_data data;
10850 	char sym_name[500];
10851 	FILE *f;
10852 	int err = 0, ret, i;
10853 	char **syms = NULL;
10854 	size_t cap = 0, cnt = 0;
10855 
10856 	f = fopen(available_functions_file, "re");
10857 	if (!f) {
10858 		err = -errno;
10859 		pr_warn("failed to open %s: %d\n", available_functions_file, err);
10860 		return err;
10861 	}
10862 
10863 	while (true) {
10864 		char *name;
10865 
10866 		ret = fscanf(f, "%499s%*[^\n]\n", sym_name);
10867 		if (ret == EOF && feof(f))
10868 			break;
10869 
10870 		if (ret != 1) {
10871 			pr_warn("failed to parse available_filter_functions entry: %d\n", ret);
10872 			err = -EINVAL;
10873 			goto cleanup;
10874 		}
10875 
10876 		if (!glob_match(sym_name, res->pattern))
10877 			continue;
10878 
10879 		err = libbpf_ensure_mem((void **)&syms, &cap, sizeof(*syms), cnt + 1);
10880 		if (err)
10881 			goto cleanup;
10882 
10883 		name = strdup(sym_name);
10884 		if (!name) {
10885 			err = -errno;
10886 			goto cleanup;
10887 		}
10888 
10889 		syms[cnt++] = name;
10890 	}
10891 
10892 	/* no entries found, bail out */
10893 	if (cnt == 0) {
10894 		err = -ENOENT;
10895 		goto cleanup;
10896 	}
10897 
10898 	/* sort available functions */
10899 	qsort(syms, cnt, sizeof(*syms), avail_func_cmp);
10900 
10901 	data.syms = syms;
10902 	data.res = res;
10903 	data.cnt = cnt;
10904 	libbpf_kallsyms_parse(avail_kallsyms_cb, &data);
10905 
10906 	if (res->cnt == 0)
10907 		err = -ENOENT;
10908 
10909 cleanup:
10910 	for (i = 0; i < cnt; i++)
10911 		free((char *)syms[i]);
10912 	free(syms);
10913 
10914 	fclose(f);
10915 	return err;
10916 }
10917 
10918 static bool has_available_filter_functions_addrs(void)
10919 {
10920 	return access(tracefs_available_filter_functions_addrs(), R_OK) != -1;
10921 }
10922 
10923 static int libbpf_available_kprobes_parse(struct kprobe_multi_resolve *res)
10924 {
10925 	const char *available_path = tracefs_available_filter_functions_addrs();
10926 	char sym_name[500];
10927 	FILE *f;
10928 	int ret, err = 0;
10929 	unsigned long long sym_addr;
10930 
10931 	f = fopen(available_path, "re");
10932 	if (!f) {
10933 		err = -errno;
10934 		pr_warn("failed to open %s: %d\n", available_path, err);
10935 		return err;
10936 	}
10937 
10938 	while (true) {
10939 		ret = fscanf(f, "%llx %499s%*[^\n]\n", &sym_addr, sym_name);
10940 		if (ret == EOF && feof(f))
10941 			break;
10942 
10943 		if (ret != 2) {
10944 			pr_warn("failed to parse available_filter_functions_addrs entry: %d\n",
10945 				ret);
10946 			err = -EINVAL;
10947 			goto cleanup;
10948 		}
10949 
10950 		if (!glob_match(sym_name, res->pattern))
10951 			continue;
10952 
10953 		err = libbpf_ensure_mem((void **)&res->addrs, &res->cap,
10954 					sizeof(*res->addrs), res->cnt + 1);
10955 		if (err)
10956 			goto cleanup;
10957 
10958 		res->addrs[res->cnt++] = (unsigned long)sym_addr;
10959 	}
10960 
10961 	if (res->cnt == 0)
10962 		err = -ENOENT;
10963 
10964 cleanup:
10965 	fclose(f);
10966 	return err;
10967 }
10968 
10969 struct bpf_link *
10970 bpf_program__attach_kprobe_multi_opts(const struct bpf_program *prog,
10971 				      const char *pattern,
10972 				      const struct bpf_kprobe_multi_opts *opts)
10973 {
10974 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
10975 	struct kprobe_multi_resolve res = {
10976 		.pattern = pattern,
10977 	};
10978 	struct bpf_link *link = NULL;
10979 	char errmsg[STRERR_BUFSIZE];
10980 	const unsigned long *addrs;
10981 	int err, link_fd, prog_fd;
10982 	const __u64 *cookies;
10983 	const char **syms;
10984 	bool retprobe;
10985 	size_t cnt;
10986 
10987 	if (!OPTS_VALID(opts, bpf_kprobe_multi_opts))
10988 		return libbpf_err_ptr(-EINVAL);
10989 
10990 	syms    = OPTS_GET(opts, syms, false);
10991 	addrs   = OPTS_GET(opts, addrs, false);
10992 	cnt     = OPTS_GET(opts, cnt, false);
10993 	cookies = OPTS_GET(opts, cookies, false);
10994 
10995 	if (!pattern && !addrs && !syms)
10996 		return libbpf_err_ptr(-EINVAL);
10997 	if (pattern && (addrs || syms || cookies || cnt))
10998 		return libbpf_err_ptr(-EINVAL);
10999 	if (!pattern && !cnt)
11000 		return libbpf_err_ptr(-EINVAL);
11001 	if (addrs && syms)
11002 		return libbpf_err_ptr(-EINVAL);
11003 
11004 	if (pattern) {
11005 		if (has_available_filter_functions_addrs())
11006 			err = libbpf_available_kprobes_parse(&res);
11007 		else
11008 			err = libbpf_available_kallsyms_parse(&res);
11009 		if (err)
11010 			goto error;
11011 		addrs = res.addrs;
11012 		cnt = res.cnt;
11013 	}
11014 
11015 	retprobe = OPTS_GET(opts, retprobe, false);
11016 
11017 	lopts.kprobe_multi.syms = syms;
11018 	lopts.kprobe_multi.addrs = addrs;
11019 	lopts.kprobe_multi.cookies = cookies;
11020 	lopts.kprobe_multi.cnt = cnt;
11021 	lopts.kprobe_multi.flags = retprobe ? BPF_F_KPROBE_MULTI_RETURN : 0;
11022 
11023 	link = calloc(1, sizeof(*link));
11024 	if (!link) {
11025 		err = -ENOMEM;
11026 		goto error;
11027 	}
11028 	link->detach = &bpf_link__detach_fd;
11029 
11030 	prog_fd = bpf_program__fd(prog);
11031 	link_fd = bpf_link_create(prog_fd, 0, BPF_TRACE_KPROBE_MULTI, &lopts);
11032 	if (link_fd < 0) {
11033 		err = -errno;
11034 		pr_warn("prog '%s': failed to attach: %s\n",
11035 			prog->name, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11036 		goto error;
11037 	}
11038 	link->fd = link_fd;
11039 	free(res.addrs);
11040 	return link;
11041 
11042 error:
11043 	free(link);
11044 	free(res.addrs);
11045 	return libbpf_err_ptr(err);
11046 }
11047 
11048 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11049 {
11050 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
11051 	unsigned long offset = 0;
11052 	const char *func_name;
11053 	char *func;
11054 	int n;
11055 
11056 	*link = NULL;
11057 
11058 	/* no auto-attach for SEC("kprobe") and SEC("kretprobe") */
11059 	if (strcmp(prog->sec_name, "kprobe") == 0 || strcmp(prog->sec_name, "kretprobe") == 0)
11060 		return 0;
11061 
11062 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
11063 	if (opts.retprobe)
11064 		func_name = prog->sec_name + sizeof("kretprobe/") - 1;
11065 	else
11066 		func_name = prog->sec_name + sizeof("kprobe/") - 1;
11067 
11068 	n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
11069 	if (n < 1) {
11070 		pr_warn("kprobe name is invalid: %s\n", func_name);
11071 		return -EINVAL;
11072 	}
11073 	if (opts.retprobe && offset != 0) {
11074 		free(func);
11075 		pr_warn("kretprobes do not support offset specification\n");
11076 		return -EINVAL;
11077 	}
11078 
11079 	opts.offset = offset;
11080 	*link = bpf_program__attach_kprobe_opts(prog, func, &opts);
11081 	free(func);
11082 	return libbpf_get_error(*link);
11083 }
11084 
11085 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11086 {
11087 	LIBBPF_OPTS(bpf_ksyscall_opts, opts);
11088 	const char *syscall_name;
11089 
11090 	*link = NULL;
11091 
11092 	/* no auto-attach for SEC("ksyscall") and SEC("kretsyscall") */
11093 	if (strcmp(prog->sec_name, "ksyscall") == 0 || strcmp(prog->sec_name, "kretsyscall") == 0)
11094 		return 0;
11095 
11096 	opts.retprobe = str_has_pfx(prog->sec_name, "kretsyscall/");
11097 	if (opts.retprobe)
11098 		syscall_name = prog->sec_name + sizeof("kretsyscall/") - 1;
11099 	else
11100 		syscall_name = prog->sec_name + sizeof("ksyscall/") - 1;
11101 
11102 	*link = bpf_program__attach_ksyscall(prog, syscall_name, &opts);
11103 	return *link ? 0 : -errno;
11104 }
11105 
11106 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11107 {
11108 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts);
11109 	const char *spec;
11110 	char *pattern;
11111 	int n;
11112 
11113 	*link = NULL;
11114 
11115 	/* no auto-attach for SEC("kprobe.multi") and SEC("kretprobe.multi") */
11116 	if (strcmp(prog->sec_name, "kprobe.multi") == 0 ||
11117 	    strcmp(prog->sec_name, "kretprobe.multi") == 0)
11118 		return 0;
11119 
11120 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe.multi/");
11121 	if (opts.retprobe)
11122 		spec = prog->sec_name + sizeof("kretprobe.multi/") - 1;
11123 	else
11124 		spec = prog->sec_name + sizeof("kprobe.multi/") - 1;
11125 
11126 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
11127 	if (n < 1) {
11128 		pr_warn("kprobe multi pattern is invalid: %s\n", pattern);
11129 		return -EINVAL;
11130 	}
11131 
11132 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
11133 	free(pattern);
11134 	return libbpf_get_error(*link);
11135 }
11136 
11137 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11138 {
11139 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
11140 	LIBBPF_OPTS(bpf_uprobe_multi_opts, opts);
11141 	int n, ret = -EINVAL;
11142 
11143 	*link = NULL;
11144 
11145 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
11146 		   &probe_type, &binary_path, &func_name);
11147 	switch (n) {
11148 	case 1:
11149 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
11150 		ret = 0;
11151 		break;
11152 	case 3:
11153 		opts.retprobe = strcmp(probe_type, "uretprobe.multi") == 0;
11154 		*link = bpf_program__attach_uprobe_multi(prog, -1, binary_path, func_name, &opts);
11155 		ret = libbpf_get_error(*link);
11156 		break;
11157 	default:
11158 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
11159 			prog->sec_name);
11160 		break;
11161 	}
11162 	free(probe_type);
11163 	free(binary_path);
11164 	free(func_name);
11165 	return ret;
11166 }
11167 
11168 static void gen_uprobe_legacy_event_name(char *buf, size_t buf_sz,
11169 					 const char *binary_path, uint64_t offset)
11170 {
11171 	int i;
11172 
11173 	snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx", getpid(), binary_path, (size_t)offset);
11174 
11175 	/* sanitize binary_path in the probe name */
11176 	for (i = 0; buf[i]; i++) {
11177 		if (!isalnum(buf[i]))
11178 			buf[i] = '_';
11179 	}
11180 }
11181 
11182 static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
11183 					  const char *binary_path, size_t offset)
11184 {
11185 	return append_to_file(tracefs_uprobe_events(), "%c:%s/%s %s:0x%zx",
11186 			      retprobe ? 'r' : 'p',
11187 			      retprobe ? "uretprobes" : "uprobes",
11188 			      probe_name, binary_path, offset);
11189 }
11190 
11191 static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
11192 {
11193 	return append_to_file(tracefs_uprobe_events(), "-:%s/%s",
11194 			      retprobe ? "uretprobes" : "uprobes", probe_name);
11195 }
11196 
11197 static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
11198 {
11199 	char file[512];
11200 
11201 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11202 		 tracefs_path(), retprobe ? "uretprobes" : "uprobes", probe_name);
11203 
11204 	return parse_uint_from_file(file, "%d\n");
11205 }
11206 
11207 static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
11208 					 const char *binary_path, size_t offset, int pid)
11209 {
11210 	const size_t attr_sz = sizeof(struct perf_event_attr);
11211 	struct perf_event_attr attr;
11212 	int type, pfd, err;
11213 
11214 	err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
11215 	if (err < 0) {
11216 		pr_warn("failed to add legacy uprobe event for %s:0x%zx: %d\n",
11217 			binary_path, (size_t)offset, err);
11218 		return err;
11219 	}
11220 	type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
11221 	if (type < 0) {
11222 		err = type;
11223 		pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %d\n",
11224 			binary_path, offset, err);
11225 		goto err_clean_legacy;
11226 	}
11227 
11228 	memset(&attr, 0, attr_sz);
11229 	attr.size = attr_sz;
11230 	attr.config = type;
11231 	attr.type = PERF_TYPE_TRACEPOINT;
11232 
11233 	pfd = syscall(__NR_perf_event_open, &attr,
11234 		      pid < 0 ? -1 : pid, /* pid */
11235 		      pid == -1 ? 0 : -1, /* cpu */
11236 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
11237 	if (pfd < 0) {
11238 		err = -errno;
11239 		pr_warn("legacy uprobe perf_event_open() failed: %d\n", err);
11240 		goto err_clean_legacy;
11241 	}
11242 	return pfd;
11243 
11244 err_clean_legacy:
11245 	/* Clear the newly added legacy uprobe_event */
11246 	remove_uprobe_event_legacy(probe_name, retprobe);
11247 	return err;
11248 }
11249 
11250 /* Find offset of function name in archive specified by path. Currently
11251  * supported are .zip files that do not compress their contents, as used on
11252  * Android in the form of APKs, for example. "file_name" is the name of the ELF
11253  * file inside the archive. "func_name" matches symbol name or name@@LIB for
11254  * library functions.
11255  *
11256  * An overview of the APK format specifically provided here:
11257  * https://en.wikipedia.org/w/index.php?title=Apk_(file_format)&oldid=1139099120#Package_contents
11258  */
11259 static long elf_find_func_offset_from_archive(const char *archive_path, const char *file_name,
11260 					      const char *func_name)
11261 {
11262 	struct zip_archive *archive;
11263 	struct zip_entry entry;
11264 	long ret;
11265 	Elf *elf;
11266 
11267 	archive = zip_archive_open(archive_path);
11268 	if (IS_ERR(archive)) {
11269 		ret = PTR_ERR(archive);
11270 		pr_warn("zip: failed to open %s: %ld\n", archive_path, ret);
11271 		return ret;
11272 	}
11273 
11274 	ret = zip_archive_find_entry(archive, file_name, &entry);
11275 	if (ret) {
11276 		pr_warn("zip: could not find archive member %s in %s: %ld\n", file_name,
11277 			archive_path, ret);
11278 		goto out;
11279 	}
11280 	pr_debug("zip: found entry for %s in %s at 0x%lx\n", file_name, archive_path,
11281 		 (unsigned long)entry.data_offset);
11282 
11283 	if (entry.compression) {
11284 		pr_warn("zip: entry %s of %s is compressed and cannot be handled\n", file_name,
11285 			archive_path);
11286 		ret = -LIBBPF_ERRNO__FORMAT;
11287 		goto out;
11288 	}
11289 
11290 	elf = elf_memory((void *)entry.data, entry.data_length);
11291 	if (!elf) {
11292 		pr_warn("elf: could not read elf file %s from %s: %s\n", file_name, archive_path,
11293 			elf_errmsg(-1));
11294 		ret = -LIBBPF_ERRNO__LIBELF;
11295 		goto out;
11296 	}
11297 
11298 	ret = elf_find_func_offset(elf, file_name, func_name);
11299 	if (ret > 0) {
11300 		pr_debug("elf: symbol address match for %s of %s in %s: 0x%x + 0x%lx = 0x%lx\n",
11301 			 func_name, file_name, archive_path, entry.data_offset, ret,
11302 			 ret + entry.data_offset);
11303 		ret += entry.data_offset;
11304 	}
11305 	elf_end(elf);
11306 
11307 out:
11308 	zip_archive_close(archive);
11309 	return ret;
11310 }
11311 
11312 static const char *arch_specific_lib_paths(void)
11313 {
11314 	/*
11315 	 * Based on https://packages.debian.org/sid/libc6.
11316 	 *
11317 	 * Assume that the traced program is built for the same architecture
11318 	 * as libbpf, which should cover the vast majority of cases.
11319 	 */
11320 #if defined(__x86_64__)
11321 	return "/lib/x86_64-linux-gnu";
11322 #elif defined(__i386__)
11323 	return "/lib/i386-linux-gnu";
11324 #elif defined(__s390x__)
11325 	return "/lib/s390x-linux-gnu";
11326 #elif defined(__s390__)
11327 	return "/lib/s390-linux-gnu";
11328 #elif defined(__arm__) && defined(__SOFTFP__)
11329 	return "/lib/arm-linux-gnueabi";
11330 #elif defined(__arm__) && !defined(__SOFTFP__)
11331 	return "/lib/arm-linux-gnueabihf";
11332 #elif defined(__aarch64__)
11333 	return "/lib/aarch64-linux-gnu";
11334 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 64
11335 	return "/lib/mips64el-linux-gnuabi64";
11336 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 32
11337 	return "/lib/mipsel-linux-gnu";
11338 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
11339 	return "/lib/powerpc64le-linux-gnu";
11340 #elif defined(__sparc__) && defined(__arch64__)
11341 	return "/lib/sparc64-linux-gnu";
11342 #elif defined(__riscv) && __riscv_xlen == 64
11343 	return "/lib/riscv64-linux-gnu";
11344 #else
11345 	return NULL;
11346 #endif
11347 }
11348 
11349 /* Get full path to program/shared library. */
11350 static int resolve_full_path(const char *file, char *result, size_t result_sz)
11351 {
11352 	const char *search_paths[3] = {};
11353 	int i, perm;
11354 
11355 	if (str_has_sfx(file, ".so") || strstr(file, ".so.")) {
11356 		search_paths[0] = getenv("LD_LIBRARY_PATH");
11357 		search_paths[1] = "/usr/lib64:/usr/lib";
11358 		search_paths[2] = arch_specific_lib_paths();
11359 		perm = R_OK;
11360 	} else {
11361 		search_paths[0] = getenv("PATH");
11362 		search_paths[1] = "/usr/bin:/usr/sbin";
11363 		perm = R_OK | X_OK;
11364 	}
11365 
11366 	for (i = 0; i < ARRAY_SIZE(search_paths); i++) {
11367 		const char *s;
11368 
11369 		if (!search_paths[i])
11370 			continue;
11371 		for (s = search_paths[i]; s != NULL; s = strchr(s, ':')) {
11372 			char *next_path;
11373 			int seg_len;
11374 
11375 			if (s[0] == ':')
11376 				s++;
11377 			next_path = strchr(s, ':');
11378 			seg_len = next_path ? next_path - s : strlen(s);
11379 			if (!seg_len)
11380 				continue;
11381 			snprintf(result, result_sz, "%.*s/%s", seg_len, s, file);
11382 			/* ensure it has required permissions */
11383 			if (faccessat(AT_FDCWD, result, perm, AT_EACCESS) < 0)
11384 				continue;
11385 			pr_debug("resolved '%s' to '%s'\n", file, result);
11386 			return 0;
11387 		}
11388 	}
11389 	return -ENOENT;
11390 }
11391 
11392 struct bpf_link *
11393 bpf_program__attach_uprobe_multi(const struct bpf_program *prog,
11394 				 pid_t pid,
11395 				 const char *path,
11396 				 const char *func_pattern,
11397 				 const struct bpf_uprobe_multi_opts *opts)
11398 {
11399 	const unsigned long *ref_ctr_offsets = NULL, *offsets = NULL;
11400 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
11401 	unsigned long *resolved_offsets = NULL;
11402 	int err = 0, link_fd, prog_fd;
11403 	struct bpf_link *link = NULL;
11404 	char errmsg[STRERR_BUFSIZE];
11405 	char full_path[PATH_MAX];
11406 	const __u64 *cookies;
11407 	const char **syms;
11408 	size_t cnt;
11409 
11410 	if (!OPTS_VALID(opts, bpf_uprobe_multi_opts))
11411 		return libbpf_err_ptr(-EINVAL);
11412 
11413 	syms = OPTS_GET(opts, syms, NULL);
11414 	offsets = OPTS_GET(opts, offsets, NULL);
11415 	ref_ctr_offsets = OPTS_GET(opts, ref_ctr_offsets, NULL);
11416 	cookies = OPTS_GET(opts, cookies, NULL);
11417 	cnt = OPTS_GET(opts, cnt, 0);
11418 
11419 	/*
11420 	 * User can specify 2 mutually exclusive set of inputs:
11421 	 *
11422 	 * 1) use only path/func_pattern/pid arguments
11423 	 *
11424 	 * 2) use path/pid with allowed combinations of:
11425 	 *    syms/offsets/ref_ctr_offsets/cookies/cnt
11426 	 *
11427 	 *    - syms and offsets are mutually exclusive
11428 	 *    - ref_ctr_offsets and cookies are optional
11429 	 *
11430 	 * Any other usage results in error.
11431 	 */
11432 
11433 	if (!path)
11434 		return libbpf_err_ptr(-EINVAL);
11435 	if (!func_pattern && cnt == 0)
11436 		return libbpf_err_ptr(-EINVAL);
11437 
11438 	if (func_pattern) {
11439 		if (syms || offsets || ref_ctr_offsets || cookies || cnt)
11440 			return libbpf_err_ptr(-EINVAL);
11441 	} else {
11442 		if (!!syms == !!offsets)
11443 			return libbpf_err_ptr(-EINVAL);
11444 	}
11445 
11446 	if (func_pattern) {
11447 		if (!strchr(path, '/')) {
11448 			err = resolve_full_path(path, full_path, sizeof(full_path));
11449 			if (err) {
11450 				pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11451 					prog->name, path, err);
11452 				return libbpf_err_ptr(err);
11453 			}
11454 			path = full_path;
11455 		}
11456 
11457 		err = elf_resolve_pattern_offsets(path, func_pattern,
11458 						  &resolved_offsets, &cnt);
11459 		if (err < 0)
11460 			return libbpf_err_ptr(err);
11461 		offsets = resolved_offsets;
11462 	} else if (syms) {
11463 		err = elf_resolve_syms_offsets(path, cnt, syms, &resolved_offsets, STT_FUNC);
11464 		if (err < 0)
11465 			return libbpf_err_ptr(err);
11466 		offsets = resolved_offsets;
11467 	}
11468 
11469 	lopts.uprobe_multi.path = path;
11470 	lopts.uprobe_multi.offsets = offsets;
11471 	lopts.uprobe_multi.ref_ctr_offsets = ref_ctr_offsets;
11472 	lopts.uprobe_multi.cookies = cookies;
11473 	lopts.uprobe_multi.cnt = cnt;
11474 	lopts.uprobe_multi.flags = OPTS_GET(opts, retprobe, false) ? BPF_F_UPROBE_MULTI_RETURN : 0;
11475 
11476 	if (pid == 0)
11477 		pid = getpid();
11478 	if (pid > 0)
11479 		lopts.uprobe_multi.pid = pid;
11480 
11481 	link = calloc(1, sizeof(*link));
11482 	if (!link) {
11483 		err = -ENOMEM;
11484 		goto error;
11485 	}
11486 	link->detach = &bpf_link__detach_fd;
11487 
11488 	prog_fd = bpf_program__fd(prog);
11489 	link_fd = bpf_link_create(prog_fd, 0, BPF_TRACE_UPROBE_MULTI, &lopts);
11490 	if (link_fd < 0) {
11491 		err = -errno;
11492 		pr_warn("prog '%s': failed to attach multi-uprobe: %s\n",
11493 			prog->name, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11494 		goto error;
11495 	}
11496 	link->fd = link_fd;
11497 	free(resolved_offsets);
11498 	return link;
11499 
11500 error:
11501 	free(resolved_offsets);
11502 	free(link);
11503 	return libbpf_err_ptr(err);
11504 }
11505 
11506 LIBBPF_API struct bpf_link *
11507 bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
11508 				const char *binary_path, size_t func_offset,
11509 				const struct bpf_uprobe_opts *opts)
11510 {
11511 	const char *archive_path = NULL, *archive_sep = NULL;
11512 	char errmsg[STRERR_BUFSIZE], *legacy_probe = NULL;
11513 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11514 	enum probe_attach_mode attach_mode;
11515 	char full_path[PATH_MAX];
11516 	struct bpf_link *link;
11517 	size_t ref_ctr_off;
11518 	int pfd, err;
11519 	bool retprobe, legacy;
11520 	const char *func_name;
11521 
11522 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
11523 		return libbpf_err_ptr(-EINVAL);
11524 
11525 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
11526 	retprobe = OPTS_GET(opts, retprobe, false);
11527 	ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
11528 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11529 
11530 	if (!binary_path)
11531 		return libbpf_err_ptr(-EINVAL);
11532 
11533 	/* Check if "binary_path" refers to an archive. */
11534 	archive_sep = strstr(binary_path, "!/");
11535 	if (archive_sep) {
11536 		full_path[0] = '\0';
11537 		libbpf_strlcpy(full_path, binary_path,
11538 			       min(sizeof(full_path), (size_t)(archive_sep - binary_path + 1)));
11539 		archive_path = full_path;
11540 		binary_path = archive_sep + 2;
11541 	} else if (!strchr(binary_path, '/')) {
11542 		err = resolve_full_path(binary_path, full_path, sizeof(full_path));
11543 		if (err) {
11544 			pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11545 				prog->name, binary_path, err);
11546 			return libbpf_err_ptr(err);
11547 		}
11548 		binary_path = full_path;
11549 	}
11550 	func_name = OPTS_GET(opts, func_name, NULL);
11551 	if (func_name) {
11552 		long sym_off;
11553 
11554 		if (archive_path) {
11555 			sym_off = elf_find_func_offset_from_archive(archive_path, binary_path,
11556 								    func_name);
11557 			binary_path = archive_path;
11558 		} else {
11559 			sym_off = elf_find_func_offset_from_file(binary_path, func_name);
11560 		}
11561 		if (sym_off < 0)
11562 			return libbpf_err_ptr(sym_off);
11563 		func_offset += sym_off;
11564 	}
11565 
11566 	legacy = determine_uprobe_perf_type() < 0;
11567 	switch (attach_mode) {
11568 	case PROBE_ATTACH_MODE_LEGACY:
11569 		legacy = true;
11570 		pe_opts.force_ioctl_attach = true;
11571 		break;
11572 	case PROBE_ATTACH_MODE_PERF:
11573 		if (legacy)
11574 			return libbpf_err_ptr(-ENOTSUP);
11575 		pe_opts.force_ioctl_attach = true;
11576 		break;
11577 	case PROBE_ATTACH_MODE_LINK:
11578 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
11579 			return libbpf_err_ptr(-ENOTSUP);
11580 		break;
11581 	case PROBE_ATTACH_MODE_DEFAULT:
11582 		break;
11583 	default:
11584 		return libbpf_err_ptr(-EINVAL);
11585 	}
11586 
11587 	if (!legacy) {
11588 		pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
11589 					    func_offset, pid, ref_ctr_off);
11590 	} else {
11591 		char probe_name[PATH_MAX + 64];
11592 
11593 		if (ref_ctr_off)
11594 			return libbpf_err_ptr(-EINVAL);
11595 
11596 		gen_uprobe_legacy_event_name(probe_name, sizeof(probe_name),
11597 					     binary_path, func_offset);
11598 
11599 		legacy_probe = strdup(probe_name);
11600 		if (!legacy_probe)
11601 			return libbpf_err_ptr(-ENOMEM);
11602 
11603 		pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
11604 						    binary_path, func_offset, pid);
11605 	}
11606 	if (pfd < 0) {
11607 		err = -errno;
11608 		pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
11609 			prog->name, retprobe ? "uretprobe" : "uprobe",
11610 			binary_path, func_offset,
11611 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11612 		goto err_out;
11613 	}
11614 
11615 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11616 	err = libbpf_get_error(link);
11617 	if (err) {
11618 		close(pfd);
11619 		pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
11620 			prog->name, retprobe ? "uretprobe" : "uprobe",
11621 			binary_path, func_offset,
11622 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11623 		goto err_clean_legacy;
11624 	}
11625 	if (legacy) {
11626 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
11627 
11628 		perf_link->legacy_probe_name = legacy_probe;
11629 		perf_link->legacy_is_kprobe = false;
11630 		perf_link->legacy_is_retprobe = retprobe;
11631 	}
11632 	return link;
11633 
11634 err_clean_legacy:
11635 	if (legacy)
11636 		remove_uprobe_event_legacy(legacy_probe, retprobe);
11637 err_out:
11638 	free(legacy_probe);
11639 	return libbpf_err_ptr(err);
11640 }
11641 
11642 /* Format of u[ret]probe section definition supporting auto-attach:
11643  * u[ret]probe/binary:function[+offset]
11644  *
11645  * binary can be an absolute/relative path or a filename; the latter is resolved to a
11646  * full binary path via bpf_program__attach_uprobe_opts.
11647  *
11648  * Specifying uprobe+ ensures we carry out strict matching; either "uprobe" must be
11649  * specified (and auto-attach is not possible) or the above format is specified for
11650  * auto-attach.
11651  */
11652 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11653 {
11654 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts);
11655 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL, *func_off;
11656 	int n, c, ret = -EINVAL;
11657 	long offset = 0;
11658 
11659 	*link = NULL;
11660 
11661 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
11662 		   &probe_type, &binary_path, &func_name);
11663 	switch (n) {
11664 	case 1:
11665 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
11666 		ret = 0;
11667 		break;
11668 	case 2:
11669 		pr_warn("prog '%s': section '%s' missing ':function[+offset]' specification\n",
11670 			prog->name, prog->sec_name);
11671 		break;
11672 	case 3:
11673 		/* check if user specifies `+offset`, if yes, this should be
11674 		 * the last part of the string, make sure sscanf read to EOL
11675 		 */
11676 		func_off = strrchr(func_name, '+');
11677 		if (func_off) {
11678 			n = sscanf(func_off, "+%li%n", &offset, &c);
11679 			if (n == 1 && *(func_off + c) == '\0')
11680 				func_off[0] = '\0';
11681 			else
11682 				offset = 0;
11683 		}
11684 		opts.retprobe = strcmp(probe_type, "uretprobe") == 0 ||
11685 				strcmp(probe_type, "uretprobe.s") == 0;
11686 		if (opts.retprobe && offset != 0) {
11687 			pr_warn("prog '%s': uretprobes do not support offset specification\n",
11688 				prog->name);
11689 			break;
11690 		}
11691 		opts.func_name = func_name;
11692 		*link = bpf_program__attach_uprobe_opts(prog, -1, binary_path, offset, &opts);
11693 		ret = libbpf_get_error(*link);
11694 		break;
11695 	default:
11696 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
11697 			prog->sec_name);
11698 		break;
11699 	}
11700 	free(probe_type);
11701 	free(binary_path);
11702 	free(func_name);
11703 
11704 	return ret;
11705 }
11706 
11707 struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
11708 					    bool retprobe, pid_t pid,
11709 					    const char *binary_path,
11710 					    size_t func_offset)
11711 {
11712 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
11713 
11714 	return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
11715 }
11716 
11717 struct bpf_link *bpf_program__attach_usdt(const struct bpf_program *prog,
11718 					  pid_t pid, const char *binary_path,
11719 					  const char *usdt_provider, const char *usdt_name,
11720 					  const struct bpf_usdt_opts *opts)
11721 {
11722 	char resolved_path[512];
11723 	struct bpf_object *obj = prog->obj;
11724 	struct bpf_link *link;
11725 	__u64 usdt_cookie;
11726 	int err;
11727 
11728 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
11729 		return libbpf_err_ptr(-EINVAL);
11730 
11731 	if (bpf_program__fd(prog) < 0) {
11732 		pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
11733 			prog->name);
11734 		return libbpf_err_ptr(-EINVAL);
11735 	}
11736 
11737 	if (!binary_path)
11738 		return libbpf_err_ptr(-EINVAL);
11739 
11740 	if (!strchr(binary_path, '/')) {
11741 		err = resolve_full_path(binary_path, resolved_path, sizeof(resolved_path));
11742 		if (err) {
11743 			pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11744 				prog->name, binary_path, err);
11745 			return libbpf_err_ptr(err);
11746 		}
11747 		binary_path = resolved_path;
11748 	}
11749 
11750 	/* USDT manager is instantiated lazily on first USDT attach. It will
11751 	 * be destroyed together with BPF object in bpf_object__close().
11752 	 */
11753 	if (IS_ERR(obj->usdt_man))
11754 		return libbpf_ptr(obj->usdt_man);
11755 	if (!obj->usdt_man) {
11756 		obj->usdt_man = usdt_manager_new(obj);
11757 		if (IS_ERR(obj->usdt_man))
11758 			return libbpf_ptr(obj->usdt_man);
11759 	}
11760 
11761 	usdt_cookie = OPTS_GET(opts, usdt_cookie, 0);
11762 	link = usdt_manager_attach_usdt(obj->usdt_man, prog, pid, binary_path,
11763 					usdt_provider, usdt_name, usdt_cookie);
11764 	err = libbpf_get_error(link);
11765 	if (err)
11766 		return libbpf_err_ptr(err);
11767 	return link;
11768 }
11769 
11770 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11771 {
11772 	char *path = NULL, *provider = NULL, *name = NULL;
11773 	const char *sec_name;
11774 	int n, err;
11775 
11776 	sec_name = bpf_program__section_name(prog);
11777 	if (strcmp(sec_name, "usdt") == 0) {
11778 		/* no auto-attach for just SEC("usdt") */
11779 		*link = NULL;
11780 		return 0;
11781 	}
11782 
11783 	n = sscanf(sec_name, "usdt/%m[^:]:%m[^:]:%m[^:]", &path, &provider, &name);
11784 	if (n != 3) {
11785 		pr_warn("invalid section '%s', expected SEC(\"usdt/<path>:<provider>:<name>\")\n",
11786 			sec_name);
11787 		err = -EINVAL;
11788 	} else {
11789 		*link = bpf_program__attach_usdt(prog, -1 /* any process */, path,
11790 						 provider, name, NULL);
11791 		err = libbpf_get_error(*link);
11792 	}
11793 	free(path);
11794 	free(provider);
11795 	free(name);
11796 	return err;
11797 }
11798 
11799 static int determine_tracepoint_id(const char *tp_category,
11800 				   const char *tp_name)
11801 {
11802 	char file[PATH_MAX];
11803 	int ret;
11804 
11805 	ret = snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11806 		       tracefs_path(), tp_category, tp_name);
11807 	if (ret < 0)
11808 		return -errno;
11809 	if (ret >= sizeof(file)) {
11810 		pr_debug("tracepoint %s/%s path is too long\n",
11811 			 tp_category, tp_name);
11812 		return -E2BIG;
11813 	}
11814 	return parse_uint_from_file(file, "%d\n");
11815 }
11816 
11817 static int perf_event_open_tracepoint(const char *tp_category,
11818 				      const char *tp_name)
11819 {
11820 	const size_t attr_sz = sizeof(struct perf_event_attr);
11821 	struct perf_event_attr attr;
11822 	char errmsg[STRERR_BUFSIZE];
11823 	int tp_id, pfd, err;
11824 
11825 	tp_id = determine_tracepoint_id(tp_category, tp_name);
11826 	if (tp_id < 0) {
11827 		pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
11828 			tp_category, tp_name,
11829 			libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
11830 		return tp_id;
11831 	}
11832 
11833 	memset(&attr, 0, attr_sz);
11834 	attr.type = PERF_TYPE_TRACEPOINT;
11835 	attr.size = attr_sz;
11836 	attr.config = tp_id;
11837 
11838 	pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
11839 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
11840 	if (pfd < 0) {
11841 		err = -errno;
11842 		pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
11843 			tp_category, tp_name,
11844 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11845 		return err;
11846 	}
11847 	return pfd;
11848 }
11849 
11850 struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
11851 						     const char *tp_category,
11852 						     const char *tp_name,
11853 						     const struct bpf_tracepoint_opts *opts)
11854 {
11855 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11856 	char errmsg[STRERR_BUFSIZE];
11857 	struct bpf_link *link;
11858 	int pfd, err;
11859 
11860 	if (!OPTS_VALID(opts, bpf_tracepoint_opts))
11861 		return libbpf_err_ptr(-EINVAL);
11862 
11863 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11864 
11865 	pfd = perf_event_open_tracepoint(tp_category, tp_name);
11866 	if (pfd < 0) {
11867 		pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
11868 			prog->name, tp_category, tp_name,
11869 			libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11870 		return libbpf_err_ptr(pfd);
11871 	}
11872 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11873 	err = libbpf_get_error(link);
11874 	if (err) {
11875 		close(pfd);
11876 		pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
11877 			prog->name, tp_category, tp_name,
11878 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11879 		return libbpf_err_ptr(err);
11880 	}
11881 	return link;
11882 }
11883 
11884 struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
11885 						const char *tp_category,
11886 						const char *tp_name)
11887 {
11888 	return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
11889 }
11890 
11891 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11892 {
11893 	char *sec_name, *tp_cat, *tp_name;
11894 
11895 	*link = NULL;
11896 
11897 	/* no auto-attach for SEC("tp") or SEC("tracepoint") */
11898 	if (strcmp(prog->sec_name, "tp") == 0 || strcmp(prog->sec_name, "tracepoint") == 0)
11899 		return 0;
11900 
11901 	sec_name = strdup(prog->sec_name);
11902 	if (!sec_name)
11903 		return -ENOMEM;
11904 
11905 	/* extract "tp/<category>/<name>" or "tracepoint/<category>/<name>" */
11906 	if (str_has_pfx(prog->sec_name, "tp/"))
11907 		tp_cat = sec_name + sizeof("tp/") - 1;
11908 	else
11909 		tp_cat = sec_name + sizeof("tracepoint/") - 1;
11910 	tp_name = strchr(tp_cat, '/');
11911 	if (!tp_name) {
11912 		free(sec_name);
11913 		return -EINVAL;
11914 	}
11915 	*tp_name = '\0';
11916 	tp_name++;
11917 
11918 	*link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
11919 	free(sec_name);
11920 	return libbpf_get_error(*link);
11921 }
11922 
11923 struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
11924 						    const char *tp_name)
11925 {
11926 	char errmsg[STRERR_BUFSIZE];
11927 	struct bpf_link *link;
11928 	int prog_fd, pfd;
11929 
11930 	prog_fd = bpf_program__fd(prog);
11931 	if (prog_fd < 0) {
11932 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11933 		return libbpf_err_ptr(-EINVAL);
11934 	}
11935 
11936 	link = calloc(1, sizeof(*link));
11937 	if (!link)
11938 		return libbpf_err_ptr(-ENOMEM);
11939 	link->detach = &bpf_link__detach_fd;
11940 
11941 	pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
11942 	if (pfd < 0) {
11943 		pfd = -errno;
11944 		free(link);
11945 		pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
11946 			prog->name, tp_name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11947 		return libbpf_err_ptr(pfd);
11948 	}
11949 	link->fd = pfd;
11950 	return link;
11951 }
11952 
11953 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11954 {
11955 	static const char *const prefixes[] = {
11956 		"raw_tp",
11957 		"raw_tracepoint",
11958 		"raw_tp.w",
11959 		"raw_tracepoint.w",
11960 	};
11961 	size_t i;
11962 	const char *tp_name = NULL;
11963 
11964 	*link = NULL;
11965 
11966 	for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
11967 		size_t pfx_len;
11968 
11969 		if (!str_has_pfx(prog->sec_name, prefixes[i]))
11970 			continue;
11971 
11972 		pfx_len = strlen(prefixes[i]);
11973 		/* no auto-attach case of, e.g., SEC("raw_tp") */
11974 		if (prog->sec_name[pfx_len] == '\0')
11975 			return 0;
11976 
11977 		if (prog->sec_name[pfx_len] != '/')
11978 			continue;
11979 
11980 		tp_name = prog->sec_name + pfx_len + 1;
11981 		break;
11982 	}
11983 
11984 	if (!tp_name) {
11985 		pr_warn("prog '%s': invalid section name '%s'\n",
11986 			prog->name, prog->sec_name);
11987 		return -EINVAL;
11988 	}
11989 
11990 	*link = bpf_program__attach_raw_tracepoint(prog, tp_name);
11991 	return libbpf_get_error(*link);
11992 }
11993 
11994 /* Common logic for all BPF program types that attach to a btf_id */
11995 static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog,
11996 						   const struct bpf_trace_opts *opts)
11997 {
11998 	LIBBPF_OPTS(bpf_link_create_opts, link_opts);
11999 	char errmsg[STRERR_BUFSIZE];
12000 	struct bpf_link *link;
12001 	int prog_fd, pfd;
12002 
12003 	if (!OPTS_VALID(opts, bpf_trace_opts))
12004 		return libbpf_err_ptr(-EINVAL);
12005 
12006 	prog_fd = bpf_program__fd(prog);
12007 	if (prog_fd < 0) {
12008 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12009 		return libbpf_err_ptr(-EINVAL);
12010 	}
12011 
12012 	link = calloc(1, sizeof(*link));
12013 	if (!link)
12014 		return libbpf_err_ptr(-ENOMEM);
12015 	link->detach = &bpf_link__detach_fd;
12016 
12017 	/* libbpf is smart enough to redirect to BPF_RAW_TRACEPOINT_OPEN on old kernels */
12018 	link_opts.tracing.cookie = OPTS_GET(opts, cookie, 0);
12019 	pfd = bpf_link_create(prog_fd, 0, bpf_program__expected_attach_type(prog), &link_opts);
12020 	if (pfd < 0) {
12021 		pfd = -errno;
12022 		free(link);
12023 		pr_warn("prog '%s': failed to attach: %s\n",
12024 			prog->name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
12025 		return libbpf_err_ptr(pfd);
12026 	}
12027 	link->fd = pfd;
12028 	return link;
12029 }
12030 
12031 struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
12032 {
12033 	return bpf_program__attach_btf_id(prog, NULL);
12034 }
12035 
12036 struct bpf_link *bpf_program__attach_trace_opts(const struct bpf_program *prog,
12037 						const struct bpf_trace_opts *opts)
12038 {
12039 	return bpf_program__attach_btf_id(prog, opts);
12040 }
12041 
12042 struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
12043 {
12044 	return bpf_program__attach_btf_id(prog, NULL);
12045 }
12046 
12047 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12048 {
12049 	*link = bpf_program__attach_trace(prog);
12050 	return libbpf_get_error(*link);
12051 }
12052 
12053 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12054 {
12055 	*link = bpf_program__attach_lsm(prog);
12056 	return libbpf_get_error(*link);
12057 }
12058 
12059 static struct bpf_link *
12060 bpf_program_attach_fd(const struct bpf_program *prog,
12061 		      int target_fd, const char *target_name,
12062 		      const struct bpf_link_create_opts *opts)
12063 {
12064 	enum bpf_attach_type attach_type;
12065 	char errmsg[STRERR_BUFSIZE];
12066 	struct bpf_link *link;
12067 	int prog_fd, link_fd;
12068 
12069 	prog_fd = bpf_program__fd(prog);
12070 	if (prog_fd < 0) {
12071 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12072 		return libbpf_err_ptr(-EINVAL);
12073 	}
12074 
12075 	link = calloc(1, sizeof(*link));
12076 	if (!link)
12077 		return libbpf_err_ptr(-ENOMEM);
12078 	link->detach = &bpf_link__detach_fd;
12079 
12080 	attach_type = bpf_program__expected_attach_type(prog);
12081 	link_fd = bpf_link_create(prog_fd, target_fd, attach_type, opts);
12082 	if (link_fd < 0) {
12083 		link_fd = -errno;
12084 		free(link);
12085 		pr_warn("prog '%s': failed to attach to %s: %s\n",
12086 			prog->name, target_name,
12087 			libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
12088 		return libbpf_err_ptr(link_fd);
12089 	}
12090 	link->fd = link_fd;
12091 	return link;
12092 }
12093 
12094 struct bpf_link *
12095 bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
12096 {
12097 	return bpf_program_attach_fd(prog, cgroup_fd, "cgroup", NULL);
12098 }
12099 
12100 struct bpf_link *
12101 bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
12102 {
12103 	return bpf_program_attach_fd(prog, netns_fd, "netns", NULL);
12104 }
12105 
12106 struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
12107 {
12108 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
12109 	return bpf_program_attach_fd(prog, ifindex, "xdp", NULL);
12110 }
12111 
12112 struct bpf_link *
12113 bpf_program__attach_tcx(const struct bpf_program *prog, int ifindex,
12114 			const struct bpf_tcx_opts *opts)
12115 {
12116 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12117 	__u32 relative_id;
12118 	int relative_fd;
12119 
12120 	if (!OPTS_VALID(opts, bpf_tcx_opts))
12121 		return libbpf_err_ptr(-EINVAL);
12122 
12123 	relative_id = OPTS_GET(opts, relative_id, 0);
12124 	relative_fd = OPTS_GET(opts, relative_fd, 0);
12125 
12126 	/* validate we don't have unexpected combinations of non-zero fields */
12127 	if (!ifindex) {
12128 		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
12129 			prog->name);
12130 		return libbpf_err_ptr(-EINVAL);
12131 	}
12132 	if (relative_fd && relative_id) {
12133 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
12134 			prog->name);
12135 		return libbpf_err_ptr(-EINVAL);
12136 	}
12137 
12138 	link_create_opts.tcx.expected_revision = OPTS_GET(opts, expected_revision, 0);
12139 	link_create_opts.tcx.relative_fd = relative_fd;
12140 	link_create_opts.tcx.relative_id = relative_id;
12141 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
12142 
12143 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
12144 	return bpf_program_attach_fd(prog, ifindex, "tcx", &link_create_opts);
12145 }
12146 
12147 struct bpf_link *
12148 bpf_program__attach_netkit(const struct bpf_program *prog, int ifindex,
12149 			   const struct bpf_netkit_opts *opts)
12150 {
12151 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12152 	__u32 relative_id;
12153 	int relative_fd;
12154 
12155 	if (!OPTS_VALID(opts, bpf_netkit_opts))
12156 		return libbpf_err_ptr(-EINVAL);
12157 
12158 	relative_id = OPTS_GET(opts, relative_id, 0);
12159 	relative_fd = OPTS_GET(opts, relative_fd, 0);
12160 
12161 	/* validate we don't have unexpected combinations of non-zero fields */
12162 	if (!ifindex) {
12163 		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
12164 			prog->name);
12165 		return libbpf_err_ptr(-EINVAL);
12166 	}
12167 	if (relative_fd && relative_id) {
12168 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
12169 			prog->name);
12170 		return libbpf_err_ptr(-EINVAL);
12171 	}
12172 
12173 	link_create_opts.netkit.expected_revision = OPTS_GET(opts, expected_revision, 0);
12174 	link_create_opts.netkit.relative_fd = relative_fd;
12175 	link_create_opts.netkit.relative_id = relative_id;
12176 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
12177 
12178 	return bpf_program_attach_fd(prog, ifindex, "netkit", &link_create_opts);
12179 }
12180 
12181 struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
12182 					      int target_fd,
12183 					      const char *attach_func_name)
12184 {
12185 	int btf_id;
12186 
12187 	if (!!target_fd != !!attach_func_name) {
12188 		pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
12189 			prog->name);
12190 		return libbpf_err_ptr(-EINVAL);
12191 	}
12192 
12193 	if (prog->type != BPF_PROG_TYPE_EXT) {
12194 		pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace",
12195 			prog->name);
12196 		return libbpf_err_ptr(-EINVAL);
12197 	}
12198 
12199 	if (target_fd) {
12200 		LIBBPF_OPTS(bpf_link_create_opts, target_opts);
12201 
12202 		btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd);
12203 		if (btf_id < 0)
12204 			return libbpf_err_ptr(btf_id);
12205 
12206 		target_opts.target_btf_id = btf_id;
12207 
12208 		return bpf_program_attach_fd(prog, target_fd, "freplace",
12209 					     &target_opts);
12210 	} else {
12211 		/* no target, so use raw_tracepoint_open for compatibility
12212 		 * with old kernels
12213 		 */
12214 		return bpf_program__attach_trace(prog);
12215 	}
12216 }
12217 
12218 struct bpf_link *
12219 bpf_program__attach_iter(const struct bpf_program *prog,
12220 			 const struct bpf_iter_attach_opts *opts)
12221 {
12222 	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12223 	char errmsg[STRERR_BUFSIZE];
12224 	struct bpf_link *link;
12225 	int prog_fd, link_fd;
12226 	__u32 target_fd = 0;
12227 
12228 	if (!OPTS_VALID(opts, bpf_iter_attach_opts))
12229 		return libbpf_err_ptr(-EINVAL);
12230 
12231 	link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
12232 	link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
12233 
12234 	prog_fd = bpf_program__fd(prog);
12235 	if (prog_fd < 0) {
12236 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12237 		return libbpf_err_ptr(-EINVAL);
12238 	}
12239 
12240 	link = calloc(1, sizeof(*link));
12241 	if (!link)
12242 		return libbpf_err_ptr(-ENOMEM);
12243 	link->detach = &bpf_link__detach_fd;
12244 
12245 	link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
12246 				  &link_create_opts);
12247 	if (link_fd < 0) {
12248 		link_fd = -errno;
12249 		free(link);
12250 		pr_warn("prog '%s': failed to attach to iterator: %s\n",
12251 			prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
12252 		return libbpf_err_ptr(link_fd);
12253 	}
12254 	link->fd = link_fd;
12255 	return link;
12256 }
12257 
12258 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12259 {
12260 	*link = bpf_program__attach_iter(prog, NULL);
12261 	return libbpf_get_error(*link);
12262 }
12263 
12264 struct bpf_link *bpf_program__attach_netfilter(const struct bpf_program *prog,
12265 					       const struct bpf_netfilter_opts *opts)
12266 {
12267 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
12268 	struct bpf_link *link;
12269 	int prog_fd, link_fd;
12270 
12271 	if (!OPTS_VALID(opts, bpf_netfilter_opts))
12272 		return libbpf_err_ptr(-EINVAL);
12273 
12274 	prog_fd = bpf_program__fd(prog);
12275 	if (prog_fd < 0) {
12276 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12277 		return libbpf_err_ptr(-EINVAL);
12278 	}
12279 
12280 	link = calloc(1, sizeof(*link));
12281 	if (!link)
12282 		return libbpf_err_ptr(-ENOMEM);
12283 
12284 	link->detach = &bpf_link__detach_fd;
12285 
12286 	lopts.netfilter.pf = OPTS_GET(opts, pf, 0);
12287 	lopts.netfilter.hooknum = OPTS_GET(opts, hooknum, 0);
12288 	lopts.netfilter.priority = OPTS_GET(opts, priority, 0);
12289 	lopts.netfilter.flags = OPTS_GET(opts, flags, 0);
12290 
12291 	link_fd = bpf_link_create(prog_fd, 0, BPF_NETFILTER, &lopts);
12292 	if (link_fd < 0) {
12293 		char errmsg[STRERR_BUFSIZE];
12294 
12295 		link_fd = -errno;
12296 		free(link);
12297 		pr_warn("prog '%s': failed to attach to netfilter: %s\n",
12298 			prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
12299 		return libbpf_err_ptr(link_fd);
12300 	}
12301 	link->fd = link_fd;
12302 
12303 	return link;
12304 }
12305 
12306 struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
12307 {
12308 	struct bpf_link *link = NULL;
12309 	int err;
12310 
12311 	if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
12312 		return libbpf_err_ptr(-EOPNOTSUPP);
12313 
12314 	err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, &link);
12315 	if (err)
12316 		return libbpf_err_ptr(err);
12317 
12318 	/* When calling bpf_program__attach() explicitly, auto-attach support
12319 	 * is expected to work, so NULL returned link is considered an error.
12320 	 * This is different for skeleton's attach, see comment in
12321 	 * bpf_object__attach_skeleton().
12322 	 */
12323 	if (!link)
12324 		return libbpf_err_ptr(-EOPNOTSUPP);
12325 
12326 	return link;
12327 }
12328 
12329 struct bpf_link_struct_ops {
12330 	struct bpf_link link;
12331 	int map_fd;
12332 };
12333 
12334 static int bpf_link__detach_struct_ops(struct bpf_link *link)
12335 {
12336 	struct bpf_link_struct_ops *st_link;
12337 	__u32 zero = 0;
12338 
12339 	st_link = container_of(link, struct bpf_link_struct_ops, link);
12340 
12341 	if (st_link->map_fd < 0)
12342 		/* w/o a real link */
12343 		return bpf_map_delete_elem(link->fd, &zero);
12344 
12345 	return close(link->fd);
12346 }
12347 
12348 struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
12349 {
12350 	struct bpf_link_struct_ops *link;
12351 	__u32 zero = 0;
12352 	int err, fd;
12353 
12354 	if (!bpf_map__is_struct_ops(map) || map->fd == -1)
12355 		return libbpf_err_ptr(-EINVAL);
12356 
12357 	link = calloc(1, sizeof(*link));
12358 	if (!link)
12359 		return libbpf_err_ptr(-EINVAL);
12360 
12361 	/* kern_vdata should be prepared during the loading phase. */
12362 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
12363 	/* It can be EBUSY if the map has been used to create or
12364 	 * update a link before.  We don't allow updating the value of
12365 	 * a struct_ops once it is set.  That ensures that the value
12366 	 * never changed.  So, it is safe to skip EBUSY.
12367 	 */
12368 	if (err && (!(map->def.map_flags & BPF_F_LINK) || err != -EBUSY)) {
12369 		free(link);
12370 		return libbpf_err_ptr(err);
12371 	}
12372 
12373 	link->link.detach = bpf_link__detach_struct_ops;
12374 
12375 	if (!(map->def.map_flags & BPF_F_LINK)) {
12376 		/* w/o a real link */
12377 		link->link.fd = map->fd;
12378 		link->map_fd = -1;
12379 		return &link->link;
12380 	}
12381 
12382 	fd = bpf_link_create(map->fd, 0, BPF_STRUCT_OPS, NULL);
12383 	if (fd < 0) {
12384 		free(link);
12385 		return libbpf_err_ptr(fd);
12386 	}
12387 
12388 	link->link.fd = fd;
12389 	link->map_fd = map->fd;
12390 
12391 	return &link->link;
12392 }
12393 
12394 /*
12395  * Swap the back struct_ops of a link with a new struct_ops map.
12396  */
12397 int bpf_link__update_map(struct bpf_link *link, const struct bpf_map *map)
12398 {
12399 	struct bpf_link_struct_ops *st_ops_link;
12400 	__u32 zero = 0;
12401 	int err;
12402 
12403 	if (!bpf_map__is_struct_ops(map) || map->fd < 0)
12404 		return -EINVAL;
12405 
12406 	st_ops_link = container_of(link, struct bpf_link_struct_ops, link);
12407 	/* Ensure the type of a link is correct */
12408 	if (st_ops_link->map_fd < 0)
12409 		return -EINVAL;
12410 
12411 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
12412 	/* It can be EBUSY if the map has been used to create or
12413 	 * update a link before.  We don't allow updating the value of
12414 	 * a struct_ops once it is set.  That ensures that the value
12415 	 * never changed.  So, it is safe to skip EBUSY.
12416 	 */
12417 	if (err && err != -EBUSY)
12418 		return err;
12419 
12420 	err = bpf_link_update(link->fd, map->fd, NULL);
12421 	if (err < 0)
12422 		return err;
12423 
12424 	st_ops_link->map_fd = map->fd;
12425 
12426 	return 0;
12427 }
12428 
12429 typedef enum bpf_perf_event_ret (*bpf_perf_event_print_t)(struct perf_event_header *hdr,
12430 							  void *private_data);
12431 
12432 static enum bpf_perf_event_ret
12433 perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
12434 		       void **copy_mem, size_t *copy_size,
12435 		       bpf_perf_event_print_t fn, void *private_data)
12436 {
12437 	struct perf_event_mmap_page *header = mmap_mem;
12438 	__u64 data_head = ring_buffer_read_head(header);
12439 	__u64 data_tail = header->data_tail;
12440 	void *base = ((__u8 *)header) + page_size;
12441 	int ret = LIBBPF_PERF_EVENT_CONT;
12442 	struct perf_event_header *ehdr;
12443 	size_t ehdr_size;
12444 
12445 	while (data_head != data_tail) {
12446 		ehdr = base + (data_tail & (mmap_size - 1));
12447 		ehdr_size = ehdr->size;
12448 
12449 		if (((void *)ehdr) + ehdr_size > base + mmap_size) {
12450 			void *copy_start = ehdr;
12451 			size_t len_first = base + mmap_size - copy_start;
12452 			size_t len_secnd = ehdr_size - len_first;
12453 
12454 			if (*copy_size < ehdr_size) {
12455 				free(*copy_mem);
12456 				*copy_mem = malloc(ehdr_size);
12457 				if (!*copy_mem) {
12458 					*copy_size = 0;
12459 					ret = LIBBPF_PERF_EVENT_ERROR;
12460 					break;
12461 				}
12462 				*copy_size = ehdr_size;
12463 			}
12464 
12465 			memcpy(*copy_mem, copy_start, len_first);
12466 			memcpy(*copy_mem + len_first, base, len_secnd);
12467 			ehdr = *copy_mem;
12468 		}
12469 
12470 		ret = fn(ehdr, private_data);
12471 		data_tail += ehdr_size;
12472 		if (ret != LIBBPF_PERF_EVENT_CONT)
12473 			break;
12474 	}
12475 
12476 	ring_buffer_write_tail(header, data_tail);
12477 	return libbpf_err(ret);
12478 }
12479 
12480 struct perf_buffer;
12481 
12482 struct perf_buffer_params {
12483 	struct perf_event_attr *attr;
12484 	/* if event_cb is specified, it takes precendence */
12485 	perf_buffer_event_fn event_cb;
12486 	/* sample_cb and lost_cb are higher-level common-case callbacks */
12487 	perf_buffer_sample_fn sample_cb;
12488 	perf_buffer_lost_fn lost_cb;
12489 	void *ctx;
12490 	int cpu_cnt;
12491 	int *cpus;
12492 	int *map_keys;
12493 };
12494 
12495 struct perf_cpu_buf {
12496 	struct perf_buffer *pb;
12497 	void *base; /* mmap()'ed memory */
12498 	void *buf; /* for reconstructing segmented data */
12499 	size_t buf_size;
12500 	int fd;
12501 	int cpu;
12502 	int map_key;
12503 };
12504 
12505 struct perf_buffer {
12506 	perf_buffer_event_fn event_cb;
12507 	perf_buffer_sample_fn sample_cb;
12508 	perf_buffer_lost_fn lost_cb;
12509 	void *ctx; /* passed into callbacks */
12510 
12511 	size_t page_size;
12512 	size_t mmap_size;
12513 	struct perf_cpu_buf **cpu_bufs;
12514 	struct epoll_event *events;
12515 	int cpu_cnt; /* number of allocated CPU buffers */
12516 	int epoll_fd; /* perf event FD */
12517 	int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
12518 };
12519 
12520 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
12521 				      struct perf_cpu_buf *cpu_buf)
12522 {
12523 	if (!cpu_buf)
12524 		return;
12525 	if (cpu_buf->base &&
12526 	    munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
12527 		pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
12528 	if (cpu_buf->fd >= 0) {
12529 		ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
12530 		close(cpu_buf->fd);
12531 	}
12532 	free(cpu_buf->buf);
12533 	free(cpu_buf);
12534 }
12535 
12536 void perf_buffer__free(struct perf_buffer *pb)
12537 {
12538 	int i;
12539 
12540 	if (IS_ERR_OR_NULL(pb))
12541 		return;
12542 	if (pb->cpu_bufs) {
12543 		for (i = 0; i < pb->cpu_cnt; i++) {
12544 			struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
12545 
12546 			if (!cpu_buf)
12547 				continue;
12548 
12549 			bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
12550 			perf_buffer__free_cpu_buf(pb, cpu_buf);
12551 		}
12552 		free(pb->cpu_bufs);
12553 	}
12554 	if (pb->epoll_fd >= 0)
12555 		close(pb->epoll_fd);
12556 	free(pb->events);
12557 	free(pb);
12558 }
12559 
12560 static struct perf_cpu_buf *
12561 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
12562 			  int cpu, int map_key)
12563 {
12564 	struct perf_cpu_buf *cpu_buf;
12565 	char msg[STRERR_BUFSIZE];
12566 	int err;
12567 
12568 	cpu_buf = calloc(1, sizeof(*cpu_buf));
12569 	if (!cpu_buf)
12570 		return ERR_PTR(-ENOMEM);
12571 
12572 	cpu_buf->pb = pb;
12573 	cpu_buf->cpu = cpu;
12574 	cpu_buf->map_key = map_key;
12575 
12576 	cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
12577 			      -1, PERF_FLAG_FD_CLOEXEC);
12578 	if (cpu_buf->fd < 0) {
12579 		err = -errno;
12580 		pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
12581 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
12582 		goto error;
12583 	}
12584 
12585 	cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
12586 			     PROT_READ | PROT_WRITE, MAP_SHARED,
12587 			     cpu_buf->fd, 0);
12588 	if (cpu_buf->base == MAP_FAILED) {
12589 		cpu_buf->base = NULL;
12590 		err = -errno;
12591 		pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
12592 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
12593 		goto error;
12594 	}
12595 
12596 	if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
12597 		err = -errno;
12598 		pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
12599 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
12600 		goto error;
12601 	}
12602 
12603 	return cpu_buf;
12604 
12605 error:
12606 	perf_buffer__free_cpu_buf(pb, cpu_buf);
12607 	return (struct perf_cpu_buf *)ERR_PTR(err);
12608 }
12609 
12610 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
12611 					      struct perf_buffer_params *p);
12612 
12613 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
12614 				     perf_buffer_sample_fn sample_cb,
12615 				     perf_buffer_lost_fn lost_cb,
12616 				     void *ctx,
12617 				     const struct perf_buffer_opts *opts)
12618 {
12619 	const size_t attr_sz = sizeof(struct perf_event_attr);
12620 	struct perf_buffer_params p = {};
12621 	struct perf_event_attr attr;
12622 	__u32 sample_period;
12623 
12624 	if (!OPTS_VALID(opts, perf_buffer_opts))
12625 		return libbpf_err_ptr(-EINVAL);
12626 
12627 	sample_period = OPTS_GET(opts, sample_period, 1);
12628 	if (!sample_period)
12629 		sample_period = 1;
12630 
12631 	memset(&attr, 0, attr_sz);
12632 	attr.size = attr_sz;
12633 	attr.config = PERF_COUNT_SW_BPF_OUTPUT;
12634 	attr.type = PERF_TYPE_SOFTWARE;
12635 	attr.sample_type = PERF_SAMPLE_RAW;
12636 	attr.sample_period = sample_period;
12637 	attr.wakeup_events = sample_period;
12638 
12639 	p.attr = &attr;
12640 	p.sample_cb = sample_cb;
12641 	p.lost_cb = lost_cb;
12642 	p.ctx = ctx;
12643 
12644 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
12645 }
12646 
12647 struct perf_buffer *perf_buffer__new_raw(int map_fd, size_t page_cnt,
12648 					 struct perf_event_attr *attr,
12649 					 perf_buffer_event_fn event_cb, void *ctx,
12650 					 const struct perf_buffer_raw_opts *opts)
12651 {
12652 	struct perf_buffer_params p = {};
12653 
12654 	if (!attr)
12655 		return libbpf_err_ptr(-EINVAL);
12656 
12657 	if (!OPTS_VALID(opts, perf_buffer_raw_opts))
12658 		return libbpf_err_ptr(-EINVAL);
12659 
12660 	p.attr = attr;
12661 	p.event_cb = event_cb;
12662 	p.ctx = ctx;
12663 	p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
12664 	p.cpus = OPTS_GET(opts, cpus, NULL);
12665 	p.map_keys = OPTS_GET(opts, map_keys, NULL);
12666 
12667 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
12668 }
12669 
12670 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
12671 					      struct perf_buffer_params *p)
12672 {
12673 	const char *online_cpus_file = "/sys/devices/system/cpu/online";
12674 	struct bpf_map_info map;
12675 	char msg[STRERR_BUFSIZE];
12676 	struct perf_buffer *pb;
12677 	bool *online = NULL;
12678 	__u32 map_info_len;
12679 	int err, i, j, n;
12680 
12681 	if (page_cnt == 0 || (page_cnt & (page_cnt - 1))) {
12682 		pr_warn("page count should be power of two, but is %zu\n",
12683 			page_cnt);
12684 		return ERR_PTR(-EINVAL);
12685 	}
12686 
12687 	/* best-effort sanity checks */
12688 	memset(&map, 0, sizeof(map));
12689 	map_info_len = sizeof(map);
12690 	err = bpf_map_get_info_by_fd(map_fd, &map, &map_info_len);
12691 	if (err) {
12692 		err = -errno;
12693 		/* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
12694 		 * -EBADFD, -EFAULT, or -E2BIG on real error
12695 		 */
12696 		if (err != -EINVAL) {
12697 			pr_warn("failed to get map info for map FD %d: %s\n",
12698 				map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
12699 			return ERR_PTR(err);
12700 		}
12701 		pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
12702 			 map_fd);
12703 	} else {
12704 		if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
12705 			pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
12706 				map.name);
12707 			return ERR_PTR(-EINVAL);
12708 		}
12709 	}
12710 
12711 	pb = calloc(1, sizeof(*pb));
12712 	if (!pb)
12713 		return ERR_PTR(-ENOMEM);
12714 
12715 	pb->event_cb = p->event_cb;
12716 	pb->sample_cb = p->sample_cb;
12717 	pb->lost_cb = p->lost_cb;
12718 	pb->ctx = p->ctx;
12719 
12720 	pb->page_size = getpagesize();
12721 	pb->mmap_size = pb->page_size * page_cnt;
12722 	pb->map_fd = map_fd;
12723 
12724 	pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
12725 	if (pb->epoll_fd < 0) {
12726 		err = -errno;
12727 		pr_warn("failed to create epoll instance: %s\n",
12728 			libbpf_strerror_r(err, msg, sizeof(msg)));
12729 		goto error;
12730 	}
12731 
12732 	if (p->cpu_cnt > 0) {
12733 		pb->cpu_cnt = p->cpu_cnt;
12734 	} else {
12735 		pb->cpu_cnt = libbpf_num_possible_cpus();
12736 		if (pb->cpu_cnt < 0) {
12737 			err = pb->cpu_cnt;
12738 			goto error;
12739 		}
12740 		if (map.max_entries && map.max_entries < pb->cpu_cnt)
12741 			pb->cpu_cnt = map.max_entries;
12742 	}
12743 
12744 	pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
12745 	if (!pb->events) {
12746 		err = -ENOMEM;
12747 		pr_warn("failed to allocate events: out of memory\n");
12748 		goto error;
12749 	}
12750 	pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
12751 	if (!pb->cpu_bufs) {
12752 		err = -ENOMEM;
12753 		pr_warn("failed to allocate buffers: out of memory\n");
12754 		goto error;
12755 	}
12756 
12757 	err = parse_cpu_mask_file(online_cpus_file, &online, &n);
12758 	if (err) {
12759 		pr_warn("failed to get online CPU mask: %d\n", err);
12760 		goto error;
12761 	}
12762 
12763 	for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
12764 		struct perf_cpu_buf *cpu_buf;
12765 		int cpu, map_key;
12766 
12767 		cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
12768 		map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
12769 
12770 		/* in case user didn't explicitly requested particular CPUs to
12771 		 * be attached to, skip offline/not present CPUs
12772 		 */
12773 		if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
12774 			continue;
12775 
12776 		cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
12777 		if (IS_ERR(cpu_buf)) {
12778 			err = PTR_ERR(cpu_buf);
12779 			goto error;
12780 		}
12781 
12782 		pb->cpu_bufs[j] = cpu_buf;
12783 
12784 		err = bpf_map_update_elem(pb->map_fd, &map_key,
12785 					  &cpu_buf->fd, 0);
12786 		if (err) {
12787 			err = -errno;
12788 			pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
12789 				cpu, map_key, cpu_buf->fd,
12790 				libbpf_strerror_r(err, msg, sizeof(msg)));
12791 			goto error;
12792 		}
12793 
12794 		pb->events[j].events = EPOLLIN;
12795 		pb->events[j].data.ptr = cpu_buf;
12796 		if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
12797 			      &pb->events[j]) < 0) {
12798 			err = -errno;
12799 			pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
12800 				cpu, cpu_buf->fd,
12801 				libbpf_strerror_r(err, msg, sizeof(msg)));
12802 			goto error;
12803 		}
12804 		j++;
12805 	}
12806 	pb->cpu_cnt = j;
12807 	free(online);
12808 
12809 	return pb;
12810 
12811 error:
12812 	free(online);
12813 	if (pb)
12814 		perf_buffer__free(pb);
12815 	return ERR_PTR(err);
12816 }
12817 
12818 struct perf_sample_raw {
12819 	struct perf_event_header header;
12820 	uint32_t size;
12821 	char data[];
12822 };
12823 
12824 struct perf_sample_lost {
12825 	struct perf_event_header header;
12826 	uint64_t id;
12827 	uint64_t lost;
12828 	uint64_t sample_id;
12829 };
12830 
12831 static enum bpf_perf_event_ret
12832 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
12833 {
12834 	struct perf_cpu_buf *cpu_buf = ctx;
12835 	struct perf_buffer *pb = cpu_buf->pb;
12836 	void *data = e;
12837 
12838 	/* user wants full control over parsing perf event */
12839 	if (pb->event_cb)
12840 		return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
12841 
12842 	switch (e->type) {
12843 	case PERF_RECORD_SAMPLE: {
12844 		struct perf_sample_raw *s = data;
12845 
12846 		if (pb->sample_cb)
12847 			pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
12848 		break;
12849 	}
12850 	case PERF_RECORD_LOST: {
12851 		struct perf_sample_lost *s = data;
12852 
12853 		if (pb->lost_cb)
12854 			pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
12855 		break;
12856 	}
12857 	default:
12858 		pr_warn("unknown perf sample type %d\n", e->type);
12859 		return LIBBPF_PERF_EVENT_ERROR;
12860 	}
12861 	return LIBBPF_PERF_EVENT_CONT;
12862 }
12863 
12864 static int perf_buffer__process_records(struct perf_buffer *pb,
12865 					struct perf_cpu_buf *cpu_buf)
12866 {
12867 	enum bpf_perf_event_ret ret;
12868 
12869 	ret = perf_event_read_simple(cpu_buf->base, pb->mmap_size,
12870 				     pb->page_size, &cpu_buf->buf,
12871 				     &cpu_buf->buf_size,
12872 				     perf_buffer__process_record, cpu_buf);
12873 	if (ret != LIBBPF_PERF_EVENT_CONT)
12874 		return ret;
12875 	return 0;
12876 }
12877 
12878 int perf_buffer__epoll_fd(const struct perf_buffer *pb)
12879 {
12880 	return pb->epoll_fd;
12881 }
12882 
12883 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
12884 {
12885 	int i, cnt, err;
12886 
12887 	cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
12888 	if (cnt < 0)
12889 		return -errno;
12890 
12891 	for (i = 0; i < cnt; i++) {
12892 		struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
12893 
12894 		err = perf_buffer__process_records(pb, cpu_buf);
12895 		if (err) {
12896 			pr_warn("error while processing records: %d\n", err);
12897 			return libbpf_err(err);
12898 		}
12899 	}
12900 	return cnt;
12901 }
12902 
12903 /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
12904  * manager.
12905  */
12906 size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
12907 {
12908 	return pb->cpu_cnt;
12909 }
12910 
12911 /*
12912  * Return perf_event FD of a ring buffer in *buf_idx* slot of
12913  * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
12914  * select()/poll()/epoll() Linux syscalls.
12915  */
12916 int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
12917 {
12918 	struct perf_cpu_buf *cpu_buf;
12919 
12920 	if (buf_idx >= pb->cpu_cnt)
12921 		return libbpf_err(-EINVAL);
12922 
12923 	cpu_buf = pb->cpu_bufs[buf_idx];
12924 	if (!cpu_buf)
12925 		return libbpf_err(-ENOENT);
12926 
12927 	return cpu_buf->fd;
12928 }
12929 
12930 int perf_buffer__buffer(struct perf_buffer *pb, int buf_idx, void **buf, size_t *buf_size)
12931 {
12932 	struct perf_cpu_buf *cpu_buf;
12933 
12934 	if (buf_idx >= pb->cpu_cnt)
12935 		return libbpf_err(-EINVAL);
12936 
12937 	cpu_buf = pb->cpu_bufs[buf_idx];
12938 	if (!cpu_buf)
12939 		return libbpf_err(-ENOENT);
12940 
12941 	*buf = cpu_buf->base;
12942 	*buf_size = pb->mmap_size;
12943 	return 0;
12944 }
12945 
12946 /*
12947  * Consume data from perf ring buffer corresponding to slot *buf_idx* in
12948  * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
12949  * consume, do nothing and return success.
12950  * Returns:
12951  *   - 0 on success;
12952  *   - <0 on failure.
12953  */
12954 int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
12955 {
12956 	struct perf_cpu_buf *cpu_buf;
12957 
12958 	if (buf_idx >= pb->cpu_cnt)
12959 		return libbpf_err(-EINVAL);
12960 
12961 	cpu_buf = pb->cpu_bufs[buf_idx];
12962 	if (!cpu_buf)
12963 		return libbpf_err(-ENOENT);
12964 
12965 	return perf_buffer__process_records(pb, cpu_buf);
12966 }
12967 
12968 int perf_buffer__consume(struct perf_buffer *pb)
12969 {
12970 	int i, err;
12971 
12972 	for (i = 0; i < pb->cpu_cnt; i++) {
12973 		struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
12974 
12975 		if (!cpu_buf)
12976 			continue;
12977 
12978 		err = perf_buffer__process_records(pb, cpu_buf);
12979 		if (err) {
12980 			pr_warn("perf_buffer: failed to process records in buffer #%d: %d\n", i, err);
12981 			return libbpf_err(err);
12982 		}
12983 	}
12984 	return 0;
12985 }
12986 
12987 int bpf_program__set_attach_target(struct bpf_program *prog,
12988 				   int attach_prog_fd,
12989 				   const char *attach_func_name)
12990 {
12991 	int btf_obj_fd = 0, btf_id = 0, err;
12992 
12993 	if (!prog || attach_prog_fd < 0)
12994 		return libbpf_err(-EINVAL);
12995 
12996 	if (prog->obj->loaded)
12997 		return libbpf_err(-EINVAL);
12998 
12999 	if (attach_prog_fd && !attach_func_name) {
13000 		/* remember attach_prog_fd and let bpf_program__load() find
13001 		 * BTF ID during the program load
13002 		 */
13003 		prog->attach_prog_fd = attach_prog_fd;
13004 		return 0;
13005 	}
13006 
13007 	if (attach_prog_fd) {
13008 		btf_id = libbpf_find_prog_btf_id(attach_func_name,
13009 						 attach_prog_fd);
13010 		if (btf_id < 0)
13011 			return libbpf_err(btf_id);
13012 	} else {
13013 		if (!attach_func_name)
13014 			return libbpf_err(-EINVAL);
13015 
13016 		/* load btf_vmlinux, if not yet */
13017 		err = bpf_object__load_vmlinux_btf(prog->obj, true);
13018 		if (err)
13019 			return libbpf_err(err);
13020 		err = find_kernel_btf_id(prog->obj, attach_func_name,
13021 					 prog->expected_attach_type,
13022 					 &btf_obj_fd, &btf_id);
13023 		if (err)
13024 			return libbpf_err(err);
13025 	}
13026 
13027 	prog->attach_btf_id = btf_id;
13028 	prog->attach_btf_obj_fd = btf_obj_fd;
13029 	prog->attach_prog_fd = attach_prog_fd;
13030 	return 0;
13031 }
13032 
13033 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
13034 {
13035 	int err = 0, n, len, start, end = -1;
13036 	bool *tmp;
13037 
13038 	*mask = NULL;
13039 	*mask_sz = 0;
13040 
13041 	/* Each sub string separated by ',' has format \d+-\d+ or \d+ */
13042 	while (*s) {
13043 		if (*s == ',' || *s == '\n') {
13044 			s++;
13045 			continue;
13046 		}
13047 		n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
13048 		if (n <= 0 || n > 2) {
13049 			pr_warn("Failed to get CPU range %s: %d\n", s, n);
13050 			err = -EINVAL;
13051 			goto cleanup;
13052 		} else if (n == 1) {
13053 			end = start;
13054 		}
13055 		if (start < 0 || start > end) {
13056 			pr_warn("Invalid CPU range [%d,%d] in %s\n",
13057 				start, end, s);
13058 			err = -EINVAL;
13059 			goto cleanup;
13060 		}
13061 		tmp = realloc(*mask, end + 1);
13062 		if (!tmp) {
13063 			err = -ENOMEM;
13064 			goto cleanup;
13065 		}
13066 		*mask = tmp;
13067 		memset(tmp + *mask_sz, 0, start - *mask_sz);
13068 		memset(tmp + start, 1, end - start + 1);
13069 		*mask_sz = end + 1;
13070 		s += len;
13071 	}
13072 	if (!*mask_sz) {
13073 		pr_warn("Empty CPU range\n");
13074 		return -EINVAL;
13075 	}
13076 	return 0;
13077 cleanup:
13078 	free(*mask);
13079 	*mask = NULL;
13080 	return err;
13081 }
13082 
13083 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
13084 {
13085 	int fd, err = 0, len;
13086 	char buf[128];
13087 
13088 	fd = open(fcpu, O_RDONLY | O_CLOEXEC);
13089 	if (fd < 0) {
13090 		err = -errno;
13091 		pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
13092 		return err;
13093 	}
13094 	len = read(fd, buf, sizeof(buf));
13095 	close(fd);
13096 	if (len <= 0) {
13097 		err = len ? -errno : -EINVAL;
13098 		pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
13099 		return err;
13100 	}
13101 	if (len >= sizeof(buf)) {
13102 		pr_warn("CPU mask is too big in file %s\n", fcpu);
13103 		return -E2BIG;
13104 	}
13105 	buf[len] = '\0';
13106 
13107 	return parse_cpu_mask_str(buf, mask, mask_sz);
13108 }
13109 
13110 int libbpf_num_possible_cpus(void)
13111 {
13112 	static const char *fcpu = "/sys/devices/system/cpu/possible";
13113 	static int cpus;
13114 	int err, n, i, tmp_cpus;
13115 	bool *mask;
13116 
13117 	tmp_cpus = READ_ONCE(cpus);
13118 	if (tmp_cpus > 0)
13119 		return tmp_cpus;
13120 
13121 	err = parse_cpu_mask_file(fcpu, &mask, &n);
13122 	if (err)
13123 		return libbpf_err(err);
13124 
13125 	tmp_cpus = 0;
13126 	for (i = 0; i < n; i++) {
13127 		if (mask[i])
13128 			tmp_cpus++;
13129 	}
13130 	free(mask);
13131 
13132 	WRITE_ONCE(cpus, tmp_cpus);
13133 	return tmp_cpus;
13134 }
13135 
13136 static int populate_skeleton_maps(const struct bpf_object *obj,
13137 				  struct bpf_map_skeleton *maps,
13138 				  size_t map_cnt)
13139 {
13140 	int i;
13141 
13142 	for (i = 0; i < map_cnt; i++) {
13143 		struct bpf_map **map = maps[i].map;
13144 		const char *name = maps[i].name;
13145 		void **mmaped = maps[i].mmaped;
13146 
13147 		*map = bpf_object__find_map_by_name(obj, name);
13148 		if (!*map) {
13149 			pr_warn("failed to find skeleton map '%s'\n", name);
13150 			return -ESRCH;
13151 		}
13152 
13153 		/* externs shouldn't be pre-setup from user code */
13154 		if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
13155 			*mmaped = (*map)->mmaped;
13156 	}
13157 	return 0;
13158 }
13159 
13160 static int populate_skeleton_progs(const struct bpf_object *obj,
13161 				   struct bpf_prog_skeleton *progs,
13162 				   size_t prog_cnt)
13163 {
13164 	int i;
13165 
13166 	for (i = 0; i < prog_cnt; i++) {
13167 		struct bpf_program **prog = progs[i].prog;
13168 		const char *name = progs[i].name;
13169 
13170 		*prog = bpf_object__find_program_by_name(obj, name);
13171 		if (!*prog) {
13172 			pr_warn("failed to find skeleton program '%s'\n", name);
13173 			return -ESRCH;
13174 		}
13175 	}
13176 	return 0;
13177 }
13178 
13179 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
13180 			      const struct bpf_object_open_opts *opts)
13181 {
13182 	DECLARE_LIBBPF_OPTS(bpf_object_open_opts, skel_opts,
13183 		.object_name = s->name,
13184 	);
13185 	struct bpf_object *obj;
13186 	int err;
13187 
13188 	/* Attempt to preserve opts->object_name, unless overriden by user
13189 	 * explicitly. Overwriting object name for skeletons is discouraged,
13190 	 * as it breaks global data maps, because they contain object name
13191 	 * prefix as their own map name prefix. When skeleton is generated,
13192 	 * bpftool is making an assumption that this name will stay the same.
13193 	 */
13194 	if (opts) {
13195 		memcpy(&skel_opts, opts, sizeof(*opts));
13196 		if (!opts->object_name)
13197 			skel_opts.object_name = s->name;
13198 	}
13199 
13200 	obj = bpf_object__open_mem(s->data, s->data_sz, &skel_opts);
13201 	err = libbpf_get_error(obj);
13202 	if (err) {
13203 		pr_warn("failed to initialize skeleton BPF object '%s': %d\n",
13204 			s->name, err);
13205 		return libbpf_err(err);
13206 	}
13207 
13208 	*s->obj = obj;
13209 	err = populate_skeleton_maps(obj, s->maps, s->map_cnt);
13210 	if (err) {
13211 		pr_warn("failed to populate skeleton maps for '%s': %d\n", s->name, err);
13212 		return libbpf_err(err);
13213 	}
13214 
13215 	err = populate_skeleton_progs(obj, s->progs, s->prog_cnt);
13216 	if (err) {
13217 		pr_warn("failed to populate skeleton progs for '%s': %d\n", s->name, err);
13218 		return libbpf_err(err);
13219 	}
13220 
13221 	return 0;
13222 }
13223 
13224 int bpf_object__open_subskeleton(struct bpf_object_subskeleton *s)
13225 {
13226 	int err, len, var_idx, i;
13227 	const char *var_name;
13228 	const struct bpf_map *map;
13229 	struct btf *btf;
13230 	__u32 map_type_id;
13231 	const struct btf_type *map_type, *var_type;
13232 	const struct bpf_var_skeleton *var_skel;
13233 	struct btf_var_secinfo *var;
13234 
13235 	if (!s->obj)
13236 		return libbpf_err(-EINVAL);
13237 
13238 	btf = bpf_object__btf(s->obj);
13239 	if (!btf) {
13240 		pr_warn("subskeletons require BTF at runtime (object %s)\n",
13241 			bpf_object__name(s->obj));
13242 		return libbpf_err(-errno);
13243 	}
13244 
13245 	err = populate_skeleton_maps(s->obj, s->maps, s->map_cnt);
13246 	if (err) {
13247 		pr_warn("failed to populate subskeleton maps: %d\n", err);
13248 		return libbpf_err(err);
13249 	}
13250 
13251 	err = populate_skeleton_progs(s->obj, s->progs, s->prog_cnt);
13252 	if (err) {
13253 		pr_warn("failed to populate subskeleton maps: %d\n", err);
13254 		return libbpf_err(err);
13255 	}
13256 
13257 	for (var_idx = 0; var_idx < s->var_cnt; var_idx++) {
13258 		var_skel = &s->vars[var_idx];
13259 		map = *var_skel->map;
13260 		map_type_id = bpf_map__btf_value_type_id(map);
13261 		map_type = btf__type_by_id(btf, map_type_id);
13262 
13263 		if (!btf_is_datasec(map_type)) {
13264 			pr_warn("type for map '%1$s' is not a datasec: %2$s",
13265 				bpf_map__name(map),
13266 				__btf_kind_str(btf_kind(map_type)));
13267 			return libbpf_err(-EINVAL);
13268 		}
13269 
13270 		len = btf_vlen(map_type);
13271 		var = btf_var_secinfos(map_type);
13272 		for (i = 0; i < len; i++, var++) {
13273 			var_type = btf__type_by_id(btf, var->type);
13274 			var_name = btf__name_by_offset(btf, var_type->name_off);
13275 			if (strcmp(var_name, var_skel->name) == 0) {
13276 				*var_skel->addr = map->mmaped + var->offset;
13277 				break;
13278 			}
13279 		}
13280 	}
13281 	return 0;
13282 }
13283 
13284 void bpf_object__destroy_subskeleton(struct bpf_object_subskeleton *s)
13285 {
13286 	if (!s)
13287 		return;
13288 	free(s->maps);
13289 	free(s->progs);
13290 	free(s->vars);
13291 	free(s);
13292 }
13293 
13294 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
13295 {
13296 	int i, err;
13297 
13298 	err = bpf_object__load(*s->obj);
13299 	if (err) {
13300 		pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
13301 		return libbpf_err(err);
13302 	}
13303 
13304 	for (i = 0; i < s->map_cnt; i++) {
13305 		struct bpf_map *map = *s->maps[i].map;
13306 		size_t mmap_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
13307 		int prot, map_fd = bpf_map__fd(map);
13308 		void **mmaped = s->maps[i].mmaped;
13309 
13310 		if (!mmaped)
13311 			continue;
13312 
13313 		if (!(map->def.map_flags & BPF_F_MMAPABLE)) {
13314 			*mmaped = NULL;
13315 			continue;
13316 		}
13317 
13318 		if (map->def.map_flags & BPF_F_RDONLY_PROG)
13319 			prot = PROT_READ;
13320 		else
13321 			prot = PROT_READ | PROT_WRITE;
13322 
13323 		/* Remap anonymous mmap()-ed "map initialization image" as
13324 		 * a BPF map-backed mmap()-ed memory, but preserving the same
13325 		 * memory address. This will cause kernel to change process'
13326 		 * page table to point to a different piece of kernel memory,
13327 		 * but from userspace point of view memory address (and its
13328 		 * contents, being identical at this point) will stay the
13329 		 * same. This mapping will be released by bpf_object__close()
13330 		 * as per normal clean up procedure, so we don't need to worry
13331 		 * about it from skeleton's clean up perspective.
13332 		 */
13333 		*mmaped = mmap(map->mmaped, mmap_sz, prot, MAP_SHARED | MAP_FIXED, map_fd, 0);
13334 		if (*mmaped == MAP_FAILED) {
13335 			err = -errno;
13336 			*mmaped = NULL;
13337 			pr_warn("failed to re-mmap() map '%s': %d\n",
13338 				 bpf_map__name(map), err);
13339 			return libbpf_err(err);
13340 		}
13341 	}
13342 
13343 	return 0;
13344 }
13345 
13346 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
13347 {
13348 	int i, err;
13349 
13350 	for (i = 0; i < s->prog_cnt; i++) {
13351 		struct bpf_program *prog = *s->progs[i].prog;
13352 		struct bpf_link **link = s->progs[i].link;
13353 
13354 		if (!prog->autoload || !prog->autoattach)
13355 			continue;
13356 
13357 		/* auto-attaching not supported for this program */
13358 		if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
13359 			continue;
13360 
13361 		/* if user already set the link manually, don't attempt auto-attach */
13362 		if (*link)
13363 			continue;
13364 
13365 		err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, link);
13366 		if (err) {
13367 			pr_warn("prog '%s': failed to auto-attach: %d\n",
13368 				bpf_program__name(prog), err);
13369 			return libbpf_err(err);
13370 		}
13371 
13372 		/* It's possible that for some SEC() definitions auto-attach
13373 		 * is supported in some cases (e.g., if definition completely
13374 		 * specifies target information), but is not in other cases.
13375 		 * SEC("uprobe") is one such case. If user specified target
13376 		 * binary and function name, such BPF program can be
13377 		 * auto-attached. But if not, it shouldn't trigger skeleton's
13378 		 * attach to fail. It should just be skipped.
13379 		 * attach_fn signals such case with returning 0 (no error) and
13380 		 * setting link to NULL.
13381 		 */
13382 	}
13383 
13384 	return 0;
13385 }
13386 
13387 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
13388 {
13389 	int i;
13390 
13391 	for (i = 0; i < s->prog_cnt; i++) {
13392 		struct bpf_link **link = s->progs[i].link;
13393 
13394 		bpf_link__destroy(*link);
13395 		*link = NULL;
13396 	}
13397 }
13398 
13399 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
13400 {
13401 	if (!s)
13402 		return;
13403 
13404 	if (s->progs)
13405 		bpf_object__detach_skeleton(s);
13406 	if (s->obj)
13407 		bpf_object__close(*s->obj);
13408 	free(s->maps);
13409 	free(s->progs);
13410 	free(s);
13411 }
13412