xref: /linux/tools/lib/bpf/libbpf.c (revision 2aceb896ee18ae35b21b14c978d8c2ef8c7b439d)
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 };
130 
131 static const char * const link_type_name[] = {
132 	[BPF_LINK_TYPE_UNSPEC]			= "unspec",
133 	[BPF_LINK_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
134 	[BPF_LINK_TYPE_TRACING]			= "tracing",
135 	[BPF_LINK_TYPE_CGROUP]			= "cgroup",
136 	[BPF_LINK_TYPE_ITER]			= "iter",
137 	[BPF_LINK_TYPE_NETNS]			= "netns",
138 	[BPF_LINK_TYPE_XDP]			= "xdp",
139 	[BPF_LINK_TYPE_PERF_EVENT]		= "perf_event",
140 	[BPF_LINK_TYPE_KPROBE_MULTI]		= "kprobe_multi",
141 	[BPF_LINK_TYPE_STRUCT_OPS]		= "struct_ops",
142 	[BPF_LINK_TYPE_NETFILTER]		= "netfilter",
143 	[BPF_LINK_TYPE_TCX]			= "tcx",
144 	[BPF_LINK_TYPE_UPROBE_MULTI]		= "uprobe_multi",
145 };
146 
147 static const char * const map_type_name[] = {
148 	[BPF_MAP_TYPE_UNSPEC]			= "unspec",
149 	[BPF_MAP_TYPE_HASH]			= "hash",
150 	[BPF_MAP_TYPE_ARRAY]			= "array",
151 	[BPF_MAP_TYPE_PROG_ARRAY]		= "prog_array",
152 	[BPF_MAP_TYPE_PERF_EVENT_ARRAY]		= "perf_event_array",
153 	[BPF_MAP_TYPE_PERCPU_HASH]		= "percpu_hash",
154 	[BPF_MAP_TYPE_PERCPU_ARRAY]		= "percpu_array",
155 	[BPF_MAP_TYPE_STACK_TRACE]		= "stack_trace",
156 	[BPF_MAP_TYPE_CGROUP_ARRAY]		= "cgroup_array",
157 	[BPF_MAP_TYPE_LRU_HASH]			= "lru_hash",
158 	[BPF_MAP_TYPE_LRU_PERCPU_HASH]		= "lru_percpu_hash",
159 	[BPF_MAP_TYPE_LPM_TRIE]			= "lpm_trie",
160 	[BPF_MAP_TYPE_ARRAY_OF_MAPS]		= "array_of_maps",
161 	[BPF_MAP_TYPE_HASH_OF_MAPS]		= "hash_of_maps",
162 	[BPF_MAP_TYPE_DEVMAP]			= "devmap",
163 	[BPF_MAP_TYPE_DEVMAP_HASH]		= "devmap_hash",
164 	[BPF_MAP_TYPE_SOCKMAP]			= "sockmap",
165 	[BPF_MAP_TYPE_CPUMAP]			= "cpumap",
166 	[BPF_MAP_TYPE_XSKMAP]			= "xskmap",
167 	[BPF_MAP_TYPE_SOCKHASH]			= "sockhash",
168 	[BPF_MAP_TYPE_CGROUP_STORAGE]		= "cgroup_storage",
169 	[BPF_MAP_TYPE_REUSEPORT_SOCKARRAY]	= "reuseport_sockarray",
170 	[BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE]	= "percpu_cgroup_storage",
171 	[BPF_MAP_TYPE_QUEUE]			= "queue",
172 	[BPF_MAP_TYPE_STACK]			= "stack",
173 	[BPF_MAP_TYPE_SK_STORAGE]		= "sk_storage",
174 	[BPF_MAP_TYPE_STRUCT_OPS]		= "struct_ops",
175 	[BPF_MAP_TYPE_RINGBUF]			= "ringbuf",
176 	[BPF_MAP_TYPE_INODE_STORAGE]		= "inode_storage",
177 	[BPF_MAP_TYPE_TASK_STORAGE]		= "task_storage",
178 	[BPF_MAP_TYPE_BLOOM_FILTER]		= "bloom_filter",
179 	[BPF_MAP_TYPE_USER_RINGBUF]             = "user_ringbuf",
180 	[BPF_MAP_TYPE_CGRP_STORAGE]		= "cgrp_storage",
181 };
182 
183 static const char * const prog_type_name[] = {
184 	[BPF_PROG_TYPE_UNSPEC]			= "unspec",
185 	[BPF_PROG_TYPE_SOCKET_FILTER]		= "socket_filter",
186 	[BPF_PROG_TYPE_KPROBE]			= "kprobe",
187 	[BPF_PROG_TYPE_SCHED_CLS]		= "sched_cls",
188 	[BPF_PROG_TYPE_SCHED_ACT]		= "sched_act",
189 	[BPF_PROG_TYPE_TRACEPOINT]		= "tracepoint",
190 	[BPF_PROG_TYPE_XDP]			= "xdp",
191 	[BPF_PROG_TYPE_PERF_EVENT]		= "perf_event",
192 	[BPF_PROG_TYPE_CGROUP_SKB]		= "cgroup_skb",
193 	[BPF_PROG_TYPE_CGROUP_SOCK]		= "cgroup_sock",
194 	[BPF_PROG_TYPE_LWT_IN]			= "lwt_in",
195 	[BPF_PROG_TYPE_LWT_OUT]			= "lwt_out",
196 	[BPF_PROG_TYPE_LWT_XMIT]		= "lwt_xmit",
197 	[BPF_PROG_TYPE_SOCK_OPS]		= "sock_ops",
198 	[BPF_PROG_TYPE_SK_SKB]			= "sk_skb",
199 	[BPF_PROG_TYPE_CGROUP_DEVICE]		= "cgroup_device",
200 	[BPF_PROG_TYPE_SK_MSG]			= "sk_msg",
201 	[BPF_PROG_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
202 	[BPF_PROG_TYPE_CGROUP_SOCK_ADDR]	= "cgroup_sock_addr",
203 	[BPF_PROG_TYPE_LWT_SEG6LOCAL]		= "lwt_seg6local",
204 	[BPF_PROG_TYPE_LIRC_MODE2]		= "lirc_mode2",
205 	[BPF_PROG_TYPE_SK_REUSEPORT]		= "sk_reuseport",
206 	[BPF_PROG_TYPE_FLOW_DISSECTOR]		= "flow_dissector",
207 	[BPF_PROG_TYPE_CGROUP_SYSCTL]		= "cgroup_sysctl",
208 	[BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE]	= "raw_tracepoint_writable",
209 	[BPF_PROG_TYPE_CGROUP_SOCKOPT]		= "cgroup_sockopt",
210 	[BPF_PROG_TYPE_TRACING]			= "tracing",
211 	[BPF_PROG_TYPE_STRUCT_OPS]		= "struct_ops",
212 	[BPF_PROG_TYPE_EXT]			= "ext",
213 	[BPF_PROG_TYPE_LSM]			= "lsm",
214 	[BPF_PROG_TYPE_SK_LOOKUP]		= "sk_lookup",
215 	[BPF_PROG_TYPE_SYSCALL]			= "syscall",
216 	[BPF_PROG_TYPE_NETFILTER]		= "netfilter",
217 };
218 
219 static int __base_pr(enum libbpf_print_level level, const char *format,
220 		     va_list args)
221 {
222 	if (level == LIBBPF_DEBUG)
223 		return 0;
224 
225 	return vfprintf(stderr, format, args);
226 }
227 
228 static libbpf_print_fn_t __libbpf_pr = __base_pr;
229 
230 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
231 {
232 	libbpf_print_fn_t old_print_fn;
233 
234 	old_print_fn = __atomic_exchange_n(&__libbpf_pr, fn, __ATOMIC_RELAXED);
235 
236 	return old_print_fn;
237 }
238 
239 __printf(2, 3)
240 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
241 {
242 	va_list args;
243 	int old_errno;
244 	libbpf_print_fn_t print_fn;
245 
246 	print_fn = __atomic_load_n(&__libbpf_pr, __ATOMIC_RELAXED);
247 	if (!print_fn)
248 		return;
249 
250 	old_errno = errno;
251 
252 	va_start(args, format);
253 	__libbpf_pr(level, format, args);
254 	va_end(args);
255 
256 	errno = old_errno;
257 }
258 
259 static void pr_perm_msg(int err)
260 {
261 	struct rlimit limit;
262 	char buf[100];
263 
264 	if (err != -EPERM || geteuid() != 0)
265 		return;
266 
267 	err = getrlimit(RLIMIT_MEMLOCK, &limit);
268 	if (err)
269 		return;
270 
271 	if (limit.rlim_cur == RLIM_INFINITY)
272 		return;
273 
274 	if (limit.rlim_cur < 1024)
275 		snprintf(buf, sizeof(buf), "%zu bytes", (size_t)limit.rlim_cur);
276 	else if (limit.rlim_cur < 1024*1024)
277 		snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
278 	else
279 		snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
280 
281 	pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
282 		buf);
283 }
284 
285 #define STRERR_BUFSIZE  128
286 
287 /* Copied from tools/perf/util/util.h */
288 #ifndef zfree
289 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
290 #endif
291 
292 #ifndef zclose
293 # define zclose(fd) ({			\
294 	int ___err = 0;			\
295 	if ((fd) >= 0)			\
296 		___err = close((fd));	\
297 	fd = -1;			\
298 	___err; })
299 #endif
300 
301 static inline __u64 ptr_to_u64(const void *ptr)
302 {
303 	return (__u64) (unsigned long) ptr;
304 }
305 
306 int libbpf_set_strict_mode(enum libbpf_strict_mode mode)
307 {
308 	/* as of v1.0 libbpf_set_strict_mode() is a no-op */
309 	return 0;
310 }
311 
312 __u32 libbpf_major_version(void)
313 {
314 	return LIBBPF_MAJOR_VERSION;
315 }
316 
317 __u32 libbpf_minor_version(void)
318 {
319 	return LIBBPF_MINOR_VERSION;
320 }
321 
322 const char *libbpf_version_string(void)
323 {
324 #define __S(X) #X
325 #define _S(X) __S(X)
326 	return  "v" _S(LIBBPF_MAJOR_VERSION) "." _S(LIBBPF_MINOR_VERSION);
327 #undef _S
328 #undef __S
329 }
330 
331 enum reloc_type {
332 	RELO_LD64,
333 	RELO_CALL,
334 	RELO_DATA,
335 	RELO_EXTERN_LD64,
336 	RELO_EXTERN_CALL,
337 	RELO_SUBPROG_ADDR,
338 	RELO_CORE,
339 };
340 
341 struct reloc_desc {
342 	enum reloc_type type;
343 	int insn_idx;
344 	union {
345 		const struct bpf_core_relo *core_relo; /* used when type == RELO_CORE */
346 		struct {
347 			int map_idx;
348 			int sym_off;
349 			int ext_idx;
350 		};
351 	};
352 };
353 
354 /* stored as sec_def->cookie for all libbpf-supported SEC()s */
355 enum sec_def_flags {
356 	SEC_NONE = 0,
357 	/* expected_attach_type is optional, if kernel doesn't support that */
358 	SEC_EXP_ATTACH_OPT = 1,
359 	/* legacy, only used by libbpf_get_type_names() and
360 	 * libbpf_attach_type_by_name(), not used by libbpf itself at all.
361 	 * This used to be associated with cgroup (and few other) BPF programs
362 	 * that were attachable through BPF_PROG_ATTACH command. Pretty
363 	 * meaningless nowadays, though.
364 	 */
365 	SEC_ATTACHABLE = 2,
366 	SEC_ATTACHABLE_OPT = SEC_ATTACHABLE | SEC_EXP_ATTACH_OPT,
367 	/* attachment target is specified through BTF ID in either kernel or
368 	 * other BPF program's BTF object
369 	 */
370 	SEC_ATTACH_BTF = 4,
371 	/* BPF program type allows sleeping/blocking in kernel */
372 	SEC_SLEEPABLE = 8,
373 	/* BPF program support non-linear XDP buffer */
374 	SEC_XDP_FRAGS = 16,
375 	/* Setup proper attach type for usdt probes. */
376 	SEC_USDT = 32,
377 };
378 
379 struct bpf_sec_def {
380 	char *sec;
381 	enum bpf_prog_type prog_type;
382 	enum bpf_attach_type expected_attach_type;
383 	long cookie;
384 	int handler_id;
385 
386 	libbpf_prog_setup_fn_t prog_setup_fn;
387 	libbpf_prog_prepare_load_fn_t prog_prepare_load_fn;
388 	libbpf_prog_attach_fn_t prog_attach_fn;
389 };
390 
391 /*
392  * bpf_prog should be a better name but it has been used in
393  * linux/filter.h.
394  */
395 struct bpf_program {
396 	char *name;
397 	char *sec_name;
398 	size_t sec_idx;
399 	const struct bpf_sec_def *sec_def;
400 	/* this program's instruction offset (in number of instructions)
401 	 * within its containing ELF section
402 	 */
403 	size_t sec_insn_off;
404 	/* number of original instructions in ELF section belonging to this
405 	 * program, not taking into account subprogram instructions possible
406 	 * appended later during relocation
407 	 */
408 	size_t sec_insn_cnt;
409 	/* Offset (in number of instructions) of the start of instruction
410 	 * belonging to this BPF program  within its containing main BPF
411 	 * program. For the entry-point (main) BPF program, this is always
412 	 * zero. For a sub-program, this gets reset before each of main BPF
413 	 * programs are processed and relocated and is used to determined
414 	 * whether sub-program was already appended to the main program, and
415 	 * if yes, at which instruction offset.
416 	 */
417 	size_t sub_insn_off;
418 
419 	/* instructions that belong to BPF program; insns[0] is located at
420 	 * sec_insn_off instruction within its ELF section in ELF file, so
421 	 * when mapping ELF file instruction index to the local instruction,
422 	 * one needs to subtract sec_insn_off; and vice versa.
423 	 */
424 	struct bpf_insn *insns;
425 	/* actual number of instruction in this BPF program's image; for
426 	 * entry-point BPF programs this includes the size of main program
427 	 * itself plus all the used sub-programs, appended at the end
428 	 */
429 	size_t insns_cnt;
430 
431 	struct reloc_desc *reloc_desc;
432 	int nr_reloc;
433 
434 	/* BPF verifier log settings */
435 	char *log_buf;
436 	size_t log_size;
437 	__u32 log_level;
438 
439 	struct bpf_object *obj;
440 
441 	int fd;
442 	bool autoload;
443 	bool autoattach;
444 	bool sym_global;
445 	bool mark_btf_static;
446 	enum bpf_prog_type type;
447 	enum bpf_attach_type expected_attach_type;
448 	int exception_cb_idx;
449 
450 	int prog_ifindex;
451 	__u32 attach_btf_obj_fd;
452 	__u32 attach_btf_id;
453 	__u32 attach_prog_fd;
454 
455 	void *func_info;
456 	__u32 func_info_rec_size;
457 	__u32 func_info_cnt;
458 
459 	void *line_info;
460 	__u32 line_info_rec_size;
461 	__u32 line_info_cnt;
462 	__u32 prog_flags;
463 };
464 
465 struct bpf_struct_ops {
466 	const char *tname;
467 	const struct btf_type *type;
468 	struct bpf_program **progs;
469 	__u32 *kern_func_off;
470 	/* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
471 	void *data;
472 	/* e.g. struct bpf_struct_ops_tcp_congestion_ops in
473 	 *      btf_vmlinux's format.
474 	 * struct bpf_struct_ops_tcp_congestion_ops {
475 	 *	[... some other kernel fields ...]
476 	 *	struct tcp_congestion_ops data;
477 	 * }
478 	 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
479 	 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
480 	 * from "data".
481 	 */
482 	void *kern_vdata;
483 	__u32 type_id;
484 };
485 
486 #define DATA_SEC ".data"
487 #define BSS_SEC ".bss"
488 #define RODATA_SEC ".rodata"
489 #define KCONFIG_SEC ".kconfig"
490 #define KSYMS_SEC ".ksyms"
491 #define STRUCT_OPS_SEC ".struct_ops"
492 #define STRUCT_OPS_LINK_SEC ".struct_ops.link"
493 
494 enum libbpf_map_type {
495 	LIBBPF_MAP_UNSPEC,
496 	LIBBPF_MAP_DATA,
497 	LIBBPF_MAP_BSS,
498 	LIBBPF_MAP_RODATA,
499 	LIBBPF_MAP_KCONFIG,
500 };
501 
502 struct bpf_map_def {
503 	unsigned int type;
504 	unsigned int key_size;
505 	unsigned int value_size;
506 	unsigned int max_entries;
507 	unsigned int map_flags;
508 };
509 
510 struct bpf_map {
511 	struct bpf_object *obj;
512 	char *name;
513 	/* real_name is defined for special internal maps (.rodata*,
514 	 * .data*, .bss, .kconfig) and preserves their original ELF section
515 	 * name. This is important to be able to find corresponding BTF
516 	 * DATASEC information.
517 	 */
518 	char *real_name;
519 	int fd;
520 	int sec_idx;
521 	size_t sec_offset;
522 	int map_ifindex;
523 	int inner_map_fd;
524 	struct bpf_map_def def;
525 	__u32 numa_node;
526 	__u32 btf_var_idx;
527 	__u32 btf_key_type_id;
528 	__u32 btf_value_type_id;
529 	__u32 btf_vmlinux_value_type_id;
530 	enum libbpf_map_type libbpf_type;
531 	void *mmaped;
532 	struct bpf_struct_ops *st_ops;
533 	struct bpf_map *inner_map;
534 	void **init_slots;
535 	int init_slots_sz;
536 	char *pin_path;
537 	bool pinned;
538 	bool reused;
539 	bool autocreate;
540 	__u64 map_extra;
541 };
542 
543 enum extern_type {
544 	EXT_UNKNOWN,
545 	EXT_KCFG,
546 	EXT_KSYM,
547 };
548 
549 enum kcfg_type {
550 	KCFG_UNKNOWN,
551 	KCFG_CHAR,
552 	KCFG_BOOL,
553 	KCFG_INT,
554 	KCFG_TRISTATE,
555 	KCFG_CHAR_ARR,
556 };
557 
558 struct extern_desc {
559 	enum extern_type type;
560 	int sym_idx;
561 	int btf_id;
562 	int sec_btf_id;
563 	const char *name;
564 	char *essent_name;
565 	bool is_set;
566 	bool is_weak;
567 	union {
568 		struct {
569 			enum kcfg_type type;
570 			int sz;
571 			int align;
572 			int data_off;
573 			bool is_signed;
574 		} kcfg;
575 		struct {
576 			unsigned long long addr;
577 
578 			/* target btf_id of the corresponding kernel var. */
579 			int kernel_btf_obj_fd;
580 			int kernel_btf_id;
581 
582 			/* local btf_id of the ksym extern's type. */
583 			__u32 type_id;
584 			/* BTF fd index to be patched in for insn->off, this is
585 			 * 0 for vmlinux BTF, index in obj->fd_array for module
586 			 * BTF
587 			 */
588 			__s16 btf_fd_idx;
589 		} ksym;
590 	};
591 };
592 
593 struct module_btf {
594 	struct btf *btf;
595 	char *name;
596 	__u32 id;
597 	int fd;
598 	int fd_array_idx;
599 };
600 
601 enum sec_type {
602 	SEC_UNUSED = 0,
603 	SEC_RELO,
604 	SEC_BSS,
605 	SEC_DATA,
606 	SEC_RODATA,
607 };
608 
609 struct elf_sec_desc {
610 	enum sec_type sec_type;
611 	Elf64_Shdr *shdr;
612 	Elf_Data *data;
613 };
614 
615 struct elf_state {
616 	int fd;
617 	const void *obj_buf;
618 	size_t obj_buf_sz;
619 	Elf *elf;
620 	Elf64_Ehdr *ehdr;
621 	Elf_Data *symbols;
622 	Elf_Data *st_ops_data;
623 	Elf_Data *st_ops_link_data;
624 	size_t shstrndx; /* section index for section name strings */
625 	size_t strtabidx;
626 	struct elf_sec_desc *secs;
627 	size_t sec_cnt;
628 	int btf_maps_shndx;
629 	__u32 btf_maps_sec_btf_id;
630 	int text_shndx;
631 	int symbols_shndx;
632 	int st_ops_shndx;
633 	int st_ops_link_shndx;
634 };
635 
636 struct usdt_manager;
637 
638 struct bpf_object {
639 	char name[BPF_OBJ_NAME_LEN];
640 	char license[64];
641 	__u32 kern_version;
642 
643 	struct bpf_program *programs;
644 	size_t nr_programs;
645 	struct bpf_map *maps;
646 	size_t nr_maps;
647 	size_t maps_cap;
648 
649 	char *kconfig;
650 	struct extern_desc *externs;
651 	int nr_extern;
652 	int kconfig_map_idx;
653 
654 	bool loaded;
655 	bool has_subcalls;
656 	bool has_rodata;
657 
658 	struct bpf_gen *gen_loader;
659 
660 	/* Information when doing ELF related work. Only valid if efile.elf is not NULL */
661 	struct elf_state efile;
662 
663 	struct btf *btf;
664 	struct btf_ext *btf_ext;
665 
666 	/* Parse and load BTF vmlinux if any of the programs in the object need
667 	 * it at load time.
668 	 */
669 	struct btf *btf_vmlinux;
670 	/* Path to the custom BTF to be used for BPF CO-RE relocations as an
671 	 * override for vmlinux BTF.
672 	 */
673 	char *btf_custom_path;
674 	/* vmlinux BTF override for CO-RE relocations */
675 	struct btf *btf_vmlinux_override;
676 	/* Lazily initialized kernel module BTFs */
677 	struct module_btf *btf_modules;
678 	bool btf_modules_loaded;
679 	size_t btf_module_cnt;
680 	size_t btf_module_cap;
681 
682 	/* optional log settings passed to BPF_BTF_LOAD and BPF_PROG_LOAD commands */
683 	char *log_buf;
684 	size_t log_size;
685 	__u32 log_level;
686 
687 	int *fd_array;
688 	size_t fd_array_cap;
689 	size_t fd_array_cnt;
690 
691 	struct usdt_manager *usdt_man;
692 
693 	char path[];
694 };
695 
696 static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
697 static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
698 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
699 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
700 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn);
701 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
702 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
703 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx);
704 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx);
705 
706 void bpf_program__unload(struct bpf_program *prog)
707 {
708 	if (!prog)
709 		return;
710 
711 	zclose(prog->fd);
712 
713 	zfree(&prog->func_info);
714 	zfree(&prog->line_info);
715 }
716 
717 static void bpf_program__exit(struct bpf_program *prog)
718 {
719 	if (!prog)
720 		return;
721 
722 	bpf_program__unload(prog);
723 	zfree(&prog->name);
724 	zfree(&prog->sec_name);
725 	zfree(&prog->insns);
726 	zfree(&prog->reloc_desc);
727 
728 	prog->nr_reloc = 0;
729 	prog->insns_cnt = 0;
730 	prog->sec_idx = -1;
731 }
732 
733 static bool insn_is_subprog_call(const struct bpf_insn *insn)
734 {
735 	return BPF_CLASS(insn->code) == BPF_JMP &&
736 	       BPF_OP(insn->code) == BPF_CALL &&
737 	       BPF_SRC(insn->code) == BPF_K &&
738 	       insn->src_reg == BPF_PSEUDO_CALL &&
739 	       insn->dst_reg == 0 &&
740 	       insn->off == 0;
741 }
742 
743 static bool is_call_insn(const struct bpf_insn *insn)
744 {
745 	return insn->code == (BPF_JMP | BPF_CALL);
746 }
747 
748 static bool insn_is_pseudo_func(struct bpf_insn *insn)
749 {
750 	return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
751 }
752 
753 static int
754 bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
755 		      const char *name, size_t sec_idx, const char *sec_name,
756 		      size_t sec_off, void *insn_data, size_t insn_data_sz)
757 {
758 	if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
759 		pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
760 			sec_name, name, sec_off, insn_data_sz);
761 		return -EINVAL;
762 	}
763 
764 	memset(prog, 0, sizeof(*prog));
765 	prog->obj = obj;
766 
767 	prog->sec_idx = sec_idx;
768 	prog->sec_insn_off = sec_off / BPF_INSN_SZ;
769 	prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
770 	/* insns_cnt can later be increased by appending used subprograms */
771 	prog->insns_cnt = prog->sec_insn_cnt;
772 
773 	prog->type = BPF_PROG_TYPE_UNSPEC;
774 	prog->fd = -1;
775 	prog->exception_cb_idx = -1;
776 
777 	/* libbpf's convention for SEC("?abc...") is that it's just like
778 	 * SEC("abc...") but the corresponding bpf_program starts out with
779 	 * autoload set to false.
780 	 */
781 	if (sec_name[0] == '?') {
782 		prog->autoload = false;
783 		/* from now on forget there was ? in section name */
784 		sec_name++;
785 	} else {
786 		prog->autoload = true;
787 	}
788 
789 	prog->autoattach = true;
790 
791 	/* inherit object's log_level */
792 	prog->log_level = obj->log_level;
793 
794 	prog->sec_name = strdup(sec_name);
795 	if (!prog->sec_name)
796 		goto errout;
797 
798 	prog->name = strdup(name);
799 	if (!prog->name)
800 		goto errout;
801 
802 	prog->insns = malloc(insn_data_sz);
803 	if (!prog->insns)
804 		goto errout;
805 	memcpy(prog->insns, insn_data, insn_data_sz);
806 
807 	return 0;
808 errout:
809 	pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
810 	bpf_program__exit(prog);
811 	return -ENOMEM;
812 }
813 
814 static int
815 bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
816 			 const char *sec_name, int sec_idx)
817 {
818 	Elf_Data *symbols = obj->efile.symbols;
819 	struct bpf_program *prog, *progs;
820 	void *data = sec_data->d_buf;
821 	size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
822 	int nr_progs, err, i;
823 	const char *name;
824 	Elf64_Sym *sym;
825 
826 	progs = obj->programs;
827 	nr_progs = obj->nr_programs;
828 	nr_syms = symbols->d_size / sizeof(Elf64_Sym);
829 
830 	for (i = 0; i < nr_syms; i++) {
831 		sym = elf_sym_by_idx(obj, i);
832 
833 		if (sym->st_shndx != sec_idx)
834 			continue;
835 		if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC)
836 			continue;
837 
838 		prog_sz = sym->st_size;
839 		sec_off = sym->st_value;
840 
841 		name = elf_sym_str(obj, sym->st_name);
842 		if (!name) {
843 			pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
844 				sec_name, sec_off);
845 			return -LIBBPF_ERRNO__FORMAT;
846 		}
847 
848 		if (sec_off + prog_sz > sec_sz) {
849 			pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
850 				sec_name, sec_off);
851 			return -LIBBPF_ERRNO__FORMAT;
852 		}
853 
854 		if (sec_idx != obj->efile.text_shndx && ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
855 			pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
856 			return -ENOTSUP;
857 		}
858 
859 		pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
860 			 sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
861 
862 		progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
863 		if (!progs) {
864 			/*
865 			 * In this case the original obj->programs
866 			 * is still valid, so don't need special treat for
867 			 * bpf_close_object().
868 			 */
869 			pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
870 				sec_name, name);
871 			return -ENOMEM;
872 		}
873 		obj->programs = progs;
874 
875 		prog = &progs[nr_progs];
876 
877 		err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
878 					    sec_off, data + sec_off, prog_sz);
879 		if (err)
880 			return err;
881 
882 		if (ELF64_ST_BIND(sym->st_info) != STB_LOCAL)
883 			prog->sym_global = true;
884 
885 		/* if function is a global/weak symbol, but has restricted
886 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
887 		 * as static to enable more permissive BPF verification mode
888 		 * with more outside context available to BPF verifier
889 		 */
890 		if (prog->sym_global && (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
891 		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL))
892 			prog->mark_btf_static = true;
893 
894 		nr_progs++;
895 		obj->nr_programs = nr_progs;
896 	}
897 
898 	return 0;
899 }
900 
901 static const struct btf_member *
902 find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
903 {
904 	struct btf_member *m;
905 	int i;
906 
907 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
908 		if (btf_member_bit_offset(t, i) == bit_offset)
909 			return m;
910 	}
911 
912 	return NULL;
913 }
914 
915 static const struct btf_member *
916 find_member_by_name(const struct btf *btf, const struct btf_type *t,
917 		    const char *name)
918 {
919 	struct btf_member *m;
920 	int i;
921 
922 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
923 		if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
924 			return m;
925 	}
926 
927 	return NULL;
928 }
929 
930 #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
931 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
932 				   const char *name, __u32 kind);
933 
934 static int
935 find_struct_ops_kern_types(const struct btf *btf, const char *tname,
936 			   const struct btf_type **type, __u32 *type_id,
937 			   const struct btf_type **vtype, __u32 *vtype_id,
938 			   const struct btf_member **data_member)
939 {
940 	const struct btf_type *kern_type, *kern_vtype;
941 	const struct btf_member *kern_data_member;
942 	__s32 kern_vtype_id, kern_type_id;
943 	__u32 i;
944 
945 	kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
946 	if (kern_type_id < 0) {
947 		pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n",
948 			tname);
949 		return kern_type_id;
950 	}
951 	kern_type = btf__type_by_id(btf, kern_type_id);
952 
953 	/* Find the corresponding "map_value" type that will be used
954 	 * in map_update(BPF_MAP_TYPE_STRUCT_OPS).  For example,
955 	 * find "struct bpf_struct_ops_tcp_congestion_ops" from the
956 	 * btf_vmlinux.
957 	 */
958 	kern_vtype_id = find_btf_by_prefix_kind(btf, STRUCT_OPS_VALUE_PREFIX,
959 						tname, BTF_KIND_STRUCT);
960 	if (kern_vtype_id < 0) {
961 		pr_warn("struct_ops init_kern: struct %s%s is not found in kernel BTF\n",
962 			STRUCT_OPS_VALUE_PREFIX, tname);
963 		return kern_vtype_id;
964 	}
965 	kern_vtype = btf__type_by_id(btf, kern_vtype_id);
966 
967 	/* Find "struct tcp_congestion_ops" from
968 	 * struct bpf_struct_ops_tcp_congestion_ops {
969 	 *	[ ... ]
970 	 *	struct tcp_congestion_ops data;
971 	 * }
972 	 */
973 	kern_data_member = btf_members(kern_vtype);
974 	for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
975 		if (kern_data_member->type == kern_type_id)
976 			break;
977 	}
978 	if (i == btf_vlen(kern_vtype)) {
979 		pr_warn("struct_ops init_kern: struct %s data is not found in struct %s%s\n",
980 			tname, STRUCT_OPS_VALUE_PREFIX, tname);
981 		return -EINVAL;
982 	}
983 
984 	*type = kern_type;
985 	*type_id = kern_type_id;
986 	*vtype = kern_vtype;
987 	*vtype_id = kern_vtype_id;
988 	*data_member = kern_data_member;
989 
990 	return 0;
991 }
992 
993 static bool bpf_map__is_struct_ops(const struct bpf_map *map)
994 {
995 	return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
996 }
997 
998 /* Init the map's fields that depend on kern_btf */
999 static int bpf_map__init_kern_struct_ops(struct bpf_map *map,
1000 					 const struct btf *btf,
1001 					 const struct btf *kern_btf)
1002 {
1003 	const struct btf_member *member, *kern_member, *kern_data_member;
1004 	const struct btf_type *type, *kern_type, *kern_vtype;
1005 	__u32 i, kern_type_id, kern_vtype_id, kern_data_off;
1006 	struct bpf_struct_ops *st_ops;
1007 	void *data, *kern_data;
1008 	const char *tname;
1009 	int err;
1010 
1011 	st_ops = map->st_ops;
1012 	type = st_ops->type;
1013 	tname = st_ops->tname;
1014 	err = find_struct_ops_kern_types(kern_btf, tname,
1015 					 &kern_type, &kern_type_id,
1016 					 &kern_vtype, &kern_vtype_id,
1017 					 &kern_data_member);
1018 	if (err)
1019 		return err;
1020 
1021 	pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
1022 		 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
1023 
1024 	map->def.value_size = kern_vtype->size;
1025 	map->btf_vmlinux_value_type_id = kern_vtype_id;
1026 
1027 	st_ops->kern_vdata = calloc(1, kern_vtype->size);
1028 	if (!st_ops->kern_vdata)
1029 		return -ENOMEM;
1030 
1031 	data = st_ops->data;
1032 	kern_data_off = kern_data_member->offset / 8;
1033 	kern_data = st_ops->kern_vdata + kern_data_off;
1034 
1035 	member = btf_members(type);
1036 	for (i = 0; i < btf_vlen(type); i++, member++) {
1037 		const struct btf_type *mtype, *kern_mtype;
1038 		__u32 mtype_id, kern_mtype_id;
1039 		void *mdata, *kern_mdata;
1040 		__s64 msize, kern_msize;
1041 		__u32 moff, kern_moff;
1042 		__u32 kern_member_idx;
1043 		const char *mname;
1044 
1045 		mname = btf__name_by_offset(btf, member->name_off);
1046 		kern_member = find_member_by_name(kern_btf, kern_type, mname);
1047 		if (!kern_member) {
1048 			pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
1049 				map->name, mname);
1050 			return -ENOTSUP;
1051 		}
1052 
1053 		kern_member_idx = kern_member - btf_members(kern_type);
1054 		if (btf_member_bitfield_size(type, i) ||
1055 		    btf_member_bitfield_size(kern_type, kern_member_idx)) {
1056 			pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
1057 				map->name, mname);
1058 			return -ENOTSUP;
1059 		}
1060 
1061 		moff = member->offset / 8;
1062 		kern_moff = kern_member->offset / 8;
1063 
1064 		mdata = data + moff;
1065 		kern_mdata = kern_data + kern_moff;
1066 
1067 		mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
1068 		kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
1069 						    &kern_mtype_id);
1070 		if (BTF_INFO_KIND(mtype->info) !=
1071 		    BTF_INFO_KIND(kern_mtype->info)) {
1072 			pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
1073 				map->name, mname, BTF_INFO_KIND(mtype->info),
1074 				BTF_INFO_KIND(kern_mtype->info));
1075 			return -ENOTSUP;
1076 		}
1077 
1078 		if (btf_is_ptr(mtype)) {
1079 			struct bpf_program *prog;
1080 
1081 			prog = st_ops->progs[i];
1082 			if (!prog)
1083 				continue;
1084 
1085 			kern_mtype = skip_mods_and_typedefs(kern_btf,
1086 							    kern_mtype->type,
1087 							    &kern_mtype_id);
1088 
1089 			/* mtype->type must be a func_proto which was
1090 			 * guaranteed in bpf_object__collect_st_ops_relos(),
1091 			 * so only check kern_mtype for func_proto here.
1092 			 */
1093 			if (!btf_is_func_proto(kern_mtype)) {
1094 				pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
1095 					map->name, mname);
1096 				return -ENOTSUP;
1097 			}
1098 
1099 			prog->attach_btf_id = kern_type_id;
1100 			prog->expected_attach_type = kern_member_idx;
1101 
1102 			st_ops->kern_func_off[i] = kern_data_off + kern_moff;
1103 
1104 			pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
1105 				 map->name, mname, prog->name, moff,
1106 				 kern_moff);
1107 
1108 			continue;
1109 		}
1110 
1111 		msize = btf__resolve_size(btf, mtype_id);
1112 		kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
1113 		if (msize < 0 || kern_msize < 0 || msize != kern_msize) {
1114 			pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
1115 				map->name, mname, (ssize_t)msize,
1116 				(ssize_t)kern_msize);
1117 			return -ENOTSUP;
1118 		}
1119 
1120 		pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
1121 			 map->name, mname, (unsigned int)msize,
1122 			 moff, kern_moff);
1123 		memcpy(kern_mdata, mdata, msize);
1124 	}
1125 
1126 	return 0;
1127 }
1128 
1129 static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
1130 {
1131 	struct bpf_map *map;
1132 	size_t i;
1133 	int err;
1134 
1135 	for (i = 0; i < obj->nr_maps; i++) {
1136 		map = &obj->maps[i];
1137 
1138 		if (!bpf_map__is_struct_ops(map))
1139 			continue;
1140 
1141 		err = bpf_map__init_kern_struct_ops(map, obj->btf,
1142 						    obj->btf_vmlinux);
1143 		if (err)
1144 			return err;
1145 	}
1146 
1147 	return 0;
1148 }
1149 
1150 static int init_struct_ops_maps(struct bpf_object *obj, const char *sec_name,
1151 				int shndx, Elf_Data *data, __u32 map_flags)
1152 {
1153 	const struct btf_type *type, *datasec;
1154 	const struct btf_var_secinfo *vsi;
1155 	struct bpf_struct_ops *st_ops;
1156 	const char *tname, *var_name;
1157 	__s32 type_id, datasec_id;
1158 	const struct btf *btf;
1159 	struct bpf_map *map;
1160 	__u32 i;
1161 
1162 	if (shndx == -1)
1163 		return 0;
1164 
1165 	btf = obj->btf;
1166 	datasec_id = btf__find_by_name_kind(btf, sec_name,
1167 					    BTF_KIND_DATASEC);
1168 	if (datasec_id < 0) {
1169 		pr_warn("struct_ops init: DATASEC %s not found\n",
1170 			sec_name);
1171 		return -EINVAL;
1172 	}
1173 
1174 	datasec = btf__type_by_id(btf, datasec_id);
1175 	vsi = btf_var_secinfos(datasec);
1176 	for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
1177 		type = btf__type_by_id(obj->btf, vsi->type);
1178 		var_name = btf__name_by_offset(obj->btf, type->name_off);
1179 
1180 		type_id = btf__resolve_type(obj->btf, vsi->type);
1181 		if (type_id < 0) {
1182 			pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
1183 				vsi->type, sec_name);
1184 			return -EINVAL;
1185 		}
1186 
1187 		type = btf__type_by_id(obj->btf, type_id);
1188 		tname = btf__name_by_offset(obj->btf, type->name_off);
1189 		if (!tname[0]) {
1190 			pr_warn("struct_ops init: anonymous type is not supported\n");
1191 			return -ENOTSUP;
1192 		}
1193 		if (!btf_is_struct(type)) {
1194 			pr_warn("struct_ops init: %s is not a struct\n", tname);
1195 			return -EINVAL;
1196 		}
1197 
1198 		map = bpf_object__add_map(obj);
1199 		if (IS_ERR(map))
1200 			return PTR_ERR(map);
1201 
1202 		map->sec_idx = shndx;
1203 		map->sec_offset = vsi->offset;
1204 		map->name = strdup(var_name);
1205 		if (!map->name)
1206 			return -ENOMEM;
1207 
1208 		map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
1209 		map->def.key_size = sizeof(int);
1210 		map->def.value_size = type->size;
1211 		map->def.max_entries = 1;
1212 		map->def.map_flags = map_flags;
1213 
1214 		map->st_ops = calloc(1, sizeof(*map->st_ops));
1215 		if (!map->st_ops)
1216 			return -ENOMEM;
1217 		st_ops = map->st_ops;
1218 		st_ops->data = malloc(type->size);
1219 		st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1220 		st_ops->kern_func_off = malloc(btf_vlen(type) *
1221 					       sizeof(*st_ops->kern_func_off));
1222 		if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1223 			return -ENOMEM;
1224 
1225 		if (vsi->offset + type->size > data->d_size) {
1226 			pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1227 				var_name, sec_name);
1228 			return -EINVAL;
1229 		}
1230 
1231 		memcpy(st_ops->data,
1232 		       data->d_buf + vsi->offset,
1233 		       type->size);
1234 		st_ops->tname = tname;
1235 		st_ops->type = type;
1236 		st_ops->type_id = type_id;
1237 
1238 		pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
1239 			 tname, type_id, var_name, vsi->offset);
1240 	}
1241 
1242 	return 0;
1243 }
1244 
1245 static int bpf_object_init_struct_ops(struct bpf_object *obj)
1246 {
1247 	int err;
1248 
1249 	err = init_struct_ops_maps(obj, STRUCT_OPS_SEC, obj->efile.st_ops_shndx,
1250 				   obj->efile.st_ops_data, 0);
1251 	err = err ?: init_struct_ops_maps(obj, STRUCT_OPS_LINK_SEC,
1252 					  obj->efile.st_ops_link_shndx,
1253 					  obj->efile.st_ops_link_data,
1254 					  BPF_F_LINK);
1255 	return err;
1256 }
1257 
1258 static struct bpf_object *bpf_object__new(const char *path,
1259 					  const void *obj_buf,
1260 					  size_t obj_buf_sz,
1261 					  const char *obj_name)
1262 {
1263 	struct bpf_object *obj;
1264 	char *end;
1265 
1266 	obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1267 	if (!obj) {
1268 		pr_warn("alloc memory failed for %s\n", path);
1269 		return ERR_PTR(-ENOMEM);
1270 	}
1271 
1272 	strcpy(obj->path, path);
1273 	if (obj_name) {
1274 		libbpf_strlcpy(obj->name, obj_name, sizeof(obj->name));
1275 	} else {
1276 		/* Using basename() GNU version which doesn't modify arg. */
1277 		libbpf_strlcpy(obj->name, basename((void *)path), sizeof(obj->name));
1278 		end = strchr(obj->name, '.');
1279 		if (end)
1280 			*end = 0;
1281 	}
1282 
1283 	obj->efile.fd = -1;
1284 	/*
1285 	 * Caller of this function should also call
1286 	 * bpf_object__elf_finish() after data collection to return
1287 	 * obj_buf to user. If not, we should duplicate the buffer to
1288 	 * avoid user freeing them before elf finish.
1289 	 */
1290 	obj->efile.obj_buf = obj_buf;
1291 	obj->efile.obj_buf_sz = obj_buf_sz;
1292 	obj->efile.btf_maps_shndx = -1;
1293 	obj->efile.st_ops_shndx = -1;
1294 	obj->efile.st_ops_link_shndx = -1;
1295 	obj->kconfig_map_idx = -1;
1296 
1297 	obj->kern_version = get_kernel_version();
1298 	obj->loaded = false;
1299 
1300 	return obj;
1301 }
1302 
1303 static void bpf_object__elf_finish(struct bpf_object *obj)
1304 {
1305 	if (!obj->efile.elf)
1306 		return;
1307 
1308 	elf_end(obj->efile.elf);
1309 	obj->efile.elf = NULL;
1310 	obj->efile.symbols = NULL;
1311 	obj->efile.st_ops_data = NULL;
1312 	obj->efile.st_ops_link_data = NULL;
1313 
1314 	zfree(&obj->efile.secs);
1315 	obj->efile.sec_cnt = 0;
1316 	zclose(obj->efile.fd);
1317 	obj->efile.obj_buf = NULL;
1318 	obj->efile.obj_buf_sz = 0;
1319 }
1320 
1321 static int bpf_object__elf_init(struct bpf_object *obj)
1322 {
1323 	Elf64_Ehdr *ehdr;
1324 	int err = 0;
1325 	Elf *elf;
1326 
1327 	if (obj->efile.elf) {
1328 		pr_warn("elf: init internal error\n");
1329 		return -LIBBPF_ERRNO__LIBELF;
1330 	}
1331 
1332 	if (obj->efile.obj_buf_sz > 0) {
1333 		/* obj_buf should have been validated by bpf_object__open_mem(). */
1334 		elf = elf_memory((char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
1335 	} else {
1336 		obj->efile.fd = open(obj->path, O_RDONLY | O_CLOEXEC);
1337 		if (obj->efile.fd < 0) {
1338 			char errmsg[STRERR_BUFSIZE], *cp;
1339 
1340 			err = -errno;
1341 			cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
1342 			pr_warn("elf: failed to open %s: %s\n", obj->path, cp);
1343 			return err;
1344 		}
1345 
1346 		elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1347 	}
1348 
1349 	if (!elf) {
1350 		pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
1351 		err = -LIBBPF_ERRNO__LIBELF;
1352 		goto errout;
1353 	}
1354 
1355 	obj->efile.elf = elf;
1356 
1357 	if (elf_kind(elf) != ELF_K_ELF) {
1358 		err = -LIBBPF_ERRNO__FORMAT;
1359 		pr_warn("elf: '%s' is not a proper ELF object\n", obj->path);
1360 		goto errout;
1361 	}
1362 
1363 	if (gelf_getclass(elf) != ELFCLASS64) {
1364 		err = -LIBBPF_ERRNO__FORMAT;
1365 		pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path);
1366 		goto errout;
1367 	}
1368 
1369 	obj->efile.ehdr = ehdr = elf64_getehdr(elf);
1370 	if (!obj->efile.ehdr) {
1371 		pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
1372 		err = -LIBBPF_ERRNO__FORMAT;
1373 		goto errout;
1374 	}
1375 
1376 	if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
1377 		pr_warn("elf: failed to get section names section index for %s: %s\n",
1378 			obj->path, elf_errmsg(-1));
1379 		err = -LIBBPF_ERRNO__FORMAT;
1380 		goto errout;
1381 	}
1382 
1383 	/* ELF is corrupted/truncated, avoid calling elf_strptr. */
1384 	if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
1385 		pr_warn("elf: failed to get section names strings from %s: %s\n",
1386 			obj->path, elf_errmsg(-1));
1387 		err = -LIBBPF_ERRNO__FORMAT;
1388 		goto errout;
1389 	}
1390 
1391 	/* Old LLVM set e_machine to EM_NONE */
1392 	if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
1393 		pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
1394 		err = -LIBBPF_ERRNO__FORMAT;
1395 		goto errout;
1396 	}
1397 
1398 	return 0;
1399 errout:
1400 	bpf_object__elf_finish(obj);
1401 	return err;
1402 }
1403 
1404 static int bpf_object__check_endianness(struct bpf_object *obj)
1405 {
1406 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1407 	if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2LSB)
1408 		return 0;
1409 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1410 	if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2MSB)
1411 		return 0;
1412 #else
1413 # error "Unrecognized __BYTE_ORDER__"
1414 #endif
1415 	pr_warn("elf: endianness mismatch in %s.\n", obj->path);
1416 	return -LIBBPF_ERRNO__ENDIAN;
1417 }
1418 
1419 static int
1420 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1421 {
1422 	if (!data) {
1423 		pr_warn("invalid license section in %s\n", obj->path);
1424 		return -LIBBPF_ERRNO__FORMAT;
1425 	}
1426 	/* libbpf_strlcpy() only copies first N - 1 bytes, so size + 1 won't
1427 	 * go over allowed ELF data section buffer
1428 	 */
1429 	libbpf_strlcpy(obj->license, data, min(size + 1, sizeof(obj->license)));
1430 	pr_debug("license of %s is %s\n", obj->path, obj->license);
1431 	return 0;
1432 }
1433 
1434 static int
1435 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1436 {
1437 	__u32 kver;
1438 
1439 	if (!data || size != sizeof(kver)) {
1440 		pr_warn("invalid kver section in %s\n", obj->path);
1441 		return -LIBBPF_ERRNO__FORMAT;
1442 	}
1443 	memcpy(&kver, data, sizeof(kver));
1444 	obj->kern_version = kver;
1445 	pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1446 	return 0;
1447 }
1448 
1449 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1450 {
1451 	if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1452 	    type == BPF_MAP_TYPE_HASH_OF_MAPS)
1453 		return true;
1454 	return false;
1455 }
1456 
1457 static int find_elf_sec_sz(const struct bpf_object *obj, const char *name, __u32 *size)
1458 {
1459 	Elf_Data *data;
1460 	Elf_Scn *scn;
1461 
1462 	if (!name)
1463 		return -EINVAL;
1464 
1465 	scn = elf_sec_by_name(obj, name);
1466 	data = elf_sec_data(obj, scn);
1467 	if (data) {
1468 		*size = data->d_size;
1469 		return 0; /* found it */
1470 	}
1471 
1472 	return -ENOENT;
1473 }
1474 
1475 static Elf64_Sym *find_elf_var_sym(const struct bpf_object *obj, const char *name)
1476 {
1477 	Elf_Data *symbols = obj->efile.symbols;
1478 	const char *sname;
1479 	size_t si;
1480 
1481 	for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
1482 		Elf64_Sym *sym = elf_sym_by_idx(obj, si);
1483 
1484 		if (ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)
1485 			continue;
1486 
1487 		if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL &&
1488 		    ELF64_ST_BIND(sym->st_info) != STB_WEAK)
1489 			continue;
1490 
1491 		sname = elf_sym_str(obj, sym->st_name);
1492 		if (!sname) {
1493 			pr_warn("failed to get sym name string for var %s\n", name);
1494 			return ERR_PTR(-EIO);
1495 		}
1496 		if (strcmp(name, sname) == 0)
1497 			return sym;
1498 	}
1499 
1500 	return ERR_PTR(-ENOENT);
1501 }
1502 
1503 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1504 {
1505 	struct bpf_map *map;
1506 	int err;
1507 
1508 	err = libbpf_ensure_mem((void **)&obj->maps, &obj->maps_cap,
1509 				sizeof(*obj->maps), obj->nr_maps + 1);
1510 	if (err)
1511 		return ERR_PTR(err);
1512 
1513 	map = &obj->maps[obj->nr_maps++];
1514 	map->obj = obj;
1515 	map->fd = -1;
1516 	map->inner_map_fd = -1;
1517 	map->autocreate = true;
1518 
1519 	return map;
1520 }
1521 
1522 static size_t bpf_map_mmap_sz(unsigned int value_sz, unsigned int max_entries)
1523 {
1524 	const long page_sz = sysconf(_SC_PAGE_SIZE);
1525 	size_t map_sz;
1526 
1527 	map_sz = (size_t)roundup(value_sz, 8) * max_entries;
1528 	map_sz = roundup(map_sz, page_sz);
1529 	return map_sz;
1530 }
1531 
1532 static int bpf_map_mmap_resize(struct bpf_map *map, size_t old_sz, size_t new_sz)
1533 {
1534 	void *mmaped;
1535 
1536 	if (!map->mmaped)
1537 		return -EINVAL;
1538 
1539 	if (old_sz == new_sz)
1540 		return 0;
1541 
1542 	mmaped = mmap(NULL, new_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1543 	if (mmaped == MAP_FAILED)
1544 		return -errno;
1545 
1546 	memcpy(mmaped, map->mmaped, min(old_sz, new_sz));
1547 	munmap(map->mmaped, old_sz);
1548 	map->mmaped = mmaped;
1549 	return 0;
1550 }
1551 
1552 static char *internal_map_name(struct bpf_object *obj, const char *real_name)
1553 {
1554 	char map_name[BPF_OBJ_NAME_LEN], *p;
1555 	int pfx_len, sfx_len = max((size_t)7, strlen(real_name));
1556 
1557 	/* This is one of the more confusing parts of libbpf for various
1558 	 * reasons, some of which are historical. The original idea for naming
1559 	 * internal names was to include as much of BPF object name prefix as
1560 	 * possible, so that it can be distinguished from similar internal
1561 	 * maps of a different BPF object.
1562 	 * As an example, let's say we have bpf_object named 'my_object_name'
1563 	 * and internal map corresponding to '.rodata' ELF section. The final
1564 	 * map name advertised to user and to the kernel will be
1565 	 * 'my_objec.rodata', taking first 8 characters of object name and
1566 	 * entire 7 characters of '.rodata'.
1567 	 * Somewhat confusingly, if internal map ELF section name is shorter
1568 	 * than 7 characters, e.g., '.bss', we still reserve 7 characters
1569 	 * for the suffix, even though we only have 4 actual characters, and
1570 	 * resulting map will be called 'my_objec.bss', not even using all 15
1571 	 * characters allowed by the kernel. Oh well, at least the truncated
1572 	 * object name is somewhat consistent in this case. But if the map
1573 	 * name is '.kconfig', we'll still have entirety of '.kconfig' added
1574 	 * (8 chars) and thus will be left with only first 7 characters of the
1575 	 * object name ('my_obje'). Happy guessing, user, that the final map
1576 	 * name will be "my_obje.kconfig".
1577 	 * Now, with libbpf starting to support arbitrarily named .rodata.*
1578 	 * and .data.* data sections, it's possible that ELF section name is
1579 	 * longer than allowed 15 chars, so we now need to be careful to take
1580 	 * only up to 15 first characters of ELF name, taking no BPF object
1581 	 * name characters at all. So '.rodata.abracadabra' will result in
1582 	 * '.rodata.abracad' kernel and user-visible name.
1583 	 * We need to keep this convoluted logic intact for .data, .bss and
1584 	 * .rodata maps, but for new custom .data.custom and .rodata.custom
1585 	 * maps we use their ELF names as is, not prepending bpf_object name
1586 	 * in front. We still need to truncate them to 15 characters for the
1587 	 * kernel. Full name can be recovered for such maps by using DATASEC
1588 	 * BTF type associated with such map's value type, though.
1589 	 */
1590 	if (sfx_len >= BPF_OBJ_NAME_LEN)
1591 		sfx_len = BPF_OBJ_NAME_LEN - 1;
1592 
1593 	/* if there are two or more dots in map name, it's a custom dot map */
1594 	if (strchr(real_name + 1, '.') != NULL)
1595 		pfx_len = 0;
1596 	else
1597 		pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
1598 
1599 	snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1600 		 sfx_len, real_name);
1601 
1602 	/* sanitise map name to characters allowed by kernel */
1603 	for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1604 		if (!isalnum(*p) && *p != '_' && *p != '.')
1605 			*p = '_';
1606 
1607 	return strdup(map_name);
1608 }
1609 
1610 static int
1611 map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map);
1612 
1613 /* Internal BPF map is mmap()'able only if at least one of corresponding
1614  * DATASEC's VARs are to be exposed through BPF skeleton. I.e., it's a GLOBAL
1615  * variable and it's not marked as __hidden (which turns it into, effectively,
1616  * a STATIC variable).
1617  */
1618 static bool map_is_mmapable(struct bpf_object *obj, struct bpf_map *map)
1619 {
1620 	const struct btf_type *t, *vt;
1621 	struct btf_var_secinfo *vsi;
1622 	int i, n;
1623 
1624 	if (!map->btf_value_type_id)
1625 		return false;
1626 
1627 	t = btf__type_by_id(obj->btf, map->btf_value_type_id);
1628 	if (!btf_is_datasec(t))
1629 		return false;
1630 
1631 	vsi = btf_var_secinfos(t);
1632 	for (i = 0, n = btf_vlen(t); i < n; i++, vsi++) {
1633 		vt = btf__type_by_id(obj->btf, vsi->type);
1634 		if (!btf_is_var(vt))
1635 			continue;
1636 
1637 		if (btf_var(vt)->linkage != BTF_VAR_STATIC)
1638 			return true;
1639 	}
1640 
1641 	return false;
1642 }
1643 
1644 static int
1645 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
1646 			      const char *real_name, int sec_idx, void *data, size_t data_sz)
1647 {
1648 	struct bpf_map_def *def;
1649 	struct bpf_map *map;
1650 	size_t mmap_sz;
1651 	int err;
1652 
1653 	map = bpf_object__add_map(obj);
1654 	if (IS_ERR(map))
1655 		return PTR_ERR(map);
1656 
1657 	map->libbpf_type = type;
1658 	map->sec_idx = sec_idx;
1659 	map->sec_offset = 0;
1660 	map->real_name = strdup(real_name);
1661 	map->name = internal_map_name(obj, real_name);
1662 	if (!map->real_name || !map->name) {
1663 		zfree(&map->real_name);
1664 		zfree(&map->name);
1665 		return -ENOMEM;
1666 	}
1667 
1668 	def = &map->def;
1669 	def->type = BPF_MAP_TYPE_ARRAY;
1670 	def->key_size = sizeof(int);
1671 	def->value_size = data_sz;
1672 	def->max_entries = 1;
1673 	def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
1674 			 ? BPF_F_RDONLY_PROG : 0;
1675 
1676 	/* failures are fine because of maps like .rodata.str1.1 */
1677 	(void) map_fill_btf_type_info(obj, map);
1678 
1679 	if (map_is_mmapable(obj, map))
1680 		def->map_flags |= BPF_F_MMAPABLE;
1681 
1682 	pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
1683 		 map->name, map->sec_idx, map->sec_offset, def->map_flags);
1684 
1685 	mmap_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
1686 	map->mmaped = mmap(NULL, mmap_sz, PROT_READ | PROT_WRITE,
1687 			   MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1688 	if (map->mmaped == MAP_FAILED) {
1689 		err = -errno;
1690 		map->mmaped = NULL;
1691 		pr_warn("failed to alloc map '%s' content buffer: %d\n",
1692 			map->name, err);
1693 		zfree(&map->real_name);
1694 		zfree(&map->name);
1695 		return err;
1696 	}
1697 
1698 	if (data)
1699 		memcpy(map->mmaped, data, data_sz);
1700 
1701 	pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
1702 	return 0;
1703 }
1704 
1705 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
1706 {
1707 	struct elf_sec_desc *sec_desc;
1708 	const char *sec_name;
1709 	int err = 0, sec_idx;
1710 
1711 	/*
1712 	 * Populate obj->maps with libbpf internal maps.
1713 	 */
1714 	for (sec_idx = 1; sec_idx < obj->efile.sec_cnt; sec_idx++) {
1715 		sec_desc = &obj->efile.secs[sec_idx];
1716 
1717 		/* Skip recognized sections with size 0. */
1718 		if (!sec_desc->data || sec_desc->data->d_size == 0)
1719 			continue;
1720 
1721 		switch (sec_desc->sec_type) {
1722 		case SEC_DATA:
1723 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1724 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
1725 							    sec_name, sec_idx,
1726 							    sec_desc->data->d_buf,
1727 							    sec_desc->data->d_size);
1728 			break;
1729 		case SEC_RODATA:
1730 			obj->has_rodata = true;
1731 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1732 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
1733 							    sec_name, sec_idx,
1734 							    sec_desc->data->d_buf,
1735 							    sec_desc->data->d_size);
1736 			break;
1737 		case SEC_BSS:
1738 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1739 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
1740 							    sec_name, sec_idx,
1741 							    NULL,
1742 							    sec_desc->data->d_size);
1743 			break;
1744 		default:
1745 			/* skip */
1746 			break;
1747 		}
1748 		if (err)
1749 			return err;
1750 	}
1751 	return 0;
1752 }
1753 
1754 
1755 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
1756 					       const void *name)
1757 {
1758 	int i;
1759 
1760 	for (i = 0; i < obj->nr_extern; i++) {
1761 		if (strcmp(obj->externs[i].name, name) == 0)
1762 			return &obj->externs[i];
1763 	}
1764 	return NULL;
1765 }
1766 
1767 static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
1768 			      char value)
1769 {
1770 	switch (ext->kcfg.type) {
1771 	case KCFG_BOOL:
1772 		if (value == 'm') {
1773 			pr_warn("extern (kcfg) '%s': value '%c' implies tristate or char type\n",
1774 				ext->name, value);
1775 			return -EINVAL;
1776 		}
1777 		*(bool *)ext_val = value == 'y' ? true : false;
1778 		break;
1779 	case KCFG_TRISTATE:
1780 		if (value == 'y')
1781 			*(enum libbpf_tristate *)ext_val = TRI_YES;
1782 		else if (value == 'm')
1783 			*(enum libbpf_tristate *)ext_val = TRI_MODULE;
1784 		else /* value == 'n' */
1785 			*(enum libbpf_tristate *)ext_val = TRI_NO;
1786 		break;
1787 	case KCFG_CHAR:
1788 		*(char *)ext_val = value;
1789 		break;
1790 	case KCFG_UNKNOWN:
1791 	case KCFG_INT:
1792 	case KCFG_CHAR_ARR:
1793 	default:
1794 		pr_warn("extern (kcfg) '%s': value '%c' implies bool, tristate, or char type\n",
1795 			ext->name, value);
1796 		return -EINVAL;
1797 	}
1798 	ext->is_set = true;
1799 	return 0;
1800 }
1801 
1802 static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
1803 			      const char *value)
1804 {
1805 	size_t len;
1806 
1807 	if (ext->kcfg.type != KCFG_CHAR_ARR) {
1808 		pr_warn("extern (kcfg) '%s': value '%s' implies char array type\n",
1809 			ext->name, value);
1810 		return -EINVAL;
1811 	}
1812 
1813 	len = strlen(value);
1814 	if (value[len - 1] != '"') {
1815 		pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
1816 			ext->name, value);
1817 		return -EINVAL;
1818 	}
1819 
1820 	/* strip quotes */
1821 	len -= 2;
1822 	if (len >= ext->kcfg.sz) {
1823 		pr_warn("extern (kcfg) '%s': long string '%s' of (%zu bytes) truncated to %d bytes\n",
1824 			ext->name, value, len, ext->kcfg.sz - 1);
1825 		len = ext->kcfg.sz - 1;
1826 	}
1827 	memcpy(ext_val, value + 1, len);
1828 	ext_val[len] = '\0';
1829 	ext->is_set = true;
1830 	return 0;
1831 }
1832 
1833 static int parse_u64(const char *value, __u64 *res)
1834 {
1835 	char *value_end;
1836 	int err;
1837 
1838 	errno = 0;
1839 	*res = strtoull(value, &value_end, 0);
1840 	if (errno) {
1841 		err = -errno;
1842 		pr_warn("failed to parse '%s' as integer: %d\n", value, err);
1843 		return err;
1844 	}
1845 	if (*value_end) {
1846 		pr_warn("failed to parse '%s' as integer completely\n", value);
1847 		return -EINVAL;
1848 	}
1849 	return 0;
1850 }
1851 
1852 static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
1853 {
1854 	int bit_sz = ext->kcfg.sz * 8;
1855 
1856 	if (ext->kcfg.sz == 8)
1857 		return true;
1858 
1859 	/* Validate that value stored in u64 fits in integer of `ext->sz`
1860 	 * bytes size without any loss of information. If the target integer
1861 	 * is signed, we rely on the following limits of integer type of
1862 	 * Y bits and subsequent transformation:
1863 	 *
1864 	 *     -2^(Y-1) <= X           <= 2^(Y-1) - 1
1865 	 *            0 <= X + 2^(Y-1) <= 2^Y - 1
1866 	 *            0 <= X + 2^(Y-1) <  2^Y
1867 	 *
1868 	 *  For unsigned target integer, check that all the (64 - Y) bits are
1869 	 *  zero.
1870 	 */
1871 	if (ext->kcfg.is_signed)
1872 		return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
1873 	else
1874 		return (v >> bit_sz) == 0;
1875 }
1876 
1877 static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
1878 			      __u64 value)
1879 {
1880 	if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR &&
1881 	    ext->kcfg.type != KCFG_BOOL) {
1882 		pr_warn("extern (kcfg) '%s': value '%llu' implies integer, char, or boolean type\n",
1883 			ext->name, (unsigned long long)value);
1884 		return -EINVAL;
1885 	}
1886 	if (ext->kcfg.type == KCFG_BOOL && value > 1) {
1887 		pr_warn("extern (kcfg) '%s': value '%llu' isn't boolean compatible\n",
1888 			ext->name, (unsigned long long)value);
1889 		return -EINVAL;
1890 
1891 	}
1892 	if (!is_kcfg_value_in_range(ext, value)) {
1893 		pr_warn("extern (kcfg) '%s': value '%llu' doesn't fit in %d bytes\n",
1894 			ext->name, (unsigned long long)value, ext->kcfg.sz);
1895 		return -ERANGE;
1896 	}
1897 	switch (ext->kcfg.sz) {
1898 	case 1:
1899 		*(__u8 *)ext_val = value;
1900 		break;
1901 	case 2:
1902 		*(__u16 *)ext_val = value;
1903 		break;
1904 	case 4:
1905 		*(__u32 *)ext_val = value;
1906 		break;
1907 	case 8:
1908 		*(__u64 *)ext_val = value;
1909 		break;
1910 	default:
1911 		return -EINVAL;
1912 	}
1913 	ext->is_set = true;
1914 	return 0;
1915 }
1916 
1917 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
1918 					    char *buf, void *data)
1919 {
1920 	struct extern_desc *ext;
1921 	char *sep, *value;
1922 	int len, err = 0;
1923 	void *ext_val;
1924 	__u64 num;
1925 
1926 	if (!str_has_pfx(buf, "CONFIG_"))
1927 		return 0;
1928 
1929 	sep = strchr(buf, '=');
1930 	if (!sep) {
1931 		pr_warn("failed to parse '%s': no separator\n", buf);
1932 		return -EINVAL;
1933 	}
1934 
1935 	/* Trim ending '\n' */
1936 	len = strlen(buf);
1937 	if (buf[len - 1] == '\n')
1938 		buf[len - 1] = '\0';
1939 	/* Split on '=' and ensure that a value is present. */
1940 	*sep = '\0';
1941 	if (!sep[1]) {
1942 		*sep = '=';
1943 		pr_warn("failed to parse '%s': no value\n", buf);
1944 		return -EINVAL;
1945 	}
1946 
1947 	ext = find_extern_by_name(obj, buf);
1948 	if (!ext || ext->is_set)
1949 		return 0;
1950 
1951 	ext_val = data + ext->kcfg.data_off;
1952 	value = sep + 1;
1953 
1954 	switch (*value) {
1955 	case 'y': case 'n': case 'm':
1956 		err = set_kcfg_value_tri(ext, ext_val, *value);
1957 		break;
1958 	case '"':
1959 		err = set_kcfg_value_str(ext, ext_val, value);
1960 		break;
1961 	default:
1962 		/* assume integer */
1963 		err = parse_u64(value, &num);
1964 		if (err) {
1965 			pr_warn("extern (kcfg) '%s': value '%s' isn't a valid integer\n", ext->name, value);
1966 			return err;
1967 		}
1968 		if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
1969 			pr_warn("extern (kcfg) '%s': value '%s' implies integer type\n", ext->name, value);
1970 			return -EINVAL;
1971 		}
1972 		err = set_kcfg_value_num(ext, ext_val, num);
1973 		break;
1974 	}
1975 	if (err)
1976 		return err;
1977 	pr_debug("extern (kcfg) '%s': set to %s\n", ext->name, value);
1978 	return 0;
1979 }
1980 
1981 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
1982 {
1983 	char buf[PATH_MAX];
1984 	struct utsname uts;
1985 	int len, err = 0;
1986 	gzFile file;
1987 
1988 	uname(&uts);
1989 	len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
1990 	if (len < 0)
1991 		return -EINVAL;
1992 	else if (len >= PATH_MAX)
1993 		return -ENAMETOOLONG;
1994 
1995 	/* gzopen also accepts uncompressed files. */
1996 	file = gzopen(buf, "re");
1997 	if (!file)
1998 		file = gzopen("/proc/config.gz", "re");
1999 
2000 	if (!file) {
2001 		pr_warn("failed to open system Kconfig\n");
2002 		return -ENOENT;
2003 	}
2004 
2005 	while (gzgets(file, buf, sizeof(buf))) {
2006 		err = bpf_object__process_kconfig_line(obj, buf, data);
2007 		if (err) {
2008 			pr_warn("error parsing system Kconfig line '%s': %d\n",
2009 				buf, err);
2010 			goto out;
2011 		}
2012 	}
2013 
2014 out:
2015 	gzclose(file);
2016 	return err;
2017 }
2018 
2019 static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
2020 					const char *config, void *data)
2021 {
2022 	char buf[PATH_MAX];
2023 	int err = 0;
2024 	FILE *file;
2025 
2026 	file = fmemopen((void *)config, strlen(config), "r");
2027 	if (!file) {
2028 		err = -errno;
2029 		pr_warn("failed to open in-memory Kconfig: %d\n", err);
2030 		return err;
2031 	}
2032 
2033 	while (fgets(buf, sizeof(buf), file)) {
2034 		err = bpf_object__process_kconfig_line(obj, buf, data);
2035 		if (err) {
2036 			pr_warn("error parsing in-memory Kconfig line '%s': %d\n",
2037 				buf, err);
2038 			break;
2039 		}
2040 	}
2041 
2042 	fclose(file);
2043 	return err;
2044 }
2045 
2046 static int bpf_object__init_kconfig_map(struct bpf_object *obj)
2047 {
2048 	struct extern_desc *last_ext = NULL, *ext;
2049 	size_t map_sz;
2050 	int i, err;
2051 
2052 	for (i = 0; i < obj->nr_extern; i++) {
2053 		ext = &obj->externs[i];
2054 		if (ext->type == EXT_KCFG)
2055 			last_ext = ext;
2056 	}
2057 
2058 	if (!last_ext)
2059 		return 0;
2060 
2061 	map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
2062 	err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
2063 					    ".kconfig", obj->efile.symbols_shndx,
2064 					    NULL, map_sz);
2065 	if (err)
2066 		return err;
2067 
2068 	obj->kconfig_map_idx = obj->nr_maps - 1;
2069 
2070 	return 0;
2071 }
2072 
2073 const struct btf_type *
2074 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
2075 {
2076 	const struct btf_type *t = btf__type_by_id(btf, id);
2077 
2078 	if (res_id)
2079 		*res_id = id;
2080 
2081 	while (btf_is_mod(t) || btf_is_typedef(t)) {
2082 		if (res_id)
2083 			*res_id = t->type;
2084 		t = btf__type_by_id(btf, t->type);
2085 	}
2086 
2087 	return t;
2088 }
2089 
2090 static const struct btf_type *
2091 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
2092 {
2093 	const struct btf_type *t;
2094 
2095 	t = skip_mods_and_typedefs(btf, id, NULL);
2096 	if (!btf_is_ptr(t))
2097 		return NULL;
2098 
2099 	t = skip_mods_and_typedefs(btf, t->type, res_id);
2100 
2101 	return btf_is_func_proto(t) ? t : NULL;
2102 }
2103 
2104 static const char *__btf_kind_str(__u16 kind)
2105 {
2106 	switch (kind) {
2107 	case BTF_KIND_UNKN: return "void";
2108 	case BTF_KIND_INT: return "int";
2109 	case BTF_KIND_PTR: return "ptr";
2110 	case BTF_KIND_ARRAY: return "array";
2111 	case BTF_KIND_STRUCT: return "struct";
2112 	case BTF_KIND_UNION: return "union";
2113 	case BTF_KIND_ENUM: return "enum";
2114 	case BTF_KIND_FWD: return "fwd";
2115 	case BTF_KIND_TYPEDEF: return "typedef";
2116 	case BTF_KIND_VOLATILE: return "volatile";
2117 	case BTF_KIND_CONST: return "const";
2118 	case BTF_KIND_RESTRICT: return "restrict";
2119 	case BTF_KIND_FUNC: return "func";
2120 	case BTF_KIND_FUNC_PROTO: return "func_proto";
2121 	case BTF_KIND_VAR: return "var";
2122 	case BTF_KIND_DATASEC: return "datasec";
2123 	case BTF_KIND_FLOAT: return "float";
2124 	case BTF_KIND_DECL_TAG: return "decl_tag";
2125 	case BTF_KIND_TYPE_TAG: return "type_tag";
2126 	case BTF_KIND_ENUM64: return "enum64";
2127 	default: return "unknown";
2128 	}
2129 }
2130 
2131 const char *btf_kind_str(const struct btf_type *t)
2132 {
2133 	return __btf_kind_str(btf_kind(t));
2134 }
2135 
2136 /*
2137  * Fetch integer attribute of BTF map definition. Such attributes are
2138  * represented using a pointer to an array, in which dimensionality of array
2139  * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2140  * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2141  * type definition, while using only sizeof(void *) space in ELF data section.
2142  */
2143 static bool get_map_field_int(const char *map_name, const struct btf *btf,
2144 			      const struct btf_member *m, __u32 *res)
2145 {
2146 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2147 	const char *name = btf__name_by_offset(btf, m->name_off);
2148 	const struct btf_array *arr_info;
2149 	const struct btf_type *arr_t;
2150 
2151 	if (!btf_is_ptr(t)) {
2152 		pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2153 			map_name, name, btf_kind_str(t));
2154 		return false;
2155 	}
2156 
2157 	arr_t = btf__type_by_id(btf, t->type);
2158 	if (!arr_t) {
2159 		pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2160 			map_name, name, t->type);
2161 		return false;
2162 	}
2163 	if (!btf_is_array(arr_t)) {
2164 		pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2165 			map_name, name, btf_kind_str(arr_t));
2166 		return false;
2167 	}
2168 	arr_info = btf_array(arr_t);
2169 	*res = arr_info->nelems;
2170 	return true;
2171 }
2172 
2173 static int pathname_concat(char *buf, size_t buf_sz, const char *path, const char *name)
2174 {
2175 	int len;
2176 
2177 	len = snprintf(buf, buf_sz, "%s/%s", path, name);
2178 	if (len < 0)
2179 		return -EINVAL;
2180 	if (len >= buf_sz)
2181 		return -ENAMETOOLONG;
2182 
2183 	return 0;
2184 }
2185 
2186 static int build_map_pin_path(struct bpf_map *map, const char *path)
2187 {
2188 	char buf[PATH_MAX];
2189 	int err;
2190 
2191 	if (!path)
2192 		path = "/sys/fs/bpf";
2193 
2194 	err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
2195 	if (err)
2196 		return err;
2197 
2198 	return bpf_map__set_pin_path(map, buf);
2199 }
2200 
2201 /* should match definition in bpf_helpers.h */
2202 enum libbpf_pin_type {
2203 	LIBBPF_PIN_NONE,
2204 	/* PIN_BY_NAME: pin maps by name (in /sys/fs/bpf by default) */
2205 	LIBBPF_PIN_BY_NAME,
2206 };
2207 
2208 int parse_btf_map_def(const char *map_name, struct btf *btf,
2209 		      const struct btf_type *def_t, bool strict,
2210 		      struct btf_map_def *map_def, struct btf_map_def *inner_def)
2211 {
2212 	const struct btf_type *t;
2213 	const struct btf_member *m;
2214 	bool is_inner = inner_def == NULL;
2215 	int vlen, i;
2216 
2217 	vlen = btf_vlen(def_t);
2218 	m = btf_members(def_t);
2219 	for (i = 0; i < vlen; i++, m++) {
2220 		const char *name = btf__name_by_offset(btf, m->name_off);
2221 
2222 		if (!name) {
2223 			pr_warn("map '%s': invalid field #%d.\n", map_name, i);
2224 			return -EINVAL;
2225 		}
2226 		if (strcmp(name, "type") == 0) {
2227 			if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
2228 				return -EINVAL;
2229 			map_def->parts |= MAP_DEF_MAP_TYPE;
2230 		} else if (strcmp(name, "max_entries") == 0) {
2231 			if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
2232 				return -EINVAL;
2233 			map_def->parts |= MAP_DEF_MAX_ENTRIES;
2234 		} else if (strcmp(name, "map_flags") == 0) {
2235 			if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
2236 				return -EINVAL;
2237 			map_def->parts |= MAP_DEF_MAP_FLAGS;
2238 		} else if (strcmp(name, "numa_node") == 0) {
2239 			if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
2240 				return -EINVAL;
2241 			map_def->parts |= MAP_DEF_NUMA_NODE;
2242 		} else if (strcmp(name, "key_size") == 0) {
2243 			__u32 sz;
2244 
2245 			if (!get_map_field_int(map_name, btf, m, &sz))
2246 				return -EINVAL;
2247 			if (map_def->key_size && map_def->key_size != sz) {
2248 				pr_warn("map '%s': conflicting key size %u != %u.\n",
2249 					map_name, map_def->key_size, sz);
2250 				return -EINVAL;
2251 			}
2252 			map_def->key_size = sz;
2253 			map_def->parts |= MAP_DEF_KEY_SIZE;
2254 		} else if (strcmp(name, "key") == 0) {
2255 			__s64 sz;
2256 
2257 			t = btf__type_by_id(btf, m->type);
2258 			if (!t) {
2259 				pr_warn("map '%s': key type [%d] not found.\n",
2260 					map_name, m->type);
2261 				return -EINVAL;
2262 			}
2263 			if (!btf_is_ptr(t)) {
2264 				pr_warn("map '%s': key spec is not PTR: %s.\n",
2265 					map_name, btf_kind_str(t));
2266 				return -EINVAL;
2267 			}
2268 			sz = btf__resolve_size(btf, t->type);
2269 			if (sz < 0) {
2270 				pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2271 					map_name, t->type, (ssize_t)sz);
2272 				return sz;
2273 			}
2274 			if (map_def->key_size && map_def->key_size != sz) {
2275 				pr_warn("map '%s': conflicting key size %u != %zd.\n",
2276 					map_name, map_def->key_size, (ssize_t)sz);
2277 				return -EINVAL;
2278 			}
2279 			map_def->key_size = sz;
2280 			map_def->key_type_id = t->type;
2281 			map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
2282 		} else if (strcmp(name, "value_size") == 0) {
2283 			__u32 sz;
2284 
2285 			if (!get_map_field_int(map_name, btf, m, &sz))
2286 				return -EINVAL;
2287 			if (map_def->value_size && map_def->value_size != sz) {
2288 				pr_warn("map '%s': conflicting value size %u != %u.\n",
2289 					map_name, map_def->value_size, sz);
2290 				return -EINVAL;
2291 			}
2292 			map_def->value_size = sz;
2293 			map_def->parts |= MAP_DEF_VALUE_SIZE;
2294 		} else if (strcmp(name, "value") == 0) {
2295 			__s64 sz;
2296 
2297 			t = btf__type_by_id(btf, m->type);
2298 			if (!t) {
2299 				pr_warn("map '%s': value type [%d] not found.\n",
2300 					map_name, m->type);
2301 				return -EINVAL;
2302 			}
2303 			if (!btf_is_ptr(t)) {
2304 				pr_warn("map '%s': value spec is not PTR: %s.\n",
2305 					map_name, btf_kind_str(t));
2306 				return -EINVAL;
2307 			}
2308 			sz = btf__resolve_size(btf, t->type);
2309 			if (sz < 0) {
2310 				pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2311 					map_name, t->type, (ssize_t)sz);
2312 				return sz;
2313 			}
2314 			if (map_def->value_size && map_def->value_size != sz) {
2315 				pr_warn("map '%s': conflicting value size %u != %zd.\n",
2316 					map_name, map_def->value_size, (ssize_t)sz);
2317 				return -EINVAL;
2318 			}
2319 			map_def->value_size = sz;
2320 			map_def->value_type_id = t->type;
2321 			map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
2322 		}
2323 		else if (strcmp(name, "values") == 0) {
2324 			bool is_map_in_map = bpf_map_type__is_map_in_map(map_def->map_type);
2325 			bool is_prog_array = map_def->map_type == BPF_MAP_TYPE_PROG_ARRAY;
2326 			const char *desc = is_map_in_map ? "map-in-map inner" : "prog-array value";
2327 			char inner_map_name[128];
2328 			int err;
2329 
2330 			if (is_inner) {
2331 				pr_warn("map '%s': multi-level inner maps not supported.\n",
2332 					map_name);
2333 				return -ENOTSUP;
2334 			}
2335 			if (i != vlen - 1) {
2336 				pr_warn("map '%s': '%s' member should be last.\n",
2337 					map_name, name);
2338 				return -EINVAL;
2339 			}
2340 			if (!is_map_in_map && !is_prog_array) {
2341 				pr_warn("map '%s': should be map-in-map or prog-array.\n",
2342 					map_name);
2343 				return -ENOTSUP;
2344 			}
2345 			if (map_def->value_size && map_def->value_size != 4) {
2346 				pr_warn("map '%s': conflicting value size %u != 4.\n",
2347 					map_name, map_def->value_size);
2348 				return -EINVAL;
2349 			}
2350 			map_def->value_size = 4;
2351 			t = btf__type_by_id(btf, m->type);
2352 			if (!t) {
2353 				pr_warn("map '%s': %s type [%d] not found.\n",
2354 					map_name, desc, m->type);
2355 				return -EINVAL;
2356 			}
2357 			if (!btf_is_array(t) || btf_array(t)->nelems) {
2358 				pr_warn("map '%s': %s spec is not a zero-sized array.\n",
2359 					map_name, desc);
2360 				return -EINVAL;
2361 			}
2362 			t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
2363 			if (!btf_is_ptr(t)) {
2364 				pr_warn("map '%s': %s def is of unexpected kind %s.\n",
2365 					map_name, desc, btf_kind_str(t));
2366 				return -EINVAL;
2367 			}
2368 			t = skip_mods_and_typedefs(btf, t->type, NULL);
2369 			if (is_prog_array) {
2370 				if (!btf_is_func_proto(t)) {
2371 					pr_warn("map '%s': prog-array value def is of unexpected kind %s.\n",
2372 						map_name, btf_kind_str(t));
2373 					return -EINVAL;
2374 				}
2375 				continue;
2376 			}
2377 			if (!btf_is_struct(t)) {
2378 				pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2379 					map_name, btf_kind_str(t));
2380 				return -EINVAL;
2381 			}
2382 
2383 			snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2384 			err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
2385 			if (err)
2386 				return err;
2387 
2388 			map_def->parts |= MAP_DEF_INNER_MAP;
2389 		} else if (strcmp(name, "pinning") == 0) {
2390 			__u32 val;
2391 
2392 			if (is_inner) {
2393 				pr_warn("map '%s': inner def can't be pinned.\n", map_name);
2394 				return -EINVAL;
2395 			}
2396 			if (!get_map_field_int(map_name, btf, m, &val))
2397 				return -EINVAL;
2398 			if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
2399 				pr_warn("map '%s': invalid pinning value %u.\n",
2400 					map_name, val);
2401 				return -EINVAL;
2402 			}
2403 			map_def->pinning = val;
2404 			map_def->parts |= MAP_DEF_PINNING;
2405 		} else if (strcmp(name, "map_extra") == 0) {
2406 			__u32 map_extra;
2407 
2408 			if (!get_map_field_int(map_name, btf, m, &map_extra))
2409 				return -EINVAL;
2410 			map_def->map_extra = map_extra;
2411 			map_def->parts |= MAP_DEF_MAP_EXTRA;
2412 		} else {
2413 			if (strict) {
2414 				pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
2415 				return -ENOTSUP;
2416 			}
2417 			pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
2418 		}
2419 	}
2420 
2421 	if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2422 		pr_warn("map '%s': map type isn't specified.\n", map_name);
2423 		return -EINVAL;
2424 	}
2425 
2426 	return 0;
2427 }
2428 
2429 static size_t adjust_ringbuf_sz(size_t sz)
2430 {
2431 	__u32 page_sz = sysconf(_SC_PAGE_SIZE);
2432 	__u32 mul;
2433 
2434 	/* if user forgot to set any size, make sure they see error */
2435 	if (sz == 0)
2436 		return 0;
2437 	/* Kernel expects BPF_MAP_TYPE_RINGBUF's max_entries to be
2438 	 * a power-of-2 multiple of kernel's page size. If user diligently
2439 	 * satisified these conditions, pass the size through.
2440 	 */
2441 	if ((sz % page_sz) == 0 && is_pow_of_2(sz / page_sz))
2442 		return sz;
2443 
2444 	/* Otherwise find closest (page_sz * power_of_2) product bigger than
2445 	 * user-set size to satisfy both user size request and kernel
2446 	 * requirements and substitute correct max_entries for map creation.
2447 	 */
2448 	for (mul = 1; mul <= UINT_MAX / page_sz; mul <<= 1) {
2449 		if (mul * page_sz > sz)
2450 			return mul * page_sz;
2451 	}
2452 
2453 	/* if it's impossible to satisfy the conditions (i.e., user size is
2454 	 * very close to UINT_MAX but is not a power-of-2 multiple of
2455 	 * page_size) then just return original size and let kernel reject it
2456 	 */
2457 	return sz;
2458 }
2459 
2460 static bool map_is_ringbuf(const struct bpf_map *map)
2461 {
2462 	return map->def.type == BPF_MAP_TYPE_RINGBUF ||
2463 	       map->def.type == BPF_MAP_TYPE_USER_RINGBUF;
2464 }
2465 
2466 static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2467 {
2468 	map->def.type = def->map_type;
2469 	map->def.key_size = def->key_size;
2470 	map->def.value_size = def->value_size;
2471 	map->def.max_entries = def->max_entries;
2472 	map->def.map_flags = def->map_flags;
2473 	map->map_extra = def->map_extra;
2474 
2475 	map->numa_node = def->numa_node;
2476 	map->btf_key_type_id = def->key_type_id;
2477 	map->btf_value_type_id = def->value_type_id;
2478 
2479 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
2480 	if (map_is_ringbuf(map))
2481 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
2482 
2483 	if (def->parts & MAP_DEF_MAP_TYPE)
2484 		pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2485 
2486 	if (def->parts & MAP_DEF_KEY_TYPE)
2487 		pr_debug("map '%s': found key [%u], sz = %u.\n",
2488 			 map->name, def->key_type_id, def->key_size);
2489 	else if (def->parts & MAP_DEF_KEY_SIZE)
2490 		pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2491 
2492 	if (def->parts & MAP_DEF_VALUE_TYPE)
2493 		pr_debug("map '%s': found value [%u], sz = %u.\n",
2494 			 map->name, def->value_type_id, def->value_size);
2495 	else if (def->parts & MAP_DEF_VALUE_SIZE)
2496 		pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2497 
2498 	if (def->parts & MAP_DEF_MAX_ENTRIES)
2499 		pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2500 	if (def->parts & MAP_DEF_MAP_FLAGS)
2501 		pr_debug("map '%s': found map_flags = 0x%x.\n", map->name, def->map_flags);
2502 	if (def->parts & MAP_DEF_MAP_EXTRA)
2503 		pr_debug("map '%s': found map_extra = 0x%llx.\n", map->name,
2504 			 (unsigned long long)def->map_extra);
2505 	if (def->parts & MAP_DEF_PINNING)
2506 		pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2507 	if (def->parts & MAP_DEF_NUMA_NODE)
2508 		pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2509 
2510 	if (def->parts & MAP_DEF_INNER_MAP)
2511 		pr_debug("map '%s': found inner map definition.\n", map->name);
2512 }
2513 
2514 static const char *btf_var_linkage_str(__u32 linkage)
2515 {
2516 	switch (linkage) {
2517 	case BTF_VAR_STATIC: return "static";
2518 	case BTF_VAR_GLOBAL_ALLOCATED: return "global";
2519 	case BTF_VAR_GLOBAL_EXTERN: return "extern";
2520 	default: return "unknown";
2521 	}
2522 }
2523 
2524 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2525 					 const struct btf_type *sec,
2526 					 int var_idx, int sec_idx,
2527 					 const Elf_Data *data, bool strict,
2528 					 const char *pin_root_path)
2529 {
2530 	struct btf_map_def map_def = {}, inner_def = {};
2531 	const struct btf_type *var, *def;
2532 	const struct btf_var_secinfo *vi;
2533 	const struct btf_var *var_extra;
2534 	const char *map_name;
2535 	struct bpf_map *map;
2536 	int err;
2537 
2538 	vi = btf_var_secinfos(sec) + var_idx;
2539 	var = btf__type_by_id(obj->btf, vi->type);
2540 	var_extra = btf_var(var);
2541 	map_name = btf__name_by_offset(obj->btf, var->name_off);
2542 
2543 	if (map_name == NULL || map_name[0] == '\0') {
2544 		pr_warn("map #%d: empty name.\n", var_idx);
2545 		return -EINVAL;
2546 	}
2547 	if ((__u64)vi->offset + vi->size > data->d_size) {
2548 		pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2549 		return -EINVAL;
2550 	}
2551 	if (!btf_is_var(var)) {
2552 		pr_warn("map '%s': unexpected var kind %s.\n",
2553 			map_name, btf_kind_str(var));
2554 		return -EINVAL;
2555 	}
2556 	if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
2557 		pr_warn("map '%s': unsupported map linkage %s.\n",
2558 			map_name, btf_var_linkage_str(var_extra->linkage));
2559 		return -EOPNOTSUPP;
2560 	}
2561 
2562 	def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2563 	if (!btf_is_struct(def)) {
2564 		pr_warn("map '%s': unexpected def kind %s.\n",
2565 			map_name, btf_kind_str(var));
2566 		return -EINVAL;
2567 	}
2568 	if (def->size > vi->size) {
2569 		pr_warn("map '%s': invalid def size.\n", map_name);
2570 		return -EINVAL;
2571 	}
2572 
2573 	map = bpf_object__add_map(obj);
2574 	if (IS_ERR(map))
2575 		return PTR_ERR(map);
2576 	map->name = strdup(map_name);
2577 	if (!map->name) {
2578 		pr_warn("map '%s': failed to alloc map name.\n", map_name);
2579 		return -ENOMEM;
2580 	}
2581 	map->libbpf_type = LIBBPF_MAP_UNSPEC;
2582 	map->def.type = BPF_MAP_TYPE_UNSPEC;
2583 	map->sec_idx = sec_idx;
2584 	map->sec_offset = vi->offset;
2585 	map->btf_var_idx = var_idx;
2586 	pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2587 		 map_name, map->sec_idx, map->sec_offset);
2588 
2589 	err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
2590 	if (err)
2591 		return err;
2592 
2593 	fill_map_from_def(map, &map_def);
2594 
2595 	if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
2596 		err = build_map_pin_path(map, pin_root_path);
2597 		if (err) {
2598 			pr_warn("map '%s': couldn't build pin path.\n", map->name);
2599 			return err;
2600 		}
2601 	}
2602 
2603 	if (map_def.parts & MAP_DEF_INNER_MAP) {
2604 		map->inner_map = calloc(1, sizeof(*map->inner_map));
2605 		if (!map->inner_map)
2606 			return -ENOMEM;
2607 		map->inner_map->fd = -1;
2608 		map->inner_map->sec_idx = sec_idx;
2609 		map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
2610 		if (!map->inner_map->name)
2611 			return -ENOMEM;
2612 		sprintf(map->inner_map->name, "%s.inner", map_name);
2613 
2614 		fill_map_from_def(map->inner_map, &inner_def);
2615 	}
2616 
2617 	err = map_fill_btf_type_info(obj, map);
2618 	if (err)
2619 		return err;
2620 
2621 	return 0;
2622 }
2623 
2624 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
2625 					  const char *pin_root_path)
2626 {
2627 	const struct btf_type *sec = NULL;
2628 	int nr_types, i, vlen, err;
2629 	const struct btf_type *t;
2630 	const char *name;
2631 	Elf_Data *data;
2632 	Elf_Scn *scn;
2633 
2634 	if (obj->efile.btf_maps_shndx < 0)
2635 		return 0;
2636 
2637 	scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
2638 	data = elf_sec_data(obj, scn);
2639 	if (!scn || !data) {
2640 		pr_warn("elf: failed to get %s map definitions for %s\n",
2641 			MAPS_ELF_SEC, obj->path);
2642 		return -EINVAL;
2643 	}
2644 
2645 	nr_types = btf__type_cnt(obj->btf);
2646 	for (i = 1; i < nr_types; i++) {
2647 		t = btf__type_by_id(obj->btf, i);
2648 		if (!btf_is_datasec(t))
2649 			continue;
2650 		name = btf__name_by_offset(obj->btf, t->name_off);
2651 		if (strcmp(name, MAPS_ELF_SEC) == 0) {
2652 			sec = t;
2653 			obj->efile.btf_maps_sec_btf_id = i;
2654 			break;
2655 		}
2656 	}
2657 
2658 	if (!sec) {
2659 		pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
2660 		return -ENOENT;
2661 	}
2662 
2663 	vlen = btf_vlen(sec);
2664 	for (i = 0; i < vlen; i++) {
2665 		err = bpf_object__init_user_btf_map(obj, sec, i,
2666 						    obj->efile.btf_maps_shndx,
2667 						    data, strict,
2668 						    pin_root_path);
2669 		if (err)
2670 			return err;
2671 	}
2672 
2673 	return 0;
2674 }
2675 
2676 static int bpf_object__init_maps(struct bpf_object *obj,
2677 				 const struct bpf_object_open_opts *opts)
2678 {
2679 	const char *pin_root_path;
2680 	bool strict;
2681 	int err = 0;
2682 
2683 	strict = !OPTS_GET(opts, relaxed_maps, false);
2684 	pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
2685 
2686 	err = bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
2687 	err = err ?: bpf_object__init_global_data_maps(obj);
2688 	err = err ?: bpf_object__init_kconfig_map(obj);
2689 	err = err ?: bpf_object_init_struct_ops(obj);
2690 
2691 	return err;
2692 }
2693 
2694 static bool section_have_execinstr(struct bpf_object *obj, int idx)
2695 {
2696 	Elf64_Shdr *sh;
2697 
2698 	sh = elf_sec_hdr(obj, elf_sec_by_idx(obj, idx));
2699 	if (!sh)
2700 		return false;
2701 
2702 	return sh->sh_flags & SHF_EXECINSTR;
2703 }
2704 
2705 static bool btf_needs_sanitization(struct bpf_object *obj)
2706 {
2707 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2708 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2709 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2710 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2711 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2712 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2713 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
2714 
2715 	return !has_func || !has_datasec || !has_func_global || !has_float ||
2716 	       !has_decl_tag || !has_type_tag || !has_enum64;
2717 }
2718 
2719 static int bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *btf)
2720 {
2721 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2722 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2723 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2724 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2725 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2726 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2727 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
2728 	int enum64_placeholder_id = 0;
2729 	struct btf_type *t;
2730 	int i, j, vlen;
2731 
2732 	for (i = 1; i < btf__type_cnt(btf); i++) {
2733 		t = (struct btf_type *)btf__type_by_id(btf, i);
2734 
2735 		if ((!has_datasec && btf_is_var(t)) || (!has_decl_tag && btf_is_decl_tag(t))) {
2736 			/* replace VAR/DECL_TAG with INT */
2737 			t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
2738 			/*
2739 			 * using size = 1 is the safest choice, 4 will be too
2740 			 * big and cause kernel BTF validation failure if
2741 			 * original variable took less than 4 bytes
2742 			 */
2743 			t->size = 1;
2744 			*(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
2745 		} else if (!has_datasec && btf_is_datasec(t)) {
2746 			/* replace DATASEC with STRUCT */
2747 			const struct btf_var_secinfo *v = btf_var_secinfos(t);
2748 			struct btf_member *m = btf_members(t);
2749 			struct btf_type *vt;
2750 			char *name;
2751 
2752 			name = (char *)btf__name_by_offset(btf, t->name_off);
2753 			while (*name) {
2754 				if (*name == '.')
2755 					*name = '_';
2756 				name++;
2757 			}
2758 
2759 			vlen = btf_vlen(t);
2760 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
2761 			for (j = 0; j < vlen; j++, v++, m++) {
2762 				/* order of field assignments is important */
2763 				m->offset = v->offset * 8;
2764 				m->type = v->type;
2765 				/* preserve variable name as member name */
2766 				vt = (void *)btf__type_by_id(btf, v->type);
2767 				m->name_off = vt->name_off;
2768 			}
2769 		} else if (!has_func && btf_is_func_proto(t)) {
2770 			/* replace FUNC_PROTO with ENUM */
2771 			vlen = btf_vlen(t);
2772 			t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
2773 			t->size = sizeof(__u32); /* kernel enforced */
2774 		} else if (!has_func && btf_is_func(t)) {
2775 			/* replace FUNC with TYPEDEF */
2776 			t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
2777 		} else if (!has_func_global && btf_is_func(t)) {
2778 			/* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
2779 			t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
2780 		} else if (!has_float && btf_is_float(t)) {
2781 			/* replace FLOAT with an equally-sized empty STRUCT;
2782 			 * since C compilers do not accept e.g. "float" as a
2783 			 * valid struct name, make it anonymous
2784 			 */
2785 			t->name_off = 0;
2786 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
2787 		} else if (!has_type_tag && btf_is_type_tag(t)) {
2788 			/* replace TYPE_TAG with a CONST */
2789 			t->name_off = 0;
2790 			t->info = BTF_INFO_ENC(BTF_KIND_CONST, 0, 0);
2791 		} else if (!has_enum64 && btf_is_enum(t)) {
2792 			/* clear the kflag */
2793 			t->info = btf_type_info(btf_kind(t), btf_vlen(t), false);
2794 		} else if (!has_enum64 && btf_is_enum64(t)) {
2795 			/* replace ENUM64 with a union */
2796 			struct btf_member *m;
2797 
2798 			if (enum64_placeholder_id == 0) {
2799 				enum64_placeholder_id = btf__add_int(btf, "enum64_placeholder", 1, 0);
2800 				if (enum64_placeholder_id < 0)
2801 					return enum64_placeholder_id;
2802 
2803 				t = (struct btf_type *)btf__type_by_id(btf, i);
2804 			}
2805 
2806 			m = btf_members(t);
2807 			vlen = btf_vlen(t);
2808 			t->info = BTF_INFO_ENC(BTF_KIND_UNION, 0, vlen);
2809 			for (j = 0; j < vlen; j++, m++) {
2810 				m->type = enum64_placeholder_id;
2811 				m->offset = 0;
2812 			}
2813 		}
2814 	}
2815 
2816 	return 0;
2817 }
2818 
2819 static bool libbpf_needs_btf(const struct bpf_object *obj)
2820 {
2821 	return obj->efile.btf_maps_shndx >= 0 ||
2822 	       obj->efile.st_ops_shndx >= 0 ||
2823 	       obj->efile.st_ops_link_shndx >= 0 ||
2824 	       obj->nr_extern > 0;
2825 }
2826 
2827 static bool kernel_needs_btf(const struct bpf_object *obj)
2828 {
2829 	return obj->efile.st_ops_shndx >= 0 || obj->efile.st_ops_link_shndx >= 0;
2830 }
2831 
2832 static int bpf_object__init_btf(struct bpf_object *obj,
2833 				Elf_Data *btf_data,
2834 				Elf_Data *btf_ext_data)
2835 {
2836 	int err = -ENOENT;
2837 
2838 	if (btf_data) {
2839 		obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
2840 		err = libbpf_get_error(obj->btf);
2841 		if (err) {
2842 			obj->btf = NULL;
2843 			pr_warn("Error loading ELF section %s: %d.\n", BTF_ELF_SEC, err);
2844 			goto out;
2845 		}
2846 		/* enforce 8-byte pointers for BPF-targeted BTFs */
2847 		btf__set_pointer_size(obj->btf, 8);
2848 	}
2849 	if (btf_ext_data) {
2850 		struct btf_ext_info *ext_segs[3];
2851 		int seg_num, sec_num;
2852 
2853 		if (!obj->btf) {
2854 			pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
2855 				 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
2856 			goto out;
2857 		}
2858 		obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
2859 		err = libbpf_get_error(obj->btf_ext);
2860 		if (err) {
2861 			pr_warn("Error loading ELF section %s: %d. Ignored and continue.\n",
2862 				BTF_EXT_ELF_SEC, err);
2863 			obj->btf_ext = NULL;
2864 			goto out;
2865 		}
2866 
2867 		/* setup .BTF.ext to ELF section mapping */
2868 		ext_segs[0] = &obj->btf_ext->func_info;
2869 		ext_segs[1] = &obj->btf_ext->line_info;
2870 		ext_segs[2] = &obj->btf_ext->core_relo_info;
2871 		for (seg_num = 0; seg_num < ARRAY_SIZE(ext_segs); seg_num++) {
2872 			struct btf_ext_info *seg = ext_segs[seg_num];
2873 			const struct btf_ext_info_sec *sec;
2874 			const char *sec_name;
2875 			Elf_Scn *scn;
2876 
2877 			if (seg->sec_cnt == 0)
2878 				continue;
2879 
2880 			seg->sec_idxs = calloc(seg->sec_cnt, sizeof(*seg->sec_idxs));
2881 			if (!seg->sec_idxs) {
2882 				err = -ENOMEM;
2883 				goto out;
2884 			}
2885 
2886 			sec_num = 0;
2887 			for_each_btf_ext_sec(seg, sec) {
2888 				/* preventively increment index to avoid doing
2889 				 * this before every continue below
2890 				 */
2891 				sec_num++;
2892 
2893 				sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
2894 				if (str_is_empty(sec_name))
2895 					continue;
2896 				scn = elf_sec_by_name(obj, sec_name);
2897 				if (!scn)
2898 					continue;
2899 
2900 				seg->sec_idxs[sec_num - 1] = elf_ndxscn(scn);
2901 			}
2902 		}
2903 	}
2904 out:
2905 	if (err && libbpf_needs_btf(obj)) {
2906 		pr_warn("BTF is required, but is missing or corrupted.\n");
2907 		return err;
2908 	}
2909 	return 0;
2910 }
2911 
2912 static int compare_vsi_off(const void *_a, const void *_b)
2913 {
2914 	const struct btf_var_secinfo *a = _a;
2915 	const struct btf_var_secinfo *b = _b;
2916 
2917 	return a->offset - b->offset;
2918 }
2919 
2920 static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
2921 			     struct btf_type *t)
2922 {
2923 	__u32 size = 0, i, vars = btf_vlen(t);
2924 	const char *sec_name = btf__name_by_offset(btf, t->name_off);
2925 	struct btf_var_secinfo *vsi;
2926 	bool fixup_offsets = false;
2927 	int err;
2928 
2929 	if (!sec_name) {
2930 		pr_debug("No name found in string section for DATASEC kind.\n");
2931 		return -ENOENT;
2932 	}
2933 
2934 	/* Extern-backing datasecs (.ksyms, .kconfig) have their size and
2935 	 * variable offsets set at the previous step. Further, not every
2936 	 * extern BTF VAR has corresponding ELF symbol preserved, so we skip
2937 	 * all fixups altogether for such sections and go straight to sorting
2938 	 * VARs within their DATASEC.
2939 	 */
2940 	if (strcmp(sec_name, KCONFIG_SEC) == 0 || strcmp(sec_name, KSYMS_SEC) == 0)
2941 		goto sort_vars;
2942 
2943 	/* Clang leaves DATASEC size and VAR offsets as zeroes, so we need to
2944 	 * fix this up. But BPF static linker already fixes this up and fills
2945 	 * all the sizes and offsets during static linking. So this step has
2946 	 * to be optional. But the STV_HIDDEN handling is non-optional for any
2947 	 * non-extern DATASEC, so the variable fixup loop below handles both
2948 	 * functions at the same time, paying the cost of BTF VAR <-> ELF
2949 	 * symbol matching just once.
2950 	 */
2951 	if (t->size == 0) {
2952 		err = find_elf_sec_sz(obj, sec_name, &size);
2953 		if (err || !size) {
2954 			pr_debug("sec '%s': failed to determine size from ELF: size %u, err %d\n",
2955 				 sec_name, size, err);
2956 			return -ENOENT;
2957 		}
2958 
2959 		t->size = size;
2960 		fixup_offsets = true;
2961 	}
2962 
2963 	for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
2964 		const struct btf_type *t_var;
2965 		struct btf_var *var;
2966 		const char *var_name;
2967 		Elf64_Sym *sym;
2968 
2969 		t_var = btf__type_by_id(btf, vsi->type);
2970 		if (!t_var || !btf_is_var(t_var)) {
2971 			pr_debug("sec '%s': unexpected non-VAR type found\n", sec_name);
2972 			return -EINVAL;
2973 		}
2974 
2975 		var = btf_var(t_var);
2976 		if (var->linkage == BTF_VAR_STATIC || var->linkage == BTF_VAR_GLOBAL_EXTERN)
2977 			continue;
2978 
2979 		var_name = btf__name_by_offset(btf, t_var->name_off);
2980 		if (!var_name) {
2981 			pr_debug("sec '%s': failed to find name of DATASEC's member #%d\n",
2982 				 sec_name, i);
2983 			return -ENOENT;
2984 		}
2985 
2986 		sym = find_elf_var_sym(obj, var_name);
2987 		if (IS_ERR(sym)) {
2988 			pr_debug("sec '%s': failed to find ELF symbol for VAR '%s'\n",
2989 				 sec_name, var_name);
2990 			return -ENOENT;
2991 		}
2992 
2993 		if (fixup_offsets)
2994 			vsi->offset = sym->st_value;
2995 
2996 		/* if variable is a global/weak symbol, but has restricted
2997 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF VAR
2998 		 * as static. This follows similar logic for functions (BPF
2999 		 * subprogs) and influences libbpf's further decisions about
3000 		 * whether to make global data BPF array maps as
3001 		 * BPF_F_MMAPABLE.
3002 		 */
3003 		if (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
3004 		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL)
3005 			var->linkage = BTF_VAR_STATIC;
3006 	}
3007 
3008 sort_vars:
3009 	qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
3010 	return 0;
3011 }
3012 
3013 static int bpf_object_fixup_btf(struct bpf_object *obj)
3014 {
3015 	int i, n, err = 0;
3016 
3017 	if (!obj->btf)
3018 		return 0;
3019 
3020 	n = btf__type_cnt(obj->btf);
3021 	for (i = 1; i < n; i++) {
3022 		struct btf_type *t = btf_type_by_id(obj->btf, i);
3023 
3024 		/* Loader needs to fix up some of the things compiler
3025 		 * couldn't get its hands on while emitting BTF. This
3026 		 * is section size and global variable offset. We use
3027 		 * the info from the ELF itself for this purpose.
3028 		 */
3029 		if (btf_is_datasec(t)) {
3030 			err = btf_fixup_datasec(obj, obj->btf, t);
3031 			if (err)
3032 				return err;
3033 		}
3034 	}
3035 
3036 	return 0;
3037 }
3038 
3039 static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
3040 {
3041 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
3042 	    prog->type == BPF_PROG_TYPE_LSM)
3043 		return true;
3044 
3045 	/* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
3046 	 * also need vmlinux BTF
3047 	 */
3048 	if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
3049 		return true;
3050 
3051 	return false;
3052 }
3053 
3054 static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
3055 {
3056 	struct bpf_program *prog;
3057 	int i;
3058 
3059 	/* CO-RE relocations need kernel BTF, only when btf_custom_path
3060 	 * is not specified
3061 	 */
3062 	if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
3063 		return true;
3064 
3065 	/* Support for typed ksyms needs kernel BTF */
3066 	for (i = 0; i < obj->nr_extern; i++) {
3067 		const struct extern_desc *ext;
3068 
3069 		ext = &obj->externs[i];
3070 		if (ext->type == EXT_KSYM && ext->ksym.type_id)
3071 			return true;
3072 	}
3073 
3074 	bpf_object__for_each_program(prog, obj) {
3075 		if (!prog->autoload)
3076 			continue;
3077 		if (prog_needs_vmlinux_btf(prog))
3078 			return true;
3079 	}
3080 
3081 	return false;
3082 }
3083 
3084 static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
3085 {
3086 	int err;
3087 
3088 	/* btf_vmlinux could be loaded earlier */
3089 	if (obj->btf_vmlinux || obj->gen_loader)
3090 		return 0;
3091 
3092 	if (!force && !obj_needs_vmlinux_btf(obj))
3093 		return 0;
3094 
3095 	obj->btf_vmlinux = btf__load_vmlinux_btf();
3096 	err = libbpf_get_error(obj->btf_vmlinux);
3097 	if (err) {
3098 		pr_warn("Error loading vmlinux BTF: %d\n", err);
3099 		obj->btf_vmlinux = NULL;
3100 		return err;
3101 	}
3102 	return 0;
3103 }
3104 
3105 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
3106 {
3107 	struct btf *kern_btf = obj->btf;
3108 	bool btf_mandatory, sanitize;
3109 	int i, err = 0;
3110 
3111 	if (!obj->btf)
3112 		return 0;
3113 
3114 	if (!kernel_supports(obj, FEAT_BTF)) {
3115 		if (kernel_needs_btf(obj)) {
3116 			err = -EOPNOTSUPP;
3117 			goto report;
3118 		}
3119 		pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
3120 		return 0;
3121 	}
3122 
3123 	/* Even though some subprogs are global/weak, user might prefer more
3124 	 * permissive BPF verification process that BPF verifier performs for
3125 	 * static functions, taking into account more context from the caller
3126 	 * functions. In such case, they need to mark such subprogs with
3127 	 * __attribute__((visibility("hidden"))) and libbpf will adjust
3128 	 * corresponding FUNC BTF type to be marked as static and trigger more
3129 	 * involved BPF verification process.
3130 	 */
3131 	for (i = 0; i < obj->nr_programs; i++) {
3132 		struct bpf_program *prog = &obj->programs[i];
3133 		struct btf_type *t;
3134 		const char *name;
3135 		int j, n;
3136 
3137 		if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
3138 			continue;
3139 
3140 		n = btf__type_cnt(obj->btf);
3141 		for (j = 1; j < n; j++) {
3142 			t = btf_type_by_id(obj->btf, j);
3143 			if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
3144 				continue;
3145 
3146 			name = btf__str_by_offset(obj->btf, t->name_off);
3147 			if (strcmp(name, prog->name) != 0)
3148 				continue;
3149 
3150 			t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
3151 			break;
3152 		}
3153 	}
3154 
3155 	if (!kernel_supports(obj, FEAT_BTF_DECL_TAG))
3156 		goto skip_exception_cb;
3157 	for (i = 0; i < obj->nr_programs; i++) {
3158 		struct bpf_program *prog = &obj->programs[i];
3159 		int j, k, n;
3160 
3161 		if (prog_is_subprog(obj, prog))
3162 			continue;
3163 		n = btf__type_cnt(obj->btf);
3164 		for (j = 1; j < n; j++) {
3165 			const char *str = "exception_callback:", *name;
3166 			size_t len = strlen(str);
3167 			struct btf_type *t;
3168 
3169 			t = btf_type_by_id(obj->btf, j);
3170 			if (!btf_is_decl_tag(t) || btf_decl_tag(t)->component_idx != -1)
3171 				continue;
3172 
3173 			name = btf__str_by_offset(obj->btf, t->name_off);
3174 			if (strncmp(name, str, len))
3175 				continue;
3176 
3177 			t = btf_type_by_id(obj->btf, t->type);
3178 			if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
3179 				pr_warn("prog '%s': exception_callback:<value> decl tag not applied to the main program\n",
3180 					prog->name);
3181 				return -EINVAL;
3182 			}
3183 			if (strcmp(prog->name, btf__str_by_offset(obj->btf, t->name_off)))
3184 				continue;
3185 			/* Multiple callbacks are specified for the same prog,
3186 			 * the verifier will eventually return an error for this
3187 			 * case, hence simply skip appending a subprog.
3188 			 */
3189 			if (prog->exception_cb_idx >= 0) {
3190 				prog->exception_cb_idx = -1;
3191 				break;
3192 			}
3193 
3194 			name += len;
3195 			if (str_is_empty(name)) {
3196 				pr_warn("prog '%s': exception_callback:<value> decl tag contains empty value\n",
3197 					prog->name);
3198 				return -EINVAL;
3199 			}
3200 
3201 			for (k = 0; k < obj->nr_programs; k++) {
3202 				struct bpf_program *subprog = &obj->programs[k];
3203 
3204 				if (!prog_is_subprog(obj, subprog))
3205 					continue;
3206 				if (strcmp(name, subprog->name))
3207 					continue;
3208 				/* Enforce non-hidden, as from verifier point of
3209 				 * view it expects global functions, whereas the
3210 				 * mark_btf_static fixes up linkage as static.
3211 				 */
3212 				if (!subprog->sym_global || subprog->mark_btf_static) {
3213 					pr_warn("prog '%s': exception callback %s must be a global non-hidden function\n",
3214 						prog->name, subprog->name);
3215 					return -EINVAL;
3216 				}
3217 				/* Let's see if we already saw a static exception callback with the same name */
3218 				if (prog->exception_cb_idx >= 0) {
3219 					pr_warn("prog '%s': multiple subprogs with same name as exception callback '%s'\n",
3220 					        prog->name, subprog->name);
3221 					return -EINVAL;
3222 				}
3223 				prog->exception_cb_idx = k;
3224 				break;
3225 			}
3226 
3227 			if (prog->exception_cb_idx >= 0)
3228 				continue;
3229 			pr_warn("prog '%s': cannot find exception callback '%s'\n", prog->name, name);
3230 			return -ENOENT;
3231 		}
3232 	}
3233 skip_exception_cb:
3234 
3235 	sanitize = btf_needs_sanitization(obj);
3236 	if (sanitize) {
3237 		const void *raw_data;
3238 		__u32 sz;
3239 
3240 		/* clone BTF to sanitize a copy and leave the original intact */
3241 		raw_data = btf__raw_data(obj->btf, &sz);
3242 		kern_btf = btf__new(raw_data, sz);
3243 		err = libbpf_get_error(kern_btf);
3244 		if (err)
3245 			return err;
3246 
3247 		/* enforce 8-byte pointers for BPF-targeted BTFs */
3248 		btf__set_pointer_size(obj->btf, 8);
3249 		err = bpf_object__sanitize_btf(obj, kern_btf);
3250 		if (err)
3251 			return err;
3252 	}
3253 
3254 	if (obj->gen_loader) {
3255 		__u32 raw_size = 0;
3256 		const void *raw_data = btf__raw_data(kern_btf, &raw_size);
3257 
3258 		if (!raw_data)
3259 			return -ENOMEM;
3260 		bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
3261 		/* Pretend to have valid FD to pass various fd >= 0 checks.
3262 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
3263 		 */
3264 		btf__set_fd(kern_btf, 0);
3265 	} else {
3266 		/* currently BPF_BTF_LOAD only supports log_level 1 */
3267 		err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
3268 					   obj->log_level ? 1 : 0);
3269 	}
3270 	if (sanitize) {
3271 		if (!err) {
3272 			/* move fd to libbpf's BTF */
3273 			btf__set_fd(obj->btf, btf__fd(kern_btf));
3274 			btf__set_fd(kern_btf, -1);
3275 		}
3276 		btf__free(kern_btf);
3277 	}
3278 report:
3279 	if (err) {
3280 		btf_mandatory = kernel_needs_btf(obj);
3281 		pr_warn("Error loading .BTF into kernel: %d. %s\n", err,
3282 			btf_mandatory ? "BTF is mandatory, can't proceed."
3283 				      : "BTF is optional, ignoring.");
3284 		if (!btf_mandatory)
3285 			err = 0;
3286 	}
3287 	return err;
3288 }
3289 
3290 static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
3291 {
3292 	const char *name;
3293 
3294 	name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
3295 	if (!name) {
3296 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3297 			off, obj->path, elf_errmsg(-1));
3298 		return NULL;
3299 	}
3300 
3301 	return name;
3302 }
3303 
3304 static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
3305 {
3306 	const char *name;
3307 
3308 	name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, 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 Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
3319 {
3320 	Elf_Scn *scn;
3321 
3322 	scn = elf_getscn(obj->efile.elf, idx);
3323 	if (!scn) {
3324 		pr_warn("elf: failed to get section(%zu) from %s: %s\n",
3325 			idx, obj->path, elf_errmsg(-1));
3326 		return NULL;
3327 	}
3328 	return scn;
3329 }
3330 
3331 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
3332 {
3333 	Elf_Scn *scn = NULL;
3334 	Elf *elf = obj->efile.elf;
3335 	const char *sec_name;
3336 
3337 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3338 		sec_name = elf_sec_name(obj, scn);
3339 		if (!sec_name)
3340 			return NULL;
3341 
3342 		if (strcmp(sec_name, name) != 0)
3343 			continue;
3344 
3345 		return scn;
3346 	}
3347 	return NULL;
3348 }
3349 
3350 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn)
3351 {
3352 	Elf64_Shdr *shdr;
3353 
3354 	if (!scn)
3355 		return NULL;
3356 
3357 	shdr = elf64_getshdr(scn);
3358 	if (!shdr) {
3359 		pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
3360 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3361 		return NULL;
3362 	}
3363 
3364 	return shdr;
3365 }
3366 
3367 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
3368 {
3369 	const char *name;
3370 	Elf64_Shdr *sh;
3371 
3372 	if (!scn)
3373 		return NULL;
3374 
3375 	sh = elf_sec_hdr(obj, scn);
3376 	if (!sh)
3377 		return NULL;
3378 
3379 	name = elf_sec_str(obj, sh->sh_name);
3380 	if (!name) {
3381 		pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
3382 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3383 		return NULL;
3384 	}
3385 
3386 	return name;
3387 }
3388 
3389 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
3390 {
3391 	Elf_Data *data;
3392 
3393 	if (!scn)
3394 		return NULL;
3395 
3396 	data = elf_getdata(scn, 0);
3397 	if (!data) {
3398 		pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
3399 			elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
3400 			obj->path, elf_errmsg(-1));
3401 		return NULL;
3402 	}
3403 
3404 	return data;
3405 }
3406 
3407 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx)
3408 {
3409 	if (idx >= obj->efile.symbols->d_size / sizeof(Elf64_Sym))
3410 		return NULL;
3411 
3412 	return (Elf64_Sym *)obj->efile.symbols->d_buf + idx;
3413 }
3414 
3415 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx)
3416 {
3417 	if (idx >= data->d_size / sizeof(Elf64_Rel))
3418 		return NULL;
3419 
3420 	return (Elf64_Rel *)data->d_buf + idx;
3421 }
3422 
3423 static bool is_sec_name_dwarf(const char *name)
3424 {
3425 	/* approximation, but the actual list is too long */
3426 	return str_has_pfx(name, ".debug_");
3427 }
3428 
3429 static bool ignore_elf_section(Elf64_Shdr *hdr, const char *name)
3430 {
3431 	/* no special handling of .strtab */
3432 	if (hdr->sh_type == SHT_STRTAB)
3433 		return true;
3434 
3435 	/* ignore .llvm_addrsig section as well */
3436 	if (hdr->sh_type == SHT_LLVM_ADDRSIG)
3437 		return true;
3438 
3439 	/* no subprograms will lead to an empty .text section, ignore it */
3440 	if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
3441 	    strcmp(name, ".text") == 0)
3442 		return true;
3443 
3444 	/* DWARF sections */
3445 	if (is_sec_name_dwarf(name))
3446 		return true;
3447 
3448 	if (str_has_pfx(name, ".rel")) {
3449 		name += sizeof(".rel") - 1;
3450 		/* DWARF section relocations */
3451 		if (is_sec_name_dwarf(name))
3452 			return true;
3453 
3454 		/* .BTF and .BTF.ext don't need relocations */
3455 		if (strcmp(name, BTF_ELF_SEC) == 0 ||
3456 		    strcmp(name, BTF_EXT_ELF_SEC) == 0)
3457 			return true;
3458 	}
3459 
3460 	return false;
3461 }
3462 
3463 static int cmp_progs(const void *_a, const void *_b)
3464 {
3465 	const struct bpf_program *a = _a;
3466 	const struct bpf_program *b = _b;
3467 
3468 	if (a->sec_idx != b->sec_idx)
3469 		return a->sec_idx < b->sec_idx ? -1 : 1;
3470 
3471 	/* sec_insn_off can't be the same within the section */
3472 	return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
3473 }
3474 
3475 static int bpf_object__elf_collect(struct bpf_object *obj)
3476 {
3477 	struct elf_sec_desc *sec_desc;
3478 	Elf *elf = obj->efile.elf;
3479 	Elf_Data *btf_ext_data = NULL;
3480 	Elf_Data *btf_data = NULL;
3481 	int idx = 0, err = 0;
3482 	const char *name;
3483 	Elf_Data *data;
3484 	Elf_Scn *scn;
3485 	Elf64_Shdr *sh;
3486 
3487 	/* ELF section indices are 0-based, but sec #0 is special "invalid"
3488 	 * section. Since section count retrieved by elf_getshdrnum() does
3489 	 * include sec #0, it is already the necessary size of an array to keep
3490 	 * all the sections.
3491 	 */
3492 	if (elf_getshdrnum(obj->efile.elf, &obj->efile.sec_cnt)) {
3493 		pr_warn("elf: failed to get the number of sections for %s: %s\n",
3494 			obj->path, elf_errmsg(-1));
3495 		return -LIBBPF_ERRNO__FORMAT;
3496 	}
3497 	obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs));
3498 	if (!obj->efile.secs)
3499 		return -ENOMEM;
3500 
3501 	/* a bunch of ELF parsing functionality depends on processing symbols,
3502 	 * so do the first pass and find the symbol table
3503 	 */
3504 	scn = NULL;
3505 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3506 		sh = elf_sec_hdr(obj, scn);
3507 		if (!sh)
3508 			return -LIBBPF_ERRNO__FORMAT;
3509 
3510 		if (sh->sh_type == SHT_SYMTAB) {
3511 			if (obj->efile.symbols) {
3512 				pr_warn("elf: multiple symbol tables in %s\n", obj->path);
3513 				return -LIBBPF_ERRNO__FORMAT;
3514 			}
3515 
3516 			data = elf_sec_data(obj, scn);
3517 			if (!data)
3518 				return -LIBBPF_ERRNO__FORMAT;
3519 
3520 			idx = elf_ndxscn(scn);
3521 
3522 			obj->efile.symbols = data;
3523 			obj->efile.symbols_shndx = idx;
3524 			obj->efile.strtabidx = sh->sh_link;
3525 		}
3526 	}
3527 
3528 	if (!obj->efile.symbols) {
3529 		pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
3530 			obj->path);
3531 		return -ENOENT;
3532 	}
3533 
3534 	scn = NULL;
3535 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3536 		idx = elf_ndxscn(scn);
3537 		sec_desc = &obj->efile.secs[idx];
3538 
3539 		sh = elf_sec_hdr(obj, scn);
3540 		if (!sh)
3541 			return -LIBBPF_ERRNO__FORMAT;
3542 
3543 		name = elf_sec_str(obj, sh->sh_name);
3544 		if (!name)
3545 			return -LIBBPF_ERRNO__FORMAT;
3546 
3547 		if (ignore_elf_section(sh, name))
3548 			continue;
3549 
3550 		data = elf_sec_data(obj, scn);
3551 		if (!data)
3552 			return -LIBBPF_ERRNO__FORMAT;
3553 
3554 		pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
3555 			 idx, name, (unsigned long)data->d_size,
3556 			 (int)sh->sh_link, (unsigned long)sh->sh_flags,
3557 			 (int)sh->sh_type);
3558 
3559 		if (strcmp(name, "license") == 0) {
3560 			err = bpf_object__init_license(obj, data->d_buf, data->d_size);
3561 			if (err)
3562 				return err;
3563 		} else if (strcmp(name, "version") == 0) {
3564 			err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
3565 			if (err)
3566 				return err;
3567 		} else if (strcmp(name, "maps") == 0) {
3568 			pr_warn("elf: legacy map definitions in 'maps' section are not supported by libbpf v1.0+\n");
3569 			return -ENOTSUP;
3570 		} else if (strcmp(name, MAPS_ELF_SEC) == 0) {
3571 			obj->efile.btf_maps_shndx = idx;
3572 		} else if (strcmp(name, BTF_ELF_SEC) == 0) {
3573 			if (sh->sh_type != SHT_PROGBITS)
3574 				return -LIBBPF_ERRNO__FORMAT;
3575 			btf_data = data;
3576 		} else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
3577 			if (sh->sh_type != SHT_PROGBITS)
3578 				return -LIBBPF_ERRNO__FORMAT;
3579 			btf_ext_data = data;
3580 		} else if (sh->sh_type == SHT_SYMTAB) {
3581 			/* already processed during the first pass above */
3582 		} else if (sh->sh_type == SHT_PROGBITS && data->d_size > 0) {
3583 			if (sh->sh_flags & SHF_EXECINSTR) {
3584 				if (strcmp(name, ".text") == 0)
3585 					obj->efile.text_shndx = idx;
3586 				err = bpf_object__add_programs(obj, data, name, idx);
3587 				if (err)
3588 					return err;
3589 			} else if (strcmp(name, DATA_SEC) == 0 ||
3590 				   str_has_pfx(name, DATA_SEC ".")) {
3591 				sec_desc->sec_type = SEC_DATA;
3592 				sec_desc->shdr = sh;
3593 				sec_desc->data = data;
3594 			} else if (strcmp(name, RODATA_SEC) == 0 ||
3595 				   str_has_pfx(name, RODATA_SEC ".")) {
3596 				sec_desc->sec_type = SEC_RODATA;
3597 				sec_desc->shdr = sh;
3598 				sec_desc->data = data;
3599 			} else if (strcmp(name, STRUCT_OPS_SEC) == 0) {
3600 				obj->efile.st_ops_data = data;
3601 				obj->efile.st_ops_shndx = idx;
3602 			} else if (strcmp(name, STRUCT_OPS_LINK_SEC) == 0) {
3603 				obj->efile.st_ops_link_data = data;
3604 				obj->efile.st_ops_link_shndx = idx;
3605 			} else {
3606 				pr_info("elf: skipping unrecognized data section(%d) %s\n",
3607 					idx, name);
3608 			}
3609 		} else if (sh->sh_type == SHT_REL) {
3610 			int targ_sec_idx = sh->sh_info; /* points to other section */
3611 
3612 			if (sh->sh_entsize != sizeof(Elf64_Rel) ||
3613 			    targ_sec_idx >= obj->efile.sec_cnt)
3614 				return -LIBBPF_ERRNO__FORMAT;
3615 
3616 			/* Only do relo for section with exec instructions */
3617 			if (!section_have_execinstr(obj, targ_sec_idx) &&
3618 			    strcmp(name, ".rel" STRUCT_OPS_SEC) &&
3619 			    strcmp(name, ".rel" STRUCT_OPS_LINK_SEC) &&
3620 			    strcmp(name, ".rel" MAPS_ELF_SEC)) {
3621 				pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
3622 					idx, name, targ_sec_idx,
3623 					elf_sec_name(obj, elf_sec_by_idx(obj, targ_sec_idx)) ?: "<?>");
3624 				continue;
3625 			}
3626 
3627 			sec_desc->sec_type = SEC_RELO;
3628 			sec_desc->shdr = sh;
3629 			sec_desc->data = data;
3630 		} else if (sh->sh_type == SHT_NOBITS && (strcmp(name, BSS_SEC) == 0 ||
3631 							 str_has_pfx(name, BSS_SEC "."))) {
3632 			sec_desc->sec_type = SEC_BSS;
3633 			sec_desc->shdr = sh;
3634 			sec_desc->data = data;
3635 		} else {
3636 			pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
3637 				(size_t)sh->sh_size);
3638 		}
3639 	}
3640 
3641 	if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
3642 		pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
3643 		return -LIBBPF_ERRNO__FORMAT;
3644 	}
3645 
3646 	/* sort BPF programs by section name and in-section instruction offset
3647 	 * for faster search
3648 	 */
3649 	if (obj->nr_programs)
3650 		qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
3651 
3652 	return bpf_object__init_btf(obj, btf_data, btf_ext_data);
3653 }
3654 
3655 static bool sym_is_extern(const Elf64_Sym *sym)
3656 {
3657 	int bind = ELF64_ST_BIND(sym->st_info);
3658 	/* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
3659 	return sym->st_shndx == SHN_UNDEF &&
3660 	       (bind == STB_GLOBAL || bind == STB_WEAK) &&
3661 	       ELF64_ST_TYPE(sym->st_info) == STT_NOTYPE;
3662 }
3663 
3664 static bool sym_is_subprog(const Elf64_Sym *sym, int text_shndx)
3665 {
3666 	int bind = ELF64_ST_BIND(sym->st_info);
3667 	int type = ELF64_ST_TYPE(sym->st_info);
3668 
3669 	/* in .text section */
3670 	if (sym->st_shndx != text_shndx)
3671 		return false;
3672 
3673 	/* local function */
3674 	if (bind == STB_LOCAL && type == STT_SECTION)
3675 		return true;
3676 
3677 	/* global function */
3678 	return bind == STB_GLOBAL && type == STT_FUNC;
3679 }
3680 
3681 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
3682 {
3683 	const struct btf_type *t;
3684 	const char *tname;
3685 	int i, n;
3686 
3687 	if (!btf)
3688 		return -ESRCH;
3689 
3690 	n = btf__type_cnt(btf);
3691 	for (i = 1; i < n; i++) {
3692 		t = btf__type_by_id(btf, i);
3693 
3694 		if (!btf_is_var(t) && !btf_is_func(t))
3695 			continue;
3696 
3697 		tname = btf__name_by_offset(btf, t->name_off);
3698 		if (strcmp(tname, ext_name))
3699 			continue;
3700 
3701 		if (btf_is_var(t) &&
3702 		    btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
3703 			return -EINVAL;
3704 
3705 		if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
3706 			return -EINVAL;
3707 
3708 		return i;
3709 	}
3710 
3711 	return -ENOENT;
3712 }
3713 
3714 static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
3715 	const struct btf_var_secinfo *vs;
3716 	const struct btf_type *t;
3717 	int i, j, n;
3718 
3719 	if (!btf)
3720 		return -ESRCH;
3721 
3722 	n = btf__type_cnt(btf);
3723 	for (i = 1; i < n; i++) {
3724 		t = btf__type_by_id(btf, i);
3725 
3726 		if (!btf_is_datasec(t))
3727 			continue;
3728 
3729 		vs = btf_var_secinfos(t);
3730 		for (j = 0; j < btf_vlen(t); j++, vs++) {
3731 			if (vs->type == ext_btf_id)
3732 				return i;
3733 		}
3734 	}
3735 
3736 	return -ENOENT;
3737 }
3738 
3739 static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
3740 				     bool *is_signed)
3741 {
3742 	const struct btf_type *t;
3743 	const char *name;
3744 
3745 	t = skip_mods_and_typedefs(btf, id, NULL);
3746 	name = btf__name_by_offset(btf, t->name_off);
3747 
3748 	if (is_signed)
3749 		*is_signed = false;
3750 	switch (btf_kind(t)) {
3751 	case BTF_KIND_INT: {
3752 		int enc = btf_int_encoding(t);
3753 
3754 		if (enc & BTF_INT_BOOL)
3755 			return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
3756 		if (is_signed)
3757 			*is_signed = enc & BTF_INT_SIGNED;
3758 		if (t->size == 1)
3759 			return KCFG_CHAR;
3760 		if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
3761 			return KCFG_UNKNOWN;
3762 		return KCFG_INT;
3763 	}
3764 	case BTF_KIND_ENUM:
3765 		if (t->size != 4)
3766 			return KCFG_UNKNOWN;
3767 		if (strcmp(name, "libbpf_tristate"))
3768 			return KCFG_UNKNOWN;
3769 		return KCFG_TRISTATE;
3770 	case BTF_KIND_ENUM64:
3771 		if (strcmp(name, "libbpf_tristate"))
3772 			return KCFG_UNKNOWN;
3773 		return KCFG_TRISTATE;
3774 	case BTF_KIND_ARRAY:
3775 		if (btf_array(t)->nelems == 0)
3776 			return KCFG_UNKNOWN;
3777 		if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
3778 			return KCFG_UNKNOWN;
3779 		return KCFG_CHAR_ARR;
3780 	default:
3781 		return KCFG_UNKNOWN;
3782 	}
3783 }
3784 
3785 static int cmp_externs(const void *_a, const void *_b)
3786 {
3787 	const struct extern_desc *a = _a;
3788 	const struct extern_desc *b = _b;
3789 
3790 	if (a->type != b->type)
3791 		return a->type < b->type ? -1 : 1;
3792 
3793 	if (a->type == EXT_KCFG) {
3794 		/* descending order by alignment requirements */
3795 		if (a->kcfg.align != b->kcfg.align)
3796 			return a->kcfg.align > b->kcfg.align ? -1 : 1;
3797 		/* ascending order by size, within same alignment class */
3798 		if (a->kcfg.sz != b->kcfg.sz)
3799 			return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
3800 	}
3801 
3802 	/* resolve ties by name */
3803 	return strcmp(a->name, b->name);
3804 }
3805 
3806 static int find_int_btf_id(const struct btf *btf)
3807 {
3808 	const struct btf_type *t;
3809 	int i, n;
3810 
3811 	n = btf__type_cnt(btf);
3812 	for (i = 1; i < n; i++) {
3813 		t = btf__type_by_id(btf, i);
3814 
3815 		if (btf_is_int(t) && btf_int_bits(t) == 32)
3816 			return i;
3817 	}
3818 
3819 	return 0;
3820 }
3821 
3822 static int add_dummy_ksym_var(struct btf *btf)
3823 {
3824 	int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
3825 	const struct btf_var_secinfo *vs;
3826 	const struct btf_type *sec;
3827 
3828 	if (!btf)
3829 		return 0;
3830 
3831 	sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
3832 					    BTF_KIND_DATASEC);
3833 	if (sec_btf_id < 0)
3834 		return 0;
3835 
3836 	sec = btf__type_by_id(btf, sec_btf_id);
3837 	vs = btf_var_secinfos(sec);
3838 	for (i = 0; i < btf_vlen(sec); i++, vs++) {
3839 		const struct btf_type *vt;
3840 
3841 		vt = btf__type_by_id(btf, vs->type);
3842 		if (btf_is_func(vt))
3843 			break;
3844 	}
3845 
3846 	/* No func in ksyms sec.  No need to add dummy var. */
3847 	if (i == btf_vlen(sec))
3848 		return 0;
3849 
3850 	int_btf_id = find_int_btf_id(btf);
3851 	dummy_var_btf_id = btf__add_var(btf,
3852 					"dummy_ksym",
3853 					BTF_VAR_GLOBAL_ALLOCATED,
3854 					int_btf_id);
3855 	if (dummy_var_btf_id < 0)
3856 		pr_warn("cannot create a dummy_ksym var\n");
3857 
3858 	return dummy_var_btf_id;
3859 }
3860 
3861 static int bpf_object__collect_externs(struct bpf_object *obj)
3862 {
3863 	struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
3864 	const struct btf_type *t;
3865 	struct extern_desc *ext;
3866 	int i, n, off, dummy_var_btf_id;
3867 	const char *ext_name, *sec_name;
3868 	size_t ext_essent_len;
3869 	Elf_Scn *scn;
3870 	Elf64_Shdr *sh;
3871 
3872 	if (!obj->efile.symbols)
3873 		return 0;
3874 
3875 	scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
3876 	sh = elf_sec_hdr(obj, scn);
3877 	if (!sh || sh->sh_entsize != sizeof(Elf64_Sym))
3878 		return -LIBBPF_ERRNO__FORMAT;
3879 
3880 	dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
3881 	if (dummy_var_btf_id < 0)
3882 		return dummy_var_btf_id;
3883 
3884 	n = sh->sh_size / sh->sh_entsize;
3885 	pr_debug("looking for externs among %d symbols...\n", n);
3886 
3887 	for (i = 0; i < n; i++) {
3888 		Elf64_Sym *sym = elf_sym_by_idx(obj, i);
3889 
3890 		if (!sym)
3891 			return -LIBBPF_ERRNO__FORMAT;
3892 		if (!sym_is_extern(sym))
3893 			continue;
3894 		ext_name = elf_sym_str(obj, sym->st_name);
3895 		if (!ext_name || !ext_name[0])
3896 			continue;
3897 
3898 		ext = obj->externs;
3899 		ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
3900 		if (!ext)
3901 			return -ENOMEM;
3902 		obj->externs = ext;
3903 		ext = &ext[obj->nr_extern];
3904 		memset(ext, 0, sizeof(*ext));
3905 		obj->nr_extern++;
3906 
3907 		ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
3908 		if (ext->btf_id <= 0) {
3909 			pr_warn("failed to find BTF for extern '%s': %d\n",
3910 				ext_name, ext->btf_id);
3911 			return ext->btf_id;
3912 		}
3913 		t = btf__type_by_id(obj->btf, ext->btf_id);
3914 		ext->name = btf__name_by_offset(obj->btf, t->name_off);
3915 		ext->sym_idx = i;
3916 		ext->is_weak = ELF64_ST_BIND(sym->st_info) == STB_WEAK;
3917 
3918 		ext_essent_len = bpf_core_essential_name_len(ext->name);
3919 		ext->essent_name = NULL;
3920 		if (ext_essent_len != strlen(ext->name)) {
3921 			ext->essent_name = strndup(ext->name, ext_essent_len);
3922 			if (!ext->essent_name)
3923 				return -ENOMEM;
3924 		}
3925 
3926 		ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
3927 		if (ext->sec_btf_id <= 0) {
3928 			pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
3929 				ext_name, ext->btf_id, ext->sec_btf_id);
3930 			return ext->sec_btf_id;
3931 		}
3932 		sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
3933 		sec_name = btf__name_by_offset(obj->btf, sec->name_off);
3934 
3935 		if (strcmp(sec_name, KCONFIG_SEC) == 0) {
3936 			if (btf_is_func(t)) {
3937 				pr_warn("extern function %s is unsupported under %s section\n",
3938 					ext->name, KCONFIG_SEC);
3939 				return -ENOTSUP;
3940 			}
3941 			kcfg_sec = sec;
3942 			ext->type = EXT_KCFG;
3943 			ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
3944 			if (ext->kcfg.sz <= 0) {
3945 				pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
3946 					ext_name, ext->kcfg.sz);
3947 				return ext->kcfg.sz;
3948 			}
3949 			ext->kcfg.align = btf__align_of(obj->btf, t->type);
3950 			if (ext->kcfg.align <= 0) {
3951 				pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
3952 					ext_name, ext->kcfg.align);
3953 				return -EINVAL;
3954 			}
3955 			ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
3956 							&ext->kcfg.is_signed);
3957 			if (ext->kcfg.type == KCFG_UNKNOWN) {
3958 				pr_warn("extern (kcfg) '%s': type is unsupported\n", ext_name);
3959 				return -ENOTSUP;
3960 			}
3961 		} else if (strcmp(sec_name, KSYMS_SEC) == 0) {
3962 			ksym_sec = sec;
3963 			ext->type = EXT_KSYM;
3964 			skip_mods_and_typedefs(obj->btf, t->type,
3965 					       &ext->ksym.type_id);
3966 		} else {
3967 			pr_warn("unrecognized extern section '%s'\n", sec_name);
3968 			return -ENOTSUP;
3969 		}
3970 	}
3971 	pr_debug("collected %d externs total\n", obj->nr_extern);
3972 
3973 	if (!obj->nr_extern)
3974 		return 0;
3975 
3976 	/* sort externs by type, for kcfg ones also by (align, size, name) */
3977 	qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
3978 
3979 	/* for .ksyms section, we need to turn all externs into allocated
3980 	 * variables in BTF to pass kernel verification; we do this by
3981 	 * pretending that each extern is a 8-byte variable
3982 	 */
3983 	if (ksym_sec) {
3984 		/* find existing 4-byte integer type in BTF to use for fake
3985 		 * extern variables in DATASEC
3986 		 */
3987 		int int_btf_id = find_int_btf_id(obj->btf);
3988 		/* For extern function, a dummy_var added earlier
3989 		 * will be used to replace the vs->type and
3990 		 * its name string will be used to refill
3991 		 * the missing param's name.
3992 		 */
3993 		const struct btf_type *dummy_var;
3994 
3995 		dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
3996 		for (i = 0; i < obj->nr_extern; i++) {
3997 			ext = &obj->externs[i];
3998 			if (ext->type != EXT_KSYM)
3999 				continue;
4000 			pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
4001 				 i, ext->sym_idx, ext->name);
4002 		}
4003 
4004 		sec = ksym_sec;
4005 		n = btf_vlen(sec);
4006 		for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
4007 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4008 			struct btf_type *vt;
4009 
4010 			vt = (void *)btf__type_by_id(obj->btf, vs->type);
4011 			ext_name = btf__name_by_offset(obj->btf, vt->name_off);
4012 			ext = find_extern_by_name(obj, ext_name);
4013 			if (!ext) {
4014 				pr_warn("failed to find extern definition for BTF %s '%s'\n",
4015 					btf_kind_str(vt), ext_name);
4016 				return -ESRCH;
4017 			}
4018 			if (btf_is_func(vt)) {
4019 				const struct btf_type *func_proto;
4020 				struct btf_param *param;
4021 				int j;
4022 
4023 				func_proto = btf__type_by_id(obj->btf,
4024 							     vt->type);
4025 				param = btf_params(func_proto);
4026 				/* Reuse the dummy_var string if the
4027 				 * func proto does not have param name.
4028 				 */
4029 				for (j = 0; j < btf_vlen(func_proto); j++)
4030 					if (param[j].type && !param[j].name_off)
4031 						param[j].name_off =
4032 							dummy_var->name_off;
4033 				vs->type = dummy_var_btf_id;
4034 				vt->info &= ~0xffff;
4035 				vt->info |= BTF_FUNC_GLOBAL;
4036 			} else {
4037 				btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4038 				vt->type = int_btf_id;
4039 			}
4040 			vs->offset = off;
4041 			vs->size = sizeof(int);
4042 		}
4043 		sec->size = off;
4044 	}
4045 
4046 	if (kcfg_sec) {
4047 		sec = kcfg_sec;
4048 		/* for kcfg externs calculate their offsets within a .kconfig map */
4049 		off = 0;
4050 		for (i = 0; i < obj->nr_extern; i++) {
4051 			ext = &obj->externs[i];
4052 			if (ext->type != EXT_KCFG)
4053 				continue;
4054 
4055 			ext->kcfg.data_off = roundup(off, ext->kcfg.align);
4056 			off = ext->kcfg.data_off + ext->kcfg.sz;
4057 			pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
4058 				 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
4059 		}
4060 		sec->size = off;
4061 		n = btf_vlen(sec);
4062 		for (i = 0; i < n; i++) {
4063 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4064 
4065 			t = btf__type_by_id(obj->btf, vs->type);
4066 			ext_name = btf__name_by_offset(obj->btf, t->name_off);
4067 			ext = find_extern_by_name(obj, ext_name);
4068 			if (!ext) {
4069 				pr_warn("failed to find extern definition for BTF var '%s'\n",
4070 					ext_name);
4071 				return -ESRCH;
4072 			}
4073 			btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4074 			vs->offset = ext->kcfg.data_off;
4075 		}
4076 	}
4077 	return 0;
4078 }
4079 
4080 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog)
4081 {
4082 	return prog->sec_idx == obj->efile.text_shndx && obj->nr_programs > 1;
4083 }
4084 
4085 struct bpf_program *
4086 bpf_object__find_program_by_name(const struct bpf_object *obj,
4087 				 const char *name)
4088 {
4089 	struct bpf_program *prog;
4090 
4091 	bpf_object__for_each_program(prog, obj) {
4092 		if (prog_is_subprog(obj, prog))
4093 			continue;
4094 		if (!strcmp(prog->name, name))
4095 			return prog;
4096 	}
4097 	return errno = ENOENT, NULL;
4098 }
4099 
4100 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
4101 				      int shndx)
4102 {
4103 	switch (obj->efile.secs[shndx].sec_type) {
4104 	case SEC_BSS:
4105 	case SEC_DATA:
4106 	case SEC_RODATA:
4107 		return true;
4108 	default:
4109 		return false;
4110 	}
4111 }
4112 
4113 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
4114 				      int shndx)
4115 {
4116 	return shndx == obj->efile.btf_maps_shndx;
4117 }
4118 
4119 static enum libbpf_map_type
4120 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
4121 {
4122 	if (shndx == obj->efile.symbols_shndx)
4123 		return LIBBPF_MAP_KCONFIG;
4124 
4125 	switch (obj->efile.secs[shndx].sec_type) {
4126 	case SEC_BSS:
4127 		return LIBBPF_MAP_BSS;
4128 	case SEC_DATA:
4129 		return LIBBPF_MAP_DATA;
4130 	case SEC_RODATA:
4131 		return LIBBPF_MAP_RODATA;
4132 	default:
4133 		return LIBBPF_MAP_UNSPEC;
4134 	}
4135 }
4136 
4137 static int bpf_program__record_reloc(struct bpf_program *prog,
4138 				     struct reloc_desc *reloc_desc,
4139 				     __u32 insn_idx, const char *sym_name,
4140 				     const Elf64_Sym *sym, const Elf64_Rel *rel)
4141 {
4142 	struct bpf_insn *insn = &prog->insns[insn_idx];
4143 	size_t map_idx, nr_maps = prog->obj->nr_maps;
4144 	struct bpf_object *obj = prog->obj;
4145 	__u32 shdr_idx = sym->st_shndx;
4146 	enum libbpf_map_type type;
4147 	const char *sym_sec_name;
4148 	struct bpf_map *map;
4149 
4150 	if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
4151 		pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n",
4152 			prog->name, sym_name, insn_idx, insn->code);
4153 		return -LIBBPF_ERRNO__RELOC;
4154 	}
4155 
4156 	if (sym_is_extern(sym)) {
4157 		int sym_idx = ELF64_R_SYM(rel->r_info);
4158 		int i, n = obj->nr_extern;
4159 		struct extern_desc *ext;
4160 
4161 		for (i = 0; i < n; i++) {
4162 			ext = &obj->externs[i];
4163 			if (ext->sym_idx == sym_idx)
4164 				break;
4165 		}
4166 		if (i >= n) {
4167 			pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
4168 				prog->name, sym_name, sym_idx);
4169 			return -LIBBPF_ERRNO__RELOC;
4170 		}
4171 		pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
4172 			 prog->name, i, ext->name, ext->sym_idx, insn_idx);
4173 		if (insn->code == (BPF_JMP | BPF_CALL))
4174 			reloc_desc->type = RELO_EXTERN_CALL;
4175 		else
4176 			reloc_desc->type = RELO_EXTERN_LD64;
4177 		reloc_desc->insn_idx = insn_idx;
4178 		reloc_desc->ext_idx = i;
4179 		return 0;
4180 	}
4181 
4182 	/* sub-program call relocation */
4183 	if (is_call_insn(insn)) {
4184 		if (insn->src_reg != BPF_PSEUDO_CALL) {
4185 			pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
4186 			return -LIBBPF_ERRNO__RELOC;
4187 		}
4188 		/* text_shndx can be 0, if no default "main" program exists */
4189 		if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
4190 			sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4191 			pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
4192 				prog->name, sym_name, sym_sec_name);
4193 			return -LIBBPF_ERRNO__RELOC;
4194 		}
4195 		if (sym->st_value % BPF_INSN_SZ) {
4196 			pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
4197 				prog->name, sym_name, (size_t)sym->st_value);
4198 			return -LIBBPF_ERRNO__RELOC;
4199 		}
4200 		reloc_desc->type = RELO_CALL;
4201 		reloc_desc->insn_idx = insn_idx;
4202 		reloc_desc->sym_off = sym->st_value;
4203 		return 0;
4204 	}
4205 
4206 	if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
4207 		pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
4208 			prog->name, sym_name, shdr_idx);
4209 		return -LIBBPF_ERRNO__RELOC;
4210 	}
4211 
4212 	/* loading subprog addresses */
4213 	if (sym_is_subprog(sym, obj->efile.text_shndx)) {
4214 		/* global_func: sym->st_value = offset in the section, insn->imm = 0.
4215 		 * local_func: sym->st_value = 0, insn->imm = offset in the section.
4216 		 */
4217 		if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
4218 			pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
4219 				prog->name, sym_name, (size_t)sym->st_value, insn->imm);
4220 			return -LIBBPF_ERRNO__RELOC;
4221 		}
4222 
4223 		reloc_desc->type = RELO_SUBPROG_ADDR;
4224 		reloc_desc->insn_idx = insn_idx;
4225 		reloc_desc->sym_off = sym->st_value;
4226 		return 0;
4227 	}
4228 
4229 	type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
4230 	sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4231 
4232 	/* generic map reference relocation */
4233 	if (type == LIBBPF_MAP_UNSPEC) {
4234 		if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
4235 			pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
4236 				prog->name, sym_name, sym_sec_name);
4237 			return -LIBBPF_ERRNO__RELOC;
4238 		}
4239 		for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4240 			map = &obj->maps[map_idx];
4241 			if (map->libbpf_type != type ||
4242 			    map->sec_idx != sym->st_shndx ||
4243 			    map->sec_offset != sym->st_value)
4244 				continue;
4245 			pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n",
4246 				 prog->name, map_idx, map->name, map->sec_idx,
4247 				 map->sec_offset, insn_idx);
4248 			break;
4249 		}
4250 		if (map_idx >= nr_maps) {
4251 			pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
4252 				prog->name, sym_sec_name, (size_t)sym->st_value);
4253 			return -LIBBPF_ERRNO__RELOC;
4254 		}
4255 		reloc_desc->type = RELO_LD64;
4256 		reloc_desc->insn_idx = insn_idx;
4257 		reloc_desc->map_idx = map_idx;
4258 		reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
4259 		return 0;
4260 	}
4261 
4262 	/* global data map relocation */
4263 	if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
4264 		pr_warn("prog '%s': bad data relo against section '%s'\n",
4265 			prog->name, sym_sec_name);
4266 		return -LIBBPF_ERRNO__RELOC;
4267 	}
4268 	for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4269 		map = &obj->maps[map_idx];
4270 		if (map->libbpf_type != type || map->sec_idx != sym->st_shndx)
4271 			continue;
4272 		pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n",
4273 			 prog->name, map_idx, map->name, map->sec_idx,
4274 			 map->sec_offset, insn_idx);
4275 		break;
4276 	}
4277 	if (map_idx >= nr_maps) {
4278 		pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
4279 			prog->name, sym_sec_name);
4280 		return -LIBBPF_ERRNO__RELOC;
4281 	}
4282 
4283 	reloc_desc->type = RELO_DATA;
4284 	reloc_desc->insn_idx = insn_idx;
4285 	reloc_desc->map_idx = map_idx;
4286 	reloc_desc->sym_off = sym->st_value;
4287 	return 0;
4288 }
4289 
4290 static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
4291 {
4292 	return insn_idx >= prog->sec_insn_off &&
4293 	       insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
4294 }
4295 
4296 static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
4297 						 size_t sec_idx, size_t insn_idx)
4298 {
4299 	int l = 0, r = obj->nr_programs - 1, m;
4300 	struct bpf_program *prog;
4301 
4302 	if (!obj->nr_programs)
4303 		return NULL;
4304 
4305 	while (l < r) {
4306 		m = l + (r - l + 1) / 2;
4307 		prog = &obj->programs[m];
4308 
4309 		if (prog->sec_idx < sec_idx ||
4310 		    (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
4311 			l = m;
4312 		else
4313 			r = m - 1;
4314 	}
4315 	/* matching program could be at index l, but it still might be the
4316 	 * wrong one, so we need to double check conditions for the last time
4317 	 */
4318 	prog = &obj->programs[l];
4319 	if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
4320 		return prog;
4321 	return NULL;
4322 }
4323 
4324 static int
4325 bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
4326 {
4327 	const char *relo_sec_name, *sec_name;
4328 	size_t sec_idx = shdr->sh_info, sym_idx;
4329 	struct bpf_program *prog;
4330 	struct reloc_desc *relos;
4331 	int err, i, nrels;
4332 	const char *sym_name;
4333 	__u32 insn_idx;
4334 	Elf_Scn *scn;
4335 	Elf_Data *scn_data;
4336 	Elf64_Sym *sym;
4337 	Elf64_Rel *rel;
4338 
4339 	if (sec_idx >= obj->efile.sec_cnt)
4340 		return -EINVAL;
4341 
4342 	scn = elf_sec_by_idx(obj, sec_idx);
4343 	scn_data = elf_sec_data(obj, scn);
4344 
4345 	relo_sec_name = elf_sec_str(obj, shdr->sh_name);
4346 	sec_name = elf_sec_name(obj, scn);
4347 	if (!relo_sec_name || !sec_name)
4348 		return -EINVAL;
4349 
4350 	pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
4351 		 relo_sec_name, sec_idx, sec_name);
4352 	nrels = shdr->sh_size / shdr->sh_entsize;
4353 
4354 	for (i = 0; i < nrels; i++) {
4355 		rel = elf_rel_by_idx(data, i);
4356 		if (!rel) {
4357 			pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
4358 			return -LIBBPF_ERRNO__FORMAT;
4359 		}
4360 
4361 		sym_idx = ELF64_R_SYM(rel->r_info);
4362 		sym = elf_sym_by_idx(obj, sym_idx);
4363 		if (!sym) {
4364 			pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
4365 				relo_sec_name, sym_idx, i);
4366 			return -LIBBPF_ERRNO__FORMAT;
4367 		}
4368 
4369 		if (sym->st_shndx >= obj->efile.sec_cnt) {
4370 			pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
4371 				relo_sec_name, sym_idx, (size_t)sym->st_shndx, i);
4372 			return -LIBBPF_ERRNO__FORMAT;
4373 		}
4374 
4375 		if (rel->r_offset % BPF_INSN_SZ || rel->r_offset >= scn_data->d_size) {
4376 			pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
4377 				relo_sec_name, (size_t)rel->r_offset, i);
4378 			return -LIBBPF_ERRNO__FORMAT;
4379 		}
4380 
4381 		insn_idx = rel->r_offset / BPF_INSN_SZ;
4382 		/* relocations against static functions are recorded as
4383 		 * relocations against the section that contains a function;
4384 		 * in such case, symbol will be STT_SECTION and sym.st_name
4385 		 * will point to empty string (0), so fetch section name
4386 		 * instead
4387 		 */
4388 		if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
4389 			sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx));
4390 		else
4391 			sym_name = elf_sym_str(obj, sym->st_name);
4392 		sym_name = sym_name ?: "<?";
4393 
4394 		pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
4395 			 relo_sec_name, i, insn_idx, sym_name);
4396 
4397 		prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
4398 		if (!prog) {
4399 			pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
4400 				relo_sec_name, i, sec_name, insn_idx);
4401 			continue;
4402 		}
4403 
4404 		relos = libbpf_reallocarray(prog->reloc_desc,
4405 					    prog->nr_reloc + 1, sizeof(*relos));
4406 		if (!relos)
4407 			return -ENOMEM;
4408 		prog->reloc_desc = relos;
4409 
4410 		/* adjust insn_idx to local BPF program frame of reference */
4411 		insn_idx -= prog->sec_insn_off;
4412 		err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
4413 						insn_idx, sym_name, sym, rel);
4414 		if (err)
4415 			return err;
4416 
4417 		prog->nr_reloc++;
4418 	}
4419 	return 0;
4420 }
4421 
4422 static int map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map)
4423 {
4424 	int id;
4425 
4426 	if (!obj->btf)
4427 		return -ENOENT;
4428 
4429 	/* if it's BTF-defined map, we don't need to search for type IDs.
4430 	 * For struct_ops map, it does not need btf_key_type_id and
4431 	 * btf_value_type_id.
4432 	 */
4433 	if (map->sec_idx == obj->efile.btf_maps_shndx || bpf_map__is_struct_ops(map))
4434 		return 0;
4435 
4436 	/*
4437 	 * LLVM annotates global data differently in BTF, that is,
4438 	 * only as '.data', '.bss' or '.rodata'.
4439 	 */
4440 	if (!bpf_map__is_internal(map))
4441 		return -ENOENT;
4442 
4443 	id = btf__find_by_name(obj->btf, map->real_name);
4444 	if (id < 0)
4445 		return id;
4446 
4447 	map->btf_key_type_id = 0;
4448 	map->btf_value_type_id = id;
4449 	return 0;
4450 }
4451 
4452 static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
4453 {
4454 	char file[PATH_MAX], buff[4096];
4455 	FILE *fp;
4456 	__u32 val;
4457 	int err;
4458 
4459 	snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
4460 	memset(info, 0, sizeof(*info));
4461 
4462 	fp = fopen(file, "re");
4463 	if (!fp) {
4464 		err = -errno;
4465 		pr_warn("failed to open %s: %d. No procfs support?\n", file,
4466 			err);
4467 		return err;
4468 	}
4469 
4470 	while (fgets(buff, sizeof(buff), fp)) {
4471 		if (sscanf(buff, "map_type:\t%u", &val) == 1)
4472 			info->type = val;
4473 		else if (sscanf(buff, "key_size:\t%u", &val) == 1)
4474 			info->key_size = val;
4475 		else if (sscanf(buff, "value_size:\t%u", &val) == 1)
4476 			info->value_size = val;
4477 		else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
4478 			info->max_entries = val;
4479 		else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
4480 			info->map_flags = val;
4481 	}
4482 
4483 	fclose(fp);
4484 
4485 	return 0;
4486 }
4487 
4488 bool bpf_map__autocreate(const struct bpf_map *map)
4489 {
4490 	return map->autocreate;
4491 }
4492 
4493 int bpf_map__set_autocreate(struct bpf_map *map, bool autocreate)
4494 {
4495 	if (map->obj->loaded)
4496 		return libbpf_err(-EBUSY);
4497 
4498 	map->autocreate = autocreate;
4499 	return 0;
4500 }
4501 
4502 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
4503 {
4504 	struct bpf_map_info info;
4505 	__u32 len = sizeof(info), name_len;
4506 	int new_fd, err;
4507 	char *new_name;
4508 
4509 	memset(&info, 0, len);
4510 	err = bpf_map_get_info_by_fd(fd, &info, &len);
4511 	if (err && errno == EINVAL)
4512 		err = bpf_get_map_info_from_fdinfo(fd, &info);
4513 	if (err)
4514 		return libbpf_err(err);
4515 
4516 	name_len = strlen(info.name);
4517 	if (name_len == BPF_OBJ_NAME_LEN - 1 && strncmp(map->name, info.name, name_len) == 0)
4518 		new_name = strdup(map->name);
4519 	else
4520 		new_name = strdup(info.name);
4521 
4522 	if (!new_name)
4523 		return libbpf_err(-errno);
4524 
4525 	/*
4526 	 * Like dup(), but make sure new FD is >= 3 and has O_CLOEXEC set.
4527 	 * This is similar to what we do in ensure_good_fd(), but without
4528 	 * closing original FD.
4529 	 */
4530 	new_fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
4531 	if (new_fd < 0) {
4532 		err = -errno;
4533 		goto err_free_new_name;
4534 	}
4535 
4536 	err = zclose(map->fd);
4537 	if (err) {
4538 		err = -errno;
4539 		goto err_close_new_fd;
4540 	}
4541 	free(map->name);
4542 
4543 	map->fd = new_fd;
4544 	map->name = new_name;
4545 	map->def.type = info.type;
4546 	map->def.key_size = info.key_size;
4547 	map->def.value_size = info.value_size;
4548 	map->def.max_entries = info.max_entries;
4549 	map->def.map_flags = info.map_flags;
4550 	map->btf_key_type_id = info.btf_key_type_id;
4551 	map->btf_value_type_id = info.btf_value_type_id;
4552 	map->reused = true;
4553 	map->map_extra = info.map_extra;
4554 
4555 	return 0;
4556 
4557 err_close_new_fd:
4558 	close(new_fd);
4559 err_free_new_name:
4560 	free(new_name);
4561 	return libbpf_err(err);
4562 }
4563 
4564 __u32 bpf_map__max_entries(const struct bpf_map *map)
4565 {
4566 	return map->def.max_entries;
4567 }
4568 
4569 struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
4570 {
4571 	if (!bpf_map_type__is_map_in_map(map->def.type))
4572 		return errno = EINVAL, NULL;
4573 
4574 	return map->inner_map;
4575 }
4576 
4577 int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
4578 {
4579 	if (map->obj->loaded)
4580 		return libbpf_err(-EBUSY);
4581 
4582 	map->def.max_entries = max_entries;
4583 
4584 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
4585 	if (map_is_ringbuf(map))
4586 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
4587 
4588 	return 0;
4589 }
4590 
4591 static int
4592 bpf_object__probe_loading(struct bpf_object *obj)
4593 {
4594 	char *cp, errmsg[STRERR_BUFSIZE];
4595 	struct bpf_insn insns[] = {
4596 		BPF_MOV64_IMM(BPF_REG_0, 0),
4597 		BPF_EXIT_INSN(),
4598 	};
4599 	int ret, insn_cnt = ARRAY_SIZE(insns);
4600 
4601 	if (obj->gen_loader)
4602 		return 0;
4603 
4604 	ret = bump_rlimit_memlock();
4605 	if (ret)
4606 		pr_warn("Failed to bump RLIMIT_MEMLOCK (err = %d), you might need to do it explicitly!\n", ret);
4607 
4608 	/* make sure basic loading works */
4609 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4610 	if (ret < 0)
4611 		ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
4612 	if (ret < 0) {
4613 		ret = errno;
4614 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4615 		pr_warn("Error in %s():%s(%d). Couldn't load trivial BPF "
4616 			"program. Make sure your kernel supports BPF "
4617 			"(CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is "
4618 			"set to big enough value.\n", __func__, cp, ret);
4619 		return -ret;
4620 	}
4621 	close(ret);
4622 
4623 	return 0;
4624 }
4625 
4626 static int probe_fd(int fd)
4627 {
4628 	if (fd >= 0)
4629 		close(fd);
4630 	return fd >= 0;
4631 }
4632 
4633 static int probe_kern_prog_name(void)
4634 {
4635 	const size_t attr_sz = offsetofend(union bpf_attr, prog_name);
4636 	struct bpf_insn insns[] = {
4637 		BPF_MOV64_IMM(BPF_REG_0, 0),
4638 		BPF_EXIT_INSN(),
4639 	};
4640 	union bpf_attr attr;
4641 	int ret;
4642 
4643 	memset(&attr, 0, attr_sz);
4644 	attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
4645 	attr.license = ptr_to_u64("GPL");
4646 	attr.insns = ptr_to_u64(insns);
4647 	attr.insn_cnt = (__u32)ARRAY_SIZE(insns);
4648 	libbpf_strlcpy(attr.prog_name, "libbpf_nametest", sizeof(attr.prog_name));
4649 
4650 	/* make sure loading with name works */
4651 	ret = sys_bpf_prog_load(&attr, attr_sz, PROG_LOAD_ATTEMPTS);
4652 	return probe_fd(ret);
4653 }
4654 
4655 static int probe_kern_global_data(void)
4656 {
4657 	char *cp, errmsg[STRERR_BUFSIZE];
4658 	struct bpf_insn insns[] = {
4659 		BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
4660 		BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
4661 		BPF_MOV64_IMM(BPF_REG_0, 0),
4662 		BPF_EXIT_INSN(),
4663 	};
4664 	int ret, map, insn_cnt = ARRAY_SIZE(insns);
4665 
4666 	map = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_global", sizeof(int), 32, 1, NULL);
4667 	if (map < 0) {
4668 		ret = -errno;
4669 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4670 		pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4671 			__func__, cp, -ret);
4672 		return ret;
4673 	}
4674 
4675 	insns[0].imm = map;
4676 
4677 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4678 	close(map);
4679 	return probe_fd(ret);
4680 }
4681 
4682 static int probe_kern_btf(void)
4683 {
4684 	static const char strs[] = "\0int";
4685 	__u32 types[] = {
4686 		/* int */
4687 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4688 	};
4689 
4690 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4691 					     strs, sizeof(strs)));
4692 }
4693 
4694 static int probe_kern_btf_func(void)
4695 {
4696 	static const char strs[] = "\0int\0x\0a";
4697 	/* void x(int a) {} */
4698 	__u32 types[] = {
4699 		/* int */
4700 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4701 		/* FUNC_PROTO */                                /* [2] */
4702 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4703 		BTF_PARAM_ENC(7, 1),
4704 		/* FUNC x */                                    /* [3] */
4705 		BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
4706 	};
4707 
4708 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4709 					     strs, sizeof(strs)));
4710 }
4711 
4712 static int probe_kern_btf_func_global(void)
4713 {
4714 	static const char strs[] = "\0int\0x\0a";
4715 	/* static void x(int a) {} */
4716 	__u32 types[] = {
4717 		/* int */
4718 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4719 		/* FUNC_PROTO */                                /* [2] */
4720 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4721 		BTF_PARAM_ENC(7, 1),
4722 		/* FUNC x BTF_FUNC_GLOBAL */                    /* [3] */
4723 		BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, BTF_FUNC_GLOBAL), 2),
4724 	};
4725 
4726 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4727 					     strs, sizeof(strs)));
4728 }
4729 
4730 static int probe_kern_btf_datasec(void)
4731 {
4732 	static const char strs[] = "\0x\0.data";
4733 	/* static int a; */
4734 	__u32 types[] = {
4735 		/* int */
4736 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4737 		/* VAR x */                                     /* [2] */
4738 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4739 		BTF_VAR_STATIC,
4740 		/* DATASEC val */                               /* [3] */
4741 		BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
4742 		BTF_VAR_SECINFO_ENC(2, 0, 4),
4743 	};
4744 
4745 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4746 					     strs, sizeof(strs)));
4747 }
4748 
4749 static int probe_kern_btf_float(void)
4750 {
4751 	static const char strs[] = "\0float";
4752 	__u32 types[] = {
4753 		/* float */
4754 		BTF_TYPE_FLOAT_ENC(1, 4),
4755 	};
4756 
4757 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4758 					     strs, sizeof(strs)));
4759 }
4760 
4761 static int probe_kern_btf_decl_tag(void)
4762 {
4763 	static const char strs[] = "\0tag";
4764 	__u32 types[] = {
4765 		/* int */
4766 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4767 		/* VAR x */                                     /* [2] */
4768 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4769 		BTF_VAR_STATIC,
4770 		/* attr */
4771 		BTF_TYPE_DECL_TAG_ENC(1, 2, -1),
4772 	};
4773 
4774 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4775 					     strs, sizeof(strs)));
4776 }
4777 
4778 static int probe_kern_btf_type_tag(void)
4779 {
4780 	static const char strs[] = "\0tag";
4781 	__u32 types[] = {
4782 		/* int */
4783 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),		/* [1] */
4784 		/* attr */
4785 		BTF_TYPE_TYPE_TAG_ENC(1, 1),				/* [2] */
4786 		/* ptr */
4787 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_PTR, 0, 0), 2),	/* [3] */
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_array_mmap(void)
4795 {
4796 	LIBBPF_OPTS(bpf_map_create_opts, opts, .map_flags = BPF_F_MMAPABLE);
4797 	int fd;
4798 
4799 	fd = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_mmap", sizeof(int), sizeof(int), 1, &opts);
4800 	return probe_fd(fd);
4801 }
4802 
4803 static int probe_kern_exp_attach_type(void)
4804 {
4805 	LIBBPF_OPTS(bpf_prog_load_opts, opts, .expected_attach_type = BPF_CGROUP_INET_SOCK_CREATE);
4806 	struct bpf_insn insns[] = {
4807 		BPF_MOV64_IMM(BPF_REG_0, 0),
4808 		BPF_EXIT_INSN(),
4809 	};
4810 	int fd, insn_cnt = ARRAY_SIZE(insns);
4811 
4812 	/* use any valid combination of program type and (optional)
4813 	 * non-zero expected attach type (i.e., not a BPF_CGROUP_INET_INGRESS)
4814 	 * to see if kernel supports expected_attach_type field for
4815 	 * BPF_PROG_LOAD command
4816 	 */
4817 	fd = bpf_prog_load(BPF_PROG_TYPE_CGROUP_SOCK, NULL, "GPL", insns, insn_cnt, &opts);
4818 	return probe_fd(fd);
4819 }
4820 
4821 static int probe_kern_probe_read_kernel(void)
4822 {
4823 	struct bpf_insn insns[] = {
4824 		BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),	/* r1 = r10 (fp) */
4825 		BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -8),	/* r1 += -8 */
4826 		BPF_MOV64_IMM(BPF_REG_2, 8),		/* r2 = 8 */
4827 		BPF_MOV64_IMM(BPF_REG_3, 0),		/* r3 = 0 */
4828 		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_probe_read_kernel),
4829 		BPF_EXIT_INSN(),
4830 	};
4831 	int fd, insn_cnt = ARRAY_SIZE(insns);
4832 
4833 	fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
4834 	return probe_fd(fd);
4835 }
4836 
4837 static int probe_prog_bind_map(void)
4838 {
4839 	char *cp, errmsg[STRERR_BUFSIZE];
4840 	struct bpf_insn insns[] = {
4841 		BPF_MOV64_IMM(BPF_REG_0, 0),
4842 		BPF_EXIT_INSN(),
4843 	};
4844 	int ret, map, prog, insn_cnt = ARRAY_SIZE(insns);
4845 
4846 	map = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_det_bind", sizeof(int), 32, 1, NULL);
4847 	if (map < 0) {
4848 		ret = -errno;
4849 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4850 		pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4851 			__func__, cp, -ret);
4852 		return ret;
4853 	}
4854 
4855 	prog = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4856 	if (prog < 0) {
4857 		close(map);
4858 		return 0;
4859 	}
4860 
4861 	ret = bpf_prog_bind_map(prog, map, NULL);
4862 
4863 	close(map);
4864 	close(prog);
4865 
4866 	return ret >= 0;
4867 }
4868 
4869 static int probe_module_btf(void)
4870 {
4871 	static const char strs[] = "\0int";
4872 	__u32 types[] = {
4873 		/* int */
4874 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4875 	};
4876 	struct bpf_btf_info info;
4877 	__u32 len = sizeof(info);
4878 	char name[16];
4879 	int fd, err;
4880 
4881 	fd = libbpf__load_raw_btf((char *)types, sizeof(types), strs, sizeof(strs));
4882 	if (fd < 0)
4883 		return 0; /* BTF not supported at all */
4884 
4885 	memset(&info, 0, sizeof(info));
4886 	info.name = ptr_to_u64(name);
4887 	info.name_len = sizeof(name);
4888 
4889 	/* check that BPF_OBJ_GET_INFO_BY_FD supports specifying name pointer;
4890 	 * kernel's module BTF support coincides with support for
4891 	 * name/name_len fields in struct bpf_btf_info.
4892 	 */
4893 	err = bpf_btf_get_info_by_fd(fd, &info, &len);
4894 	close(fd);
4895 	return !err;
4896 }
4897 
4898 static int probe_perf_link(void)
4899 {
4900 	struct bpf_insn insns[] = {
4901 		BPF_MOV64_IMM(BPF_REG_0, 0),
4902 		BPF_EXIT_INSN(),
4903 	};
4904 	int prog_fd, link_fd, err;
4905 
4906 	prog_fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL",
4907 				insns, ARRAY_SIZE(insns), NULL);
4908 	if (prog_fd < 0)
4909 		return -errno;
4910 
4911 	/* use invalid perf_event FD to get EBADF, if link is supported;
4912 	 * otherwise EINVAL should be returned
4913 	 */
4914 	link_fd = bpf_link_create(prog_fd, -1, BPF_PERF_EVENT, NULL);
4915 	err = -errno; /* close() can clobber errno */
4916 
4917 	if (link_fd >= 0)
4918 		close(link_fd);
4919 	close(prog_fd);
4920 
4921 	return link_fd < 0 && err == -EBADF;
4922 }
4923 
4924 static int probe_uprobe_multi_link(void)
4925 {
4926 	LIBBPF_OPTS(bpf_prog_load_opts, load_opts,
4927 		.expected_attach_type = BPF_TRACE_UPROBE_MULTI,
4928 	);
4929 	LIBBPF_OPTS(bpf_link_create_opts, link_opts);
4930 	struct bpf_insn insns[] = {
4931 		BPF_MOV64_IMM(BPF_REG_0, 0),
4932 		BPF_EXIT_INSN(),
4933 	};
4934 	int prog_fd, link_fd, err;
4935 	unsigned long offset = 0;
4936 
4937 	prog_fd = bpf_prog_load(BPF_PROG_TYPE_KPROBE, NULL, "GPL",
4938 				insns, ARRAY_SIZE(insns), &load_opts);
4939 	if (prog_fd < 0)
4940 		return -errno;
4941 
4942 	/* Creating uprobe in '/' binary should fail with -EBADF. */
4943 	link_opts.uprobe_multi.path = "/";
4944 	link_opts.uprobe_multi.offsets = &offset;
4945 	link_opts.uprobe_multi.cnt = 1;
4946 
4947 	link_fd = bpf_link_create(prog_fd, -1, BPF_TRACE_UPROBE_MULTI, &link_opts);
4948 	err = -errno; /* close() can clobber errno */
4949 
4950 	if (link_fd >= 0)
4951 		close(link_fd);
4952 	close(prog_fd);
4953 
4954 	return link_fd < 0 && err == -EBADF;
4955 }
4956 
4957 static int probe_kern_bpf_cookie(void)
4958 {
4959 	struct bpf_insn insns[] = {
4960 		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_get_attach_cookie),
4961 		BPF_EXIT_INSN(),
4962 	};
4963 	int ret, insn_cnt = ARRAY_SIZE(insns);
4964 
4965 	ret = bpf_prog_load(BPF_PROG_TYPE_KPROBE, NULL, "GPL", insns, insn_cnt, NULL);
4966 	return probe_fd(ret);
4967 }
4968 
4969 static int probe_kern_btf_enum64(void)
4970 {
4971 	static const char strs[] = "\0enum64";
4972 	__u32 types[] = {
4973 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_ENUM64, 0, 0), 8),
4974 	};
4975 
4976 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4977 					     strs, sizeof(strs)));
4978 }
4979 
4980 static int probe_kern_syscall_wrapper(void);
4981 
4982 enum kern_feature_result {
4983 	FEAT_UNKNOWN = 0,
4984 	FEAT_SUPPORTED = 1,
4985 	FEAT_MISSING = 2,
4986 };
4987 
4988 typedef int (*feature_probe_fn)(void);
4989 
4990 static struct kern_feature_desc {
4991 	const char *desc;
4992 	feature_probe_fn probe;
4993 	enum kern_feature_result res;
4994 } feature_probes[__FEAT_CNT] = {
4995 	[FEAT_PROG_NAME] = {
4996 		"BPF program name", probe_kern_prog_name,
4997 	},
4998 	[FEAT_GLOBAL_DATA] = {
4999 		"global variables", probe_kern_global_data,
5000 	},
5001 	[FEAT_BTF] = {
5002 		"minimal BTF", probe_kern_btf,
5003 	},
5004 	[FEAT_BTF_FUNC] = {
5005 		"BTF functions", probe_kern_btf_func,
5006 	},
5007 	[FEAT_BTF_GLOBAL_FUNC] = {
5008 		"BTF global function", probe_kern_btf_func_global,
5009 	},
5010 	[FEAT_BTF_DATASEC] = {
5011 		"BTF data section and variable", probe_kern_btf_datasec,
5012 	},
5013 	[FEAT_ARRAY_MMAP] = {
5014 		"ARRAY map mmap()", probe_kern_array_mmap,
5015 	},
5016 	[FEAT_EXP_ATTACH_TYPE] = {
5017 		"BPF_PROG_LOAD expected_attach_type attribute",
5018 		probe_kern_exp_attach_type,
5019 	},
5020 	[FEAT_PROBE_READ_KERN] = {
5021 		"bpf_probe_read_kernel() helper", probe_kern_probe_read_kernel,
5022 	},
5023 	[FEAT_PROG_BIND_MAP] = {
5024 		"BPF_PROG_BIND_MAP support", probe_prog_bind_map,
5025 	},
5026 	[FEAT_MODULE_BTF] = {
5027 		"module BTF support", probe_module_btf,
5028 	},
5029 	[FEAT_BTF_FLOAT] = {
5030 		"BTF_KIND_FLOAT support", probe_kern_btf_float,
5031 	},
5032 	[FEAT_PERF_LINK] = {
5033 		"BPF perf link support", probe_perf_link,
5034 	},
5035 	[FEAT_BTF_DECL_TAG] = {
5036 		"BTF_KIND_DECL_TAG support", probe_kern_btf_decl_tag,
5037 	},
5038 	[FEAT_BTF_TYPE_TAG] = {
5039 		"BTF_KIND_TYPE_TAG support", probe_kern_btf_type_tag,
5040 	},
5041 	[FEAT_MEMCG_ACCOUNT] = {
5042 		"memcg-based memory accounting", probe_memcg_account,
5043 	},
5044 	[FEAT_BPF_COOKIE] = {
5045 		"BPF cookie support", probe_kern_bpf_cookie,
5046 	},
5047 	[FEAT_BTF_ENUM64] = {
5048 		"BTF_KIND_ENUM64 support", probe_kern_btf_enum64,
5049 	},
5050 	[FEAT_SYSCALL_WRAPPER] = {
5051 		"Kernel using syscall wrapper", probe_kern_syscall_wrapper,
5052 	},
5053 	[FEAT_UPROBE_MULTI_LINK] = {
5054 		"BPF multi-uprobe link support", probe_uprobe_multi_link,
5055 	},
5056 };
5057 
5058 bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
5059 {
5060 	struct kern_feature_desc *feat = &feature_probes[feat_id];
5061 	int ret;
5062 
5063 	if (obj && obj->gen_loader)
5064 		/* To generate loader program assume the latest kernel
5065 		 * to avoid doing extra prog_load, map_create syscalls.
5066 		 */
5067 		return true;
5068 
5069 	if (READ_ONCE(feat->res) == FEAT_UNKNOWN) {
5070 		ret = feat->probe();
5071 		if (ret > 0) {
5072 			WRITE_ONCE(feat->res, FEAT_SUPPORTED);
5073 		} else if (ret == 0) {
5074 			WRITE_ONCE(feat->res, FEAT_MISSING);
5075 		} else {
5076 			pr_warn("Detection of kernel %s support failed: %d\n", feat->desc, ret);
5077 			WRITE_ONCE(feat->res, FEAT_MISSING);
5078 		}
5079 	}
5080 
5081 	return READ_ONCE(feat->res) == FEAT_SUPPORTED;
5082 }
5083 
5084 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
5085 {
5086 	struct bpf_map_info map_info;
5087 	char msg[STRERR_BUFSIZE];
5088 	__u32 map_info_len = sizeof(map_info);
5089 	int err;
5090 
5091 	memset(&map_info, 0, map_info_len);
5092 	err = bpf_map_get_info_by_fd(map_fd, &map_info, &map_info_len);
5093 	if (err && errno == EINVAL)
5094 		err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
5095 	if (err) {
5096 		pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
5097 			libbpf_strerror_r(errno, msg, sizeof(msg)));
5098 		return false;
5099 	}
5100 
5101 	return (map_info.type == map->def.type &&
5102 		map_info.key_size == map->def.key_size &&
5103 		map_info.value_size == map->def.value_size &&
5104 		map_info.max_entries == map->def.max_entries &&
5105 		map_info.map_flags == map->def.map_flags &&
5106 		map_info.map_extra == map->map_extra);
5107 }
5108 
5109 static int
5110 bpf_object__reuse_map(struct bpf_map *map)
5111 {
5112 	char *cp, errmsg[STRERR_BUFSIZE];
5113 	int err, pin_fd;
5114 
5115 	pin_fd = bpf_obj_get(map->pin_path);
5116 	if (pin_fd < 0) {
5117 		err = -errno;
5118 		if (err == -ENOENT) {
5119 			pr_debug("found no pinned map to reuse at '%s'\n",
5120 				 map->pin_path);
5121 			return 0;
5122 		}
5123 
5124 		cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
5125 		pr_warn("couldn't retrieve pinned map '%s': %s\n",
5126 			map->pin_path, cp);
5127 		return err;
5128 	}
5129 
5130 	if (!map_is_reuse_compat(map, pin_fd)) {
5131 		pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
5132 			map->pin_path);
5133 		close(pin_fd);
5134 		return -EINVAL;
5135 	}
5136 
5137 	err = bpf_map__reuse_fd(map, pin_fd);
5138 	close(pin_fd);
5139 	if (err)
5140 		return err;
5141 
5142 	map->pinned = true;
5143 	pr_debug("reused pinned map at '%s'\n", map->pin_path);
5144 
5145 	return 0;
5146 }
5147 
5148 static int
5149 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
5150 {
5151 	enum libbpf_map_type map_type = map->libbpf_type;
5152 	char *cp, errmsg[STRERR_BUFSIZE];
5153 	int err, zero = 0;
5154 
5155 	if (obj->gen_loader) {
5156 		bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
5157 					 map->mmaped, map->def.value_size);
5158 		if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
5159 			bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
5160 		return 0;
5161 	}
5162 	err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
5163 	if (err) {
5164 		err = -errno;
5165 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5166 		pr_warn("Error setting initial map(%s) contents: %s\n",
5167 			map->name, cp);
5168 		return err;
5169 	}
5170 
5171 	/* Freeze .rodata and .kconfig map as read-only from syscall side. */
5172 	if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
5173 		err = bpf_map_freeze(map->fd);
5174 		if (err) {
5175 			err = -errno;
5176 			cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5177 			pr_warn("Error freezing map(%s) as read-only: %s\n",
5178 				map->name, cp);
5179 			return err;
5180 		}
5181 	}
5182 	return 0;
5183 }
5184 
5185 static void bpf_map__destroy(struct bpf_map *map);
5186 
5187 static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
5188 {
5189 	LIBBPF_OPTS(bpf_map_create_opts, create_attr);
5190 	struct bpf_map_def *def = &map->def;
5191 	const char *map_name = NULL;
5192 	int err = 0;
5193 
5194 	if (kernel_supports(obj, FEAT_PROG_NAME))
5195 		map_name = map->name;
5196 	create_attr.map_ifindex = map->map_ifindex;
5197 	create_attr.map_flags = def->map_flags;
5198 	create_attr.numa_node = map->numa_node;
5199 	create_attr.map_extra = map->map_extra;
5200 
5201 	if (bpf_map__is_struct_ops(map))
5202 		create_attr.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
5203 
5204 	if (obj->btf && btf__fd(obj->btf) >= 0) {
5205 		create_attr.btf_fd = btf__fd(obj->btf);
5206 		create_attr.btf_key_type_id = map->btf_key_type_id;
5207 		create_attr.btf_value_type_id = map->btf_value_type_id;
5208 	}
5209 
5210 	if (bpf_map_type__is_map_in_map(def->type)) {
5211 		if (map->inner_map) {
5212 			err = bpf_object__create_map(obj, map->inner_map, true);
5213 			if (err) {
5214 				pr_warn("map '%s': failed to create inner map: %d\n",
5215 					map->name, err);
5216 				return err;
5217 			}
5218 			map->inner_map_fd = bpf_map__fd(map->inner_map);
5219 		}
5220 		if (map->inner_map_fd >= 0)
5221 			create_attr.inner_map_fd = map->inner_map_fd;
5222 	}
5223 
5224 	switch (def->type) {
5225 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5226 	case BPF_MAP_TYPE_CGROUP_ARRAY:
5227 	case BPF_MAP_TYPE_STACK_TRACE:
5228 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5229 	case BPF_MAP_TYPE_HASH_OF_MAPS:
5230 	case BPF_MAP_TYPE_DEVMAP:
5231 	case BPF_MAP_TYPE_DEVMAP_HASH:
5232 	case BPF_MAP_TYPE_CPUMAP:
5233 	case BPF_MAP_TYPE_XSKMAP:
5234 	case BPF_MAP_TYPE_SOCKMAP:
5235 	case BPF_MAP_TYPE_SOCKHASH:
5236 	case BPF_MAP_TYPE_QUEUE:
5237 	case BPF_MAP_TYPE_STACK:
5238 		create_attr.btf_fd = 0;
5239 		create_attr.btf_key_type_id = 0;
5240 		create_attr.btf_value_type_id = 0;
5241 		map->btf_key_type_id = 0;
5242 		map->btf_value_type_id = 0;
5243 	default:
5244 		break;
5245 	}
5246 
5247 	if (obj->gen_loader) {
5248 		bpf_gen__map_create(obj->gen_loader, def->type, map_name,
5249 				    def->key_size, def->value_size, def->max_entries,
5250 				    &create_attr, is_inner ? -1 : map - obj->maps);
5251 		/* Pretend to have valid FD to pass various fd >= 0 checks.
5252 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
5253 		 */
5254 		map->fd = 0;
5255 	} else {
5256 		map->fd = bpf_map_create(def->type, map_name,
5257 					 def->key_size, def->value_size,
5258 					 def->max_entries, &create_attr);
5259 	}
5260 	if (map->fd < 0 && (create_attr.btf_key_type_id ||
5261 			    create_attr.btf_value_type_id)) {
5262 		char *cp, errmsg[STRERR_BUFSIZE];
5263 
5264 		err = -errno;
5265 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5266 		pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
5267 			map->name, cp, err);
5268 		create_attr.btf_fd = 0;
5269 		create_attr.btf_key_type_id = 0;
5270 		create_attr.btf_value_type_id = 0;
5271 		map->btf_key_type_id = 0;
5272 		map->btf_value_type_id = 0;
5273 		map->fd = bpf_map_create(def->type, map_name,
5274 					 def->key_size, def->value_size,
5275 					 def->max_entries, &create_attr);
5276 	}
5277 
5278 	err = map->fd < 0 ? -errno : 0;
5279 
5280 	if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
5281 		if (obj->gen_loader)
5282 			map->inner_map->fd = -1;
5283 		bpf_map__destroy(map->inner_map);
5284 		zfree(&map->inner_map);
5285 	}
5286 
5287 	return err;
5288 }
5289 
5290 static int init_map_in_map_slots(struct bpf_object *obj, struct bpf_map *map)
5291 {
5292 	const struct bpf_map *targ_map;
5293 	unsigned int i;
5294 	int fd, err = 0;
5295 
5296 	for (i = 0; i < map->init_slots_sz; i++) {
5297 		if (!map->init_slots[i])
5298 			continue;
5299 
5300 		targ_map = map->init_slots[i];
5301 		fd = bpf_map__fd(targ_map);
5302 
5303 		if (obj->gen_loader) {
5304 			bpf_gen__populate_outer_map(obj->gen_loader,
5305 						    map - obj->maps, i,
5306 						    targ_map - obj->maps);
5307 		} else {
5308 			err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5309 		}
5310 		if (err) {
5311 			err = -errno;
5312 			pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %d\n",
5313 				map->name, i, targ_map->name, fd, err);
5314 			return err;
5315 		}
5316 		pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
5317 			 map->name, i, targ_map->name, fd);
5318 	}
5319 
5320 	zfree(&map->init_slots);
5321 	map->init_slots_sz = 0;
5322 
5323 	return 0;
5324 }
5325 
5326 static int init_prog_array_slots(struct bpf_object *obj, struct bpf_map *map)
5327 {
5328 	const struct bpf_program *targ_prog;
5329 	unsigned int i;
5330 	int fd, err;
5331 
5332 	if (obj->gen_loader)
5333 		return -ENOTSUP;
5334 
5335 	for (i = 0; i < map->init_slots_sz; i++) {
5336 		if (!map->init_slots[i])
5337 			continue;
5338 
5339 		targ_prog = map->init_slots[i];
5340 		fd = bpf_program__fd(targ_prog);
5341 
5342 		err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5343 		if (err) {
5344 			err = -errno;
5345 			pr_warn("map '%s': failed to initialize slot [%d] to prog '%s' fd=%d: %d\n",
5346 				map->name, i, targ_prog->name, fd, err);
5347 			return err;
5348 		}
5349 		pr_debug("map '%s': slot [%d] set to prog '%s' fd=%d\n",
5350 			 map->name, i, targ_prog->name, fd);
5351 	}
5352 
5353 	zfree(&map->init_slots);
5354 	map->init_slots_sz = 0;
5355 
5356 	return 0;
5357 }
5358 
5359 static int bpf_object_init_prog_arrays(struct bpf_object *obj)
5360 {
5361 	struct bpf_map *map;
5362 	int i, err;
5363 
5364 	for (i = 0; i < obj->nr_maps; i++) {
5365 		map = &obj->maps[i];
5366 
5367 		if (!map->init_slots_sz || map->def.type != BPF_MAP_TYPE_PROG_ARRAY)
5368 			continue;
5369 
5370 		err = init_prog_array_slots(obj, map);
5371 		if (err < 0) {
5372 			zclose(map->fd);
5373 			return err;
5374 		}
5375 	}
5376 	return 0;
5377 }
5378 
5379 static int map_set_def_max_entries(struct bpf_map *map)
5380 {
5381 	if (map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !map->def.max_entries) {
5382 		int nr_cpus;
5383 
5384 		nr_cpus = libbpf_num_possible_cpus();
5385 		if (nr_cpus < 0) {
5386 			pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
5387 				map->name, nr_cpus);
5388 			return nr_cpus;
5389 		}
5390 		pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
5391 		map->def.max_entries = nr_cpus;
5392 	}
5393 
5394 	return 0;
5395 }
5396 
5397 static int
5398 bpf_object__create_maps(struct bpf_object *obj)
5399 {
5400 	struct bpf_map *map;
5401 	char *cp, errmsg[STRERR_BUFSIZE];
5402 	unsigned int i, j;
5403 	int err;
5404 	bool retried;
5405 
5406 	for (i = 0; i < obj->nr_maps; i++) {
5407 		map = &obj->maps[i];
5408 
5409 		/* To support old kernels, we skip creating global data maps
5410 		 * (.rodata, .data, .kconfig, etc); later on, during program
5411 		 * loading, if we detect that at least one of the to-be-loaded
5412 		 * programs is referencing any global data map, we'll error
5413 		 * out with program name and relocation index logged.
5414 		 * This approach allows to accommodate Clang emitting
5415 		 * unnecessary .rodata.str1.1 sections for string literals,
5416 		 * but also it allows to have CO-RE applications that use
5417 		 * global variables in some of BPF programs, but not others.
5418 		 * If those global variable-using programs are not loaded at
5419 		 * runtime due to bpf_program__set_autoload(prog, false),
5420 		 * bpf_object loading will succeed just fine even on old
5421 		 * kernels.
5422 		 */
5423 		if (bpf_map__is_internal(map) && !kernel_supports(obj, FEAT_GLOBAL_DATA))
5424 			map->autocreate = false;
5425 
5426 		if (!map->autocreate) {
5427 			pr_debug("map '%s': skipped auto-creating...\n", map->name);
5428 			continue;
5429 		}
5430 
5431 		err = map_set_def_max_entries(map);
5432 		if (err)
5433 			goto err_out;
5434 
5435 		retried = false;
5436 retry:
5437 		if (map->pin_path) {
5438 			err = bpf_object__reuse_map(map);
5439 			if (err) {
5440 				pr_warn("map '%s': error reusing pinned map\n",
5441 					map->name);
5442 				goto err_out;
5443 			}
5444 			if (retried && map->fd < 0) {
5445 				pr_warn("map '%s': cannot find pinned map\n",
5446 					map->name);
5447 				err = -ENOENT;
5448 				goto err_out;
5449 			}
5450 		}
5451 
5452 		if (map->fd >= 0) {
5453 			pr_debug("map '%s': skipping creation (preset fd=%d)\n",
5454 				 map->name, map->fd);
5455 		} else {
5456 			err = bpf_object__create_map(obj, map, false);
5457 			if (err)
5458 				goto err_out;
5459 
5460 			pr_debug("map '%s': created successfully, fd=%d\n",
5461 				 map->name, map->fd);
5462 
5463 			if (bpf_map__is_internal(map)) {
5464 				err = bpf_object__populate_internal_map(obj, map);
5465 				if (err < 0) {
5466 					zclose(map->fd);
5467 					goto err_out;
5468 				}
5469 			}
5470 
5471 			if (map->init_slots_sz && map->def.type != BPF_MAP_TYPE_PROG_ARRAY) {
5472 				err = init_map_in_map_slots(obj, map);
5473 				if (err < 0) {
5474 					zclose(map->fd);
5475 					goto err_out;
5476 				}
5477 			}
5478 		}
5479 
5480 		if (map->pin_path && !map->pinned) {
5481 			err = bpf_map__pin(map, NULL);
5482 			if (err) {
5483 				zclose(map->fd);
5484 				if (!retried && err == -EEXIST) {
5485 					retried = true;
5486 					goto retry;
5487 				}
5488 				pr_warn("map '%s': failed to auto-pin at '%s': %d\n",
5489 					map->name, map->pin_path, err);
5490 				goto err_out;
5491 			}
5492 		}
5493 	}
5494 
5495 	return 0;
5496 
5497 err_out:
5498 	cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5499 	pr_warn("map '%s': failed to create: %s(%d)\n", map->name, cp, err);
5500 	pr_perm_msg(err);
5501 	for (j = 0; j < i; j++)
5502 		zclose(obj->maps[j].fd);
5503 	return err;
5504 }
5505 
5506 static bool bpf_core_is_flavor_sep(const char *s)
5507 {
5508 	/* check X___Y name pattern, where X and Y are not underscores */
5509 	return s[0] != '_' &&				      /* X */
5510 	       s[1] == '_' && s[2] == '_' && s[3] == '_' &&   /* ___ */
5511 	       s[4] != '_';				      /* Y */
5512 }
5513 
5514 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
5515  * before last triple underscore. Struct name part after last triple
5516  * underscore is ignored by BPF CO-RE relocation during relocation matching.
5517  */
5518 size_t bpf_core_essential_name_len(const char *name)
5519 {
5520 	size_t n = strlen(name);
5521 	int i;
5522 
5523 	for (i = n - 5; i >= 0; i--) {
5524 		if (bpf_core_is_flavor_sep(name + i))
5525 			return i + 1;
5526 	}
5527 	return n;
5528 }
5529 
5530 void bpf_core_free_cands(struct bpf_core_cand_list *cands)
5531 {
5532 	if (!cands)
5533 		return;
5534 
5535 	free(cands->cands);
5536 	free(cands);
5537 }
5538 
5539 int bpf_core_add_cands(struct bpf_core_cand *local_cand,
5540 		       size_t local_essent_len,
5541 		       const struct btf *targ_btf,
5542 		       const char *targ_btf_name,
5543 		       int targ_start_id,
5544 		       struct bpf_core_cand_list *cands)
5545 {
5546 	struct bpf_core_cand *new_cands, *cand;
5547 	const struct btf_type *t, *local_t;
5548 	const char *targ_name, *local_name;
5549 	size_t targ_essent_len;
5550 	int n, i;
5551 
5552 	local_t = btf__type_by_id(local_cand->btf, local_cand->id);
5553 	local_name = btf__str_by_offset(local_cand->btf, local_t->name_off);
5554 
5555 	n = btf__type_cnt(targ_btf);
5556 	for (i = targ_start_id; i < n; i++) {
5557 		t = btf__type_by_id(targ_btf, i);
5558 		if (!btf_kind_core_compat(t, local_t))
5559 			continue;
5560 
5561 		targ_name = btf__name_by_offset(targ_btf, t->name_off);
5562 		if (str_is_empty(targ_name))
5563 			continue;
5564 
5565 		targ_essent_len = bpf_core_essential_name_len(targ_name);
5566 		if (targ_essent_len != local_essent_len)
5567 			continue;
5568 
5569 		if (strncmp(local_name, targ_name, local_essent_len) != 0)
5570 			continue;
5571 
5572 		pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s in [%s]\n",
5573 			 local_cand->id, btf_kind_str(local_t),
5574 			 local_name, i, btf_kind_str(t), targ_name,
5575 			 targ_btf_name);
5576 		new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
5577 					      sizeof(*cands->cands));
5578 		if (!new_cands)
5579 			return -ENOMEM;
5580 
5581 		cand = &new_cands[cands->len];
5582 		cand->btf = targ_btf;
5583 		cand->id = i;
5584 
5585 		cands->cands = new_cands;
5586 		cands->len++;
5587 	}
5588 	return 0;
5589 }
5590 
5591 static int load_module_btfs(struct bpf_object *obj)
5592 {
5593 	struct bpf_btf_info info;
5594 	struct module_btf *mod_btf;
5595 	struct btf *btf;
5596 	char name[64];
5597 	__u32 id = 0, len;
5598 	int err, fd;
5599 
5600 	if (obj->btf_modules_loaded)
5601 		return 0;
5602 
5603 	if (obj->gen_loader)
5604 		return 0;
5605 
5606 	/* don't do this again, even if we find no module BTFs */
5607 	obj->btf_modules_loaded = true;
5608 
5609 	/* kernel too old to support module BTFs */
5610 	if (!kernel_supports(obj, FEAT_MODULE_BTF))
5611 		return 0;
5612 
5613 	while (true) {
5614 		err = bpf_btf_get_next_id(id, &id);
5615 		if (err && errno == ENOENT)
5616 			return 0;
5617 		if (err && errno == EPERM) {
5618 			pr_debug("skipping module BTFs loading, missing privileges\n");
5619 			return 0;
5620 		}
5621 		if (err) {
5622 			err = -errno;
5623 			pr_warn("failed to iterate BTF objects: %d\n", err);
5624 			return err;
5625 		}
5626 
5627 		fd = bpf_btf_get_fd_by_id(id);
5628 		if (fd < 0) {
5629 			if (errno == ENOENT)
5630 				continue; /* expected race: BTF was unloaded */
5631 			err = -errno;
5632 			pr_warn("failed to get BTF object #%d FD: %d\n", id, err);
5633 			return err;
5634 		}
5635 
5636 		len = sizeof(info);
5637 		memset(&info, 0, sizeof(info));
5638 		info.name = ptr_to_u64(name);
5639 		info.name_len = sizeof(name);
5640 
5641 		err = bpf_btf_get_info_by_fd(fd, &info, &len);
5642 		if (err) {
5643 			err = -errno;
5644 			pr_warn("failed to get BTF object #%d info: %d\n", id, err);
5645 			goto err_out;
5646 		}
5647 
5648 		/* ignore non-module BTFs */
5649 		if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
5650 			close(fd);
5651 			continue;
5652 		}
5653 
5654 		btf = btf_get_from_fd(fd, obj->btf_vmlinux);
5655 		err = libbpf_get_error(btf);
5656 		if (err) {
5657 			pr_warn("failed to load module [%s]'s BTF object #%d: %d\n",
5658 				name, id, err);
5659 			goto err_out;
5660 		}
5661 
5662 		err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
5663 					sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
5664 		if (err)
5665 			goto err_out;
5666 
5667 		mod_btf = &obj->btf_modules[obj->btf_module_cnt++];
5668 
5669 		mod_btf->btf = btf;
5670 		mod_btf->id = id;
5671 		mod_btf->fd = fd;
5672 		mod_btf->name = strdup(name);
5673 		if (!mod_btf->name) {
5674 			err = -ENOMEM;
5675 			goto err_out;
5676 		}
5677 		continue;
5678 
5679 err_out:
5680 		close(fd);
5681 		return err;
5682 	}
5683 
5684 	return 0;
5685 }
5686 
5687 static struct bpf_core_cand_list *
5688 bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
5689 {
5690 	struct bpf_core_cand local_cand = {};
5691 	struct bpf_core_cand_list *cands;
5692 	const struct btf *main_btf;
5693 	const struct btf_type *local_t;
5694 	const char *local_name;
5695 	size_t local_essent_len;
5696 	int err, i;
5697 
5698 	local_cand.btf = local_btf;
5699 	local_cand.id = local_type_id;
5700 	local_t = btf__type_by_id(local_btf, local_type_id);
5701 	if (!local_t)
5702 		return ERR_PTR(-EINVAL);
5703 
5704 	local_name = btf__name_by_offset(local_btf, local_t->name_off);
5705 	if (str_is_empty(local_name))
5706 		return ERR_PTR(-EINVAL);
5707 	local_essent_len = bpf_core_essential_name_len(local_name);
5708 
5709 	cands = calloc(1, sizeof(*cands));
5710 	if (!cands)
5711 		return ERR_PTR(-ENOMEM);
5712 
5713 	/* Attempt to find target candidates in vmlinux BTF first */
5714 	main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
5715 	err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
5716 	if (err)
5717 		goto err_out;
5718 
5719 	/* if vmlinux BTF has any candidate, don't got for module BTFs */
5720 	if (cands->len)
5721 		return cands;
5722 
5723 	/* if vmlinux BTF was overridden, don't attempt to load module BTFs */
5724 	if (obj->btf_vmlinux_override)
5725 		return cands;
5726 
5727 	/* now look through module BTFs, trying to still find candidates */
5728 	err = load_module_btfs(obj);
5729 	if (err)
5730 		goto err_out;
5731 
5732 	for (i = 0; i < obj->btf_module_cnt; i++) {
5733 		err = bpf_core_add_cands(&local_cand, local_essent_len,
5734 					 obj->btf_modules[i].btf,
5735 					 obj->btf_modules[i].name,
5736 					 btf__type_cnt(obj->btf_vmlinux),
5737 					 cands);
5738 		if (err)
5739 			goto err_out;
5740 	}
5741 
5742 	return cands;
5743 err_out:
5744 	bpf_core_free_cands(cands);
5745 	return ERR_PTR(err);
5746 }
5747 
5748 /* Check local and target types for compatibility. This check is used for
5749  * type-based CO-RE relocations and follow slightly different rules than
5750  * field-based relocations. This function assumes that root types were already
5751  * checked for name match. Beyond that initial root-level name check, names
5752  * are completely ignored. Compatibility rules are as follows:
5753  *   - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
5754  *     kind should match for local and target types (i.e., STRUCT is not
5755  *     compatible with UNION);
5756  *   - for ENUMs, the size is ignored;
5757  *   - for INT, size and signedness are ignored;
5758  *   - for ARRAY, dimensionality is ignored, element types are checked for
5759  *     compatibility recursively;
5760  *   - CONST/VOLATILE/RESTRICT modifiers are ignored;
5761  *   - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
5762  *   - FUNC_PROTOs are compatible if they have compatible signature: same
5763  *     number of input args and compatible return and argument types.
5764  * These rules are not set in stone and probably will be adjusted as we get
5765  * more experience with using BPF CO-RE relocations.
5766  */
5767 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
5768 			      const struct btf *targ_btf, __u32 targ_id)
5769 {
5770 	return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id, 32);
5771 }
5772 
5773 int bpf_core_types_match(const struct btf *local_btf, __u32 local_id,
5774 			 const struct btf *targ_btf, __u32 targ_id)
5775 {
5776 	return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false, 32);
5777 }
5778 
5779 static size_t bpf_core_hash_fn(const long key, void *ctx)
5780 {
5781 	return key;
5782 }
5783 
5784 static bool bpf_core_equal_fn(const long k1, const long k2, void *ctx)
5785 {
5786 	return k1 == k2;
5787 }
5788 
5789 static int record_relo_core(struct bpf_program *prog,
5790 			    const struct bpf_core_relo *core_relo, int insn_idx)
5791 {
5792 	struct reloc_desc *relos, *relo;
5793 
5794 	relos = libbpf_reallocarray(prog->reloc_desc,
5795 				    prog->nr_reloc + 1, sizeof(*relos));
5796 	if (!relos)
5797 		return -ENOMEM;
5798 	relo = &relos[prog->nr_reloc];
5799 	relo->type = RELO_CORE;
5800 	relo->insn_idx = insn_idx;
5801 	relo->core_relo = core_relo;
5802 	prog->reloc_desc = relos;
5803 	prog->nr_reloc++;
5804 	return 0;
5805 }
5806 
5807 static const struct bpf_core_relo *find_relo_core(struct bpf_program *prog, int insn_idx)
5808 {
5809 	struct reloc_desc *relo;
5810 	int i;
5811 
5812 	for (i = 0; i < prog->nr_reloc; i++) {
5813 		relo = &prog->reloc_desc[i];
5814 		if (relo->type != RELO_CORE || relo->insn_idx != insn_idx)
5815 			continue;
5816 
5817 		return relo->core_relo;
5818 	}
5819 
5820 	return NULL;
5821 }
5822 
5823 static int bpf_core_resolve_relo(struct bpf_program *prog,
5824 				 const struct bpf_core_relo *relo,
5825 				 int relo_idx,
5826 				 const struct btf *local_btf,
5827 				 struct hashmap *cand_cache,
5828 				 struct bpf_core_relo_res *targ_res)
5829 {
5830 	struct bpf_core_spec specs_scratch[3] = {};
5831 	struct bpf_core_cand_list *cands = NULL;
5832 	const char *prog_name = prog->name;
5833 	const struct btf_type *local_type;
5834 	const char *local_name;
5835 	__u32 local_id = relo->type_id;
5836 	int err;
5837 
5838 	local_type = btf__type_by_id(local_btf, local_id);
5839 	if (!local_type)
5840 		return -EINVAL;
5841 
5842 	local_name = btf__name_by_offset(local_btf, local_type->name_off);
5843 	if (!local_name)
5844 		return -EINVAL;
5845 
5846 	if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
5847 	    !hashmap__find(cand_cache, local_id, &cands)) {
5848 		cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
5849 		if (IS_ERR(cands)) {
5850 			pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n",
5851 				prog_name, relo_idx, local_id, btf_kind_str(local_type),
5852 				local_name, PTR_ERR(cands));
5853 			return PTR_ERR(cands);
5854 		}
5855 		err = hashmap__set(cand_cache, local_id, cands, NULL, NULL);
5856 		if (err) {
5857 			bpf_core_free_cands(cands);
5858 			return err;
5859 		}
5860 	}
5861 
5862 	return bpf_core_calc_relo_insn(prog_name, relo, relo_idx, local_btf, cands, specs_scratch,
5863 				       targ_res);
5864 }
5865 
5866 static int
5867 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
5868 {
5869 	const struct btf_ext_info_sec *sec;
5870 	struct bpf_core_relo_res targ_res;
5871 	const struct bpf_core_relo *rec;
5872 	const struct btf_ext_info *seg;
5873 	struct hashmap_entry *entry;
5874 	struct hashmap *cand_cache = NULL;
5875 	struct bpf_program *prog;
5876 	struct bpf_insn *insn;
5877 	const char *sec_name;
5878 	int i, err = 0, insn_idx, sec_idx, sec_num;
5879 
5880 	if (obj->btf_ext->core_relo_info.len == 0)
5881 		return 0;
5882 
5883 	if (targ_btf_path) {
5884 		obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
5885 		err = libbpf_get_error(obj->btf_vmlinux_override);
5886 		if (err) {
5887 			pr_warn("failed to parse target BTF: %d\n", err);
5888 			return err;
5889 		}
5890 	}
5891 
5892 	cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
5893 	if (IS_ERR(cand_cache)) {
5894 		err = PTR_ERR(cand_cache);
5895 		goto out;
5896 	}
5897 
5898 	seg = &obj->btf_ext->core_relo_info;
5899 	sec_num = 0;
5900 	for_each_btf_ext_sec(seg, sec) {
5901 		sec_idx = seg->sec_idxs[sec_num];
5902 		sec_num++;
5903 
5904 		sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
5905 		if (str_is_empty(sec_name)) {
5906 			err = -EINVAL;
5907 			goto out;
5908 		}
5909 
5910 		pr_debug("sec '%s': found %d CO-RE relocations\n", sec_name, sec->num_info);
5911 
5912 		for_each_btf_ext_rec(seg, sec, i, rec) {
5913 			if (rec->insn_off % BPF_INSN_SZ)
5914 				return -EINVAL;
5915 			insn_idx = rec->insn_off / BPF_INSN_SZ;
5916 			prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
5917 			if (!prog) {
5918 				/* When __weak subprog is "overridden" by another instance
5919 				 * of the subprog from a different object file, linker still
5920 				 * appends all the .BTF.ext info that used to belong to that
5921 				 * eliminated subprogram.
5922 				 * This is similar to what x86-64 linker does for relocations.
5923 				 * So just ignore such relocations just like we ignore
5924 				 * subprog instructions when discovering subprograms.
5925 				 */
5926 				pr_debug("sec '%s': skipping CO-RE relocation #%d for insn #%d belonging to eliminated weak subprogram\n",
5927 					 sec_name, i, insn_idx);
5928 				continue;
5929 			}
5930 			/* no need to apply CO-RE relocation if the program is
5931 			 * not going to be loaded
5932 			 */
5933 			if (!prog->autoload)
5934 				continue;
5935 
5936 			/* adjust insn_idx from section frame of reference to the local
5937 			 * program's frame of reference; (sub-)program code is not yet
5938 			 * relocated, so it's enough to just subtract in-section offset
5939 			 */
5940 			insn_idx = insn_idx - prog->sec_insn_off;
5941 			if (insn_idx >= prog->insns_cnt)
5942 				return -EINVAL;
5943 			insn = &prog->insns[insn_idx];
5944 
5945 			err = record_relo_core(prog, rec, insn_idx);
5946 			if (err) {
5947 				pr_warn("prog '%s': relo #%d: failed to record relocation: %d\n",
5948 					prog->name, i, err);
5949 				goto out;
5950 			}
5951 
5952 			if (prog->obj->gen_loader)
5953 				continue;
5954 
5955 			err = bpf_core_resolve_relo(prog, rec, i, obj->btf, cand_cache, &targ_res);
5956 			if (err) {
5957 				pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
5958 					prog->name, i, err);
5959 				goto out;
5960 			}
5961 
5962 			err = bpf_core_patch_insn(prog->name, insn, insn_idx, rec, i, &targ_res);
5963 			if (err) {
5964 				pr_warn("prog '%s': relo #%d: failed to patch insn #%u: %d\n",
5965 					prog->name, i, insn_idx, err);
5966 				goto out;
5967 			}
5968 		}
5969 	}
5970 
5971 out:
5972 	/* obj->btf_vmlinux and module BTFs are freed after object load */
5973 	btf__free(obj->btf_vmlinux_override);
5974 	obj->btf_vmlinux_override = NULL;
5975 
5976 	if (!IS_ERR_OR_NULL(cand_cache)) {
5977 		hashmap__for_each_entry(cand_cache, entry, i) {
5978 			bpf_core_free_cands(entry->pvalue);
5979 		}
5980 		hashmap__free(cand_cache);
5981 	}
5982 	return err;
5983 }
5984 
5985 /* base map load ldimm64 special constant, used also for log fixup logic */
5986 #define POISON_LDIMM64_MAP_BASE 2001000000
5987 #define POISON_LDIMM64_MAP_PFX "200100"
5988 
5989 static void poison_map_ldimm64(struct bpf_program *prog, int relo_idx,
5990 			       int insn_idx, struct bpf_insn *insn,
5991 			       int map_idx, const struct bpf_map *map)
5992 {
5993 	int i;
5994 
5995 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that loads map #%d '%s'\n",
5996 		 prog->name, relo_idx, insn_idx, map_idx, map->name);
5997 
5998 	/* we turn single ldimm64 into two identical invalid calls */
5999 	for (i = 0; i < 2; i++) {
6000 		insn->code = BPF_JMP | BPF_CALL;
6001 		insn->dst_reg = 0;
6002 		insn->src_reg = 0;
6003 		insn->off = 0;
6004 		/* if this instruction is reachable (not a dead code),
6005 		 * verifier will complain with something like:
6006 		 * invalid func unknown#2001000123
6007 		 * where lower 123 is map index into obj->maps[] array
6008 		 */
6009 		insn->imm = POISON_LDIMM64_MAP_BASE + map_idx;
6010 
6011 		insn++;
6012 	}
6013 }
6014 
6015 /* unresolved kfunc call special constant, used also for log fixup logic */
6016 #define POISON_CALL_KFUNC_BASE 2002000000
6017 #define POISON_CALL_KFUNC_PFX "2002"
6018 
6019 static void poison_kfunc_call(struct bpf_program *prog, int relo_idx,
6020 			      int insn_idx, struct bpf_insn *insn,
6021 			      int ext_idx, const struct extern_desc *ext)
6022 {
6023 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that calls kfunc '%s'\n",
6024 		 prog->name, relo_idx, insn_idx, ext->name);
6025 
6026 	/* we turn kfunc call into invalid helper call with identifiable constant */
6027 	insn->code = BPF_JMP | BPF_CALL;
6028 	insn->dst_reg = 0;
6029 	insn->src_reg = 0;
6030 	insn->off = 0;
6031 	/* if this instruction is reachable (not a dead code),
6032 	 * verifier will complain with something like:
6033 	 * invalid func unknown#2001000123
6034 	 * where lower 123 is extern index into obj->externs[] array
6035 	 */
6036 	insn->imm = POISON_CALL_KFUNC_BASE + ext_idx;
6037 }
6038 
6039 /* Relocate data references within program code:
6040  *  - map references;
6041  *  - global variable references;
6042  *  - extern references.
6043  */
6044 static int
6045 bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
6046 {
6047 	int i;
6048 
6049 	for (i = 0; i < prog->nr_reloc; i++) {
6050 		struct reloc_desc *relo = &prog->reloc_desc[i];
6051 		struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6052 		const struct bpf_map *map;
6053 		struct extern_desc *ext;
6054 
6055 		switch (relo->type) {
6056 		case RELO_LD64:
6057 			map = &obj->maps[relo->map_idx];
6058 			if (obj->gen_loader) {
6059 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
6060 				insn[0].imm = relo->map_idx;
6061 			} else if (map->autocreate) {
6062 				insn[0].src_reg = BPF_PSEUDO_MAP_FD;
6063 				insn[0].imm = map->fd;
6064 			} else {
6065 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6066 						   relo->map_idx, map);
6067 			}
6068 			break;
6069 		case RELO_DATA:
6070 			map = &obj->maps[relo->map_idx];
6071 			insn[1].imm = insn[0].imm + relo->sym_off;
6072 			if (obj->gen_loader) {
6073 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6074 				insn[0].imm = relo->map_idx;
6075 			} else if (map->autocreate) {
6076 				insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6077 				insn[0].imm = map->fd;
6078 			} else {
6079 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6080 						   relo->map_idx, map);
6081 			}
6082 			break;
6083 		case RELO_EXTERN_LD64:
6084 			ext = &obj->externs[relo->ext_idx];
6085 			if (ext->type == EXT_KCFG) {
6086 				if (obj->gen_loader) {
6087 					insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6088 					insn[0].imm = obj->kconfig_map_idx;
6089 				} else {
6090 					insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6091 					insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
6092 				}
6093 				insn[1].imm = ext->kcfg.data_off;
6094 			} else /* EXT_KSYM */ {
6095 				if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
6096 					insn[0].src_reg = BPF_PSEUDO_BTF_ID;
6097 					insn[0].imm = ext->ksym.kernel_btf_id;
6098 					insn[1].imm = ext->ksym.kernel_btf_obj_fd;
6099 				} else { /* typeless ksyms or unresolved typed ksyms */
6100 					insn[0].imm = (__u32)ext->ksym.addr;
6101 					insn[1].imm = ext->ksym.addr >> 32;
6102 				}
6103 			}
6104 			break;
6105 		case RELO_EXTERN_CALL:
6106 			ext = &obj->externs[relo->ext_idx];
6107 			insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
6108 			if (ext->is_set) {
6109 				insn[0].imm = ext->ksym.kernel_btf_id;
6110 				insn[0].off = ext->ksym.btf_fd_idx;
6111 			} else { /* unresolved weak kfunc call */
6112 				poison_kfunc_call(prog, i, relo->insn_idx, insn,
6113 						  relo->ext_idx, ext);
6114 			}
6115 			break;
6116 		case RELO_SUBPROG_ADDR:
6117 			if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
6118 				pr_warn("prog '%s': relo #%d: bad insn\n",
6119 					prog->name, i);
6120 				return -EINVAL;
6121 			}
6122 			/* handled already */
6123 			break;
6124 		case RELO_CALL:
6125 			/* handled already */
6126 			break;
6127 		case RELO_CORE:
6128 			/* will be handled by bpf_program_record_relos() */
6129 			break;
6130 		default:
6131 			pr_warn("prog '%s': relo #%d: bad relo type %d\n",
6132 				prog->name, i, relo->type);
6133 			return -EINVAL;
6134 		}
6135 	}
6136 
6137 	return 0;
6138 }
6139 
6140 static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
6141 				    const struct bpf_program *prog,
6142 				    const struct btf_ext_info *ext_info,
6143 				    void **prog_info, __u32 *prog_rec_cnt,
6144 				    __u32 *prog_rec_sz)
6145 {
6146 	void *copy_start = NULL, *copy_end = NULL;
6147 	void *rec, *rec_end, *new_prog_info;
6148 	const struct btf_ext_info_sec *sec;
6149 	size_t old_sz, new_sz;
6150 	int i, sec_num, sec_idx, off_adj;
6151 
6152 	sec_num = 0;
6153 	for_each_btf_ext_sec(ext_info, sec) {
6154 		sec_idx = ext_info->sec_idxs[sec_num];
6155 		sec_num++;
6156 		if (prog->sec_idx != sec_idx)
6157 			continue;
6158 
6159 		for_each_btf_ext_rec(ext_info, sec, i, rec) {
6160 			__u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
6161 
6162 			if (insn_off < prog->sec_insn_off)
6163 				continue;
6164 			if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
6165 				break;
6166 
6167 			if (!copy_start)
6168 				copy_start = rec;
6169 			copy_end = rec + ext_info->rec_size;
6170 		}
6171 
6172 		if (!copy_start)
6173 			return -ENOENT;
6174 
6175 		/* append func/line info of a given (sub-)program to the main
6176 		 * program func/line info
6177 		 */
6178 		old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
6179 		new_sz = old_sz + (copy_end - copy_start);
6180 		new_prog_info = realloc(*prog_info, new_sz);
6181 		if (!new_prog_info)
6182 			return -ENOMEM;
6183 		*prog_info = new_prog_info;
6184 		*prog_rec_cnt = new_sz / ext_info->rec_size;
6185 		memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
6186 
6187 		/* Kernel instruction offsets are in units of 8-byte
6188 		 * instructions, while .BTF.ext instruction offsets generated
6189 		 * by Clang are in units of bytes. So convert Clang offsets
6190 		 * into kernel offsets and adjust offset according to program
6191 		 * relocated position.
6192 		 */
6193 		off_adj = prog->sub_insn_off - prog->sec_insn_off;
6194 		rec = new_prog_info + old_sz;
6195 		rec_end = new_prog_info + new_sz;
6196 		for (; rec < rec_end; rec += ext_info->rec_size) {
6197 			__u32 *insn_off = rec;
6198 
6199 			*insn_off = *insn_off / BPF_INSN_SZ + off_adj;
6200 		}
6201 		*prog_rec_sz = ext_info->rec_size;
6202 		return 0;
6203 	}
6204 
6205 	return -ENOENT;
6206 }
6207 
6208 static int
6209 reloc_prog_func_and_line_info(const struct bpf_object *obj,
6210 			      struct bpf_program *main_prog,
6211 			      const struct bpf_program *prog)
6212 {
6213 	int err;
6214 
6215 	/* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
6216 	 * supprot func/line info
6217 	 */
6218 	if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
6219 		return 0;
6220 
6221 	/* only attempt func info relocation if main program's func_info
6222 	 * relocation was successful
6223 	 */
6224 	if (main_prog != prog && !main_prog->func_info)
6225 		goto line_info;
6226 
6227 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
6228 				       &main_prog->func_info,
6229 				       &main_prog->func_info_cnt,
6230 				       &main_prog->func_info_rec_size);
6231 	if (err) {
6232 		if (err != -ENOENT) {
6233 			pr_warn("prog '%s': error relocating .BTF.ext function info: %d\n",
6234 				prog->name, err);
6235 			return err;
6236 		}
6237 		if (main_prog->func_info) {
6238 			/*
6239 			 * Some info has already been found but has problem
6240 			 * in the last btf_ext reloc. Must have to error out.
6241 			 */
6242 			pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
6243 			return err;
6244 		}
6245 		/* Have problem loading the very first info. Ignore the rest. */
6246 		pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
6247 			prog->name);
6248 	}
6249 
6250 line_info:
6251 	/* don't relocate line info if main program's relocation failed */
6252 	if (main_prog != prog && !main_prog->line_info)
6253 		return 0;
6254 
6255 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
6256 				       &main_prog->line_info,
6257 				       &main_prog->line_info_cnt,
6258 				       &main_prog->line_info_rec_size);
6259 	if (err) {
6260 		if (err != -ENOENT) {
6261 			pr_warn("prog '%s': error relocating .BTF.ext line info: %d\n",
6262 				prog->name, err);
6263 			return err;
6264 		}
6265 		if (main_prog->line_info) {
6266 			/*
6267 			 * Some info has already been found but has problem
6268 			 * in the last btf_ext reloc. Must have to error out.
6269 			 */
6270 			pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
6271 			return err;
6272 		}
6273 		/* Have problem loading the very first info. Ignore the rest. */
6274 		pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
6275 			prog->name);
6276 	}
6277 	return 0;
6278 }
6279 
6280 static int cmp_relo_by_insn_idx(const void *key, const void *elem)
6281 {
6282 	size_t insn_idx = *(const size_t *)key;
6283 	const struct reloc_desc *relo = elem;
6284 
6285 	if (insn_idx == relo->insn_idx)
6286 		return 0;
6287 	return insn_idx < relo->insn_idx ? -1 : 1;
6288 }
6289 
6290 static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
6291 {
6292 	if (!prog->nr_reloc)
6293 		return NULL;
6294 	return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
6295 		       sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
6296 }
6297 
6298 static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
6299 {
6300 	int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
6301 	struct reloc_desc *relos;
6302 	int i;
6303 
6304 	if (main_prog == subprog)
6305 		return 0;
6306 	relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
6307 	/* if new count is zero, reallocarray can return a valid NULL result;
6308 	 * in this case the previous pointer will be freed, so we *have to*
6309 	 * reassign old pointer to the new value (even if it's NULL)
6310 	 */
6311 	if (!relos && new_cnt)
6312 		return -ENOMEM;
6313 	if (subprog->nr_reloc)
6314 		memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
6315 		       sizeof(*relos) * subprog->nr_reloc);
6316 
6317 	for (i = main_prog->nr_reloc; i < new_cnt; i++)
6318 		relos[i].insn_idx += subprog->sub_insn_off;
6319 	/* After insn_idx adjustment the 'relos' array is still sorted
6320 	 * by insn_idx and doesn't break bsearch.
6321 	 */
6322 	main_prog->reloc_desc = relos;
6323 	main_prog->nr_reloc = new_cnt;
6324 	return 0;
6325 }
6326 
6327 static int
6328 bpf_object__append_subprog_code(struct bpf_object *obj, struct bpf_program *main_prog,
6329 				struct bpf_program *subprog)
6330 {
6331        struct bpf_insn *insns;
6332        size_t new_cnt;
6333        int err;
6334 
6335        subprog->sub_insn_off = main_prog->insns_cnt;
6336 
6337        new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
6338        insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
6339        if (!insns) {
6340                pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
6341                return -ENOMEM;
6342        }
6343        main_prog->insns = insns;
6344        main_prog->insns_cnt = new_cnt;
6345 
6346        memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
6347               subprog->insns_cnt * sizeof(*insns));
6348 
6349        pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
6350                 main_prog->name, subprog->insns_cnt, subprog->name);
6351 
6352        /* The subprog insns are now appended. Append its relos too. */
6353        err = append_subprog_relos(main_prog, subprog);
6354        if (err)
6355                return err;
6356        return 0;
6357 }
6358 
6359 static int
6360 bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
6361 		       struct bpf_program *prog)
6362 {
6363 	size_t sub_insn_idx, insn_idx;
6364 	struct bpf_program *subprog;
6365 	struct reloc_desc *relo;
6366 	struct bpf_insn *insn;
6367 	int err;
6368 
6369 	err = reloc_prog_func_and_line_info(obj, main_prog, prog);
6370 	if (err)
6371 		return err;
6372 
6373 	for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
6374 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6375 		if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
6376 			continue;
6377 
6378 		relo = find_prog_insn_relo(prog, insn_idx);
6379 		if (relo && relo->type == RELO_EXTERN_CALL)
6380 			/* kfunc relocations will be handled later
6381 			 * in bpf_object__relocate_data()
6382 			 */
6383 			continue;
6384 		if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
6385 			pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
6386 				prog->name, insn_idx, relo->type);
6387 			return -LIBBPF_ERRNO__RELOC;
6388 		}
6389 		if (relo) {
6390 			/* sub-program instruction index is a combination of
6391 			 * an offset of a symbol pointed to by relocation and
6392 			 * call instruction's imm field; for global functions,
6393 			 * call always has imm = -1, but for static functions
6394 			 * relocation is against STT_SECTION and insn->imm
6395 			 * points to a start of a static function
6396 			 *
6397 			 * for subprog addr relocation, the relo->sym_off + insn->imm is
6398 			 * the byte offset in the corresponding section.
6399 			 */
6400 			if (relo->type == RELO_CALL)
6401 				sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
6402 			else
6403 				sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
6404 		} else if (insn_is_pseudo_func(insn)) {
6405 			/*
6406 			 * RELO_SUBPROG_ADDR relo is always emitted even if both
6407 			 * functions are in the same section, so it shouldn't reach here.
6408 			 */
6409 			pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
6410 				prog->name, insn_idx);
6411 			return -LIBBPF_ERRNO__RELOC;
6412 		} else {
6413 			/* if subprogram call is to a static function within
6414 			 * the same ELF section, there won't be any relocation
6415 			 * emitted, but it also means there is no additional
6416 			 * offset necessary, insns->imm is relative to
6417 			 * instruction's original position within the section
6418 			 */
6419 			sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
6420 		}
6421 
6422 		/* we enforce that sub-programs should be in .text section */
6423 		subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
6424 		if (!subprog) {
6425 			pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
6426 				prog->name);
6427 			return -LIBBPF_ERRNO__RELOC;
6428 		}
6429 
6430 		/* if it's the first call instruction calling into this
6431 		 * subprogram (meaning this subprog hasn't been processed
6432 		 * yet) within the context of current main program:
6433 		 *   - append it at the end of main program's instructions blog;
6434 		 *   - process is recursively, while current program is put on hold;
6435 		 *   - if that subprogram calls some other not yet processes
6436 		 *   subprogram, same thing will happen recursively until
6437 		 *   there are no more unprocesses subprograms left to append
6438 		 *   and relocate.
6439 		 */
6440 		if (subprog->sub_insn_off == 0) {
6441 			err = bpf_object__append_subprog_code(obj, main_prog, subprog);
6442 			if (err)
6443 				return err;
6444 			err = bpf_object__reloc_code(obj, main_prog, subprog);
6445 			if (err)
6446 				return err;
6447 		}
6448 
6449 		/* main_prog->insns memory could have been re-allocated, so
6450 		 * calculate pointer again
6451 		 */
6452 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6453 		/* calculate correct instruction position within current main
6454 		 * prog; each main prog can have a different set of
6455 		 * subprograms appended (potentially in different order as
6456 		 * well), so position of any subprog can be different for
6457 		 * different main programs
6458 		 */
6459 		insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
6460 
6461 		pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
6462 			 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
6463 	}
6464 
6465 	return 0;
6466 }
6467 
6468 /*
6469  * Relocate sub-program calls.
6470  *
6471  * Algorithm operates as follows. Each entry-point BPF program (referred to as
6472  * main prog) is processed separately. For each subprog (non-entry functions,
6473  * that can be called from either entry progs or other subprogs) gets their
6474  * sub_insn_off reset to zero. This serves as indicator that this subprogram
6475  * hasn't been yet appended and relocated within current main prog. Once its
6476  * relocated, sub_insn_off will point at the position within current main prog
6477  * where given subprog was appended. This will further be used to relocate all
6478  * the call instructions jumping into this subprog.
6479  *
6480  * We start with main program and process all call instructions. If the call
6481  * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
6482  * is zero), subprog instructions are appended at the end of main program's
6483  * instruction array. Then main program is "put on hold" while we recursively
6484  * process newly appended subprogram. If that subprogram calls into another
6485  * subprogram that hasn't been appended, new subprogram is appended again to
6486  * the *main* prog's instructions (subprog's instructions are always left
6487  * untouched, as they need to be in unmodified state for subsequent main progs
6488  * and subprog instructions are always sent only as part of a main prog) and
6489  * the process continues recursively. Once all the subprogs called from a main
6490  * prog or any of its subprogs are appended (and relocated), all their
6491  * positions within finalized instructions array are known, so it's easy to
6492  * rewrite call instructions with correct relative offsets, corresponding to
6493  * desired target subprog.
6494  *
6495  * Its important to realize that some subprogs might not be called from some
6496  * main prog and any of its called/used subprogs. Those will keep their
6497  * subprog->sub_insn_off as zero at all times and won't be appended to current
6498  * main prog and won't be relocated within the context of current main prog.
6499  * They might still be used from other main progs later.
6500  *
6501  * Visually this process can be shown as below. Suppose we have two main
6502  * programs mainA and mainB and BPF object contains three subprogs: subA,
6503  * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
6504  * subC both call subB:
6505  *
6506  *        +--------+ +-------+
6507  *        |        v v       |
6508  *     +--+---+ +--+-+-+ +---+--+
6509  *     | subA | | subB | | subC |
6510  *     +--+---+ +------+ +---+--+
6511  *        ^                  ^
6512  *        |                  |
6513  *    +---+-------+   +------+----+
6514  *    |   mainA   |   |   mainB   |
6515  *    +-----------+   +-----------+
6516  *
6517  * We'll start relocating mainA, will find subA, append it and start
6518  * processing sub A recursively:
6519  *
6520  *    +-----------+------+
6521  *    |   mainA   | subA |
6522  *    +-----------+------+
6523  *
6524  * At this point we notice that subB is used from subA, so we append it and
6525  * relocate (there are no further subcalls from subB):
6526  *
6527  *    +-----------+------+------+
6528  *    |   mainA   | subA | subB |
6529  *    +-----------+------+------+
6530  *
6531  * At this point, we relocate subA calls, then go one level up and finish with
6532  * relocatin mainA calls. mainA is done.
6533  *
6534  * For mainB process is similar but results in different order. We start with
6535  * mainB and skip subA and subB, as mainB never calls them (at least
6536  * directly), but we see subC is needed, so we append and start processing it:
6537  *
6538  *    +-----------+------+
6539  *    |   mainB   | subC |
6540  *    +-----------+------+
6541  * Now we see subC needs subB, so we go back to it, append and relocate it:
6542  *
6543  *    +-----------+------+------+
6544  *    |   mainB   | subC | subB |
6545  *    +-----------+------+------+
6546  *
6547  * At this point we unwind recursion, relocate calls in subC, then in mainB.
6548  */
6549 static int
6550 bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
6551 {
6552 	struct bpf_program *subprog;
6553 	int i, err;
6554 
6555 	/* mark all subprogs as not relocated (yet) within the context of
6556 	 * current main program
6557 	 */
6558 	for (i = 0; i < obj->nr_programs; i++) {
6559 		subprog = &obj->programs[i];
6560 		if (!prog_is_subprog(obj, subprog))
6561 			continue;
6562 
6563 		subprog->sub_insn_off = 0;
6564 	}
6565 
6566 	err = bpf_object__reloc_code(obj, prog, prog);
6567 	if (err)
6568 		return err;
6569 
6570 	return 0;
6571 }
6572 
6573 static void
6574 bpf_object__free_relocs(struct bpf_object *obj)
6575 {
6576 	struct bpf_program *prog;
6577 	int i;
6578 
6579 	/* free up relocation descriptors */
6580 	for (i = 0; i < obj->nr_programs; i++) {
6581 		prog = &obj->programs[i];
6582 		zfree(&prog->reloc_desc);
6583 		prog->nr_reloc = 0;
6584 	}
6585 }
6586 
6587 static int cmp_relocs(const void *_a, const void *_b)
6588 {
6589 	const struct reloc_desc *a = _a;
6590 	const struct reloc_desc *b = _b;
6591 
6592 	if (a->insn_idx != b->insn_idx)
6593 		return a->insn_idx < b->insn_idx ? -1 : 1;
6594 
6595 	/* no two relocations should have the same insn_idx, but ... */
6596 	if (a->type != b->type)
6597 		return a->type < b->type ? -1 : 1;
6598 
6599 	return 0;
6600 }
6601 
6602 static void bpf_object__sort_relos(struct bpf_object *obj)
6603 {
6604 	int i;
6605 
6606 	for (i = 0; i < obj->nr_programs; i++) {
6607 		struct bpf_program *p = &obj->programs[i];
6608 
6609 		if (!p->nr_reloc)
6610 			continue;
6611 
6612 		qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
6613 	}
6614 }
6615 
6616 static int
6617 bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
6618 {
6619 	struct bpf_program *prog;
6620 	size_t i, j;
6621 	int err;
6622 
6623 	if (obj->btf_ext) {
6624 		err = bpf_object__relocate_core(obj, targ_btf_path);
6625 		if (err) {
6626 			pr_warn("failed to perform CO-RE relocations: %d\n",
6627 				err);
6628 			return err;
6629 		}
6630 		bpf_object__sort_relos(obj);
6631 	}
6632 
6633 	/* Before relocating calls pre-process relocations and mark
6634 	 * few ld_imm64 instructions that points to subprogs.
6635 	 * Otherwise bpf_object__reloc_code() later would have to consider
6636 	 * all ld_imm64 insns as relocation candidates. That would
6637 	 * reduce relocation speed, since amount of find_prog_insn_relo()
6638 	 * would increase and most of them will fail to find a relo.
6639 	 */
6640 	for (i = 0; i < obj->nr_programs; i++) {
6641 		prog = &obj->programs[i];
6642 		for (j = 0; j < prog->nr_reloc; j++) {
6643 			struct reloc_desc *relo = &prog->reloc_desc[j];
6644 			struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6645 
6646 			/* mark the insn, so it's recognized by insn_is_pseudo_func() */
6647 			if (relo->type == RELO_SUBPROG_ADDR)
6648 				insn[0].src_reg = BPF_PSEUDO_FUNC;
6649 		}
6650 	}
6651 
6652 	/* relocate subprogram calls and append used subprograms to main
6653 	 * programs; each copy of subprogram code needs to be relocated
6654 	 * differently for each main program, because its code location might
6655 	 * have changed.
6656 	 * Append subprog relos to main programs to allow data relos to be
6657 	 * processed after text is completely relocated.
6658 	 */
6659 	for (i = 0; i < obj->nr_programs; i++) {
6660 		prog = &obj->programs[i];
6661 		/* sub-program's sub-calls are relocated within the context of
6662 		 * its main program only
6663 		 */
6664 		if (prog_is_subprog(obj, prog))
6665 			continue;
6666 		if (!prog->autoload)
6667 			continue;
6668 
6669 		err = bpf_object__relocate_calls(obj, prog);
6670 		if (err) {
6671 			pr_warn("prog '%s': failed to relocate calls: %d\n",
6672 				prog->name, err);
6673 			return err;
6674 		}
6675 
6676 		/* Now, also append exception callback if it has not been done already. */
6677 		if (prog->exception_cb_idx >= 0) {
6678 			struct bpf_program *subprog = &obj->programs[prog->exception_cb_idx];
6679 
6680 			/* Calling exception callback directly is disallowed, which the
6681 			 * verifier will reject later. In case it was processed already,
6682 			 * we can skip this step, otherwise for all other valid cases we
6683 			 * have to append exception callback now.
6684 			 */
6685 			if (subprog->sub_insn_off == 0) {
6686 				err = bpf_object__append_subprog_code(obj, prog, subprog);
6687 				if (err)
6688 					return err;
6689 				err = bpf_object__reloc_code(obj, prog, subprog);
6690 				if (err)
6691 					return err;
6692 			}
6693 		}
6694 	}
6695 	/* Process data relos for main programs */
6696 	for (i = 0; i < obj->nr_programs; i++) {
6697 		prog = &obj->programs[i];
6698 		if (prog_is_subprog(obj, prog))
6699 			continue;
6700 		if (!prog->autoload)
6701 			continue;
6702 		err = bpf_object__relocate_data(obj, prog);
6703 		if (err) {
6704 			pr_warn("prog '%s': failed to relocate data references: %d\n",
6705 				prog->name, err);
6706 			return err;
6707 		}
6708 	}
6709 
6710 	return 0;
6711 }
6712 
6713 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
6714 					    Elf64_Shdr *shdr, Elf_Data *data);
6715 
6716 static int bpf_object__collect_map_relos(struct bpf_object *obj,
6717 					 Elf64_Shdr *shdr, Elf_Data *data)
6718 {
6719 	const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
6720 	int i, j, nrels, new_sz;
6721 	const struct btf_var_secinfo *vi = NULL;
6722 	const struct btf_type *sec, *var, *def;
6723 	struct bpf_map *map = NULL, *targ_map = NULL;
6724 	struct bpf_program *targ_prog = NULL;
6725 	bool is_prog_array, is_map_in_map;
6726 	const struct btf_member *member;
6727 	const char *name, *mname, *type;
6728 	unsigned int moff;
6729 	Elf64_Sym *sym;
6730 	Elf64_Rel *rel;
6731 	void *tmp;
6732 
6733 	if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
6734 		return -EINVAL;
6735 	sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
6736 	if (!sec)
6737 		return -EINVAL;
6738 
6739 	nrels = shdr->sh_size / shdr->sh_entsize;
6740 	for (i = 0; i < nrels; i++) {
6741 		rel = elf_rel_by_idx(data, i);
6742 		if (!rel) {
6743 			pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
6744 			return -LIBBPF_ERRNO__FORMAT;
6745 		}
6746 
6747 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
6748 		if (!sym) {
6749 			pr_warn(".maps relo #%d: symbol %zx not found\n",
6750 				i, (size_t)ELF64_R_SYM(rel->r_info));
6751 			return -LIBBPF_ERRNO__FORMAT;
6752 		}
6753 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
6754 
6755 		pr_debug(".maps relo #%d: for %zd value %zd rel->r_offset %zu name %d ('%s')\n",
6756 			 i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
6757 			 (size_t)rel->r_offset, sym->st_name, name);
6758 
6759 		for (j = 0; j < obj->nr_maps; j++) {
6760 			map = &obj->maps[j];
6761 			if (map->sec_idx != obj->efile.btf_maps_shndx)
6762 				continue;
6763 
6764 			vi = btf_var_secinfos(sec) + map->btf_var_idx;
6765 			if (vi->offset <= rel->r_offset &&
6766 			    rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size)
6767 				break;
6768 		}
6769 		if (j == obj->nr_maps) {
6770 			pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
6771 				i, name, (size_t)rel->r_offset);
6772 			return -EINVAL;
6773 		}
6774 
6775 		is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
6776 		is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
6777 		type = is_map_in_map ? "map" : "prog";
6778 		if (is_map_in_map) {
6779 			if (sym->st_shndx != obj->efile.btf_maps_shndx) {
6780 				pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
6781 					i, name);
6782 				return -LIBBPF_ERRNO__RELOC;
6783 			}
6784 			if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
6785 			    map->def.key_size != sizeof(int)) {
6786 				pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
6787 					i, map->name, sizeof(int));
6788 				return -EINVAL;
6789 			}
6790 			targ_map = bpf_object__find_map_by_name(obj, name);
6791 			if (!targ_map) {
6792 				pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
6793 					i, name);
6794 				return -ESRCH;
6795 			}
6796 		} else if (is_prog_array) {
6797 			targ_prog = bpf_object__find_program_by_name(obj, name);
6798 			if (!targ_prog) {
6799 				pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
6800 					i, name);
6801 				return -ESRCH;
6802 			}
6803 			if (targ_prog->sec_idx != sym->st_shndx ||
6804 			    targ_prog->sec_insn_off * 8 != sym->st_value ||
6805 			    prog_is_subprog(obj, targ_prog)) {
6806 				pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
6807 					i, name);
6808 				return -LIBBPF_ERRNO__RELOC;
6809 			}
6810 		} else {
6811 			return -EINVAL;
6812 		}
6813 
6814 		var = btf__type_by_id(obj->btf, vi->type);
6815 		def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
6816 		if (btf_vlen(def) == 0)
6817 			return -EINVAL;
6818 		member = btf_members(def) + btf_vlen(def) - 1;
6819 		mname = btf__name_by_offset(obj->btf, member->name_off);
6820 		if (strcmp(mname, "values"))
6821 			return -EINVAL;
6822 
6823 		moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
6824 		if (rel->r_offset - vi->offset < moff)
6825 			return -EINVAL;
6826 
6827 		moff = rel->r_offset - vi->offset - moff;
6828 		/* here we use BPF pointer size, which is always 64 bit, as we
6829 		 * are parsing ELF that was built for BPF target
6830 		 */
6831 		if (moff % bpf_ptr_sz)
6832 			return -EINVAL;
6833 		moff /= bpf_ptr_sz;
6834 		if (moff >= map->init_slots_sz) {
6835 			new_sz = moff + 1;
6836 			tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
6837 			if (!tmp)
6838 				return -ENOMEM;
6839 			map->init_slots = tmp;
6840 			memset(map->init_slots + map->init_slots_sz, 0,
6841 			       (new_sz - map->init_slots_sz) * host_ptr_sz);
6842 			map->init_slots_sz = new_sz;
6843 		}
6844 		map->init_slots[moff] = is_map_in_map ? (void *)targ_map : (void *)targ_prog;
6845 
6846 		pr_debug(".maps relo #%d: map '%s' slot [%d] points to %s '%s'\n",
6847 			 i, map->name, moff, type, name);
6848 	}
6849 
6850 	return 0;
6851 }
6852 
6853 static int bpf_object__collect_relos(struct bpf_object *obj)
6854 {
6855 	int i, err;
6856 
6857 	for (i = 0; i < obj->efile.sec_cnt; i++) {
6858 		struct elf_sec_desc *sec_desc = &obj->efile.secs[i];
6859 		Elf64_Shdr *shdr;
6860 		Elf_Data *data;
6861 		int idx;
6862 
6863 		if (sec_desc->sec_type != SEC_RELO)
6864 			continue;
6865 
6866 		shdr = sec_desc->shdr;
6867 		data = sec_desc->data;
6868 		idx = shdr->sh_info;
6869 
6870 		if (shdr->sh_type != SHT_REL) {
6871 			pr_warn("internal error at %d\n", __LINE__);
6872 			return -LIBBPF_ERRNO__INTERNAL;
6873 		}
6874 
6875 		if (idx == obj->efile.st_ops_shndx || idx == obj->efile.st_ops_link_shndx)
6876 			err = bpf_object__collect_st_ops_relos(obj, shdr, data);
6877 		else if (idx == obj->efile.btf_maps_shndx)
6878 			err = bpf_object__collect_map_relos(obj, shdr, data);
6879 		else
6880 			err = bpf_object__collect_prog_relos(obj, shdr, data);
6881 		if (err)
6882 			return err;
6883 	}
6884 
6885 	bpf_object__sort_relos(obj);
6886 	return 0;
6887 }
6888 
6889 static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
6890 {
6891 	if (BPF_CLASS(insn->code) == BPF_JMP &&
6892 	    BPF_OP(insn->code) == BPF_CALL &&
6893 	    BPF_SRC(insn->code) == BPF_K &&
6894 	    insn->src_reg == 0 &&
6895 	    insn->dst_reg == 0) {
6896 		    *func_id = insn->imm;
6897 		    return true;
6898 	}
6899 	return false;
6900 }
6901 
6902 static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
6903 {
6904 	struct bpf_insn *insn = prog->insns;
6905 	enum bpf_func_id func_id;
6906 	int i;
6907 
6908 	if (obj->gen_loader)
6909 		return 0;
6910 
6911 	for (i = 0; i < prog->insns_cnt; i++, insn++) {
6912 		if (!insn_is_helper_call(insn, &func_id))
6913 			continue;
6914 
6915 		/* on kernels that don't yet support
6916 		 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
6917 		 * to bpf_probe_read() which works well for old kernels
6918 		 */
6919 		switch (func_id) {
6920 		case BPF_FUNC_probe_read_kernel:
6921 		case BPF_FUNC_probe_read_user:
6922 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6923 				insn->imm = BPF_FUNC_probe_read;
6924 			break;
6925 		case BPF_FUNC_probe_read_kernel_str:
6926 		case BPF_FUNC_probe_read_user_str:
6927 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6928 				insn->imm = BPF_FUNC_probe_read_str;
6929 			break;
6930 		default:
6931 			break;
6932 		}
6933 	}
6934 	return 0;
6935 }
6936 
6937 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
6938 				     int *btf_obj_fd, int *btf_type_id);
6939 
6940 /* this is called as prog->sec_def->prog_prepare_load_fn for libbpf-supported sec_defs */
6941 static int libbpf_prepare_prog_load(struct bpf_program *prog,
6942 				    struct bpf_prog_load_opts *opts, long cookie)
6943 {
6944 	enum sec_def_flags def = cookie;
6945 
6946 	/* old kernels might not support specifying expected_attach_type */
6947 	if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
6948 		opts->expected_attach_type = 0;
6949 
6950 	if (def & SEC_SLEEPABLE)
6951 		opts->prog_flags |= BPF_F_SLEEPABLE;
6952 
6953 	if (prog->type == BPF_PROG_TYPE_XDP && (def & SEC_XDP_FRAGS))
6954 		opts->prog_flags |= BPF_F_XDP_HAS_FRAGS;
6955 
6956 	/* special check for usdt to use uprobe_multi link */
6957 	if ((def & SEC_USDT) && kernel_supports(prog->obj, FEAT_UPROBE_MULTI_LINK))
6958 		prog->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
6959 
6960 	if ((def & SEC_ATTACH_BTF) && !prog->attach_btf_id) {
6961 		int btf_obj_fd = 0, btf_type_id = 0, err;
6962 		const char *attach_name;
6963 
6964 		attach_name = strchr(prog->sec_name, '/');
6965 		if (!attach_name) {
6966 			/* if BPF program is annotated with just SEC("fentry")
6967 			 * (or similar) without declaratively specifying
6968 			 * target, then it is expected that target will be
6969 			 * specified with bpf_program__set_attach_target() at
6970 			 * runtime before BPF object load step. If not, then
6971 			 * there is nothing to load into the kernel as BPF
6972 			 * verifier won't be able to validate BPF program
6973 			 * correctness anyways.
6974 			 */
6975 			pr_warn("prog '%s': no BTF-based attach target is specified, use bpf_program__set_attach_target()\n",
6976 				prog->name);
6977 			return -EINVAL;
6978 		}
6979 		attach_name++; /* skip over / */
6980 
6981 		err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
6982 		if (err)
6983 			return err;
6984 
6985 		/* cache resolved BTF FD and BTF type ID in the prog */
6986 		prog->attach_btf_obj_fd = btf_obj_fd;
6987 		prog->attach_btf_id = btf_type_id;
6988 
6989 		/* but by now libbpf common logic is not utilizing
6990 		 * prog->atach_btf_obj_fd/prog->attach_btf_id anymore because
6991 		 * this callback is called after opts were populated by
6992 		 * libbpf, so this callback has to update opts explicitly here
6993 		 */
6994 		opts->attach_btf_obj_fd = btf_obj_fd;
6995 		opts->attach_btf_id = btf_type_id;
6996 	}
6997 	return 0;
6998 }
6999 
7000 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz);
7001 
7002 static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
7003 				struct bpf_insn *insns, int insns_cnt,
7004 				const char *license, __u32 kern_version, int *prog_fd)
7005 {
7006 	LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
7007 	const char *prog_name = NULL;
7008 	char *cp, errmsg[STRERR_BUFSIZE];
7009 	size_t log_buf_size = 0;
7010 	char *log_buf = NULL, *tmp;
7011 	int btf_fd, ret, err;
7012 	bool own_log_buf = true;
7013 	__u32 log_level = prog->log_level;
7014 
7015 	if (prog->type == BPF_PROG_TYPE_UNSPEC) {
7016 		/*
7017 		 * The program type must be set.  Most likely we couldn't find a proper
7018 		 * section definition at load time, and thus we didn't infer the type.
7019 		 */
7020 		pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
7021 			prog->name, prog->sec_name);
7022 		return -EINVAL;
7023 	}
7024 
7025 	if (!insns || !insns_cnt)
7026 		return -EINVAL;
7027 
7028 	if (kernel_supports(obj, FEAT_PROG_NAME))
7029 		prog_name = prog->name;
7030 	load_attr.attach_prog_fd = prog->attach_prog_fd;
7031 	load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
7032 	load_attr.attach_btf_id = prog->attach_btf_id;
7033 	load_attr.kern_version = kern_version;
7034 	load_attr.prog_ifindex = prog->prog_ifindex;
7035 
7036 	/* specify func_info/line_info only if kernel supports them */
7037 	btf_fd = bpf_object__btf_fd(obj);
7038 	if (btf_fd >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
7039 		load_attr.prog_btf_fd = btf_fd;
7040 		load_attr.func_info = prog->func_info;
7041 		load_attr.func_info_rec_size = prog->func_info_rec_size;
7042 		load_attr.func_info_cnt = prog->func_info_cnt;
7043 		load_attr.line_info = prog->line_info;
7044 		load_attr.line_info_rec_size = prog->line_info_rec_size;
7045 		load_attr.line_info_cnt = prog->line_info_cnt;
7046 	}
7047 	load_attr.log_level = log_level;
7048 	load_attr.prog_flags = prog->prog_flags;
7049 	load_attr.fd_array = obj->fd_array;
7050 
7051 	/* adjust load_attr if sec_def provides custom preload callback */
7052 	if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
7053 		err = prog->sec_def->prog_prepare_load_fn(prog, &load_attr, prog->sec_def->cookie);
7054 		if (err < 0) {
7055 			pr_warn("prog '%s': failed to prepare load attributes: %d\n",
7056 				prog->name, err);
7057 			return err;
7058 		}
7059 		insns = prog->insns;
7060 		insns_cnt = prog->insns_cnt;
7061 	}
7062 
7063 	/* allow prog_prepare_load_fn to change expected_attach_type */
7064 	load_attr.expected_attach_type = prog->expected_attach_type;
7065 
7066 	if (obj->gen_loader) {
7067 		bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
7068 				   license, insns, insns_cnt, &load_attr,
7069 				   prog - obj->programs);
7070 		*prog_fd = -1;
7071 		return 0;
7072 	}
7073 
7074 retry_load:
7075 	/* if log_level is zero, we don't request logs initially even if
7076 	 * custom log_buf is specified; if the program load fails, then we'll
7077 	 * bump log_level to 1 and use either custom log_buf or we'll allocate
7078 	 * our own and retry the load to get details on what failed
7079 	 */
7080 	if (log_level) {
7081 		if (prog->log_buf) {
7082 			log_buf = prog->log_buf;
7083 			log_buf_size = prog->log_size;
7084 			own_log_buf = false;
7085 		} else if (obj->log_buf) {
7086 			log_buf = obj->log_buf;
7087 			log_buf_size = obj->log_size;
7088 			own_log_buf = false;
7089 		} else {
7090 			log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
7091 			tmp = realloc(log_buf, log_buf_size);
7092 			if (!tmp) {
7093 				ret = -ENOMEM;
7094 				goto out;
7095 			}
7096 			log_buf = tmp;
7097 			log_buf[0] = '\0';
7098 			own_log_buf = true;
7099 		}
7100 	}
7101 
7102 	load_attr.log_buf = log_buf;
7103 	load_attr.log_size = log_buf_size;
7104 	load_attr.log_level = log_level;
7105 
7106 	ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
7107 	if (ret >= 0) {
7108 		if (log_level && own_log_buf) {
7109 			pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
7110 				 prog->name, log_buf);
7111 		}
7112 
7113 		if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
7114 			struct bpf_map *map;
7115 			int i;
7116 
7117 			for (i = 0; i < obj->nr_maps; i++) {
7118 				map = &prog->obj->maps[i];
7119 				if (map->libbpf_type != LIBBPF_MAP_RODATA)
7120 					continue;
7121 
7122 				if (bpf_prog_bind_map(ret, bpf_map__fd(map), NULL)) {
7123 					cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
7124 					pr_warn("prog '%s': failed to bind map '%s': %s\n",
7125 						prog->name, map->real_name, cp);
7126 					/* Don't fail hard if can't bind rodata. */
7127 				}
7128 			}
7129 		}
7130 
7131 		*prog_fd = ret;
7132 		ret = 0;
7133 		goto out;
7134 	}
7135 
7136 	if (log_level == 0) {
7137 		log_level = 1;
7138 		goto retry_load;
7139 	}
7140 	/* On ENOSPC, increase log buffer size and retry, unless custom
7141 	 * log_buf is specified.
7142 	 * Be careful to not overflow u32, though. Kernel's log buf size limit
7143 	 * isn't part of UAPI so it can always be bumped to full 4GB. So don't
7144 	 * multiply by 2 unless we are sure we'll fit within 32 bits.
7145 	 * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
7146 	 */
7147 	if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
7148 		goto retry_load;
7149 
7150 	ret = -errno;
7151 
7152 	/* post-process verifier log to improve error descriptions */
7153 	fixup_verifier_log(prog, log_buf, log_buf_size);
7154 
7155 	cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
7156 	pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, cp);
7157 	pr_perm_msg(ret);
7158 
7159 	if (own_log_buf && log_buf && log_buf[0] != '\0') {
7160 		pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
7161 			prog->name, log_buf);
7162 	}
7163 
7164 out:
7165 	if (own_log_buf)
7166 		free(log_buf);
7167 	return ret;
7168 }
7169 
7170 static char *find_prev_line(char *buf, char *cur)
7171 {
7172 	char *p;
7173 
7174 	if (cur == buf) /* end of a log buf */
7175 		return NULL;
7176 
7177 	p = cur - 1;
7178 	while (p - 1 >= buf && *(p - 1) != '\n')
7179 		p--;
7180 
7181 	return p;
7182 }
7183 
7184 static void patch_log(char *buf, size_t buf_sz, size_t log_sz,
7185 		      char *orig, size_t orig_sz, const char *patch)
7186 {
7187 	/* size of the remaining log content to the right from the to-be-replaced part */
7188 	size_t rem_sz = (buf + log_sz) - (orig + orig_sz);
7189 	size_t patch_sz = strlen(patch);
7190 
7191 	if (patch_sz != orig_sz) {
7192 		/* If patch line(s) are longer than original piece of verifier log,
7193 		 * shift log contents by (patch_sz - orig_sz) bytes to the right
7194 		 * starting from after to-be-replaced part of the log.
7195 		 *
7196 		 * If patch line(s) are shorter than original piece of verifier log,
7197 		 * shift log contents by (orig_sz - patch_sz) bytes to the left
7198 		 * starting from after to-be-replaced part of the log
7199 		 *
7200 		 * We need to be careful about not overflowing available
7201 		 * buf_sz capacity. If that's the case, we'll truncate the end
7202 		 * of the original log, as necessary.
7203 		 */
7204 		if (patch_sz > orig_sz) {
7205 			if (orig + patch_sz >= buf + buf_sz) {
7206 				/* patch is big enough to cover remaining space completely */
7207 				patch_sz -= (orig + patch_sz) - (buf + buf_sz) + 1;
7208 				rem_sz = 0;
7209 			} else if (patch_sz - orig_sz > buf_sz - log_sz) {
7210 				/* patch causes part of remaining log to be truncated */
7211 				rem_sz -= (patch_sz - orig_sz) - (buf_sz - log_sz);
7212 			}
7213 		}
7214 		/* shift remaining log to the right by calculated amount */
7215 		memmove(orig + patch_sz, orig + orig_sz, rem_sz);
7216 	}
7217 
7218 	memcpy(orig, patch, patch_sz);
7219 }
7220 
7221 static void fixup_log_failed_core_relo(struct bpf_program *prog,
7222 				       char *buf, size_t buf_sz, size_t log_sz,
7223 				       char *line1, char *line2, char *line3)
7224 {
7225 	/* Expected log for failed and not properly guarded CO-RE relocation:
7226 	 * line1 -> 123: (85) call unknown#195896080
7227 	 * line2 -> invalid func unknown#195896080
7228 	 * line3 -> <anything else or end of buffer>
7229 	 *
7230 	 * "123" is the index of the instruction that was poisoned. We extract
7231 	 * instruction index to find corresponding CO-RE relocation and
7232 	 * replace this part of the log with more relevant information about
7233 	 * failed CO-RE relocation.
7234 	 */
7235 	const struct bpf_core_relo *relo;
7236 	struct bpf_core_spec spec;
7237 	char patch[512], spec_buf[256];
7238 	int insn_idx, err, spec_len;
7239 
7240 	if (sscanf(line1, "%d: (%*d) call unknown#195896080\n", &insn_idx) != 1)
7241 		return;
7242 
7243 	relo = find_relo_core(prog, insn_idx);
7244 	if (!relo)
7245 		return;
7246 
7247 	err = bpf_core_parse_spec(prog->name, prog->obj->btf, relo, &spec);
7248 	if (err)
7249 		return;
7250 
7251 	spec_len = bpf_core_format_spec(spec_buf, sizeof(spec_buf), &spec);
7252 	snprintf(patch, sizeof(patch),
7253 		 "%d: <invalid CO-RE relocation>\n"
7254 		 "failed to resolve CO-RE relocation %s%s\n",
7255 		 insn_idx, spec_buf, spec_len >= sizeof(spec_buf) ? "..." : "");
7256 
7257 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7258 }
7259 
7260 static void fixup_log_missing_map_load(struct bpf_program *prog,
7261 				       char *buf, size_t buf_sz, size_t log_sz,
7262 				       char *line1, char *line2, char *line3)
7263 {
7264 	/* Expected log for failed and not properly guarded map reference:
7265 	 * line1 -> 123: (85) call unknown#2001000345
7266 	 * line2 -> invalid func unknown#2001000345
7267 	 * line3 -> <anything else or end of buffer>
7268 	 *
7269 	 * "123" is the index of the instruction that was poisoned.
7270 	 * "345" in "2001000345" is a map index in obj->maps to fetch map name.
7271 	 */
7272 	struct bpf_object *obj = prog->obj;
7273 	const struct bpf_map *map;
7274 	int insn_idx, map_idx;
7275 	char patch[128];
7276 
7277 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &map_idx) != 2)
7278 		return;
7279 
7280 	map_idx -= POISON_LDIMM64_MAP_BASE;
7281 	if (map_idx < 0 || map_idx >= obj->nr_maps)
7282 		return;
7283 	map = &obj->maps[map_idx];
7284 
7285 	snprintf(patch, sizeof(patch),
7286 		 "%d: <invalid BPF map reference>\n"
7287 		 "BPF map '%s' is referenced but wasn't created\n",
7288 		 insn_idx, map->name);
7289 
7290 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7291 }
7292 
7293 static void fixup_log_missing_kfunc_call(struct bpf_program *prog,
7294 					 char *buf, size_t buf_sz, size_t log_sz,
7295 					 char *line1, char *line2, char *line3)
7296 {
7297 	/* Expected log for failed and not properly guarded kfunc call:
7298 	 * line1 -> 123: (85) call unknown#2002000345
7299 	 * line2 -> invalid func unknown#2002000345
7300 	 * line3 -> <anything else or end of buffer>
7301 	 *
7302 	 * "123" is the index of the instruction that was poisoned.
7303 	 * "345" in "2002000345" is an extern index in obj->externs to fetch kfunc name.
7304 	 */
7305 	struct bpf_object *obj = prog->obj;
7306 	const struct extern_desc *ext;
7307 	int insn_idx, ext_idx;
7308 	char patch[128];
7309 
7310 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &ext_idx) != 2)
7311 		return;
7312 
7313 	ext_idx -= POISON_CALL_KFUNC_BASE;
7314 	if (ext_idx < 0 || ext_idx >= obj->nr_extern)
7315 		return;
7316 	ext = &obj->externs[ext_idx];
7317 
7318 	snprintf(patch, sizeof(patch),
7319 		 "%d: <invalid kfunc call>\n"
7320 		 "kfunc '%s' is referenced but wasn't resolved\n",
7321 		 insn_idx, ext->name);
7322 
7323 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7324 }
7325 
7326 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz)
7327 {
7328 	/* look for familiar error patterns in last N lines of the log */
7329 	const size_t max_last_line_cnt = 10;
7330 	char *prev_line, *cur_line, *next_line;
7331 	size_t log_sz;
7332 	int i;
7333 
7334 	if (!buf)
7335 		return;
7336 
7337 	log_sz = strlen(buf) + 1;
7338 	next_line = buf + log_sz - 1;
7339 
7340 	for (i = 0; i < max_last_line_cnt; i++, next_line = cur_line) {
7341 		cur_line = find_prev_line(buf, next_line);
7342 		if (!cur_line)
7343 			return;
7344 
7345 		if (str_has_pfx(cur_line, "invalid func unknown#195896080\n")) {
7346 			prev_line = find_prev_line(buf, cur_line);
7347 			if (!prev_line)
7348 				continue;
7349 
7350 			/* failed CO-RE relocation case */
7351 			fixup_log_failed_core_relo(prog, buf, buf_sz, log_sz,
7352 						   prev_line, cur_line, next_line);
7353 			return;
7354 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_LDIMM64_MAP_PFX)) {
7355 			prev_line = find_prev_line(buf, cur_line);
7356 			if (!prev_line)
7357 				continue;
7358 
7359 			/* reference to uncreated BPF map */
7360 			fixup_log_missing_map_load(prog, buf, buf_sz, log_sz,
7361 						   prev_line, cur_line, next_line);
7362 			return;
7363 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_CALL_KFUNC_PFX)) {
7364 			prev_line = find_prev_line(buf, cur_line);
7365 			if (!prev_line)
7366 				continue;
7367 
7368 			/* reference to unresolved kfunc */
7369 			fixup_log_missing_kfunc_call(prog, buf, buf_sz, log_sz,
7370 						     prev_line, cur_line, next_line);
7371 			return;
7372 		}
7373 	}
7374 }
7375 
7376 static int bpf_program_record_relos(struct bpf_program *prog)
7377 {
7378 	struct bpf_object *obj = prog->obj;
7379 	int i;
7380 
7381 	for (i = 0; i < prog->nr_reloc; i++) {
7382 		struct reloc_desc *relo = &prog->reloc_desc[i];
7383 		struct extern_desc *ext = &obj->externs[relo->ext_idx];
7384 		int kind;
7385 
7386 		switch (relo->type) {
7387 		case RELO_EXTERN_LD64:
7388 			if (ext->type != EXT_KSYM)
7389 				continue;
7390 			kind = btf_is_var(btf__type_by_id(obj->btf, ext->btf_id)) ?
7391 				BTF_KIND_VAR : BTF_KIND_FUNC;
7392 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7393 					       ext->is_weak, !ext->ksym.type_id,
7394 					       true, kind, relo->insn_idx);
7395 			break;
7396 		case RELO_EXTERN_CALL:
7397 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7398 					       ext->is_weak, false, false, BTF_KIND_FUNC,
7399 					       relo->insn_idx);
7400 			break;
7401 		case RELO_CORE: {
7402 			struct bpf_core_relo cr = {
7403 				.insn_off = relo->insn_idx * 8,
7404 				.type_id = relo->core_relo->type_id,
7405 				.access_str_off = relo->core_relo->access_str_off,
7406 				.kind = relo->core_relo->kind,
7407 			};
7408 
7409 			bpf_gen__record_relo_core(obj->gen_loader, &cr);
7410 			break;
7411 		}
7412 		default:
7413 			continue;
7414 		}
7415 	}
7416 	return 0;
7417 }
7418 
7419 static int
7420 bpf_object__load_progs(struct bpf_object *obj, int log_level)
7421 {
7422 	struct bpf_program *prog;
7423 	size_t i;
7424 	int err;
7425 
7426 	for (i = 0; i < obj->nr_programs; i++) {
7427 		prog = &obj->programs[i];
7428 		err = bpf_object__sanitize_prog(obj, prog);
7429 		if (err)
7430 			return err;
7431 	}
7432 
7433 	for (i = 0; i < obj->nr_programs; i++) {
7434 		prog = &obj->programs[i];
7435 		if (prog_is_subprog(obj, prog))
7436 			continue;
7437 		if (!prog->autoload) {
7438 			pr_debug("prog '%s': skipped loading\n", prog->name);
7439 			continue;
7440 		}
7441 		prog->log_level |= log_level;
7442 
7443 		if (obj->gen_loader)
7444 			bpf_program_record_relos(prog);
7445 
7446 		err = bpf_object_load_prog(obj, prog, prog->insns, prog->insns_cnt,
7447 					   obj->license, obj->kern_version, &prog->fd);
7448 		if (err) {
7449 			pr_warn("prog '%s': failed to load: %d\n", prog->name, err);
7450 			return err;
7451 		}
7452 	}
7453 
7454 	bpf_object__free_relocs(obj);
7455 	return 0;
7456 }
7457 
7458 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
7459 
7460 static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
7461 {
7462 	struct bpf_program *prog;
7463 	int err;
7464 
7465 	bpf_object__for_each_program(prog, obj) {
7466 		prog->sec_def = find_sec_def(prog->sec_name);
7467 		if (!prog->sec_def) {
7468 			/* couldn't guess, but user might manually specify */
7469 			pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
7470 				prog->name, prog->sec_name);
7471 			continue;
7472 		}
7473 
7474 		prog->type = prog->sec_def->prog_type;
7475 		prog->expected_attach_type = prog->sec_def->expected_attach_type;
7476 
7477 		/* sec_def can have custom callback which should be called
7478 		 * after bpf_program is initialized to adjust its properties
7479 		 */
7480 		if (prog->sec_def->prog_setup_fn) {
7481 			err = prog->sec_def->prog_setup_fn(prog, prog->sec_def->cookie);
7482 			if (err < 0) {
7483 				pr_warn("prog '%s': failed to initialize: %d\n",
7484 					prog->name, err);
7485 				return err;
7486 			}
7487 		}
7488 	}
7489 
7490 	return 0;
7491 }
7492 
7493 static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
7494 					  const struct bpf_object_open_opts *opts)
7495 {
7496 	const char *obj_name, *kconfig, *btf_tmp_path;
7497 	struct bpf_object *obj;
7498 	char tmp_name[64];
7499 	int err;
7500 	char *log_buf;
7501 	size_t log_size;
7502 	__u32 log_level;
7503 
7504 	if (elf_version(EV_CURRENT) == EV_NONE) {
7505 		pr_warn("failed to init libelf for %s\n",
7506 			path ? : "(mem buf)");
7507 		return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
7508 	}
7509 
7510 	if (!OPTS_VALID(opts, bpf_object_open_opts))
7511 		return ERR_PTR(-EINVAL);
7512 
7513 	obj_name = OPTS_GET(opts, object_name, NULL);
7514 	if (obj_buf) {
7515 		if (!obj_name) {
7516 			snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
7517 				 (unsigned long)obj_buf,
7518 				 (unsigned long)obj_buf_sz);
7519 			obj_name = tmp_name;
7520 		}
7521 		path = obj_name;
7522 		pr_debug("loading object '%s' from buffer\n", obj_name);
7523 	}
7524 
7525 	log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
7526 	log_size = OPTS_GET(opts, kernel_log_size, 0);
7527 	log_level = OPTS_GET(opts, kernel_log_level, 0);
7528 	if (log_size > UINT_MAX)
7529 		return ERR_PTR(-EINVAL);
7530 	if (log_size && !log_buf)
7531 		return ERR_PTR(-EINVAL);
7532 
7533 	obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
7534 	if (IS_ERR(obj))
7535 		return obj;
7536 
7537 	obj->log_buf = log_buf;
7538 	obj->log_size = log_size;
7539 	obj->log_level = log_level;
7540 
7541 	btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
7542 	if (btf_tmp_path) {
7543 		if (strlen(btf_tmp_path) >= PATH_MAX) {
7544 			err = -ENAMETOOLONG;
7545 			goto out;
7546 		}
7547 		obj->btf_custom_path = strdup(btf_tmp_path);
7548 		if (!obj->btf_custom_path) {
7549 			err = -ENOMEM;
7550 			goto out;
7551 		}
7552 	}
7553 
7554 	kconfig = OPTS_GET(opts, kconfig, NULL);
7555 	if (kconfig) {
7556 		obj->kconfig = strdup(kconfig);
7557 		if (!obj->kconfig) {
7558 			err = -ENOMEM;
7559 			goto out;
7560 		}
7561 	}
7562 
7563 	err = bpf_object__elf_init(obj);
7564 	err = err ? : bpf_object__check_endianness(obj);
7565 	err = err ? : bpf_object__elf_collect(obj);
7566 	err = err ? : bpf_object__collect_externs(obj);
7567 	err = err ? : bpf_object_fixup_btf(obj);
7568 	err = err ? : bpf_object__init_maps(obj, opts);
7569 	err = err ? : bpf_object_init_progs(obj, opts);
7570 	err = err ? : bpf_object__collect_relos(obj);
7571 	if (err)
7572 		goto out;
7573 
7574 	bpf_object__elf_finish(obj);
7575 
7576 	return obj;
7577 out:
7578 	bpf_object__close(obj);
7579 	return ERR_PTR(err);
7580 }
7581 
7582 struct bpf_object *
7583 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
7584 {
7585 	if (!path)
7586 		return libbpf_err_ptr(-EINVAL);
7587 
7588 	pr_debug("loading %s\n", path);
7589 
7590 	return libbpf_ptr(bpf_object_open(path, NULL, 0, opts));
7591 }
7592 
7593 struct bpf_object *bpf_object__open(const char *path)
7594 {
7595 	return bpf_object__open_file(path, NULL);
7596 }
7597 
7598 struct bpf_object *
7599 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
7600 		     const struct bpf_object_open_opts *opts)
7601 {
7602 	if (!obj_buf || obj_buf_sz == 0)
7603 		return libbpf_err_ptr(-EINVAL);
7604 
7605 	return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, opts));
7606 }
7607 
7608 static int bpf_object_unload(struct bpf_object *obj)
7609 {
7610 	size_t i;
7611 
7612 	if (!obj)
7613 		return libbpf_err(-EINVAL);
7614 
7615 	for (i = 0; i < obj->nr_maps; i++) {
7616 		zclose(obj->maps[i].fd);
7617 		if (obj->maps[i].st_ops)
7618 			zfree(&obj->maps[i].st_ops->kern_vdata);
7619 	}
7620 
7621 	for (i = 0; i < obj->nr_programs; i++)
7622 		bpf_program__unload(&obj->programs[i]);
7623 
7624 	return 0;
7625 }
7626 
7627 static int bpf_object__sanitize_maps(struct bpf_object *obj)
7628 {
7629 	struct bpf_map *m;
7630 
7631 	bpf_object__for_each_map(m, obj) {
7632 		if (!bpf_map__is_internal(m))
7633 			continue;
7634 		if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
7635 			m->def.map_flags &= ~BPF_F_MMAPABLE;
7636 	}
7637 
7638 	return 0;
7639 }
7640 
7641 int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
7642 {
7643 	char sym_type, sym_name[500];
7644 	unsigned long long sym_addr;
7645 	int ret, err = 0;
7646 	FILE *f;
7647 
7648 	f = fopen("/proc/kallsyms", "re");
7649 	if (!f) {
7650 		err = -errno;
7651 		pr_warn("failed to open /proc/kallsyms: %d\n", err);
7652 		return err;
7653 	}
7654 
7655 	while (true) {
7656 		ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
7657 			     &sym_addr, &sym_type, sym_name);
7658 		if (ret == EOF && feof(f))
7659 			break;
7660 		if (ret != 3) {
7661 			pr_warn("failed to read kallsyms entry: %d\n", ret);
7662 			err = -EINVAL;
7663 			break;
7664 		}
7665 
7666 		err = cb(sym_addr, sym_type, sym_name, ctx);
7667 		if (err)
7668 			break;
7669 	}
7670 
7671 	fclose(f);
7672 	return err;
7673 }
7674 
7675 static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
7676 		       const char *sym_name, void *ctx)
7677 {
7678 	struct bpf_object *obj = ctx;
7679 	const struct btf_type *t;
7680 	struct extern_desc *ext;
7681 
7682 	ext = find_extern_by_name(obj, sym_name);
7683 	if (!ext || ext->type != EXT_KSYM)
7684 		return 0;
7685 
7686 	t = btf__type_by_id(obj->btf, ext->btf_id);
7687 	if (!btf_is_var(t))
7688 		return 0;
7689 
7690 	if (ext->is_set && ext->ksym.addr != sym_addr) {
7691 		pr_warn("extern (ksym) '%s': resolution is ambiguous: 0x%llx or 0x%llx\n",
7692 			sym_name, ext->ksym.addr, sym_addr);
7693 		return -EINVAL;
7694 	}
7695 	if (!ext->is_set) {
7696 		ext->is_set = true;
7697 		ext->ksym.addr = sym_addr;
7698 		pr_debug("extern (ksym) '%s': set to 0x%llx\n", sym_name, sym_addr);
7699 	}
7700 	return 0;
7701 }
7702 
7703 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
7704 {
7705 	return libbpf_kallsyms_parse(kallsyms_cb, obj);
7706 }
7707 
7708 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
7709 			    __u16 kind, struct btf **res_btf,
7710 			    struct module_btf **res_mod_btf)
7711 {
7712 	struct module_btf *mod_btf;
7713 	struct btf *btf;
7714 	int i, id, err;
7715 
7716 	btf = obj->btf_vmlinux;
7717 	mod_btf = NULL;
7718 	id = btf__find_by_name_kind(btf, ksym_name, kind);
7719 
7720 	if (id == -ENOENT) {
7721 		err = load_module_btfs(obj);
7722 		if (err)
7723 			return err;
7724 
7725 		for (i = 0; i < obj->btf_module_cnt; i++) {
7726 			/* we assume module_btf's BTF FD is always >0 */
7727 			mod_btf = &obj->btf_modules[i];
7728 			btf = mod_btf->btf;
7729 			id = btf__find_by_name_kind_own(btf, ksym_name, kind);
7730 			if (id != -ENOENT)
7731 				break;
7732 		}
7733 	}
7734 	if (id <= 0)
7735 		return -ESRCH;
7736 
7737 	*res_btf = btf;
7738 	*res_mod_btf = mod_btf;
7739 	return id;
7740 }
7741 
7742 static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
7743 					       struct extern_desc *ext)
7744 {
7745 	const struct btf_type *targ_var, *targ_type;
7746 	__u32 targ_type_id, local_type_id;
7747 	struct module_btf *mod_btf = NULL;
7748 	const char *targ_var_name;
7749 	struct btf *btf = NULL;
7750 	int id, err;
7751 
7752 	id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
7753 	if (id < 0) {
7754 		if (id == -ESRCH && ext->is_weak)
7755 			return 0;
7756 		pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
7757 			ext->name);
7758 		return id;
7759 	}
7760 
7761 	/* find local type_id */
7762 	local_type_id = ext->ksym.type_id;
7763 
7764 	/* find target type_id */
7765 	targ_var = btf__type_by_id(btf, id);
7766 	targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
7767 	targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
7768 
7769 	err = bpf_core_types_are_compat(obj->btf, local_type_id,
7770 					btf, targ_type_id);
7771 	if (err <= 0) {
7772 		const struct btf_type *local_type;
7773 		const char *targ_name, *local_name;
7774 
7775 		local_type = btf__type_by_id(obj->btf, local_type_id);
7776 		local_name = btf__name_by_offset(obj->btf, local_type->name_off);
7777 		targ_name = btf__name_by_offset(btf, targ_type->name_off);
7778 
7779 		pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
7780 			ext->name, local_type_id,
7781 			btf_kind_str(local_type), local_name, targ_type_id,
7782 			btf_kind_str(targ_type), targ_name);
7783 		return -EINVAL;
7784 	}
7785 
7786 	ext->is_set = true;
7787 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
7788 	ext->ksym.kernel_btf_id = id;
7789 	pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
7790 		 ext->name, id, btf_kind_str(targ_var), targ_var_name);
7791 
7792 	return 0;
7793 }
7794 
7795 static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
7796 						struct extern_desc *ext)
7797 {
7798 	int local_func_proto_id, kfunc_proto_id, kfunc_id;
7799 	struct module_btf *mod_btf = NULL;
7800 	const struct btf_type *kern_func;
7801 	struct btf *kern_btf = NULL;
7802 	int ret;
7803 
7804 	local_func_proto_id = ext->ksym.type_id;
7805 
7806 	kfunc_id = find_ksym_btf_id(obj, ext->essent_name ?: ext->name, BTF_KIND_FUNC, &kern_btf,
7807 				    &mod_btf);
7808 	if (kfunc_id < 0) {
7809 		if (kfunc_id == -ESRCH && ext->is_weak)
7810 			return 0;
7811 		pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
7812 			ext->name);
7813 		return kfunc_id;
7814 	}
7815 
7816 	kern_func = btf__type_by_id(kern_btf, kfunc_id);
7817 	kfunc_proto_id = kern_func->type;
7818 
7819 	ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
7820 					kern_btf, kfunc_proto_id);
7821 	if (ret <= 0) {
7822 		if (ext->is_weak)
7823 			return 0;
7824 
7825 		pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with %s [%d]\n",
7826 			ext->name, local_func_proto_id,
7827 			mod_btf ? mod_btf->name : "vmlinux", kfunc_proto_id);
7828 		return -EINVAL;
7829 	}
7830 
7831 	/* set index for module BTF fd in fd_array, if unset */
7832 	if (mod_btf && !mod_btf->fd_array_idx) {
7833 		/* insn->off is s16 */
7834 		if (obj->fd_array_cnt == INT16_MAX) {
7835 			pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
7836 				ext->name, mod_btf->fd_array_idx);
7837 			return -E2BIG;
7838 		}
7839 		/* Cannot use index 0 for module BTF fd */
7840 		if (!obj->fd_array_cnt)
7841 			obj->fd_array_cnt = 1;
7842 
7843 		ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
7844 					obj->fd_array_cnt + 1);
7845 		if (ret)
7846 			return ret;
7847 		mod_btf->fd_array_idx = obj->fd_array_cnt;
7848 		/* we assume module BTF FD is always >0 */
7849 		obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
7850 	}
7851 
7852 	ext->is_set = true;
7853 	ext->ksym.kernel_btf_id = kfunc_id;
7854 	ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
7855 	/* Also set kernel_btf_obj_fd to make sure that bpf_object__relocate_data()
7856 	 * populates FD into ld_imm64 insn when it's used to point to kfunc.
7857 	 * {kernel_btf_id, btf_fd_idx} -> fixup bpf_call.
7858 	 * {kernel_btf_id, kernel_btf_obj_fd} -> fixup ld_imm64.
7859 	 */
7860 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
7861 	pr_debug("extern (func ksym) '%s': resolved to %s [%d]\n",
7862 		 ext->name, mod_btf ? mod_btf->name : "vmlinux", kfunc_id);
7863 
7864 	return 0;
7865 }
7866 
7867 static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
7868 {
7869 	const struct btf_type *t;
7870 	struct extern_desc *ext;
7871 	int i, err;
7872 
7873 	for (i = 0; i < obj->nr_extern; i++) {
7874 		ext = &obj->externs[i];
7875 		if (ext->type != EXT_KSYM || !ext->ksym.type_id)
7876 			continue;
7877 
7878 		if (obj->gen_loader) {
7879 			ext->is_set = true;
7880 			ext->ksym.kernel_btf_obj_fd = 0;
7881 			ext->ksym.kernel_btf_id = 0;
7882 			continue;
7883 		}
7884 		t = btf__type_by_id(obj->btf, ext->btf_id);
7885 		if (btf_is_var(t))
7886 			err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
7887 		else
7888 			err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
7889 		if (err)
7890 			return err;
7891 	}
7892 	return 0;
7893 }
7894 
7895 static int bpf_object__resolve_externs(struct bpf_object *obj,
7896 				       const char *extra_kconfig)
7897 {
7898 	bool need_config = false, need_kallsyms = false;
7899 	bool need_vmlinux_btf = false;
7900 	struct extern_desc *ext;
7901 	void *kcfg_data = NULL;
7902 	int err, i;
7903 
7904 	if (obj->nr_extern == 0)
7905 		return 0;
7906 
7907 	if (obj->kconfig_map_idx >= 0)
7908 		kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
7909 
7910 	for (i = 0; i < obj->nr_extern; i++) {
7911 		ext = &obj->externs[i];
7912 
7913 		if (ext->type == EXT_KSYM) {
7914 			if (ext->ksym.type_id)
7915 				need_vmlinux_btf = true;
7916 			else
7917 				need_kallsyms = true;
7918 			continue;
7919 		} else if (ext->type == EXT_KCFG) {
7920 			void *ext_ptr = kcfg_data + ext->kcfg.data_off;
7921 			__u64 value = 0;
7922 
7923 			/* Kconfig externs need actual /proc/config.gz */
7924 			if (str_has_pfx(ext->name, "CONFIG_")) {
7925 				need_config = true;
7926 				continue;
7927 			}
7928 
7929 			/* Virtual kcfg externs are customly handled by libbpf */
7930 			if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
7931 				value = get_kernel_version();
7932 				if (!value) {
7933 					pr_warn("extern (kcfg) '%s': failed to get kernel version\n", ext->name);
7934 					return -EINVAL;
7935 				}
7936 			} else if (strcmp(ext->name, "LINUX_HAS_BPF_COOKIE") == 0) {
7937 				value = kernel_supports(obj, FEAT_BPF_COOKIE);
7938 			} else if (strcmp(ext->name, "LINUX_HAS_SYSCALL_WRAPPER") == 0) {
7939 				value = kernel_supports(obj, FEAT_SYSCALL_WRAPPER);
7940 			} else if (!str_has_pfx(ext->name, "LINUX_") || !ext->is_weak) {
7941 				/* Currently libbpf supports only CONFIG_ and LINUX_ prefixed
7942 				 * __kconfig externs, where LINUX_ ones are virtual and filled out
7943 				 * customly by libbpf (their values don't come from Kconfig).
7944 				 * If LINUX_xxx variable is not recognized by libbpf, but is marked
7945 				 * __weak, it defaults to zero value, just like for CONFIG_xxx
7946 				 * externs.
7947 				 */
7948 				pr_warn("extern (kcfg) '%s': unrecognized virtual extern\n", ext->name);
7949 				return -EINVAL;
7950 			}
7951 
7952 			err = set_kcfg_value_num(ext, ext_ptr, value);
7953 			if (err)
7954 				return err;
7955 			pr_debug("extern (kcfg) '%s': set to 0x%llx\n",
7956 				 ext->name, (long long)value);
7957 		} else {
7958 			pr_warn("extern '%s': unrecognized extern kind\n", ext->name);
7959 			return -EINVAL;
7960 		}
7961 	}
7962 	if (need_config && extra_kconfig) {
7963 		err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
7964 		if (err)
7965 			return -EINVAL;
7966 		need_config = false;
7967 		for (i = 0; i < obj->nr_extern; i++) {
7968 			ext = &obj->externs[i];
7969 			if (ext->type == EXT_KCFG && !ext->is_set) {
7970 				need_config = true;
7971 				break;
7972 			}
7973 		}
7974 	}
7975 	if (need_config) {
7976 		err = bpf_object__read_kconfig_file(obj, kcfg_data);
7977 		if (err)
7978 			return -EINVAL;
7979 	}
7980 	if (need_kallsyms) {
7981 		err = bpf_object__read_kallsyms_file(obj);
7982 		if (err)
7983 			return -EINVAL;
7984 	}
7985 	if (need_vmlinux_btf) {
7986 		err = bpf_object__resolve_ksyms_btf_id(obj);
7987 		if (err)
7988 			return -EINVAL;
7989 	}
7990 	for (i = 0; i < obj->nr_extern; i++) {
7991 		ext = &obj->externs[i];
7992 
7993 		if (!ext->is_set && !ext->is_weak) {
7994 			pr_warn("extern '%s' (strong): not resolved\n", ext->name);
7995 			return -ESRCH;
7996 		} else if (!ext->is_set) {
7997 			pr_debug("extern '%s' (weak): not resolved, defaulting to zero\n",
7998 				 ext->name);
7999 		}
8000 	}
8001 
8002 	return 0;
8003 }
8004 
8005 static void bpf_map_prepare_vdata(const struct bpf_map *map)
8006 {
8007 	struct bpf_struct_ops *st_ops;
8008 	__u32 i;
8009 
8010 	st_ops = map->st_ops;
8011 	for (i = 0; i < btf_vlen(st_ops->type); i++) {
8012 		struct bpf_program *prog = st_ops->progs[i];
8013 		void *kern_data;
8014 		int prog_fd;
8015 
8016 		if (!prog)
8017 			continue;
8018 
8019 		prog_fd = bpf_program__fd(prog);
8020 		kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
8021 		*(unsigned long *)kern_data = prog_fd;
8022 	}
8023 }
8024 
8025 static int bpf_object_prepare_struct_ops(struct bpf_object *obj)
8026 {
8027 	int i;
8028 
8029 	for (i = 0; i < obj->nr_maps; i++)
8030 		if (bpf_map__is_struct_ops(&obj->maps[i]))
8031 			bpf_map_prepare_vdata(&obj->maps[i]);
8032 
8033 	return 0;
8034 }
8035 
8036 static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
8037 {
8038 	int err, i;
8039 
8040 	if (!obj)
8041 		return libbpf_err(-EINVAL);
8042 
8043 	if (obj->loaded) {
8044 		pr_warn("object '%s': load can't be attempted twice\n", obj->name);
8045 		return libbpf_err(-EINVAL);
8046 	}
8047 
8048 	if (obj->gen_loader)
8049 		bpf_gen__init(obj->gen_loader, extra_log_level, obj->nr_programs, obj->nr_maps);
8050 
8051 	err = bpf_object__probe_loading(obj);
8052 	err = err ? : bpf_object__load_vmlinux_btf(obj, false);
8053 	err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
8054 	err = err ? : bpf_object__sanitize_and_load_btf(obj);
8055 	err = err ? : bpf_object__sanitize_maps(obj);
8056 	err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
8057 	err = err ? : bpf_object__create_maps(obj);
8058 	err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
8059 	err = err ? : bpf_object__load_progs(obj, extra_log_level);
8060 	err = err ? : bpf_object_init_prog_arrays(obj);
8061 	err = err ? : bpf_object_prepare_struct_ops(obj);
8062 
8063 	if (obj->gen_loader) {
8064 		/* reset FDs */
8065 		if (obj->btf)
8066 			btf__set_fd(obj->btf, -1);
8067 		for (i = 0; i < obj->nr_maps; i++)
8068 			obj->maps[i].fd = -1;
8069 		if (!err)
8070 			err = bpf_gen__finish(obj->gen_loader, obj->nr_programs, obj->nr_maps);
8071 	}
8072 
8073 	/* clean up fd_array */
8074 	zfree(&obj->fd_array);
8075 
8076 	/* clean up module BTFs */
8077 	for (i = 0; i < obj->btf_module_cnt; i++) {
8078 		close(obj->btf_modules[i].fd);
8079 		btf__free(obj->btf_modules[i].btf);
8080 		free(obj->btf_modules[i].name);
8081 	}
8082 	free(obj->btf_modules);
8083 
8084 	/* clean up vmlinux BTF */
8085 	btf__free(obj->btf_vmlinux);
8086 	obj->btf_vmlinux = NULL;
8087 
8088 	obj->loaded = true; /* doesn't matter if successfully or not */
8089 
8090 	if (err)
8091 		goto out;
8092 
8093 	return 0;
8094 out:
8095 	/* unpin any maps that were auto-pinned during load */
8096 	for (i = 0; i < obj->nr_maps; i++)
8097 		if (obj->maps[i].pinned && !obj->maps[i].reused)
8098 			bpf_map__unpin(&obj->maps[i], NULL);
8099 
8100 	bpf_object_unload(obj);
8101 	pr_warn("failed to load object '%s'\n", obj->path);
8102 	return libbpf_err(err);
8103 }
8104 
8105 int bpf_object__load(struct bpf_object *obj)
8106 {
8107 	return bpf_object_load(obj, 0, NULL);
8108 }
8109 
8110 static int make_parent_dir(const char *path)
8111 {
8112 	char *cp, errmsg[STRERR_BUFSIZE];
8113 	char *dname, *dir;
8114 	int err = 0;
8115 
8116 	dname = strdup(path);
8117 	if (dname == NULL)
8118 		return -ENOMEM;
8119 
8120 	dir = dirname(dname);
8121 	if (mkdir(dir, 0700) && errno != EEXIST)
8122 		err = -errno;
8123 
8124 	free(dname);
8125 	if (err) {
8126 		cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
8127 		pr_warn("failed to mkdir %s: %s\n", path, cp);
8128 	}
8129 	return err;
8130 }
8131 
8132 static int check_path(const char *path)
8133 {
8134 	char *cp, errmsg[STRERR_BUFSIZE];
8135 	struct statfs st_fs;
8136 	char *dname, *dir;
8137 	int err = 0;
8138 
8139 	if (path == NULL)
8140 		return -EINVAL;
8141 
8142 	dname = strdup(path);
8143 	if (dname == NULL)
8144 		return -ENOMEM;
8145 
8146 	dir = dirname(dname);
8147 	if (statfs(dir, &st_fs)) {
8148 		cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
8149 		pr_warn("failed to statfs %s: %s\n", dir, cp);
8150 		err = -errno;
8151 	}
8152 	free(dname);
8153 
8154 	if (!err && st_fs.f_type != BPF_FS_MAGIC) {
8155 		pr_warn("specified path %s is not on BPF FS\n", path);
8156 		err = -EINVAL;
8157 	}
8158 
8159 	return err;
8160 }
8161 
8162 int bpf_program__pin(struct bpf_program *prog, const char *path)
8163 {
8164 	char *cp, errmsg[STRERR_BUFSIZE];
8165 	int err;
8166 
8167 	if (prog->fd < 0) {
8168 		pr_warn("prog '%s': can't pin program that wasn't loaded\n", prog->name);
8169 		return libbpf_err(-EINVAL);
8170 	}
8171 
8172 	err = make_parent_dir(path);
8173 	if (err)
8174 		return libbpf_err(err);
8175 
8176 	err = check_path(path);
8177 	if (err)
8178 		return libbpf_err(err);
8179 
8180 	if (bpf_obj_pin(prog->fd, path)) {
8181 		err = -errno;
8182 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
8183 		pr_warn("prog '%s': failed to pin at '%s': %s\n", prog->name, path, cp);
8184 		return libbpf_err(err);
8185 	}
8186 
8187 	pr_debug("prog '%s': pinned at '%s'\n", prog->name, path);
8188 	return 0;
8189 }
8190 
8191 int bpf_program__unpin(struct bpf_program *prog, const char *path)
8192 {
8193 	int err;
8194 
8195 	if (prog->fd < 0) {
8196 		pr_warn("prog '%s': can't unpin program that wasn't loaded\n", prog->name);
8197 		return libbpf_err(-EINVAL);
8198 	}
8199 
8200 	err = check_path(path);
8201 	if (err)
8202 		return libbpf_err(err);
8203 
8204 	err = unlink(path);
8205 	if (err)
8206 		return libbpf_err(-errno);
8207 
8208 	pr_debug("prog '%s': unpinned from '%s'\n", prog->name, path);
8209 	return 0;
8210 }
8211 
8212 int bpf_map__pin(struct bpf_map *map, const char *path)
8213 {
8214 	char *cp, errmsg[STRERR_BUFSIZE];
8215 	int err;
8216 
8217 	if (map == NULL) {
8218 		pr_warn("invalid map pointer\n");
8219 		return libbpf_err(-EINVAL);
8220 	}
8221 
8222 	if (map->pin_path) {
8223 		if (path && strcmp(path, map->pin_path)) {
8224 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8225 				bpf_map__name(map), map->pin_path, path);
8226 			return libbpf_err(-EINVAL);
8227 		} else if (map->pinned) {
8228 			pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
8229 				 bpf_map__name(map), map->pin_path);
8230 			return 0;
8231 		}
8232 	} else {
8233 		if (!path) {
8234 			pr_warn("missing a path to pin map '%s' at\n",
8235 				bpf_map__name(map));
8236 			return libbpf_err(-EINVAL);
8237 		} else if (map->pinned) {
8238 			pr_warn("map '%s' already pinned\n", bpf_map__name(map));
8239 			return libbpf_err(-EEXIST);
8240 		}
8241 
8242 		map->pin_path = strdup(path);
8243 		if (!map->pin_path) {
8244 			err = -errno;
8245 			goto out_err;
8246 		}
8247 	}
8248 
8249 	err = make_parent_dir(map->pin_path);
8250 	if (err)
8251 		return libbpf_err(err);
8252 
8253 	err = check_path(map->pin_path);
8254 	if (err)
8255 		return libbpf_err(err);
8256 
8257 	if (bpf_obj_pin(map->fd, map->pin_path)) {
8258 		err = -errno;
8259 		goto out_err;
8260 	}
8261 
8262 	map->pinned = true;
8263 	pr_debug("pinned map '%s'\n", map->pin_path);
8264 
8265 	return 0;
8266 
8267 out_err:
8268 	cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
8269 	pr_warn("failed to pin map: %s\n", cp);
8270 	return libbpf_err(err);
8271 }
8272 
8273 int bpf_map__unpin(struct bpf_map *map, const char *path)
8274 {
8275 	int err;
8276 
8277 	if (map == NULL) {
8278 		pr_warn("invalid map pointer\n");
8279 		return libbpf_err(-EINVAL);
8280 	}
8281 
8282 	if (map->pin_path) {
8283 		if (path && strcmp(path, map->pin_path)) {
8284 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8285 				bpf_map__name(map), map->pin_path, path);
8286 			return libbpf_err(-EINVAL);
8287 		}
8288 		path = map->pin_path;
8289 	} else if (!path) {
8290 		pr_warn("no path to unpin map '%s' from\n",
8291 			bpf_map__name(map));
8292 		return libbpf_err(-EINVAL);
8293 	}
8294 
8295 	err = check_path(path);
8296 	if (err)
8297 		return libbpf_err(err);
8298 
8299 	err = unlink(path);
8300 	if (err != 0)
8301 		return libbpf_err(-errno);
8302 
8303 	map->pinned = false;
8304 	pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
8305 
8306 	return 0;
8307 }
8308 
8309 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
8310 {
8311 	char *new = NULL;
8312 
8313 	if (path) {
8314 		new = strdup(path);
8315 		if (!new)
8316 			return libbpf_err(-errno);
8317 	}
8318 
8319 	free(map->pin_path);
8320 	map->pin_path = new;
8321 	return 0;
8322 }
8323 
8324 __alias(bpf_map__pin_path)
8325 const char *bpf_map__get_pin_path(const struct bpf_map *map);
8326 
8327 const char *bpf_map__pin_path(const struct bpf_map *map)
8328 {
8329 	return map->pin_path;
8330 }
8331 
8332 bool bpf_map__is_pinned(const struct bpf_map *map)
8333 {
8334 	return map->pinned;
8335 }
8336 
8337 static void sanitize_pin_path(char *s)
8338 {
8339 	/* bpffs disallows periods in path names */
8340 	while (*s) {
8341 		if (*s == '.')
8342 			*s = '_';
8343 		s++;
8344 	}
8345 }
8346 
8347 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
8348 {
8349 	struct bpf_map *map;
8350 	int err;
8351 
8352 	if (!obj)
8353 		return libbpf_err(-ENOENT);
8354 
8355 	if (!obj->loaded) {
8356 		pr_warn("object not yet loaded; load it first\n");
8357 		return libbpf_err(-ENOENT);
8358 	}
8359 
8360 	bpf_object__for_each_map(map, obj) {
8361 		char *pin_path = NULL;
8362 		char buf[PATH_MAX];
8363 
8364 		if (!map->autocreate)
8365 			continue;
8366 
8367 		if (path) {
8368 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8369 			if (err)
8370 				goto err_unpin_maps;
8371 			sanitize_pin_path(buf);
8372 			pin_path = buf;
8373 		} else if (!map->pin_path) {
8374 			continue;
8375 		}
8376 
8377 		err = bpf_map__pin(map, pin_path);
8378 		if (err)
8379 			goto err_unpin_maps;
8380 	}
8381 
8382 	return 0;
8383 
8384 err_unpin_maps:
8385 	while ((map = bpf_object__prev_map(obj, map))) {
8386 		if (!map->pin_path)
8387 			continue;
8388 
8389 		bpf_map__unpin(map, NULL);
8390 	}
8391 
8392 	return libbpf_err(err);
8393 }
8394 
8395 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
8396 {
8397 	struct bpf_map *map;
8398 	int err;
8399 
8400 	if (!obj)
8401 		return libbpf_err(-ENOENT);
8402 
8403 	bpf_object__for_each_map(map, obj) {
8404 		char *pin_path = NULL;
8405 		char buf[PATH_MAX];
8406 
8407 		if (path) {
8408 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8409 			if (err)
8410 				return libbpf_err(err);
8411 			sanitize_pin_path(buf);
8412 			pin_path = buf;
8413 		} else if (!map->pin_path) {
8414 			continue;
8415 		}
8416 
8417 		err = bpf_map__unpin(map, pin_path);
8418 		if (err)
8419 			return libbpf_err(err);
8420 	}
8421 
8422 	return 0;
8423 }
8424 
8425 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
8426 {
8427 	struct bpf_program *prog;
8428 	char buf[PATH_MAX];
8429 	int err;
8430 
8431 	if (!obj)
8432 		return libbpf_err(-ENOENT);
8433 
8434 	if (!obj->loaded) {
8435 		pr_warn("object not yet loaded; load it first\n");
8436 		return libbpf_err(-ENOENT);
8437 	}
8438 
8439 	bpf_object__for_each_program(prog, obj) {
8440 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
8441 		if (err)
8442 			goto err_unpin_programs;
8443 
8444 		err = bpf_program__pin(prog, buf);
8445 		if (err)
8446 			goto err_unpin_programs;
8447 	}
8448 
8449 	return 0;
8450 
8451 err_unpin_programs:
8452 	while ((prog = bpf_object__prev_program(obj, prog))) {
8453 		if (pathname_concat(buf, sizeof(buf), path, prog->name))
8454 			continue;
8455 
8456 		bpf_program__unpin(prog, buf);
8457 	}
8458 
8459 	return libbpf_err(err);
8460 }
8461 
8462 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
8463 {
8464 	struct bpf_program *prog;
8465 	int err;
8466 
8467 	if (!obj)
8468 		return libbpf_err(-ENOENT);
8469 
8470 	bpf_object__for_each_program(prog, obj) {
8471 		char buf[PATH_MAX];
8472 
8473 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
8474 		if (err)
8475 			return libbpf_err(err);
8476 
8477 		err = bpf_program__unpin(prog, buf);
8478 		if (err)
8479 			return libbpf_err(err);
8480 	}
8481 
8482 	return 0;
8483 }
8484 
8485 int bpf_object__pin(struct bpf_object *obj, const char *path)
8486 {
8487 	int err;
8488 
8489 	err = bpf_object__pin_maps(obj, path);
8490 	if (err)
8491 		return libbpf_err(err);
8492 
8493 	err = bpf_object__pin_programs(obj, path);
8494 	if (err) {
8495 		bpf_object__unpin_maps(obj, path);
8496 		return libbpf_err(err);
8497 	}
8498 
8499 	return 0;
8500 }
8501 
8502 int bpf_object__unpin(struct bpf_object *obj, const char *path)
8503 {
8504 	int err;
8505 
8506 	err = bpf_object__unpin_programs(obj, path);
8507 	if (err)
8508 		return libbpf_err(err);
8509 
8510 	err = bpf_object__unpin_maps(obj, path);
8511 	if (err)
8512 		return libbpf_err(err);
8513 
8514 	return 0;
8515 }
8516 
8517 static void bpf_map__destroy(struct bpf_map *map)
8518 {
8519 	if (map->inner_map) {
8520 		bpf_map__destroy(map->inner_map);
8521 		zfree(&map->inner_map);
8522 	}
8523 
8524 	zfree(&map->init_slots);
8525 	map->init_slots_sz = 0;
8526 
8527 	if (map->mmaped) {
8528 		size_t mmap_sz;
8529 
8530 		mmap_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
8531 		munmap(map->mmaped, mmap_sz);
8532 		map->mmaped = NULL;
8533 	}
8534 
8535 	if (map->st_ops) {
8536 		zfree(&map->st_ops->data);
8537 		zfree(&map->st_ops->progs);
8538 		zfree(&map->st_ops->kern_func_off);
8539 		zfree(&map->st_ops);
8540 	}
8541 
8542 	zfree(&map->name);
8543 	zfree(&map->real_name);
8544 	zfree(&map->pin_path);
8545 
8546 	if (map->fd >= 0)
8547 		zclose(map->fd);
8548 }
8549 
8550 void bpf_object__close(struct bpf_object *obj)
8551 {
8552 	size_t i;
8553 
8554 	if (IS_ERR_OR_NULL(obj))
8555 		return;
8556 
8557 	usdt_manager_free(obj->usdt_man);
8558 	obj->usdt_man = NULL;
8559 
8560 	bpf_gen__free(obj->gen_loader);
8561 	bpf_object__elf_finish(obj);
8562 	bpf_object_unload(obj);
8563 	btf__free(obj->btf);
8564 	btf__free(obj->btf_vmlinux);
8565 	btf_ext__free(obj->btf_ext);
8566 
8567 	for (i = 0; i < obj->nr_maps; i++)
8568 		bpf_map__destroy(&obj->maps[i]);
8569 
8570 	zfree(&obj->btf_custom_path);
8571 	zfree(&obj->kconfig);
8572 
8573 	for (i = 0; i < obj->nr_extern; i++)
8574 		zfree(&obj->externs[i].essent_name);
8575 
8576 	zfree(&obj->externs);
8577 	obj->nr_extern = 0;
8578 
8579 	zfree(&obj->maps);
8580 	obj->nr_maps = 0;
8581 
8582 	if (obj->programs && obj->nr_programs) {
8583 		for (i = 0; i < obj->nr_programs; i++)
8584 			bpf_program__exit(&obj->programs[i]);
8585 	}
8586 	zfree(&obj->programs);
8587 
8588 	free(obj);
8589 }
8590 
8591 const char *bpf_object__name(const struct bpf_object *obj)
8592 {
8593 	return obj ? obj->name : libbpf_err_ptr(-EINVAL);
8594 }
8595 
8596 unsigned int bpf_object__kversion(const struct bpf_object *obj)
8597 {
8598 	return obj ? obj->kern_version : 0;
8599 }
8600 
8601 struct btf *bpf_object__btf(const struct bpf_object *obj)
8602 {
8603 	return obj ? obj->btf : NULL;
8604 }
8605 
8606 int bpf_object__btf_fd(const struct bpf_object *obj)
8607 {
8608 	return obj->btf ? btf__fd(obj->btf) : -1;
8609 }
8610 
8611 int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
8612 {
8613 	if (obj->loaded)
8614 		return libbpf_err(-EINVAL);
8615 
8616 	obj->kern_version = kern_version;
8617 
8618 	return 0;
8619 }
8620 
8621 int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
8622 {
8623 	struct bpf_gen *gen;
8624 
8625 	if (!opts)
8626 		return -EFAULT;
8627 	if (!OPTS_VALID(opts, gen_loader_opts))
8628 		return -EINVAL;
8629 	gen = calloc(sizeof(*gen), 1);
8630 	if (!gen)
8631 		return -ENOMEM;
8632 	gen->opts = opts;
8633 	obj->gen_loader = gen;
8634 	return 0;
8635 }
8636 
8637 static struct bpf_program *
8638 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
8639 		    bool forward)
8640 {
8641 	size_t nr_programs = obj->nr_programs;
8642 	ssize_t idx;
8643 
8644 	if (!nr_programs)
8645 		return NULL;
8646 
8647 	if (!p)
8648 		/* Iter from the beginning */
8649 		return forward ? &obj->programs[0] :
8650 			&obj->programs[nr_programs - 1];
8651 
8652 	if (p->obj != obj) {
8653 		pr_warn("error: program handler doesn't match object\n");
8654 		return errno = EINVAL, NULL;
8655 	}
8656 
8657 	idx = (p - obj->programs) + (forward ? 1 : -1);
8658 	if (idx >= obj->nr_programs || idx < 0)
8659 		return NULL;
8660 	return &obj->programs[idx];
8661 }
8662 
8663 struct bpf_program *
8664 bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
8665 {
8666 	struct bpf_program *prog = prev;
8667 
8668 	do {
8669 		prog = __bpf_program__iter(prog, obj, true);
8670 	} while (prog && prog_is_subprog(obj, prog));
8671 
8672 	return prog;
8673 }
8674 
8675 struct bpf_program *
8676 bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
8677 {
8678 	struct bpf_program *prog = next;
8679 
8680 	do {
8681 		prog = __bpf_program__iter(prog, obj, false);
8682 	} while (prog && prog_is_subprog(obj, prog));
8683 
8684 	return prog;
8685 }
8686 
8687 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
8688 {
8689 	prog->prog_ifindex = ifindex;
8690 }
8691 
8692 const char *bpf_program__name(const struct bpf_program *prog)
8693 {
8694 	return prog->name;
8695 }
8696 
8697 const char *bpf_program__section_name(const struct bpf_program *prog)
8698 {
8699 	return prog->sec_name;
8700 }
8701 
8702 bool bpf_program__autoload(const struct bpf_program *prog)
8703 {
8704 	return prog->autoload;
8705 }
8706 
8707 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
8708 {
8709 	if (prog->obj->loaded)
8710 		return libbpf_err(-EINVAL);
8711 
8712 	prog->autoload = autoload;
8713 	return 0;
8714 }
8715 
8716 bool bpf_program__autoattach(const struct bpf_program *prog)
8717 {
8718 	return prog->autoattach;
8719 }
8720 
8721 void bpf_program__set_autoattach(struct bpf_program *prog, bool autoattach)
8722 {
8723 	prog->autoattach = autoattach;
8724 }
8725 
8726 const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
8727 {
8728 	return prog->insns;
8729 }
8730 
8731 size_t bpf_program__insn_cnt(const struct bpf_program *prog)
8732 {
8733 	return prog->insns_cnt;
8734 }
8735 
8736 int bpf_program__set_insns(struct bpf_program *prog,
8737 			   struct bpf_insn *new_insns, size_t new_insn_cnt)
8738 {
8739 	struct bpf_insn *insns;
8740 
8741 	if (prog->obj->loaded)
8742 		return -EBUSY;
8743 
8744 	insns = libbpf_reallocarray(prog->insns, new_insn_cnt, sizeof(*insns));
8745 	/* NULL is a valid return from reallocarray if the new count is zero */
8746 	if (!insns && new_insn_cnt) {
8747 		pr_warn("prog '%s': failed to realloc prog code\n", prog->name);
8748 		return -ENOMEM;
8749 	}
8750 	memcpy(insns, new_insns, new_insn_cnt * sizeof(*insns));
8751 
8752 	prog->insns = insns;
8753 	prog->insns_cnt = new_insn_cnt;
8754 	return 0;
8755 }
8756 
8757 int bpf_program__fd(const struct bpf_program *prog)
8758 {
8759 	if (!prog)
8760 		return libbpf_err(-EINVAL);
8761 
8762 	if (prog->fd < 0)
8763 		return libbpf_err(-ENOENT);
8764 
8765 	return prog->fd;
8766 }
8767 
8768 __alias(bpf_program__type)
8769 enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog);
8770 
8771 enum bpf_prog_type bpf_program__type(const struct bpf_program *prog)
8772 {
8773 	return prog->type;
8774 }
8775 
8776 static size_t custom_sec_def_cnt;
8777 static struct bpf_sec_def *custom_sec_defs;
8778 static struct bpf_sec_def custom_fallback_def;
8779 static bool has_custom_fallback_def;
8780 static int last_custom_sec_def_handler_id;
8781 
8782 int bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
8783 {
8784 	if (prog->obj->loaded)
8785 		return libbpf_err(-EBUSY);
8786 
8787 	/* if type is not changed, do nothing */
8788 	if (prog->type == type)
8789 		return 0;
8790 
8791 	prog->type = type;
8792 
8793 	/* If a program type was changed, we need to reset associated SEC()
8794 	 * handler, as it will be invalid now. The only exception is a generic
8795 	 * fallback handler, which by definition is program type-agnostic and
8796 	 * is a catch-all custom handler, optionally set by the application,
8797 	 * so should be able to handle any type of BPF program.
8798 	 */
8799 	if (prog->sec_def != &custom_fallback_def)
8800 		prog->sec_def = NULL;
8801 	return 0;
8802 }
8803 
8804 __alias(bpf_program__expected_attach_type)
8805 enum bpf_attach_type bpf_program__get_expected_attach_type(const struct bpf_program *prog);
8806 
8807 enum bpf_attach_type bpf_program__expected_attach_type(const struct bpf_program *prog)
8808 {
8809 	return prog->expected_attach_type;
8810 }
8811 
8812 int bpf_program__set_expected_attach_type(struct bpf_program *prog,
8813 					   enum bpf_attach_type type)
8814 {
8815 	if (prog->obj->loaded)
8816 		return libbpf_err(-EBUSY);
8817 
8818 	prog->expected_attach_type = type;
8819 	return 0;
8820 }
8821 
8822 __u32 bpf_program__flags(const struct bpf_program *prog)
8823 {
8824 	return prog->prog_flags;
8825 }
8826 
8827 int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
8828 {
8829 	if (prog->obj->loaded)
8830 		return libbpf_err(-EBUSY);
8831 
8832 	prog->prog_flags = flags;
8833 	return 0;
8834 }
8835 
8836 __u32 bpf_program__log_level(const struct bpf_program *prog)
8837 {
8838 	return prog->log_level;
8839 }
8840 
8841 int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
8842 {
8843 	if (prog->obj->loaded)
8844 		return libbpf_err(-EBUSY);
8845 
8846 	prog->log_level = log_level;
8847 	return 0;
8848 }
8849 
8850 const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
8851 {
8852 	*log_size = prog->log_size;
8853 	return prog->log_buf;
8854 }
8855 
8856 int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
8857 {
8858 	if (log_size && !log_buf)
8859 		return -EINVAL;
8860 	if (prog->log_size > UINT_MAX)
8861 		return -EINVAL;
8862 	if (prog->obj->loaded)
8863 		return -EBUSY;
8864 
8865 	prog->log_buf = log_buf;
8866 	prog->log_size = log_size;
8867 	return 0;
8868 }
8869 
8870 #define SEC_DEF(sec_pfx, ptype, atype, flags, ...) {			    \
8871 	.sec = (char *)sec_pfx,						    \
8872 	.prog_type = BPF_PROG_TYPE_##ptype,				    \
8873 	.expected_attach_type = atype,					    \
8874 	.cookie = (long)(flags),					    \
8875 	.prog_prepare_load_fn = libbpf_prepare_prog_load,		    \
8876 	__VA_ARGS__							    \
8877 }
8878 
8879 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8880 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8881 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8882 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8883 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8884 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8885 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8886 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8887 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8888 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8889 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8890 
8891 static const struct bpf_sec_def section_defs[] = {
8892 	SEC_DEF("socket",		SOCKET_FILTER, 0, SEC_NONE),
8893 	SEC_DEF("sk_reuseport/migrate",	SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE),
8894 	SEC_DEF("sk_reuseport",		SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE),
8895 	SEC_DEF("kprobe+",		KPROBE,	0, SEC_NONE, attach_kprobe),
8896 	SEC_DEF("uprobe+",		KPROBE,	0, SEC_NONE, attach_uprobe),
8897 	SEC_DEF("uprobe.s+",		KPROBE,	0, SEC_SLEEPABLE, attach_uprobe),
8898 	SEC_DEF("kretprobe+",		KPROBE, 0, SEC_NONE, attach_kprobe),
8899 	SEC_DEF("uretprobe+",		KPROBE, 0, SEC_NONE, attach_uprobe),
8900 	SEC_DEF("uretprobe.s+",		KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
8901 	SEC_DEF("kprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
8902 	SEC_DEF("kretprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
8903 	SEC_DEF("uprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
8904 	SEC_DEF("uretprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
8905 	SEC_DEF("uprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
8906 	SEC_DEF("uretprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
8907 	SEC_DEF("ksyscall+",		KPROBE,	0, SEC_NONE, attach_ksyscall),
8908 	SEC_DEF("kretsyscall+",		KPROBE, 0, SEC_NONE, attach_ksyscall),
8909 	SEC_DEF("usdt+",		KPROBE,	0, SEC_USDT, attach_usdt),
8910 	SEC_DEF("usdt.s+",		KPROBE,	0, SEC_USDT | SEC_SLEEPABLE, attach_usdt),
8911 	SEC_DEF("tc/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE), /* alias for tcx */
8912 	SEC_DEF("tc/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),  /* alias for tcx */
8913 	SEC_DEF("tcx/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE),
8914 	SEC_DEF("tcx/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),
8915 	SEC_DEF("tc",			SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
8916 	SEC_DEF("classifier",		SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
8917 	SEC_DEF("action",		SCHED_ACT, 0, SEC_NONE), /* deprecated / legacy, use tcx */
8918 	SEC_DEF("tracepoint+",		TRACEPOINT, 0, SEC_NONE, attach_tp),
8919 	SEC_DEF("tp+",			TRACEPOINT, 0, SEC_NONE, attach_tp),
8920 	SEC_DEF("raw_tracepoint+",	RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
8921 	SEC_DEF("raw_tp+",		RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
8922 	SEC_DEF("raw_tracepoint.w+",	RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
8923 	SEC_DEF("raw_tp.w+",		RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
8924 	SEC_DEF("tp_btf+",		TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
8925 	SEC_DEF("fentry+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
8926 	SEC_DEF("fmod_ret+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
8927 	SEC_DEF("fexit+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
8928 	SEC_DEF("fentry.s+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8929 	SEC_DEF("fmod_ret.s+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8930 	SEC_DEF("fexit.s+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8931 	SEC_DEF("freplace+",		EXT, 0, SEC_ATTACH_BTF, attach_trace),
8932 	SEC_DEF("lsm+",			LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
8933 	SEC_DEF("lsm.s+",		LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
8934 	SEC_DEF("lsm_cgroup+",		LSM, BPF_LSM_CGROUP, SEC_ATTACH_BTF),
8935 	SEC_DEF("iter+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
8936 	SEC_DEF("iter.s+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_iter),
8937 	SEC_DEF("syscall",		SYSCALL, 0, SEC_SLEEPABLE),
8938 	SEC_DEF("xdp.frags/devmap",	XDP, BPF_XDP_DEVMAP, SEC_XDP_FRAGS),
8939 	SEC_DEF("xdp/devmap",		XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
8940 	SEC_DEF("xdp.frags/cpumap",	XDP, BPF_XDP_CPUMAP, SEC_XDP_FRAGS),
8941 	SEC_DEF("xdp/cpumap",		XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
8942 	SEC_DEF("xdp.frags",		XDP, BPF_XDP, SEC_XDP_FRAGS),
8943 	SEC_DEF("xdp",			XDP, BPF_XDP, SEC_ATTACHABLE_OPT),
8944 	SEC_DEF("perf_event",		PERF_EVENT, 0, SEC_NONE),
8945 	SEC_DEF("lwt_in",		LWT_IN, 0, SEC_NONE),
8946 	SEC_DEF("lwt_out",		LWT_OUT, 0, SEC_NONE),
8947 	SEC_DEF("lwt_xmit",		LWT_XMIT, 0, SEC_NONE),
8948 	SEC_DEF("lwt_seg6local",	LWT_SEG6LOCAL, 0, SEC_NONE),
8949 	SEC_DEF("sockops",		SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT),
8950 	SEC_DEF("sk_skb/stream_parser",	SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT),
8951 	SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT),
8952 	SEC_DEF("sk_skb",		SK_SKB, 0, SEC_NONE),
8953 	SEC_DEF("sk_msg",		SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT),
8954 	SEC_DEF("lirc_mode2",		LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT),
8955 	SEC_DEF("flow_dissector",	FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT),
8956 	SEC_DEF("cgroup_skb/ingress",	CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT),
8957 	SEC_DEF("cgroup_skb/egress",	CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT),
8958 	SEC_DEF("cgroup/skb",		CGROUP_SKB, 0, SEC_NONE),
8959 	SEC_DEF("cgroup/sock_create",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE),
8960 	SEC_DEF("cgroup/sock_release",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE),
8961 	SEC_DEF("cgroup/sock",		CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT),
8962 	SEC_DEF("cgroup/post_bind4",	CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE),
8963 	SEC_DEF("cgroup/post_bind6",	CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE),
8964 	SEC_DEF("cgroup/bind4",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE),
8965 	SEC_DEF("cgroup/bind6",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE),
8966 	SEC_DEF("cgroup/connect4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE),
8967 	SEC_DEF("cgroup/connect6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE),
8968 	SEC_DEF("cgroup/connect_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_CONNECT, SEC_ATTACHABLE),
8969 	SEC_DEF("cgroup/sendmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE),
8970 	SEC_DEF("cgroup/sendmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE),
8971 	SEC_DEF("cgroup/sendmsg_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_SENDMSG, SEC_ATTACHABLE),
8972 	SEC_DEF("cgroup/recvmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE),
8973 	SEC_DEF("cgroup/recvmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE),
8974 	SEC_DEF("cgroup/recvmsg_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_RECVMSG, SEC_ATTACHABLE),
8975 	SEC_DEF("cgroup/getpeername4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE),
8976 	SEC_DEF("cgroup/getpeername6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE),
8977 	SEC_DEF("cgroup/getpeername_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETPEERNAME, SEC_ATTACHABLE),
8978 	SEC_DEF("cgroup/getsockname4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE),
8979 	SEC_DEF("cgroup/getsockname6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE),
8980 	SEC_DEF("cgroup/getsockname_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETSOCKNAME, SEC_ATTACHABLE),
8981 	SEC_DEF("cgroup/sysctl",	CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE),
8982 	SEC_DEF("cgroup/getsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE),
8983 	SEC_DEF("cgroup/setsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE),
8984 	SEC_DEF("cgroup/dev",		CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT),
8985 	SEC_DEF("struct_ops+",		STRUCT_OPS, 0, SEC_NONE),
8986 	SEC_DEF("struct_ops.s+",	STRUCT_OPS, 0, SEC_SLEEPABLE),
8987 	SEC_DEF("sk_lookup",		SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE),
8988 	SEC_DEF("netfilter",		NETFILTER, BPF_NETFILTER, SEC_NONE),
8989 };
8990 
8991 int libbpf_register_prog_handler(const char *sec,
8992 				 enum bpf_prog_type prog_type,
8993 				 enum bpf_attach_type exp_attach_type,
8994 				 const struct libbpf_prog_handler_opts *opts)
8995 {
8996 	struct bpf_sec_def *sec_def;
8997 
8998 	if (!OPTS_VALID(opts, libbpf_prog_handler_opts))
8999 		return libbpf_err(-EINVAL);
9000 
9001 	if (last_custom_sec_def_handler_id == INT_MAX) /* prevent overflow */
9002 		return libbpf_err(-E2BIG);
9003 
9004 	if (sec) {
9005 		sec_def = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt + 1,
9006 					      sizeof(*sec_def));
9007 		if (!sec_def)
9008 			return libbpf_err(-ENOMEM);
9009 
9010 		custom_sec_defs = sec_def;
9011 		sec_def = &custom_sec_defs[custom_sec_def_cnt];
9012 	} else {
9013 		if (has_custom_fallback_def)
9014 			return libbpf_err(-EBUSY);
9015 
9016 		sec_def = &custom_fallback_def;
9017 	}
9018 
9019 	sec_def->sec = sec ? strdup(sec) : NULL;
9020 	if (sec && !sec_def->sec)
9021 		return libbpf_err(-ENOMEM);
9022 
9023 	sec_def->prog_type = prog_type;
9024 	sec_def->expected_attach_type = exp_attach_type;
9025 	sec_def->cookie = OPTS_GET(opts, cookie, 0);
9026 
9027 	sec_def->prog_setup_fn = OPTS_GET(opts, prog_setup_fn, NULL);
9028 	sec_def->prog_prepare_load_fn = OPTS_GET(opts, prog_prepare_load_fn, NULL);
9029 	sec_def->prog_attach_fn = OPTS_GET(opts, prog_attach_fn, NULL);
9030 
9031 	sec_def->handler_id = ++last_custom_sec_def_handler_id;
9032 
9033 	if (sec)
9034 		custom_sec_def_cnt++;
9035 	else
9036 		has_custom_fallback_def = true;
9037 
9038 	return sec_def->handler_id;
9039 }
9040 
9041 int libbpf_unregister_prog_handler(int handler_id)
9042 {
9043 	struct bpf_sec_def *sec_defs;
9044 	int i;
9045 
9046 	if (handler_id <= 0)
9047 		return libbpf_err(-EINVAL);
9048 
9049 	if (has_custom_fallback_def && custom_fallback_def.handler_id == handler_id) {
9050 		memset(&custom_fallback_def, 0, sizeof(custom_fallback_def));
9051 		has_custom_fallback_def = false;
9052 		return 0;
9053 	}
9054 
9055 	for (i = 0; i < custom_sec_def_cnt; i++) {
9056 		if (custom_sec_defs[i].handler_id == handler_id)
9057 			break;
9058 	}
9059 
9060 	if (i == custom_sec_def_cnt)
9061 		return libbpf_err(-ENOENT);
9062 
9063 	free(custom_sec_defs[i].sec);
9064 	for (i = i + 1; i < custom_sec_def_cnt; i++)
9065 		custom_sec_defs[i - 1] = custom_sec_defs[i];
9066 	custom_sec_def_cnt--;
9067 
9068 	/* try to shrink the array, but it's ok if we couldn't */
9069 	sec_defs = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt, sizeof(*sec_defs));
9070 	/* if new count is zero, reallocarray can return a valid NULL result;
9071 	 * in this case the previous pointer will be freed, so we *have to*
9072 	 * reassign old pointer to the new value (even if it's NULL)
9073 	 */
9074 	if (sec_defs || custom_sec_def_cnt == 0)
9075 		custom_sec_defs = sec_defs;
9076 
9077 	return 0;
9078 }
9079 
9080 static bool sec_def_matches(const struct bpf_sec_def *sec_def, const char *sec_name)
9081 {
9082 	size_t len = strlen(sec_def->sec);
9083 
9084 	/* "type/" always has to have proper SEC("type/extras") form */
9085 	if (sec_def->sec[len - 1] == '/') {
9086 		if (str_has_pfx(sec_name, sec_def->sec))
9087 			return true;
9088 		return false;
9089 	}
9090 
9091 	/* "type+" means it can be either exact SEC("type") or
9092 	 * well-formed SEC("type/extras") with proper '/' separator
9093 	 */
9094 	if (sec_def->sec[len - 1] == '+') {
9095 		len--;
9096 		/* not even a prefix */
9097 		if (strncmp(sec_name, sec_def->sec, len) != 0)
9098 			return false;
9099 		/* exact match or has '/' separator */
9100 		if (sec_name[len] == '\0' || sec_name[len] == '/')
9101 			return true;
9102 		return false;
9103 	}
9104 
9105 	return strcmp(sec_name, sec_def->sec) == 0;
9106 }
9107 
9108 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
9109 {
9110 	const struct bpf_sec_def *sec_def;
9111 	int i, n;
9112 
9113 	n = custom_sec_def_cnt;
9114 	for (i = 0; i < n; i++) {
9115 		sec_def = &custom_sec_defs[i];
9116 		if (sec_def_matches(sec_def, sec_name))
9117 			return sec_def;
9118 	}
9119 
9120 	n = ARRAY_SIZE(section_defs);
9121 	for (i = 0; i < n; i++) {
9122 		sec_def = &section_defs[i];
9123 		if (sec_def_matches(sec_def, sec_name))
9124 			return sec_def;
9125 	}
9126 
9127 	if (has_custom_fallback_def)
9128 		return &custom_fallback_def;
9129 
9130 	return NULL;
9131 }
9132 
9133 #define MAX_TYPE_NAME_SIZE 32
9134 
9135 static char *libbpf_get_type_names(bool attach_type)
9136 {
9137 	int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
9138 	char *buf;
9139 
9140 	buf = malloc(len);
9141 	if (!buf)
9142 		return NULL;
9143 
9144 	buf[0] = '\0';
9145 	/* Forge string buf with all available names */
9146 	for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
9147 		const struct bpf_sec_def *sec_def = &section_defs[i];
9148 
9149 		if (attach_type) {
9150 			if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
9151 				continue;
9152 
9153 			if (!(sec_def->cookie & SEC_ATTACHABLE))
9154 				continue;
9155 		}
9156 
9157 		if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
9158 			free(buf);
9159 			return NULL;
9160 		}
9161 		strcat(buf, " ");
9162 		strcat(buf, section_defs[i].sec);
9163 	}
9164 
9165 	return buf;
9166 }
9167 
9168 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
9169 			     enum bpf_attach_type *expected_attach_type)
9170 {
9171 	const struct bpf_sec_def *sec_def;
9172 	char *type_names;
9173 
9174 	if (!name)
9175 		return libbpf_err(-EINVAL);
9176 
9177 	sec_def = find_sec_def(name);
9178 	if (sec_def) {
9179 		*prog_type = sec_def->prog_type;
9180 		*expected_attach_type = sec_def->expected_attach_type;
9181 		return 0;
9182 	}
9183 
9184 	pr_debug("failed to guess program type from ELF section '%s'\n", name);
9185 	type_names = libbpf_get_type_names(false);
9186 	if (type_names != NULL) {
9187 		pr_debug("supported section(type) names are:%s\n", type_names);
9188 		free(type_names);
9189 	}
9190 
9191 	return libbpf_err(-ESRCH);
9192 }
9193 
9194 const char *libbpf_bpf_attach_type_str(enum bpf_attach_type t)
9195 {
9196 	if (t < 0 || t >= ARRAY_SIZE(attach_type_name))
9197 		return NULL;
9198 
9199 	return attach_type_name[t];
9200 }
9201 
9202 const char *libbpf_bpf_link_type_str(enum bpf_link_type t)
9203 {
9204 	if (t < 0 || t >= ARRAY_SIZE(link_type_name))
9205 		return NULL;
9206 
9207 	return link_type_name[t];
9208 }
9209 
9210 const char *libbpf_bpf_map_type_str(enum bpf_map_type t)
9211 {
9212 	if (t < 0 || t >= ARRAY_SIZE(map_type_name))
9213 		return NULL;
9214 
9215 	return map_type_name[t];
9216 }
9217 
9218 const char *libbpf_bpf_prog_type_str(enum bpf_prog_type t)
9219 {
9220 	if (t < 0 || t >= ARRAY_SIZE(prog_type_name))
9221 		return NULL;
9222 
9223 	return prog_type_name[t];
9224 }
9225 
9226 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
9227 						     int sec_idx,
9228 						     size_t offset)
9229 {
9230 	struct bpf_map *map;
9231 	size_t i;
9232 
9233 	for (i = 0; i < obj->nr_maps; i++) {
9234 		map = &obj->maps[i];
9235 		if (!bpf_map__is_struct_ops(map))
9236 			continue;
9237 		if (map->sec_idx == sec_idx &&
9238 		    map->sec_offset <= offset &&
9239 		    offset - map->sec_offset < map->def.value_size)
9240 			return map;
9241 	}
9242 
9243 	return NULL;
9244 }
9245 
9246 /* Collect the reloc from ELF and populate the st_ops->progs[] */
9247 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
9248 					    Elf64_Shdr *shdr, Elf_Data *data)
9249 {
9250 	const struct btf_member *member;
9251 	struct bpf_struct_ops *st_ops;
9252 	struct bpf_program *prog;
9253 	unsigned int shdr_idx;
9254 	const struct btf *btf;
9255 	struct bpf_map *map;
9256 	unsigned int moff, insn_idx;
9257 	const char *name;
9258 	__u32 member_idx;
9259 	Elf64_Sym *sym;
9260 	Elf64_Rel *rel;
9261 	int i, nrels;
9262 
9263 	btf = obj->btf;
9264 	nrels = shdr->sh_size / shdr->sh_entsize;
9265 	for (i = 0; i < nrels; i++) {
9266 		rel = elf_rel_by_idx(data, i);
9267 		if (!rel) {
9268 			pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
9269 			return -LIBBPF_ERRNO__FORMAT;
9270 		}
9271 
9272 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
9273 		if (!sym) {
9274 			pr_warn("struct_ops reloc: symbol %zx not found\n",
9275 				(size_t)ELF64_R_SYM(rel->r_info));
9276 			return -LIBBPF_ERRNO__FORMAT;
9277 		}
9278 
9279 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
9280 		map = find_struct_ops_map_by_offset(obj, shdr->sh_info, rel->r_offset);
9281 		if (!map) {
9282 			pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
9283 				(size_t)rel->r_offset);
9284 			return -EINVAL;
9285 		}
9286 
9287 		moff = rel->r_offset - map->sec_offset;
9288 		shdr_idx = sym->st_shndx;
9289 		st_ops = map->st_ops;
9290 		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",
9291 			 map->name,
9292 			 (long long)(rel->r_info >> 32),
9293 			 (long long)sym->st_value,
9294 			 shdr_idx, (size_t)rel->r_offset,
9295 			 map->sec_offset, sym->st_name, name);
9296 
9297 		if (shdr_idx >= SHN_LORESERVE) {
9298 			pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
9299 				map->name, (size_t)rel->r_offset, shdr_idx);
9300 			return -LIBBPF_ERRNO__RELOC;
9301 		}
9302 		if (sym->st_value % BPF_INSN_SZ) {
9303 			pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
9304 				map->name, (unsigned long long)sym->st_value);
9305 			return -LIBBPF_ERRNO__FORMAT;
9306 		}
9307 		insn_idx = sym->st_value / BPF_INSN_SZ;
9308 
9309 		member = find_member_by_offset(st_ops->type, moff * 8);
9310 		if (!member) {
9311 			pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
9312 				map->name, moff);
9313 			return -EINVAL;
9314 		}
9315 		member_idx = member - btf_members(st_ops->type);
9316 		name = btf__name_by_offset(btf, member->name_off);
9317 
9318 		if (!resolve_func_ptr(btf, member->type, NULL)) {
9319 			pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
9320 				map->name, name);
9321 			return -EINVAL;
9322 		}
9323 
9324 		prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
9325 		if (!prog) {
9326 			pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
9327 				map->name, shdr_idx, name);
9328 			return -EINVAL;
9329 		}
9330 
9331 		/* prevent the use of BPF prog with invalid type */
9332 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
9333 			pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
9334 				map->name, prog->name);
9335 			return -EINVAL;
9336 		}
9337 
9338 		/* if we haven't yet processed this BPF program, record proper
9339 		 * attach_btf_id and member_idx
9340 		 */
9341 		if (!prog->attach_btf_id) {
9342 			prog->attach_btf_id = st_ops->type_id;
9343 			prog->expected_attach_type = member_idx;
9344 		}
9345 
9346 		/* struct_ops BPF prog can be re-used between multiple
9347 		 * .struct_ops & .struct_ops.link as long as it's the
9348 		 * same struct_ops struct definition and the same
9349 		 * function pointer field
9350 		 */
9351 		if (prog->attach_btf_id != st_ops->type_id ||
9352 		    prog->expected_attach_type != member_idx) {
9353 			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",
9354 				map->name, prog->name, prog->sec_name, prog->type,
9355 				prog->attach_btf_id, prog->expected_attach_type, name);
9356 			return -EINVAL;
9357 		}
9358 
9359 		st_ops->progs[member_idx] = prog;
9360 	}
9361 
9362 	return 0;
9363 }
9364 
9365 #define BTF_TRACE_PREFIX "btf_trace_"
9366 #define BTF_LSM_PREFIX "bpf_lsm_"
9367 #define BTF_ITER_PREFIX "bpf_iter_"
9368 #define BTF_MAX_NAME_SIZE 128
9369 
9370 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
9371 				const char **prefix, int *kind)
9372 {
9373 	switch (attach_type) {
9374 	case BPF_TRACE_RAW_TP:
9375 		*prefix = BTF_TRACE_PREFIX;
9376 		*kind = BTF_KIND_TYPEDEF;
9377 		break;
9378 	case BPF_LSM_MAC:
9379 	case BPF_LSM_CGROUP:
9380 		*prefix = BTF_LSM_PREFIX;
9381 		*kind = BTF_KIND_FUNC;
9382 		break;
9383 	case BPF_TRACE_ITER:
9384 		*prefix = BTF_ITER_PREFIX;
9385 		*kind = BTF_KIND_FUNC;
9386 		break;
9387 	default:
9388 		*prefix = "";
9389 		*kind = BTF_KIND_FUNC;
9390 	}
9391 }
9392 
9393 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
9394 				   const char *name, __u32 kind)
9395 {
9396 	char btf_type_name[BTF_MAX_NAME_SIZE];
9397 	int ret;
9398 
9399 	ret = snprintf(btf_type_name, sizeof(btf_type_name),
9400 		       "%s%s", prefix, name);
9401 	/* snprintf returns the number of characters written excluding the
9402 	 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
9403 	 * indicates truncation.
9404 	 */
9405 	if (ret < 0 || ret >= sizeof(btf_type_name))
9406 		return -ENAMETOOLONG;
9407 	return btf__find_by_name_kind(btf, btf_type_name, kind);
9408 }
9409 
9410 static inline int find_attach_btf_id(struct btf *btf, const char *name,
9411 				     enum bpf_attach_type attach_type)
9412 {
9413 	const char *prefix;
9414 	int kind;
9415 
9416 	btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
9417 	return find_btf_by_prefix_kind(btf, prefix, name, kind);
9418 }
9419 
9420 int libbpf_find_vmlinux_btf_id(const char *name,
9421 			       enum bpf_attach_type attach_type)
9422 {
9423 	struct btf *btf;
9424 	int err;
9425 
9426 	btf = btf__load_vmlinux_btf();
9427 	err = libbpf_get_error(btf);
9428 	if (err) {
9429 		pr_warn("vmlinux BTF is not found\n");
9430 		return libbpf_err(err);
9431 	}
9432 
9433 	err = find_attach_btf_id(btf, name, attach_type);
9434 	if (err <= 0)
9435 		pr_warn("%s is not found in vmlinux BTF\n", name);
9436 
9437 	btf__free(btf);
9438 	return libbpf_err(err);
9439 }
9440 
9441 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
9442 {
9443 	struct bpf_prog_info info;
9444 	__u32 info_len = sizeof(info);
9445 	struct btf *btf;
9446 	int err;
9447 
9448 	memset(&info, 0, info_len);
9449 	err = bpf_prog_get_info_by_fd(attach_prog_fd, &info, &info_len);
9450 	if (err) {
9451 		pr_warn("failed bpf_prog_get_info_by_fd for FD %d: %d\n",
9452 			attach_prog_fd, err);
9453 		return err;
9454 	}
9455 
9456 	err = -EINVAL;
9457 	if (!info.btf_id) {
9458 		pr_warn("The target program doesn't have BTF\n");
9459 		goto out;
9460 	}
9461 	btf = btf__load_from_kernel_by_id(info.btf_id);
9462 	err = libbpf_get_error(btf);
9463 	if (err) {
9464 		pr_warn("Failed to get BTF %d of the program: %d\n", info.btf_id, err);
9465 		goto out;
9466 	}
9467 	err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
9468 	btf__free(btf);
9469 	if (err <= 0) {
9470 		pr_warn("%s is not found in prog's BTF\n", name);
9471 		goto out;
9472 	}
9473 out:
9474 	return err;
9475 }
9476 
9477 static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
9478 			      enum bpf_attach_type attach_type,
9479 			      int *btf_obj_fd, int *btf_type_id)
9480 {
9481 	int ret, i;
9482 
9483 	ret = find_attach_btf_id(obj->btf_vmlinux, attach_name, attach_type);
9484 	if (ret > 0) {
9485 		*btf_obj_fd = 0; /* vmlinux BTF */
9486 		*btf_type_id = ret;
9487 		return 0;
9488 	}
9489 	if (ret != -ENOENT)
9490 		return ret;
9491 
9492 	ret = load_module_btfs(obj);
9493 	if (ret)
9494 		return ret;
9495 
9496 	for (i = 0; i < obj->btf_module_cnt; i++) {
9497 		const struct module_btf *mod = &obj->btf_modules[i];
9498 
9499 		ret = find_attach_btf_id(mod->btf, attach_name, attach_type);
9500 		if (ret > 0) {
9501 			*btf_obj_fd = mod->fd;
9502 			*btf_type_id = ret;
9503 			return 0;
9504 		}
9505 		if (ret == -ENOENT)
9506 			continue;
9507 
9508 		return ret;
9509 	}
9510 
9511 	return -ESRCH;
9512 }
9513 
9514 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
9515 				     int *btf_obj_fd, int *btf_type_id)
9516 {
9517 	enum bpf_attach_type attach_type = prog->expected_attach_type;
9518 	__u32 attach_prog_fd = prog->attach_prog_fd;
9519 	int err = 0;
9520 
9521 	/* BPF program's BTF ID */
9522 	if (prog->type == BPF_PROG_TYPE_EXT || attach_prog_fd) {
9523 		if (!attach_prog_fd) {
9524 			pr_warn("prog '%s': attach program FD is not set\n", prog->name);
9525 			return -EINVAL;
9526 		}
9527 		err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd);
9528 		if (err < 0) {
9529 			pr_warn("prog '%s': failed to find BPF program (FD %d) BTF ID for '%s': %d\n",
9530 				 prog->name, attach_prog_fd, attach_name, err);
9531 			return err;
9532 		}
9533 		*btf_obj_fd = 0;
9534 		*btf_type_id = err;
9535 		return 0;
9536 	}
9537 
9538 	/* kernel/module BTF ID */
9539 	if (prog->obj->gen_loader) {
9540 		bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
9541 		*btf_obj_fd = 0;
9542 		*btf_type_id = 1;
9543 	} else {
9544 		err = find_kernel_btf_id(prog->obj, attach_name, attach_type, btf_obj_fd, btf_type_id);
9545 	}
9546 	if (err) {
9547 		pr_warn("prog '%s': failed to find kernel BTF type ID of '%s': %d\n",
9548 			prog->name, attach_name, err);
9549 		return err;
9550 	}
9551 	return 0;
9552 }
9553 
9554 int libbpf_attach_type_by_name(const char *name,
9555 			       enum bpf_attach_type *attach_type)
9556 {
9557 	char *type_names;
9558 	const struct bpf_sec_def *sec_def;
9559 
9560 	if (!name)
9561 		return libbpf_err(-EINVAL);
9562 
9563 	sec_def = find_sec_def(name);
9564 	if (!sec_def) {
9565 		pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
9566 		type_names = libbpf_get_type_names(true);
9567 		if (type_names != NULL) {
9568 			pr_debug("attachable section(type) names are:%s\n", type_names);
9569 			free(type_names);
9570 		}
9571 
9572 		return libbpf_err(-EINVAL);
9573 	}
9574 
9575 	if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
9576 		return libbpf_err(-EINVAL);
9577 	if (!(sec_def->cookie & SEC_ATTACHABLE))
9578 		return libbpf_err(-EINVAL);
9579 
9580 	*attach_type = sec_def->expected_attach_type;
9581 	return 0;
9582 }
9583 
9584 int bpf_map__fd(const struct bpf_map *map)
9585 {
9586 	return map ? map->fd : libbpf_err(-EINVAL);
9587 }
9588 
9589 static bool map_uses_real_name(const struct bpf_map *map)
9590 {
9591 	/* Since libbpf started to support custom .data.* and .rodata.* maps,
9592 	 * their user-visible name differs from kernel-visible name. Users see
9593 	 * such map's corresponding ELF section name as a map name.
9594 	 * This check distinguishes .data/.rodata from .data.* and .rodata.*
9595 	 * maps to know which name has to be returned to the user.
9596 	 */
9597 	if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
9598 		return true;
9599 	if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
9600 		return true;
9601 	return false;
9602 }
9603 
9604 const char *bpf_map__name(const struct bpf_map *map)
9605 {
9606 	if (!map)
9607 		return NULL;
9608 
9609 	if (map_uses_real_name(map))
9610 		return map->real_name;
9611 
9612 	return map->name;
9613 }
9614 
9615 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
9616 {
9617 	return map->def.type;
9618 }
9619 
9620 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
9621 {
9622 	if (map->fd >= 0)
9623 		return libbpf_err(-EBUSY);
9624 	map->def.type = type;
9625 	return 0;
9626 }
9627 
9628 __u32 bpf_map__map_flags(const struct bpf_map *map)
9629 {
9630 	return map->def.map_flags;
9631 }
9632 
9633 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
9634 {
9635 	if (map->fd >= 0)
9636 		return libbpf_err(-EBUSY);
9637 	map->def.map_flags = flags;
9638 	return 0;
9639 }
9640 
9641 __u64 bpf_map__map_extra(const struct bpf_map *map)
9642 {
9643 	return map->map_extra;
9644 }
9645 
9646 int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
9647 {
9648 	if (map->fd >= 0)
9649 		return libbpf_err(-EBUSY);
9650 	map->map_extra = map_extra;
9651 	return 0;
9652 }
9653 
9654 __u32 bpf_map__numa_node(const struct bpf_map *map)
9655 {
9656 	return map->numa_node;
9657 }
9658 
9659 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
9660 {
9661 	if (map->fd >= 0)
9662 		return libbpf_err(-EBUSY);
9663 	map->numa_node = numa_node;
9664 	return 0;
9665 }
9666 
9667 __u32 bpf_map__key_size(const struct bpf_map *map)
9668 {
9669 	return map->def.key_size;
9670 }
9671 
9672 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
9673 {
9674 	if (map->fd >= 0)
9675 		return libbpf_err(-EBUSY);
9676 	map->def.key_size = size;
9677 	return 0;
9678 }
9679 
9680 __u32 bpf_map__value_size(const struct bpf_map *map)
9681 {
9682 	return map->def.value_size;
9683 }
9684 
9685 static int map_btf_datasec_resize(struct bpf_map *map, __u32 size)
9686 {
9687 	struct btf *btf;
9688 	struct btf_type *datasec_type, *var_type;
9689 	struct btf_var_secinfo *var;
9690 	const struct btf_type *array_type;
9691 	const struct btf_array *array;
9692 	int vlen, element_sz, new_array_id;
9693 	__u32 nr_elements;
9694 
9695 	/* check btf existence */
9696 	btf = bpf_object__btf(map->obj);
9697 	if (!btf)
9698 		return -ENOENT;
9699 
9700 	/* verify map is datasec */
9701 	datasec_type = btf_type_by_id(btf, bpf_map__btf_value_type_id(map));
9702 	if (!btf_is_datasec(datasec_type)) {
9703 		pr_warn("map '%s': cannot be resized, map value type is not a datasec\n",
9704 			bpf_map__name(map));
9705 		return -EINVAL;
9706 	}
9707 
9708 	/* verify datasec has at least one var */
9709 	vlen = btf_vlen(datasec_type);
9710 	if (vlen == 0) {
9711 		pr_warn("map '%s': cannot be resized, map value datasec is empty\n",
9712 			bpf_map__name(map));
9713 		return -EINVAL;
9714 	}
9715 
9716 	/* verify last var in the datasec is an array */
9717 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
9718 	var_type = btf_type_by_id(btf, var->type);
9719 	array_type = skip_mods_and_typedefs(btf, var_type->type, NULL);
9720 	if (!btf_is_array(array_type)) {
9721 		pr_warn("map '%s': cannot be resized, last var must be an array\n",
9722 			bpf_map__name(map));
9723 		return -EINVAL;
9724 	}
9725 
9726 	/* verify request size aligns with array */
9727 	array = btf_array(array_type);
9728 	element_sz = btf__resolve_size(btf, array->type);
9729 	if (element_sz <= 0 || (size - var->offset) % element_sz != 0) {
9730 		pr_warn("map '%s': cannot be resized, element size (%d) doesn't align with new total size (%u)\n",
9731 			bpf_map__name(map), element_sz, size);
9732 		return -EINVAL;
9733 	}
9734 
9735 	/* create a new array based on the existing array, but with new length */
9736 	nr_elements = (size - var->offset) / element_sz;
9737 	new_array_id = btf__add_array(btf, array->index_type, array->type, nr_elements);
9738 	if (new_array_id < 0)
9739 		return new_array_id;
9740 
9741 	/* adding a new btf type invalidates existing pointers to btf objects,
9742 	 * so refresh pointers before proceeding
9743 	 */
9744 	datasec_type = btf_type_by_id(btf, map->btf_value_type_id);
9745 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
9746 	var_type = btf_type_by_id(btf, var->type);
9747 
9748 	/* finally update btf info */
9749 	datasec_type->size = size;
9750 	var->size = size - var->offset;
9751 	var_type->type = new_array_id;
9752 
9753 	return 0;
9754 }
9755 
9756 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
9757 {
9758 	if (map->fd >= 0)
9759 		return libbpf_err(-EBUSY);
9760 
9761 	if (map->mmaped) {
9762 		int err;
9763 		size_t mmap_old_sz, mmap_new_sz;
9764 
9765 		mmap_old_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
9766 		mmap_new_sz = bpf_map_mmap_sz(size, map->def.max_entries);
9767 		err = bpf_map_mmap_resize(map, mmap_old_sz, mmap_new_sz);
9768 		if (err) {
9769 			pr_warn("map '%s': failed to resize memory-mapped region: %d\n",
9770 				bpf_map__name(map), err);
9771 			return err;
9772 		}
9773 		err = map_btf_datasec_resize(map, size);
9774 		if (err && err != -ENOENT) {
9775 			pr_warn("map '%s': failed to adjust resized BTF, clearing BTF key/value info: %d\n",
9776 				bpf_map__name(map), err);
9777 			map->btf_value_type_id = 0;
9778 			map->btf_key_type_id = 0;
9779 		}
9780 	}
9781 
9782 	map->def.value_size = size;
9783 	return 0;
9784 }
9785 
9786 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
9787 {
9788 	return map ? map->btf_key_type_id : 0;
9789 }
9790 
9791 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
9792 {
9793 	return map ? map->btf_value_type_id : 0;
9794 }
9795 
9796 int bpf_map__set_initial_value(struct bpf_map *map,
9797 			       const void *data, size_t size)
9798 {
9799 	if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG ||
9800 	    size != map->def.value_size || map->fd >= 0)
9801 		return libbpf_err(-EINVAL);
9802 
9803 	memcpy(map->mmaped, data, size);
9804 	return 0;
9805 }
9806 
9807 void *bpf_map__initial_value(struct bpf_map *map, size_t *psize)
9808 {
9809 	if (!map->mmaped)
9810 		return NULL;
9811 	*psize = map->def.value_size;
9812 	return map->mmaped;
9813 }
9814 
9815 bool bpf_map__is_internal(const struct bpf_map *map)
9816 {
9817 	return map->libbpf_type != LIBBPF_MAP_UNSPEC;
9818 }
9819 
9820 __u32 bpf_map__ifindex(const struct bpf_map *map)
9821 {
9822 	return map->map_ifindex;
9823 }
9824 
9825 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
9826 {
9827 	if (map->fd >= 0)
9828 		return libbpf_err(-EBUSY);
9829 	map->map_ifindex = ifindex;
9830 	return 0;
9831 }
9832 
9833 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
9834 {
9835 	if (!bpf_map_type__is_map_in_map(map->def.type)) {
9836 		pr_warn("error: unsupported map type\n");
9837 		return libbpf_err(-EINVAL);
9838 	}
9839 	if (map->inner_map_fd != -1) {
9840 		pr_warn("error: inner_map_fd already specified\n");
9841 		return libbpf_err(-EINVAL);
9842 	}
9843 	if (map->inner_map) {
9844 		bpf_map__destroy(map->inner_map);
9845 		zfree(&map->inner_map);
9846 	}
9847 	map->inner_map_fd = fd;
9848 	return 0;
9849 }
9850 
9851 static struct bpf_map *
9852 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
9853 {
9854 	ssize_t idx;
9855 	struct bpf_map *s, *e;
9856 
9857 	if (!obj || !obj->maps)
9858 		return errno = EINVAL, NULL;
9859 
9860 	s = obj->maps;
9861 	e = obj->maps + obj->nr_maps;
9862 
9863 	if ((m < s) || (m >= e)) {
9864 		pr_warn("error in %s: map handler doesn't belong to object\n",
9865 			 __func__);
9866 		return errno = EINVAL, NULL;
9867 	}
9868 
9869 	idx = (m - obj->maps) + i;
9870 	if (idx >= obj->nr_maps || idx < 0)
9871 		return NULL;
9872 	return &obj->maps[idx];
9873 }
9874 
9875 struct bpf_map *
9876 bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
9877 {
9878 	if (prev == NULL)
9879 		return obj->maps;
9880 
9881 	return __bpf_map__iter(prev, obj, 1);
9882 }
9883 
9884 struct bpf_map *
9885 bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
9886 {
9887 	if (next == NULL) {
9888 		if (!obj->nr_maps)
9889 			return NULL;
9890 		return obj->maps + obj->nr_maps - 1;
9891 	}
9892 
9893 	return __bpf_map__iter(next, obj, -1);
9894 }
9895 
9896 struct bpf_map *
9897 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
9898 {
9899 	struct bpf_map *pos;
9900 
9901 	bpf_object__for_each_map(pos, obj) {
9902 		/* if it's a special internal map name (which always starts
9903 		 * with dot) then check if that special name matches the
9904 		 * real map name (ELF section name)
9905 		 */
9906 		if (name[0] == '.') {
9907 			if (pos->real_name && strcmp(pos->real_name, name) == 0)
9908 				return pos;
9909 			continue;
9910 		}
9911 		/* otherwise map name has to be an exact match */
9912 		if (map_uses_real_name(pos)) {
9913 			if (strcmp(pos->real_name, name) == 0)
9914 				return pos;
9915 			continue;
9916 		}
9917 		if (strcmp(pos->name, name) == 0)
9918 			return pos;
9919 	}
9920 	return errno = ENOENT, NULL;
9921 }
9922 
9923 int
9924 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
9925 {
9926 	return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
9927 }
9928 
9929 static int validate_map_op(const struct bpf_map *map, size_t key_sz,
9930 			   size_t value_sz, bool check_value_sz)
9931 {
9932 	if (map->fd <= 0)
9933 		return -ENOENT;
9934 
9935 	if (map->def.key_size != key_sz) {
9936 		pr_warn("map '%s': unexpected key size %zu provided, expected %u\n",
9937 			map->name, key_sz, map->def.key_size);
9938 		return -EINVAL;
9939 	}
9940 
9941 	if (!check_value_sz)
9942 		return 0;
9943 
9944 	switch (map->def.type) {
9945 	case BPF_MAP_TYPE_PERCPU_ARRAY:
9946 	case BPF_MAP_TYPE_PERCPU_HASH:
9947 	case BPF_MAP_TYPE_LRU_PERCPU_HASH:
9948 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: {
9949 		int num_cpu = libbpf_num_possible_cpus();
9950 		size_t elem_sz = roundup(map->def.value_size, 8);
9951 
9952 		if (value_sz != num_cpu * elem_sz) {
9953 			pr_warn("map '%s': unexpected value size %zu provided for per-CPU map, expected %d * %zu = %zd\n",
9954 				map->name, value_sz, num_cpu, elem_sz, num_cpu * elem_sz);
9955 			return -EINVAL;
9956 		}
9957 		break;
9958 	}
9959 	default:
9960 		if (map->def.value_size != value_sz) {
9961 			pr_warn("map '%s': unexpected value size %zu provided, expected %u\n",
9962 				map->name, value_sz, map->def.value_size);
9963 			return -EINVAL;
9964 		}
9965 		break;
9966 	}
9967 	return 0;
9968 }
9969 
9970 int bpf_map__lookup_elem(const struct bpf_map *map,
9971 			 const void *key, size_t key_sz,
9972 			 void *value, size_t value_sz, __u64 flags)
9973 {
9974 	int err;
9975 
9976 	err = validate_map_op(map, key_sz, value_sz, true);
9977 	if (err)
9978 		return libbpf_err(err);
9979 
9980 	return bpf_map_lookup_elem_flags(map->fd, key, value, flags);
9981 }
9982 
9983 int bpf_map__update_elem(const struct bpf_map *map,
9984 			 const void *key, size_t key_sz,
9985 			 const void *value, size_t value_sz, __u64 flags)
9986 {
9987 	int err;
9988 
9989 	err = validate_map_op(map, key_sz, value_sz, true);
9990 	if (err)
9991 		return libbpf_err(err);
9992 
9993 	return bpf_map_update_elem(map->fd, key, value, flags);
9994 }
9995 
9996 int bpf_map__delete_elem(const struct bpf_map *map,
9997 			 const void *key, size_t key_sz, __u64 flags)
9998 {
9999 	int err;
10000 
10001 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
10002 	if (err)
10003 		return libbpf_err(err);
10004 
10005 	return bpf_map_delete_elem_flags(map->fd, key, flags);
10006 }
10007 
10008 int bpf_map__lookup_and_delete_elem(const struct bpf_map *map,
10009 				    const void *key, size_t key_sz,
10010 				    void *value, size_t value_sz, __u64 flags)
10011 {
10012 	int err;
10013 
10014 	err = validate_map_op(map, key_sz, value_sz, true);
10015 	if (err)
10016 		return libbpf_err(err);
10017 
10018 	return bpf_map_lookup_and_delete_elem_flags(map->fd, key, value, flags);
10019 }
10020 
10021 int bpf_map__get_next_key(const struct bpf_map *map,
10022 			  const void *cur_key, void *next_key, size_t key_sz)
10023 {
10024 	int err;
10025 
10026 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
10027 	if (err)
10028 		return libbpf_err(err);
10029 
10030 	return bpf_map_get_next_key(map->fd, cur_key, next_key);
10031 }
10032 
10033 long libbpf_get_error(const void *ptr)
10034 {
10035 	if (!IS_ERR_OR_NULL(ptr))
10036 		return 0;
10037 
10038 	if (IS_ERR(ptr))
10039 		errno = -PTR_ERR(ptr);
10040 
10041 	/* If ptr == NULL, then errno should be already set by the failing
10042 	 * API, because libbpf never returns NULL on success and it now always
10043 	 * sets errno on error. So no extra errno handling for ptr == NULL
10044 	 * case.
10045 	 */
10046 	return -errno;
10047 }
10048 
10049 /* Replace link's underlying BPF program with the new one */
10050 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
10051 {
10052 	int ret;
10053 
10054 	ret = bpf_link_update(bpf_link__fd(link), bpf_program__fd(prog), NULL);
10055 	return libbpf_err_errno(ret);
10056 }
10057 
10058 /* Release "ownership" of underlying BPF resource (typically, BPF program
10059  * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
10060  * link, when destructed through bpf_link__destroy() call won't attempt to
10061  * detach/unregisted that BPF resource. This is useful in situations where,
10062  * say, attached BPF program has to outlive userspace program that attached it
10063  * in the system. Depending on type of BPF program, though, there might be
10064  * additional steps (like pinning BPF program in BPF FS) necessary to ensure
10065  * exit of userspace program doesn't trigger automatic detachment and clean up
10066  * inside the kernel.
10067  */
10068 void bpf_link__disconnect(struct bpf_link *link)
10069 {
10070 	link->disconnected = true;
10071 }
10072 
10073 int bpf_link__destroy(struct bpf_link *link)
10074 {
10075 	int err = 0;
10076 
10077 	if (IS_ERR_OR_NULL(link))
10078 		return 0;
10079 
10080 	if (!link->disconnected && link->detach)
10081 		err = link->detach(link);
10082 	if (link->pin_path)
10083 		free(link->pin_path);
10084 	if (link->dealloc)
10085 		link->dealloc(link);
10086 	else
10087 		free(link);
10088 
10089 	return libbpf_err(err);
10090 }
10091 
10092 int bpf_link__fd(const struct bpf_link *link)
10093 {
10094 	return link->fd;
10095 }
10096 
10097 const char *bpf_link__pin_path(const struct bpf_link *link)
10098 {
10099 	return link->pin_path;
10100 }
10101 
10102 static int bpf_link__detach_fd(struct bpf_link *link)
10103 {
10104 	return libbpf_err_errno(close(link->fd));
10105 }
10106 
10107 struct bpf_link *bpf_link__open(const char *path)
10108 {
10109 	struct bpf_link *link;
10110 	int fd;
10111 
10112 	fd = bpf_obj_get(path);
10113 	if (fd < 0) {
10114 		fd = -errno;
10115 		pr_warn("failed to open link at %s: %d\n", path, fd);
10116 		return libbpf_err_ptr(fd);
10117 	}
10118 
10119 	link = calloc(1, sizeof(*link));
10120 	if (!link) {
10121 		close(fd);
10122 		return libbpf_err_ptr(-ENOMEM);
10123 	}
10124 	link->detach = &bpf_link__detach_fd;
10125 	link->fd = fd;
10126 
10127 	link->pin_path = strdup(path);
10128 	if (!link->pin_path) {
10129 		bpf_link__destroy(link);
10130 		return libbpf_err_ptr(-ENOMEM);
10131 	}
10132 
10133 	return link;
10134 }
10135 
10136 int bpf_link__detach(struct bpf_link *link)
10137 {
10138 	return bpf_link_detach(link->fd) ? -errno : 0;
10139 }
10140 
10141 int bpf_link__pin(struct bpf_link *link, const char *path)
10142 {
10143 	int err;
10144 
10145 	if (link->pin_path)
10146 		return libbpf_err(-EBUSY);
10147 	err = make_parent_dir(path);
10148 	if (err)
10149 		return libbpf_err(err);
10150 	err = check_path(path);
10151 	if (err)
10152 		return libbpf_err(err);
10153 
10154 	link->pin_path = strdup(path);
10155 	if (!link->pin_path)
10156 		return libbpf_err(-ENOMEM);
10157 
10158 	if (bpf_obj_pin(link->fd, link->pin_path)) {
10159 		err = -errno;
10160 		zfree(&link->pin_path);
10161 		return libbpf_err(err);
10162 	}
10163 
10164 	pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
10165 	return 0;
10166 }
10167 
10168 int bpf_link__unpin(struct bpf_link *link)
10169 {
10170 	int err;
10171 
10172 	if (!link->pin_path)
10173 		return libbpf_err(-EINVAL);
10174 
10175 	err = unlink(link->pin_path);
10176 	if (err != 0)
10177 		return -errno;
10178 
10179 	pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
10180 	zfree(&link->pin_path);
10181 	return 0;
10182 }
10183 
10184 struct bpf_link_perf {
10185 	struct bpf_link link;
10186 	int perf_event_fd;
10187 	/* legacy kprobe support: keep track of probe identifier and type */
10188 	char *legacy_probe_name;
10189 	bool legacy_is_kprobe;
10190 	bool legacy_is_retprobe;
10191 };
10192 
10193 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
10194 static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
10195 
10196 static int bpf_link_perf_detach(struct bpf_link *link)
10197 {
10198 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10199 	int err = 0;
10200 
10201 	if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
10202 		err = -errno;
10203 
10204 	if (perf_link->perf_event_fd != link->fd)
10205 		close(perf_link->perf_event_fd);
10206 	close(link->fd);
10207 
10208 	/* legacy uprobe/kprobe needs to be removed after perf event fd closure */
10209 	if (perf_link->legacy_probe_name) {
10210 		if (perf_link->legacy_is_kprobe) {
10211 			err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
10212 							 perf_link->legacy_is_retprobe);
10213 		} else {
10214 			err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
10215 							 perf_link->legacy_is_retprobe);
10216 		}
10217 	}
10218 
10219 	return err;
10220 }
10221 
10222 static void bpf_link_perf_dealloc(struct bpf_link *link)
10223 {
10224 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10225 
10226 	free(perf_link->legacy_probe_name);
10227 	free(perf_link);
10228 }
10229 
10230 struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
10231 						     const struct bpf_perf_event_opts *opts)
10232 {
10233 	char errmsg[STRERR_BUFSIZE];
10234 	struct bpf_link_perf *link;
10235 	int prog_fd, link_fd = -1, err;
10236 	bool force_ioctl_attach;
10237 
10238 	if (!OPTS_VALID(opts, bpf_perf_event_opts))
10239 		return libbpf_err_ptr(-EINVAL);
10240 
10241 	if (pfd < 0) {
10242 		pr_warn("prog '%s': invalid perf event FD %d\n",
10243 			prog->name, pfd);
10244 		return libbpf_err_ptr(-EINVAL);
10245 	}
10246 	prog_fd = bpf_program__fd(prog);
10247 	if (prog_fd < 0) {
10248 		pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
10249 			prog->name);
10250 		return libbpf_err_ptr(-EINVAL);
10251 	}
10252 
10253 	link = calloc(1, sizeof(*link));
10254 	if (!link)
10255 		return libbpf_err_ptr(-ENOMEM);
10256 	link->link.detach = &bpf_link_perf_detach;
10257 	link->link.dealloc = &bpf_link_perf_dealloc;
10258 	link->perf_event_fd = pfd;
10259 
10260 	force_ioctl_attach = OPTS_GET(opts, force_ioctl_attach, false);
10261 	if (kernel_supports(prog->obj, FEAT_PERF_LINK) && !force_ioctl_attach) {
10262 		DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
10263 			.perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
10264 
10265 		link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
10266 		if (link_fd < 0) {
10267 			err = -errno;
10268 			pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %d (%s)\n",
10269 				prog->name, pfd,
10270 				err, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10271 			goto err_out;
10272 		}
10273 		link->link.fd = link_fd;
10274 	} else {
10275 		if (OPTS_GET(opts, bpf_cookie, 0)) {
10276 			pr_warn("prog '%s': user context value is not supported\n", prog->name);
10277 			err = -EOPNOTSUPP;
10278 			goto err_out;
10279 		}
10280 
10281 		if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
10282 			err = -errno;
10283 			pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
10284 				prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10285 			if (err == -EPROTO)
10286 				pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
10287 					prog->name, pfd);
10288 			goto err_out;
10289 		}
10290 		link->link.fd = pfd;
10291 	}
10292 	if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
10293 		err = -errno;
10294 		pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
10295 			prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10296 		goto err_out;
10297 	}
10298 
10299 	return &link->link;
10300 err_out:
10301 	if (link_fd >= 0)
10302 		close(link_fd);
10303 	free(link);
10304 	return libbpf_err_ptr(err);
10305 }
10306 
10307 struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
10308 {
10309 	return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
10310 }
10311 
10312 /*
10313  * this function is expected to parse integer in the range of [0, 2^31-1] from
10314  * given file using scanf format string fmt. If actual parsed value is
10315  * negative, the result might be indistinguishable from error
10316  */
10317 static int parse_uint_from_file(const char *file, const char *fmt)
10318 {
10319 	char buf[STRERR_BUFSIZE];
10320 	int err, ret;
10321 	FILE *f;
10322 
10323 	f = fopen(file, "re");
10324 	if (!f) {
10325 		err = -errno;
10326 		pr_debug("failed to open '%s': %s\n", file,
10327 			 libbpf_strerror_r(err, buf, sizeof(buf)));
10328 		return err;
10329 	}
10330 	err = fscanf(f, fmt, &ret);
10331 	if (err != 1) {
10332 		err = err == EOF ? -EIO : -errno;
10333 		pr_debug("failed to parse '%s': %s\n", file,
10334 			libbpf_strerror_r(err, buf, sizeof(buf)));
10335 		fclose(f);
10336 		return err;
10337 	}
10338 	fclose(f);
10339 	return ret;
10340 }
10341 
10342 static int determine_kprobe_perf_type(void)
10343 {
10344 	const char *file = "/sys/bus/event_source/devices/kprobe/type";
10345 
10346 	return parse_uint_from_file(file, "%d\n");
10347 }
10348 
10349 static int determine_uprobe_perf_type(void)
10350 {
10351 	const char *file = "/sys/bus/event_source/devices/uprobe/type";
10352 
10353 	return parse_uint_from_file(file, "%d\n");
10354 }
10355 
10356 static int determine_kprobe_retprobe_bit(void)
10357 {
10358 	const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
10359 
10360 	return parse_uint_from_file(file, "config:%d\n");
10361 }
10362 
10363 static int determine_uprobe_retprobe_bit(void)
10364 {
10365 	const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
10366 
10367 	return parse_uint_from_file(file, "config:%d\n");
10368 }
10369 
10370 #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
10371 #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
10372 
10373 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
10374 				 uint64_t offset, int pid, size_t ref_ctr_off)
10375 {
10376 	const size_t attr_sz = sizeof(struct perf_event_attr);
10377 	struct perf_event_attr attr;
10378 	char errmsg[STRERR_BUFSIZE];
10379 	int type, pfd;
10380 
10381 	if ((__u64)ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
10382 		return -EINVAL;
10383 
10384 	memset(&attr, 0, attr_sz);
10385 
10386 	type = uprobe ? determine_uprobe_perf_type()
10387 		      : determine_kprobe_perf_type();
10388 	if (type < 0) {
10389 		pr_warn("failed to determine %s perf type: %s\n",
10390 			uprobe ? "uprobe" : "kprobe",
10391 			libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
10392 		return type;
10393 	}
10394 	if (retprobe) {
10395 		int bit = uprobe ? determine_uprobe_retprobe_bit()
10396 				 : determine_kprobe_retprobe_bit();
10397 
10398 		if (bit < 0) {
10399 			pr_warn("failed to determine %s retprobe bit: %s\n",
10400 				uprobe ? "uprobe" : "kprobe",
10401 				libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
10402 			return bit;
10403 		}
10404 		attr.config |= 1 << bit;
10405 	}
10406 	attr.size = attr_sz;
10407 	attr.type = type;
10408 	attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
10409 	attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
10410 	attr.config2 = offset;		 /* kprobe_addr or probe_offset */
10411 
10412 	/* pid filter is meaningful only for uprobes */
10413 	pfd = syscall(__NR_perf_event_open, &attr,
10414 		      pid < 0 ? -1 : pid /* pid */,
10415 		      pid == -1 ? 0 : -1 /* cpu */,
10416 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
10417 	return pfd >= 0 ? pfd : -errno;
10418 }
10419 
10420 static int append_to_file(const char *file, const char *fmt, ...)
10421 {
10422 	int fd, n, err = 0;
10423 	va_list ap;
10424 	char buf[1024];
10425 
10426 	va_start(ap, fmt);
10427 	n = vsnprintf(buf, sizeof(buf), fmt, ap);
10428 	va_end(ap);
10429 
10430 	if (n < 0 || n >= sizeof(buf))
10431 		return -EINVAL;
10432 
10433 	fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
10434 	if (fd < 0)
10435 		return -errno;
10436 
10437 	if (write(fd, buf, n) < 0)
10438 		err = -errno;
10439 
10440 	close(fd);
10441 	return err;
10442 }
10443 
10444 #define DEBUGFS "/sys/kernel/debug/tracing"
10445 #define TRACEFS "/sys/kernel/tracing"
10446 
10447 static bool use_debugfs(void)
10448 {
10449 	static int has_debugfs = -1;
10450 
10451 	if (has_debugfs < 0)
10452 		has_debugfs = faccessat(AT_FDCWD, DEBUGFS, F_OK, AT_EACCESS) == 0;
10453 
10454 	return has_debugfs == 1;
10455 }
10456 
10457 static const char *tracefs_path(void)
10458 {
10459 	return use_debugfs() ? DEBUGFS : TRACEFS;
10460 }
10461 
10462 static const char *tracefs_kprobe_events(void)
10463 {
10464 	return use_debugfs() ? DEBUGFS"/kprobe_events" : TRACEFS"/kprobe_events";
10465 }
10466 
10467 static const char *tracefs_uprobe_events(void)
10468 {
10469 	return use_debugfs() ? DEBUGFS"/uprobe_events" : TRACEFS"/uprobe_events";
10470 }
10471 
10472 static const char *tracefs_available_filter_functions(void)
10473 {
10474 	return use_debugfs() ? DEBUGFS"/available_filter_functions"
10475 			     : TRACEFS"/available_filter_functions";
10476 }
10477 
10478 static const char *tracefs_available_filter_functions_addrs(void)
10479 {
10480 	return use_debugfs() ? DEBUGFS"/available_filter_functions_addrs"
10481 			     : TRACEFS"/available_filter_functions_addrs";
10482 }
10483 
10484 static void gen_kprobe_legacy_event_name(char *buf, size_t buf_sz,
10485 					 const char *kfunc_name, size_t offset)
10486 {
10487 	static int index = 0;
10488 	int i;
10489 
10490 	snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx_%d", getpid(), kfunc_name, offset,
10491 		 __sync_fetch_and_add(&index, 1));
10492 
10493 	/* sanitize binary_path in the probe name */
10494 	for (i = 0; buf[i]; i++) {
10495 		if (!isalnum(buf[i]))
10496 			buf[i] = '_';
10497 	}
10498 }
10499 
10500 static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
10501 				   const char *kfunc_name, size_t offset)
10502 {
10503 	return append_to_file(tracefs_kprobe_events(), "%c:%s/%s %s+0x%zx",
10504 			      retprobe ? 'r' : 'p',
10505 			      retprobe ? "kretprobes" : "kprobes",
10506 			      probe_name, kfunc_name, offset);
10507 }
10508 
10509 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
10510 {
10511 	return append_to_file(tracefs_kprobe_events(), "-:%s/%s",
10512 			      retprobe ? "kretprobes" : "kprobes", probe_name);
10513 }
10514 
10515 static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
10516 {
10517 	char file[256];
10518 
10519 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
10520 		 tracefs_path(), retprobe ? "kretprobes" : "kprobes", probe_name);
10521 
10522 	return parse_uint_from_file(file, "%d\n");
10523 }
10524 
10525 static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
10526 					 const char *kfunc_name, size_t offset, int pid)
10527 {
10528 	const size_t attr_sz = sizeof(struct perf_event_attr);
10529 	struct perf_event_attr attr;
10530 	char errmsg[STRERR_BUFSIZE];
10531 	int type, pfd, err;
10532 
10533 	err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
10534 	if (err < 0) {
10535 		pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
10536 			kfunc_name, offset,
10537 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10538 		return err;
10539 	}
10540 	type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
10541 	if (type < 0) {
10542 		err = type;
10543 		pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
10544 			kfunc_name, offset,
10545 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10546 		goto err_clean_legacy;
10547 	}
10548 
10549 	memset(&attr, 0, attr_sz);
10550 	attr.size = attr_sz;
10551 	attr.config = type;
10552 	attr.type = PERF_TYPE_TRACEPOINT;
10553 
10554 	pfd = syscall(__NR_perf_event_open, &attr,
10555 		      pid < 0 ? -1 : pid, /* pid */
10556 		      pid == -1 ? 0 : -1, /* cpu */
10557 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
10558 	if (pfd < 0) {
10559 		err = -errno;
10560 		pr_warn("legacy kprobe perf_event_open() failed: %s\n",
10561 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10562 		goto err_clean_legacy;
10563 	}
10564 	return pfd;
10565 
10566 err_clean_legacy:
10567 	/* Clear the newly added legacy kprobe_event */
10568 	remove_kprobe_event_legacy(probe_name, retprobe);
10569 	return err;
10570 }
10571 
10572 static const char *arch_specific_syscall_pfx(void)
10573 {
10574 #if defined(__x86_64__)
10575 	return "x64";
10576 #elif defined(__i386__)
10577 	return "ia32";
10578 #elif defined(__s390x__)
10579 	return "s390x";
10580 #elif defined(__s390__)
10581 	return "s390";
10582 #elif defined(__arm__)
10583 	return "arm";
10584 #elif defined(__aarch64__)
10585 	return "arm64";
10586 #elif defined(__mips__)
10587 	return "mips";
10588 #elif defined(__riscv)
10589 	return "riscv";
10590 #elif defined(__powerpc__)
10591 	return "powerpc";
10592 #elif defined(__powerpc64__)
10593 	return "powerpc64";
10594 #else
10595 	return NULL;
10596 #endif
10597 }
10598 
10599 static int probe_kern_syscall_wrapper(void)
10600 {
10601 	char syscall_name[64];
10602 	const char *ksys_pfx;
10603 
10604 	ksys_pfx = arch_specific_syscall_pfx();
10605 	if (!ksys_pfx)
10606 		return 0;
10607 
10608 	snprintf(syscall_name, sizeof(syscall_name), "__%s_sys_bpf", ksys_pfx);
10609 
10610 	if (determine_kprobe_perf_type() >= 0) {
10611 		int pfd;
10612 
10613 		pfd = perf_event_open_probe(false, false, syscall_name, 0, getpid(), 0);
10614 		if (pfd >= 0)
10615 			close(pfd);
10616 
10617 		return pfd >= 0 ? 1 : 0;
10618 	} else { /* legacy mode */
10619 		char probe_name[128];
10620 
10621 		gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name), syscall_name, 0);
10622 		if (add_kprobe_event_legacy(probe_name, false, syscall_name, 0) < 0)
10623 			return 0;
10624 
10625 		(void)remove_kprobe_event_legacy(probe_name, false);
10626 		return 1;
10627 	}
10628 }
10629 
10630 struct bpf_link *
10631 bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
10632 				const char *func_name,
10633 				const struct bpf_kprobe_opts *opts)
10634 {
10635 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
10636 	enum probe_attach_mode attach_mode;
10637 	char errmsg[STRERR_BUFSIZE];
10638 	char *legacy_probe = NULL;
10639 	struct bpf_link *link;
10640 	size_t offset;
10641 	bool retprobe, legacy;
10642 	int pfd, err;
10643 
10644 	if (!OPTS_VALID(opts, bpf_kprobe_opts))
10645 		return libbpf_err_ptr(-EINVAL);
10646 
10647 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
10648 	retprobe = OPTS_GET(opts, retprobe, false);
10649 	offset = OPTS_GET(opts, offset, 0);
10650 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10651 
10652 	legacy = determine_kprobe_perf_type() < 0;
10653 	switch (attach_mode) {
10654 	case PROBE_ATTACH_MODE_LEGACY:
10655 		legacy = true;
10656 		pe_opts.force_ioctl_attach = true;
10657 		break;
10658 	case PROBE_ATTACH_MODE_PERF:
10659 		if (legacy)
10660 			return libbpf_err_ptr(-ENOTSUP);
10661 		pe_opts.force_ioctl_attach = true;
10662 		break;
10663 	case PROBE_ATTACH_MODE_LINK:
10664 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
10665 			return libbpf_err_ptr(-ENOTSUP);
10666 		break;
10667 	case PROBE_ATTACH_MODE_DEFAULT:
10668 		break;
10669 	default:
10670 		return libbpf_err_ptr(-EINVAL);
10671 	}
10672 
10673 	if (!legacy) {
10674 		pfd = perf_event_open_probe(false /* uprobe */, retprobe,
10675 					    func_name, offset,
10676 					    -1 /* pid */, 0 /* ref_ctr_off */);
10677 	} else {
10678 		char probe_name[256];
10679 
10680 		gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name),
10681 					     func_name, offset);
10682 
10683 		legacy_probe = strdup(probe_name);
10684 		if (!legacy_probe)
10685 			return libbpf_err_ptr(-ENOMEM);
10686 
10687 		pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
10688 						    offset, -1 /* pid */);
10689 	}
10690 	if (pfd < 0) {
10691 		err = -errno;
10692 		pr_warn("prog '%s': failed to create %s '%s+0x%zx' perf event: %s\n",
10693 			prog->name, retprobe ? "kretprobe" : "kprobe",
10694 			func_name, offset,
10695 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10696 		goto err_out;
10697 	}
10698 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
10699 	err = libbpf_get_error(link);
10700 	if (err) {
10701 		close(pfd);
10702 		pr_warn("prog '%s': failed to attach to %s '%s+0x%zx': %s\n",
10703 			prog->name, retprobe ? "kretprobe" : "kprobe",
10704 			func_name, offset,
10705 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10706 		goto err_clean_legacy;
10707 	}
10708 	if (legacy) {
10709 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10710 
10711 		perf_link->legacy_probe_name = legacy_probe;
10712 		perf_link->legacy_is_kprobe = true;
10713 		perf_link->legacy_is_retprobe = retprobe;
10714 	}
10715 
10716 	return link;
10717 
10718 err_clean_legacy:
10719 	if (legacy)
10720 		remove_kprobe_event_legacy(legacy_probe, retprobe);
10721 err_out:
10722 	free(legacy_probe);
10723 	return libbpf_err_ptr(err);
10724 }
10725 
10726 struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
10727 					    bool retprobe,
10728 					    const char *func_name)
10729 {
10730 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
10731 		.retprobe = retprobe,
10732 	);
10733 
10734 	return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
10735 }
10736 
10737 struct bpf_link *bpf_program__attach_ksyscall(const struct bpf_program *prog,
10738 					      const char *syscall_name,
10739 					      const struct bpf_ksyscall_opts *opts)
10740 {
10741 	LIBBPF_OPTS(bpf_kprobe_opts, kprobe_opts);
10742 	char func_name[128];
10743 
10744 	if (!OPTS_VALID(opts, bpf_ksyscall_opts))
10745 		return libbpf_err_ptr(-EINVAL);
10746 
10747 	if (kernel_supports(prog->obj, FEAT_SYSCALL_WRAPPER)) {
10748 		/* arch_specific_syscall_pfx() should never return NULL here
10749 		 * because it is guarded by kernel_supports(). However, since
10750 		 * compiler does not know that we have an explicit conditional
10751 		 * as well.
10752 		 */
10753 		snprintf(func_name, sizeof(func_name), "__%s_sys_%s",
10754 			 arch_specific_syscall_pfx() ? : "", syscall_name);
10755 	} else {
10756 		snprintf(func_name, sizeof(func_name), "__se_sys_%s", syscall_name);
10757 	}
10758 
10759 	kprobe_opts.retprobe = OPTS_GET(opts, retprobe, false);
10760 	kprobe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10761 
10762 	return bpf_program__attach_kprobe_opts(prog, func_name, &kprobe_opts);
10763 }
10764 
10765 /* Adapted from perf/util/string.c */
10766 bool glob_match(const char *str, const char *pat)
10767 {
10768 	while (*str && *pat && *pat != '*') {
10769 		if (*pat == '?') {      /* Matches any single character */
10770 			str++;
10771 			pat++;
10772 			continue;
10773 		}
10774 		if (*str != *pat)
10775 			return false;
10776 		str++;
10777 		pat++;
10778 	}
10779 	/* Check wild card */
10780 	if (*pat == '*') {
10781 		while (*pat == '*')
10782 			pat++;
10783 		if (!*pat) /* Tail wild card matches all */
10784 			return true;
10785 		while (*str)
10786 			if (glob_match(str++, pat))
10787 				return true;
10788 	}
10789 	return !*str && !*pat;
10790 }
10791 
10792 struct kprobe_multi_resolve {
10793 	const char *pattern;
10794 	unsigned long *addrs;
10795 	size_t cap;
10796 	size_t cnt;
10797 };
10798 
10799 struct avail_kallsyms_data {
10800 	char **syms;
10801 	size_t cnt;
10802 	struct kprobe_multi_resolve *res;
10803 };
10804 
10805 static int avail_func_cmp(const void *a, const void *b)
10806 {
10807 	return strcmp(*(const char **)a, *(const char **)b);
10808 }
10809 
10810 static int avail_kallsyms_cb(unsigned long long sym_addr, char sym_type,
10811 			     const char *sym_name, void *ctx)
10812 {
10813 	struct avail_kallsyms_data *data = ctx;
10814 	struct kprobe_multi_resolve *res = data->res;
10815 	int err;
10816 
10817 	if (!bsearch(&sym_name, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp))
10818 		return 0;
10819 
10820 	err = libbpf_ensure_mem((void **)&res->addrs, &res->cap, sizeof(*res->addrs), res->cnt + 1);
10821 	if (err)
10822 		return err;
10823 
10824 	res->addrs[res->cnt++] = (unsigned long)sym_addr;
10825 	return 0;
10826 }
10827 
10828 static int libbpf_available_kallsyms_parse(struct kprobe_multi_resolve *res)
10829 {
10830 	const char *available_functions_file = tracefs_available_filter_functions();
10831 	struct avail_kallsyms_data data;
10832 	char sym_name[500];
10833 	FILE *f;
10834 	int err = 0, ret, i;
10835 	char **syms = NULL;
10836 	size_t cap = 0, cnt = 0;
10837 
10838 	f = fopen(available_functions_file, "re");
10839 	if (!f) {
10840 		err = -errno;
10841 		pr_warn("failed to open %s: %d\n", available_functions_file, err);
10842 		return err;
10843 	}
10844 
10845 	while (true) {
10846 		char *name;
10847 
10848 		ret = fscanf(f, "%499s%*[^\n]\n", sym_name);
10849 		if (ret == EOF && feof(f))
10850 			break;
10851 
10852 		if (ret != 1) {
10853 			pr_warn("failed to parse available_filter_functions entry: %d\n", ret);
10854 			err = -EINVAL;
10855 			goto cleanup;
10856 		}
10857 
10858 		if (!glob_match(sym_name, res->pattern))
10859 			continue;
10860 
10861 		err = libbpf_ensure_mem((void **)&syms, &cap, sizeof(*syms), cnt + 1);
10862 		if (err)
10863 			goto cleanup;
10864 
10865 		name = strdup(sym_name);
10866 		if (!name) {
10867 			err = -errno;
10868 			goto cleanup;
10869 		}
10870 
10871 		syms[cnt++] = name;
10872 	}
10873 
10874 	/* no entries found, bail out */
10875 	if (cnt == 0) {
10876 		err = -ENOENT;
10877 		goto cleanup;
10878 	}
10879 
10880 	/* sort available functions */
10881 	qsort(syms, cnt, sizeof(*syms), avail_func_cmp);
10882 
10883 	data.syms = syms;
10884 	data.res = res;
10885 	data.cnt = cnt;
10886 	libbpf_kallsyms_parse(avail_kallsyms_cb, &data);
10887 
10888 	if (res->cnt == 0)
10889 		err = -ENOENT;
10890 
10891 cleanup:
10892 	for (i = 0; i < cnt; i++)
10893 		free((char *)syms[i]);
10894 	free(syms);
10895 
10896 	fclose(f);
10897 	return err;
10898 }
10899 
10900 static bool has_available_filter_functions_addrs(void)
10901 {
10902 	return access(tracefs_available_filter_functions_addrs(), R_OK) != -1;
10903 }
10904 
10905 static int libbpf_available_kprobes_parse(struct kprobe_multi_resolve *res)
10906 {
10907 	const char *available_path = tracefs_available_filter_functions_addrs();
10908 	char sym_name[500];
10909 	FILE *f;
10910 	int ret, err = 0;
10911 	unsigned long long sym_addr;
10912 
10913 	f = fopen(available_path, "re");
10914 	if (!f) {
10915 		err = -errno;
10916 		pr_warn("failed to open %s: %d\n", available_path, err);
10917 		return err;
10918 	}
10919 
10920 	while (true) {
10921 		ret = fscanf(f, "%llx %499s%*[^\n]\n", &sym_addr, sym_name);
10922 		if (ret == EOF && feof(f))
10923 			break;
10924 
10925 		if (ret != 2) {
10926 			pr_warn("failed to parse available_filter_functions_addrs entry: %d\n",
10927 				ret);
10928 			err = -EINVAL;
10929 			goto cleanup;
10930 		}
10931 
10932 		if (!glob_match(sym_name, res->pattern))
10933 			continue;
10934 
10935 		err = libbpf_ensure_mem((void **)&res->addrs, &res->cap,
10936 					sizeof(*res->addrs), res->cnt + 1);
10937 		if (err)
10938 			goto cleanup;
10939 
10940 		res->addrs[res->cnt++] = (unsigned long)sym_addr;
10941 	}
10942 
10943 	if (res->cnt == 0)
10944 		err = -ENOENT;
10945 
10946 cleanup:
10947 	fclose(f);
10948 	return err;
10949 }
10950 
10951 struct bpf_link *
10952 bpf_program__attach_kprobe_multi_opts(const struct bpf_program *prog,
10953 				      const char *pattern,
10954 				      const struct bpf_kprobe_multi_opts *opts)
10955 {
10956 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
10957 	struct kprobe_multi_resolve res = {
10958 		.pattern = pattern,
10959 	};
10960 	struct bpf_link *link = NULL;
10961 	char errmsg[STRERR_BUFSIZE];
10962 	const unsigned long *addrs;
10963 	int err, link_fd, prog_fd;
10964 	const __u64 *cookies;
10965 	const char **syms;
10966 	bool retprobe;
10967 	size_t cnt;
10968 
10969 	if (!OPTS_VALID(opts, bpf_kprobe_multi_opts))
10970 		return libbpf_err_ptr(-EINVAL);
10971 
10972 	syms    = OPTS_GET(opts, syms, false);
10973 	addrs   = OPTS_GET(opts, addrs, false);
10974 	cnt     = OPTS_GET(opts, cnt, false);
10975 	cookies = OPTS_GET(opts, cookies, false);
10976 
10977 	if (!pattern && !addrs && !syms)
10978 		return libbpf_err_ptr(-EINVAL);
10979 	if (pattern && (addrs || syms || cookies || cnt))
10980 		return libbpf_err_ptr(-EINVAL);
10981 	if (!pattern && !cnt)
10982 		return libbpf_err_ptr(-EINVAL);
10983 	if (addrs && syms)
10984 		return libbpf_err_ptr(-EINVAL);
10985 
10986 	if (pattern) {
10987 		if (has_available_filter_functions_addrs())
10988 			err = libbpf_available_kprobes_parse(&res);
10989 		else
10990 			err = libbpf_available_kallsyms_parse(&res);
10991 		if (err)
10992 			goto error;
10993 		addrs = res.addrs;
10994 		cnt = res.cnt;
10995 	}
10996 
10997 	retprobe = OPTS_GET(opts, retprobe, false);
10998 
10999 	lopts.kprobe_multi.syms = syms;
11000 	lopts.kprobe_multi.addrs = addrs;
11001 	lopts.kprobe_multi.cookies = cookies;
11002 	lopts.kprobe_multi.cnt = cnt;
11003 	lopts.kprobe_multi.flags = retprobe ? BPF_F_KPROBE_MULTI_RETURN : 0;
11004 
11005 	link = calloc(1, sizeof(*link));
11006 	if (!link) {
11007 		err = -ENOMEM;
11008 		goto error;
11009 	}
11010 	link->detach = &bpf_link__detach_fd;
11011 
11012 	prog_fd = bpf_program__fd(prog);
11013 	link_fd = bpf_link_create(prog_fd, 0, BPF_TRACE_KPROBE_MULTI, &lopts);
11014 	if (link_fd < 0) {
11015 		err = -errno;
11016 		pr_warn("prog '%s': failed to attach: %s\n",
11017 			prog->name, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11018 		goto error;
11019 	}
11020 	link->fd = link_fd;
11021 	free(res.addrs);
11022 	return link;
11023 
11024 error:
11025 	free(link);
11026 	free(res.addrs);
11027 	return libbpf_err_ptr(err);
11028 }
11029 
11030 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11031 {
11032 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
11033 	unsigned long offset = 0;
11034 	const char *func_name;
11035 	char *func;
11036 	int n;
11037 
11038 	*link = NULL;
11039 
11040 	/* no auto-attach for SEC("kprobe") and SEC("kretprobe") */
11041 	if (strcmp(prog->sec_name, "kprobe") == 0 || strcmp(prog->sec_name, "kretprobe") == 0)
11042 		return 0;
11043 
11044 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
11045 	if (opts.retprobe)
11046 		func_name = prog->sec_name + sizeof("kretprobe/") - 1;
11047 	else
11048 		func_name = prog->sec_name + sizeof("kprobe/") - 1;
11049 
11050 	n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
11051 	if (n < 1) {
11052 		pr_warn("kprobe name is invalid: %s\n", func_name);
11053 		return -EINVAL;
11054 	}
11055 	if (opts.retprobe && offset != 0) {
11056 		free(func);
11057 		pr_warn("kretprobes do not support offset specification\n");
11058 		return -EINVAL;
11059 	}
11060 
11061 	opts.offset = offset;
11062 	*link = bpf_program__attach_kprobe_opts(prog, func, &opts);
11063 	free(func);
11064 	return libbpf_get_error(*link);
11065 }
11066 
11067 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11068 {
11069 	LIBBPF_OPTS(bpf_ksyscall_opts, opts);
11070 	const char *syscall_name;
11071 
11072 	*link = NULL;
11073 
11074 	/* no auto-attach for SEC("ksyscall") and SEC("kretsyscall") */
11075 	if (strcmp(prog->sec_name, "ksyscall") == 0 || strcmp(prog->sec_name, "kretsyscall") == 0)
11076 		return 0;
11077 
11078 	opts.retprobe = str_has_pfx(prog->sec_name, "kretsyscall/");
11079 	if (opts.retprobe)
11080 		syscall_name = prog->sec_name + sizeof("kretsyscall/") - 1;
11081 	else
11082 		syscall_name = prog->sec_name + sizeof("ksyscall/") - 1;
11083 
11084 	*link = bpf_program__attach_ksyscall(prog, syscall_name, &opts);
11085 	return *link ? 0 : -errno;
11086 }
11087 
11088 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11089 {
11090 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts);
11091 	const char *spec;
11092 	char *pattern;
11093 	int n;
11094 
11095 	*link = NULL;
11096 
11097 	/* no auto-attach for SEC("kprobe.multi") and SEC("kretprobe.multi") */
11098 	if (strcmp(prog->sec_name, "kprobe.multi") == 0 ||
11099 	    strcmp(prog->sec_name, "kretprobe.multi") == 0)
11100 		return 0;
11101 
11102 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe.multi/");
11103 	if (opts.retprobe)
11104 		spec = prog->sec_name + sizeof("kretprobe.multi/") - 1;
11105 	else
11106 		spec = prog->sec_name + sizeof("kprobe.multi/") - 1;
11107 
11108 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
11109 	if (n < 1) {
11110 		pr_warn("kprobe multi pattern is invalid: %s\n", pattern);
11111 		return -EINVAL;
11112 	}
11113 
11114 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
11115 	free(pattern);
11116 	return libbpf_get_error(*link);
11117 }
11118 
11119 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11120 {
11121 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
11122 	LIBBPF_OPTS(bpf_uprobe_multi_opts, opts);
11123 	int n, ret = -EINVAL;
11124 
11125 	*link = NULL;
11126 
11127 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
11128 		   &probe_type, &binary_path, &func_name);
11129 	switch (n) {
11130 	case 1:
11131 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
11132 		ret = 0;
11133 		break;
11134 	case 3:
11135 		opts.retprobe = strcmp(probe_type, "uretprobe.multi") == 0;
11136 		*link = bpf_program__attach_uprobe_multi(prog, -1, binary_path, func_name, &opts);
11137 		ret = libbpf_get_error(*link);
11138 		break;
11139 	default:
11140 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
11141 			prog->sec_name);
11142 		break;
11143 	}
11144 	free(probe_type);
11145 	free(binary_path);
11146 	free(func_name);
11147 	return ret;
11148 }
11149 
11150 static void gen_uprobe_legacy_event_name(char *buf, size_t buf_sz,
11151 					 const char *binary_path, uint64_t offset)
11152 {
11153 	int i;
11154 
11155 	snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx", getpid(), binary_path, (size_t)offset);
11156 
11157 	/* sanitize binary_path in the probe name */
11158 	for (i = 0; buf[i]; i++) {
11159 		if (!isalnum(buf[i]))
11160 			buf[i] = '_';
11161 	}
11162 }
11163 
11164 static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
11165 					  const char *binary_path, size_t offset)
11166 {
11167 	return append_to_file(tracefs_uprobe_events(), "%c:%s/%s %s:0x%zx",
11168 			      retprobe ? 'r' : 'p',
11169 			      retprobe ? "uretprobes" : "uprobes",
11170 			      probe_name, binary_path, offset);
11171 }
11172 
11173 static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
11174 {
11175 	return append_to_file(tracefs_uprobe_events(), "-:%s/%s",
11176 			      retprobe ? "uretprobes" : "uprobes", probe_name);
11177 }
11178 
11179 static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
11180 {
11181 	char file[512];
11182 
11183 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11184 		 tracefs_path(), retprobe ? "uretprobes" : "uprobes", probe_name);
11185 
11186 	return parse_uint_from_file(file, "%d\n");
11187 }
11188 
11189 static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
11190 					 const char *binary_path, size_t offset, int pid)
11191 {
11192 	const size_t attr_sz = sizeof(struct perf_event_attr);
11193 	struct perf_event_attr attr;
11194 	int type, pfd, err;
11195 
11196 	err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
11197 	if (err < 0) {
11198 		pr_warn("failed to add legacy uprobe event for %s:0x%zx: %d\n",
11199 			binary_path, (size_t)offset, err);
11200 		return err;
11201 	}
11202 	type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
11203 	if (type < 0) {
11204 		err = type;
11205 		pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %d\n",
11206 			binary_path, offset, err);
11207 		goto err_clean_legacy;
11208 	}
11209 
11210 	memset(&attr, 0, attr_sz);
11211 	attr.size = attr_sz;
11212 	attr.config = type;
11213 	attr.type = PERF_TYPE_TRACEPOINT;
11214 
11215 	pfd = syscall(__NR_perf_event_open, &attr,
11216 		      pid < 0 ? -1 : pid, /* pid */
11217 		      pid == -1 ? 0 : -1, /* cpu */
11218 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
11219 	if (pfd < 0) {
11220 		err = -errno;
11221 		pr_warn("legacy uprobe perf_event_open() failed: %d\n", err);
11222 		goto err_clean_legacy;
11223 	}
11224 	return pfd;
11225 
11226 err_clean_legacy:
11227 	/* Clear the newly added legacy uprobe_event */
11228 	remove_uprobe_event_legacy(probe_name, retprobe);
11229 	return err;
11230 }
11231 
11232 /* Find offset of function name in archive specified by path. Currently
11233  * supported are .zip files that do not compress their contents, as used on
11234  * Android in the form of APKs, for example. "file_name" is the name of the ELF
11235  * file inside the archive. "func_name" matches symbol name or name@@LIB for
11236  * library functions.
11237  *
11238  * An overview of the APK format specifically provided here:
11239  * https://en.wikipedia.org/w/index.php?title=Apk_(file_format)&oldid=1139099120#Package_contents
11240  */
11241 static long elf_find_func_offset_from_archive(const char *archive_path, const char *file_name,
11242 					      const char *func_name)
11243 {
11244 	struct zip_archive *archive;
11245 	struct zip_entry entry;
11246 	long ret;
11247 	Elf *elf;
11248 
11249 	archive = zip_archive_open(archive_path);
11250 	if (IS_ERR(archive)) {
11251 		ret = PTR_ERR(archive);
11252 		pr_warn("zip: failed to open %s: %ld\n", archive_path, ret);
11253 		return ret;
11254 	}
11255 
11256 	ret = zip_archive_find_entry(archive, file_name, &entry);
11257 	if (ret) {
11258 		pr_warn("zip: could not find archive member %s in %s: %ld\n", file_name,
11259 			archive_path, ret);
11260 		goto out;
11261 	}
11262 	pr_debug("zip: found entry for %s in %s at 0x%lx\n", file_name, archive_path,
11263 		 (unsigned long)entry.data_offset);
11264 
11265 	if (entry.compression) {
11266 		pr_warn("zip: entry %s of %s is compressed and cannot be handled\n", file_name,
11267 			archive_path);
11268 		ret = -LIBBPF_ERRNO__FORMAT;
11269 		goto out;
11270 	}
11271 
11272 	elf = elf_memory((void *)entry.data, entry.data_length);
11273 	if (!elf) {
11274 		pr_warn("elf: could not read elf file %s from %s: %s\n", file_name, archive_path,
11275 			elf_errmsg(-1));
11276 		ret = -LIBBPF_ERRNO__LIBELF;
11277 		goto out;
11278 	}
11279 
11280 	ret = elf_find_func_offset(elf, file_name, func_name);
11281 	if (ret > 0) {
11282 		pr_debug("elf: symbol address match for %s of %s in %s: 0x%x + 0x%lx = 0x%lx\n",
11283 			 func_name, file_name, archive_path, entry.data_offset, ret,
11284 			 ret + entry.data_offset);
11285 		ret += entry.data_offset;
11286 	}
11287 	elf_end(elf);
11288 
11289 out:
11290 	zip_archive_close(archive);
11291 	return ret;
11292 }
11293 
11294 static const char *arch_specific_lib_paths(void)
11295 {
11296 	/*
11297 	 * Based on https://packages.debian.org/sid/libc6.
11298 	 *
11299 	 * Assume that the traced program is built for the same architecture
11300 	 * as libbpf, which should cover the vast majority of cases.
11301 	 */
11302 #if defined(__x86_64__)
11303 	return "/lib/x86_64-linux-gnu";
11304 #elif defined(__i386__)
11305 	return "/lib/i386-linux-gnu";
11306 #elif defined(__s390x__)
11307 	return "/lib/s390x-linux-gnu";
11308 #elif defined(__s390__)
11309 	return "/lib/s390-linux-gnu";
11310 #elif defined(__arm__) && defined(__SOFTFP__)
11311 	return "/lib/arm-linux-gnueabi";
11312 #elif defined(__arm__) && !defined(__SOFTFP__)
11313 	return "/lib/arm-linux-gnueabihf";
11314 #elif defined(__aarch64__)
11315 	return "/lib/aarch64-linux-gnu";
11316 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 64
11317 	return "/lib/mips64el-linux-gnuabi64";
11318 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 32
11319 	return "/lib/mipsel-linux-gnu";
11320 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
11321 	return "/lib/powerpc64le-linux-gnu";
11322 #elif defined(__sparc__) && defined(__arch64__)
11323 	return "/lib/sparc64-linux-gnu";
11324 #elif defined(__riscv) && __riscv_xlen == 64
11325 	return "/lib/riscv64-linux-gnu";
11326 #else
11327 	return NULL;
11328 #endif
11329 }
11330 
11331 /* Get full path to program/shared library. */
11332 static int resolve_full_path(const char *file, char *result, size_t result_sz)
11333 {
11334 	const char *search_paths[3] = {};
11335 	int i, perm;
11336 
11337 	if (str_has_sfx(file, ".so") || strstr(file, ".so.")) {
11338 		search_paths[0] = getenv("LD_LIBRARY_PATH");
11339 		search_paths[1] = "/usr/lib64:/usr/lib";
11340 		search_paths[2] = arch_specific_lib_paths();
11341 		perm = R_OK;
11342 	} else {
11343 		search_paths[0] = getenv("PATH");
11344 		search_paths[1] = "/usr/bin:/usr/sbin";
11345 		perm = R_OK | X_OK;
11346 	}
11347 
11348 	for (i = 0; i < ARRAY_SIZE(search_paths); i++) {
11349 		const char *s;
11350 
11351 		if (!search_paths[i])
11352 			continue;
11353 		for (s = search_paths[i]; s != NULL; s = strchr(s, ':')) {
11354 			char *next_path;
11355 			int seg_len;
11356 
11357 			if (s[0] == ':')
11358 				s++;
11359 			next_path = strchr(s, ':');
11360 			seg_len = next_path ? next_path - s : strlen(s);
11361 			if (!seg_len)
11362 				continue;
11363 			snprintf(result, result_sz, "%.*s/%s", seg_len, s, file);
11364 			/* ensure it has required permissions */
11365 			if (faccessat(AT_FDCWD, result, perm, AT_EACCESS) < 0)
11366 				continue;
11367 			pr_debug("resolved '%s' to '%s'\n", file, result);
11368 			return 0;
11369 		}
11370 	}
11371 	return -ENOENT;
11372 }
11373 
11374 struct bpf_link *
11375 bpf_program__attach_uprobe_multi(const struct bpf_program *prog,
11376 				 pid_t pid,
11377 				 const char *path,
11378 				 const char *func_pattern,
11379 				 const struct bpf_uprobe_multi_opts *opts)
11380 {
11381 	const unsigned long *ref_ctr_offsets = NULL, *offsets = NULL;
11382 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
11383 	unsigned long *resolved_offsets = NULL;
11384 	int err = 0, link_fd, prog_fd;
11385 	struct bpf_link *link = NULL;
11386 	char errmsg[STRERR_BUFSIZE];
11387 	char full_path[PATH_MAX];
11388 	const __u64 *cookies;
11389 	const char **syms;
11390 	size_t cnt;
11391 
11392 	if (!OPTS_VALID(opts, bpf_uprobe_multi_opts))
11393 		return libbpf_err_ptr(-EINVAL);
11394 
11395 	syms = OPTS_GET(opts, syms, NULL);
11396 	offsets = OPTS_GET(opts, offsets, NULL);
11397 	ref_ctr_offsets = OPTS_GET(opts, ref_ctr_offsets, NULL);
11398 	cookies = OPTS_GET(opts, cookies, NULL);
11399 	cnt = OPTS_GET(opts, cnt, 0);
11400 
11401 	/*
11402 	 * User can specify 2 mutually exclusive set of inputs:
11403 	 *
11404 	 * 1) use only path/func_pattern/pid arguments
11405 	 *
11406 	 * 2) use path/pid with allowed combinations of:
11407 	 *    syms/offsets/ref_ctr_offsets/cookies/cnt
11408 	 *
11409 	 *    - syms and offsets are mutually exclusive
11410 	 *    - ref_ctr_offsets and cookies are optional
11411 	 *
11412 	 * Any other usage results in error.
11413 	 */
11414 
11415 	if (!path)
11416 		return libbpf_err_ptr(-EINVAL);
11417 	if (!func_pattern && cnt == 0)
11418 		return libbpf_err_ptr(-EINVAL);
11419 
11420 	if (func_pattern) {
11421 		if (syms || offsets || ref_ctr_offsets || cookies || cnt)
11422 			return libbpf_err_ptr(-EINVAL);
11423 	} else {
11424 		if (!!syms == !!offsets)
11425 			return libbpf_err_ptr(-EINVAL);
11426 	}
11427 
11428 	if (func_pattern) {
11429 		if (!strchr(path, '/')) {
11430 			err = resolve_full_path(path, full_path, sizeof(full_path));
11431 			if (err) {
11432 				pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11433 					prog->name, path, err);
11434 				return libbpf_err_ptr(err);
11435 			}
11436 			path = full_path;
11437 		}
11438 
11439 		err = elf_resolve_pattern_offsets(path, func_pattern,
11440 						  &resolved_offsets, &cnt);
11441 		if (err < 0)
11442 			return libbpf_err_ptr(err);
11443 		offsets = resolved_offsets;
11444 	} else if (syms) {
11445 		err = elf_resolve_syms_offsets(path, cnt, syms, &resolved_offsets);
11446 		if (err < 0)
11447 			return libbpf_err_ptr(err);
11448 		offsets = resolved_offsets;
11449 	}
11450 
11451 	lopts.uprobe_multi.path = path;
11452 	lopts.uprobe_multi.offsets = offsets;
11453 	lopts.uprobe_multi.ref_ctr_offsets = ref_ctr_offsets;
11454 	lopts.uprobe_multi.cookies = cookies;
11455 	lopts.uprobe_multi.cnt = cnt;
11456 	lopts.uprobe_multi.flags = OPTS_GET(opts, retprobe, false) ? BPF_F_UPROBE_MULTI_RETURN : 0;
11457 
11458 	if (pid == 0)
11459 		pid = getpid();
11460 	if (pid > 0)
11461 		lopts.uprobe_multi.pid = pid;
11462 
11463 	link = calloc(1, sizeof(*link));
11464 	if (!link) {
11465 		err = -ENOMEM;
11466 		goto error;
11467 	}
11468 	link->detach = &bpf_link__detach_fd;
11469 
11470 	prog_fd = bpf_program__fd(prog);
11471 	link_fd = bpf_link_create(prog_fd, 0, BPF_TRACE_UPROBE_MULTI, &lopts);
11472 	if (link_fd < 0) {
11473 		err = -errno;
11474 		pr_warn("prog '%s': failed to attach multi-uprobe: %s\n",
11475 			prog->name, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11476 		goto error;
11477 	}
11478 	link->fd = link_fd;
11479 	free(resolved_offsets);
11480 	return link;
11481 
11482 error:
11483 	free(resolved_offsets);
11484 	free(link);
11485 	return libbpf_err_ptr(err);
11486 }
11487 
11488 LIBBPF_API struct bpf_link *
11489 bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
11490 				const char *binary_path, size_t func_offset,
11491 				const struct bpf_uprobe_opts *opts)
11492 {
11493 	const char *archive_path = NULL, *archive_sep = NULL;
11494 	char errmsg[STRERR_BUFSIZE], *legacy_probe = NULL;
11495 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11496 	enum probe_attach_mode attach_mode;
11497 	char full_path[PATH_MAX];
11498 	struct bpf_link *link;
11499 	size_t ref_ctr_off;
11500 	int pfd, err;
11501 	bool retprobe, legacy;
11502 	const char *func_name;
11503 
11504 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
11505 		return libbpf_err_ptr(-EINVAL);
11506 
11507 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
11508 	retprobe = OPTS_GET(opts, retprobe, false);
11509 	ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
11510 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11511 
11512 	if (!binary_path)
11513 		return libbpf_err_ptr(-EINVAL);
11514 
11515 	/* Check if "binary_path" refers to an archive. */
11516 	archive_sep = strstr(binary_path, "!/");
11517 	if (archive_sep) {
11518 		full_path[0] = '\0';
11519 		libbpf_strlcpy(full_path, binary_path,
11520 			       min(sizeof(full_path), (size_t)(archive_sep - binary_path + 1)));
11521 		archive_path = full_path;
11522 		binary_path = archive_sep + 2;
11523 	} else if (!strchr(binary_path, '/')) {
11524 		err = resolve_full_path(binary_path, full_path, sizeof(full_path));
11525 		if (err) {
11526 			pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11527 				prog->name, binary_path, err);
11528 			return libbpf_err_ptr(err);
11529 		}
11530 		binary_path = full_path;
11531 	}
11532 	func_name = OPTS_GET(opts, func_name, NULL);
11533 	if (func_name) {
11534 		long sym_off;
11535 
11536 		if (archive_path) {
11537 			sym_off = elf_find_func_offset_from_archive(archive_path, binary_path,
11538 								    func_name);
11539 			binary_path = archive_path;
11540 		} else {
11541 			sym_off = elf_find_func_offset_from_file(binary_path, func_name);
11542 		}
11543 		if (sym_off < 0)
11544 			return libbpf_err_ptr(sym_off);
11545 		func_offset += sym_off;
11546 	}
11547 
11548 	legacy = determine_uprobe_perf_type() < 0;
11549 	switch (attach_mode) {
11550 	case PROBE_ATTACH_MODE_LEGACY:
11551 		legacy = true;
11552 		pe_opts.force_ioctl_attach = true;
11553 		break;
11554 	case PROBE_ATTACH_MODE_PERF:
11555 		if (legacy)
11556 			return libbpf_err_ptr(-ENOTSUP);
11557 		pe_opts.force_ioctl_attach = true;
11558 		break;
11559 	case PROBE_ATTACH_MODE_LINK:
11560 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
11561 			return libbpf_err_ptr(-ENOTSUP);
11562 		break;
11563 	case PROBE_ATTACH_MODE_DEFAULT:
11564 		break;
11565 	default:
11566 		return libbpf_err_ptr(-EINVAL);
11567 	}
11568 
11569 	if (!legacy) {
11570 		pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
11571 					    func_offset, pid, ref_ctr_off);
11572 	} else {
11573 		char probe_name[PATH_MAX + 64];
11574 
11575 		if (ref_ctr_off)
11576 			return libbpf_err_ptr(-EINVAL);
11577 
11578 		gen_uprobe_legacy_event_name(probe_name, sizeof(probe_name),
11579 					     binary_path, func_offset);
11580 
11581 		legacy_probe = strdup(probe_name);
11582 		if (!legacy_probe)
11583 			return libbpf_err_ptr(-ENOMEM);
11584 
11585 		pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
11586 						    binary_path, func_offset, pid);
11587 	}
11588 	if (pfd < 0) {
11589 		err = -errno;
11590 		pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
11591 			prog->name, retprobe ? "uretprobe" : "uprobe",
11592 			binary_path, func_offset,
11593 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11594 		goto err_out;
11595 	}
11596 
11597 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11598 	err = libbpf_get_error(link);
11599 	if (err) {
11600 		close(pfd);
11601 		pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
11602 			prog->name, retprobe ? "uretprobe" : "uprobe",
11603 			binary_path, func_offset,
11604 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11605 		goto err_clean_legacy;
11606 	}
11607 	if (legacy) {
11608 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
11609 
11610 		perf_link->legacy_probe_name = legacy_probe;
11611 		perf_link->legacy_is_kprobe = false;
11612 		perf_link->legacy_is_retprobe = retprobe;
11613 	}
11614 	return link;
11615 
11616 err_clean_legacy:
11617 	if (legacy)
11618 		remove_uprobe_event_legacy(legacy_probe, retprobe);
11619 err_out:
11620 	free(legacy_probe);
11621 	return libbpf_err_ptr(err);
11622 }
11623 
11624 /* Format of u[ret]probe section definition supporting auto-attach:
11625  * u[ret]probe/binary:function[+offset]
11626  *
11627  * binary can be an absolute/relative path or a filename; the latter is resolved to a
11628  * full binary path via bpf_program__attach_uprobe_opts.
11629  *
11630  * Specifying uprobe+ ensures we carry out strict matching; either "uprobe" must be
11631  * specified (and auto-attach is not possible) or the above format is specified for
11632  * auto-attach.
11633  */
11634 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11635 {
11636 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts);
11637 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL, *func_off;
11638 	int n, c, ret = -EINVAL;
11639 	long offset = 0;
11640 
11641 	*link = NULL;
11642 
11643 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
11644 		   &probe_type, &binary_path, &func_name);
11645 	switch (n) {
11646 	case 1:
11647 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
11648 		ret = 0;
11649 		break;
11650 	case 2:
11651 		pr_warn("prog '%s': section '%s' missing ':function[+offset]' specification\n",
11652 			prog->name, prog->sec_name);
11653 		break;
11654 	case 3:
11655 		/* check if user specifies `+offset`, if yes, this should be
11656 		 * the last part of the string, make sure sscanf read to EOL
11657 		 */
11658 		func_off = strrchr(func_name, '+');
11659 		if (func_off) {
11660 			n = sscanf(func_off, "+%li%n", &offset, &c);
11661 			if (n == 1 && *(func_off + c) == '\0')
11662 				func_off[0] = '\0';
11663 			else
11664 				offset = 0;
11665 		}
11666 		opts.retprobe = strcmp(probe_type, "uretprobe") == 0 ||
11667 				strcmp(probe_type, "uretprobe.s") == 0;
11668 		if (opts.retprobe && offset != 0) {
11669 			pr_warn("prog '%s': uretprobes do not support offset specification\n",
11670 				prog->name);
11671 			break;
11672 		}
11673 		opts.func_name = func_name;
11674 		*link = bpf_program__attach_uprobe_opts(prog, -1, binary_path, offset, &opts);
11675 		ret = libbpf_get_error(*link);
11676 		break;
11677 	default:
11678 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
11679 			prog->sec_name);
11680 		break;
11681 	}
11682 	free(probe_type);
11683 	free(binary_path);
11684 	free(func_name);
11685 
11686 	return ret;
11687 }
11688 
11689 struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
11690 					    bool retprobe, pid_t pid,
11691 					    const char *binary_path,
11692 					    size_t func_offset)
11693 {
11694 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
11695 
11696 	return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
11697 }
11698 
11699 struct bpf_link *bpf_program__attach_usdt(const struct bpf_program *prog,
11700 					  pid_t pid, const char *binary_path,
11701 					  const char *usdt_provider, const char *usdt_name,
11702 					  const struct bpf_usdt_opts *opts)
11703 {
11704 	char resolved_path[512];
11705 	struct bpf_object *obj = prog->obj;
11706 	struct bpf_link *link;
11707 	__u64 usdt_cookie;
11708 	int err;
11709 
11710 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
11711 		return libbpf_err_ptr(-EINVAL);
11712 
11713 	if (bpf_program__fd(prog) < 0) {
11714 		pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
11715 			prog->name);
11716 		return libbpf_err_ptr(-EINVAL);
11717 	}
11718 
11719 	if (!binary_path)
11720 		return libbpf_err_ptr(-EINVAL);
11721 
11722 	if (!strchr(binary_path, '/')) {
11723 		err = resolve_full_path(binary_path, resolved_path, sizeof(resolved_path));
11724 		if (err) {
11725 			pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11726 				prog->name, binary_path, err);
11727 			return libbpf_err_ptr(err);
11728 		}
11729 		binary_path = resolved_path;
11730 	}
11731 
11732 	/* USDT manager is instantiated lazily on first USDT attach. It will
11733 	 * be destroyed together with BPF object in bpf_object__close().
11734 	 */
11735 	if (IS_ERR(obj->usdt_man))
11736 		return libbpf_ptr(obj->usdt_man);
11737 	if (!obj->usdt_man) {
11738 		obj->usdt_man = usdt_manager_new(obj);
11739 		if (IS_ERR(obj->usdt_man))
11740 			return libbpf_ptr(obj->usdt_man);
11741 	}
11742 
11743 	usdt_cookie = OPTS_GET(opts, usdt_cookie, 0);
11744 	link = usdt_manager_attach_usdt(obj->usdt_man, prog, pid, binary_path,
11745 					usdt_provider, usdt_name, usdt_cookie);
11746 	err = libbpf_get_error(link);
11747 	if (err)
11748 		return libbpf_err_ptr(err);
11749 	return link;
11750 }
11751 
11752 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11753 {
11754 	char *path = NULL, *provider = NULL, *name = NULL;
11755 	const char *sec_name;
11756 	int n, err;
11757 
11758 	sec_name = bpf_program__section_name(prog);
11759 	if (strcmp(sec_name, "usdt") == 0) {
11760 		/* no auto-attach for just SEC("usdt") */
11761 		*link = NULL;
11762 		return 0;
11763 	}
11764 
11765 	n = sscanf(sec_name, "usdt/%m[^:]:%m[^:]:%m[^:]", &path, &provider, &name);
11766 	if (n != 3) {
11767 		pr_warn("invalid section '%s', expected SEC(\"usdt/<path>:<provider>:<name>\")\n",
11768 			sec_name);
11769 		err = -EINVAL;
11770 	} else {
11771 		*link = bpf_program__attach_usdt(prog, -1 /* any process */, path,
11772 						 provider, name, NULL);
11773 		err = libbpf_get_error(*link);
11774 	}
11775 	free(path);
11776 	free(provider);
11777 	free(name);
11778 	return err;
11779 }
11780 
11781 static int determine_tracepoint_id(const char *tp_category,
11782 				   const char *tp_name)
11783 {
11784 	char file[PATH_MAX];
11785 	int ret;
11786 
11787 	ret = snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11788 		       tracefs_path(), tp_category, tp_name);
11789 	if (ret < 0)
11790 		return -errno;
11791 	if (ret >= sizeof(file)) {
11792 		pr_debug("tracepoint %s/%s path is too long\n",
11793 			 tp_category, tp_name);
11794 		return -E2BIG;
11795 	}
11796 	return parse_uint_from_file(file, "%d\n");
11797 }
11798 
11799 static int perf_event_open_tracepoint(const char *tp_category,
11800 				      const char *tp_name)
11801 {
11802 	const size_t attr_sz = sizeof(struct perf_event_attr);
11803 	struct perf_event_attr attr;
11804 	char errmsg[STRERR_BUFSIZE];
11805 	int tp_id, pfd, err;
11806 
11807 	tp_id = determine_tracepoint_id(tp_category, tp_name);
11808 	if (tp_id < 0) {
11809 		pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
11810 			tp_category, tp_name,
11811 			libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
11812 		return tp_id;
11813 	}
11814 
11815 	memset(&attr, 0, attr_sz);
11816 	attr.type = PERF_TYPE_TRACEPOINT;
11817 	attr.size = attr_sz;
11818 	attr.config = tp_id;
11819 
11820 	pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
11821 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
11822 	if (pfd < 0) {
11823 		err = -errno;
11824 		pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
11825 			tp_category, tp_name,
11826 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11827 		return err;
11828 	}
11829 	return pfd;
11830 }
11831 
11832 struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
11833 						     const char *tp_category,
11834 						     const char *tp_name,
11835 						     const struct bpf_tracepoint_opts *opts)
11836 {
11837 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11838 	char errmsg[STRERR_BUFSIZE];
11839 	struct bpf_link *link;
11840 	int pfd, err;
11841 
11842 	if (!OPTS_VALID(opts, bpf_tracepoint_opts))
11843 		return libbpf_err_ptr(-EINVAL);
11844 
11845 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11846 
11847 	pfd = perf_event_open_tracepoint(tp_category, tp_name);
11848 	if (pfd < 0) {
11849 		pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
11850 			prog->name, tp_category, tp_name,
11851 			libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11852 		return libbpf_err_ptr(pfd);
11853 	}
11854 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11855 	err = libbpf_get_error(link);
11856 	if (err) {
11857 		close(pfd);
11858 		pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
11859 			prog->name, tp_category, tp_name,
11860 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11861 		return libbpf_err_ptr(err);
11862 	}
11863 	return link;
11864 }
11865 
11866 struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
11867 						const char *tp_category,
11868 						const char *tp_name)
11869 {
11870 	return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
11871 }
11872 
11873 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11874 {
11875 	char *sec_name, *tp_cat, *tp_name;
11876 
11877 	*link = NULL;
11878 
11879 	/* no auto-attach for SEC("tp") or SEC("tracepoint") */
11880 	if (strcmp(prog->sec_name, "tp") == 0 || strcmp(prog->sec_name, "tracepoint") == 0)
11881 		return 0;
11882 
11883 	sec_name = strdup(prog->sec_name);
11884 	if (!sec_name)
11885 		return -ENOMEM;
11886 
11887 	/* extract "tp/<category>/<name>" or "tracepoint/<category>/<name>" */
11888 	if (str_has_pfx(prog->sec_name, "tp/"))
11889 		tp_cat = sec_name + sizeof("tp/") - 1;
11890 	else
11891 		tp_cat = sec_name + sizeof("tracepoint/") - 1;
11892 	tp_name = strchr(tp_cat, '/');
11893 	if (!tp_name) {
11894 		free(sec_name);
11895 		return -EINVAL;
11896 	}
11897 	*tp_name = '\0';
11898 	tp_name++;
11899 
11900 	*link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
11901 	free(sec_name);
11902 	return libbpf_get_error(*link);
11903 }
11904 
11905 struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
11906 						    const char *tp_name)
11907 {
11908 	char errmsg[STRERR_BUFSIZE];
11909 	struct bpf_link *link;
11910 	int prog_fd, pfd;
11911 
11912 	prog_fd = bpf_program__fd(prog);
11913 	if (prog_fd < 0) {
11914 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11915 		return libbpf_err_ptr(-EINVAL);
11916 	}
11917 
11918 	link = calloc(1, sizeof(*link));
11919 	if (!link)
11920 		return libbpf_err_ptr(-ENOMEM);
11921 	link->detach = &bpf_link__detach_fd;
11922 
11923 	pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
11924 	if (pfd < 0) {
11925 		pfd = -errno;
11926 		free(link);
11927 		pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
11928 			prog->name, tp_name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11929 		return libbpf_err_ptr(pfd);
11930 	}
11931 	link->fd = pfd;
11932 	return link;
11933 }
11934 
11935 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11936 {
11937 	static const char *const prefixes[] = {
11938 		"raw_tp",
11939 		"raw_tracepoint",
11940 		"raw_tp.w",
11941 		"raw_tracepoint.w",
11942 	};
11943 	size_t i;
11944 	const char *tp_name = NULL;
11945 
11946 	*link = NULL;
11947 
11948 	for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
11949 		size_t pfx_len;
11950 
11951 		if (!str_has_pfx(prog->sec_name, prefixes[i]))
11952 			continue;
11953 
11954 		pfx_len = strlen(prefixes[i]);
11955 		/* no auto-attach case of, e.g., SEC("raw_tp") */
11956 		if (prog->sec_name[pfx_len] == '\0')
11957 			return 0;
11958 
11959 		if (prog->sec_name[pfx_len] != '/')
11960 			continue;
11961 
11962 		tp_name = prog->sec_name + pfx_len + 1;
11963 		break;
11964 	}
11965 
11966 	if (!tp_name) {
11967 		pr_warn("prog '%s': invalid section name '%s'\n",
11968 			prog->name, prog->sec_name);
11969 		return -EINVAL;
11970 	}
11971 
11972 	*link = bpf_program__attach_raw_tracepoint(prog, tp_name);
11973 	return libbpf_get_error(*link);
11974 }
11975 
11976 /* Common logic for all BPF program types that attach to a btf_id */
11977 static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog,
11978 						   const struct bpf_trace_opts *opts)
11979 {
11980 	LIBBPF_OPTS(bpf_link_create_opts, link_opts);
11981 	char errmsg[STRERR_BUFSIZE];
11982 	struct bpf_link *link;
11983 	int prog_fd, pfd;
11984 
11985 	if (!OPTS_VALID(opts, bpf_trace_opts))
11986 		return libbpf_err_ptr(-EINVAL);
11987 
11988 	prog_fd = bpf_program__fd(prog);
11989 	if (prog_fd < 0) {
11990 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11991 		return libbpf_err_ptr(-EINVAL);
11992 	}
11993 
11994 	link = calloc(1, sizeof(*link));
11995 	if (!link)
11996 		return libbpf_err_ptr(-ENOMEM);
11997 	link->detach = &bpf_link__detach_fd;
11998 
11999 	/* libbpf is smart enough to redirect to BPF_RAW_TRACEPOINT_OPEN on old kernels */
12000 	link_opts.tracing.cookie = OPTS_GET(opts, cookie, 0);
12001 	pfd = bpf_link_create(prog_fd, 0, bpf_program__expected_attach_type(prog), &link_opts);
12002 	if (pfd < 0) {
12003 		pfd = -errno;
12004 		free(link);
12005 		pr_warn("prog '%s': failed to attach: %s\n",
12006 			prog->name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
12007 		return libbpf_err_ptr(pfd);
12008 	}
12009 	link->fd = pfd;
12010 	return link;
12011 }
12012 
12013 struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
12014 {
12015 	return bpf_program__attach_btf_id(prog, NULL);
12016 }
12017 
12018 struct bpf_link *bpf_program__attach_trace_opts(const struct bpf_program *prog,
12019 						const struct bpf_trace_opts *opts)
12020 {
12021 	return bpf_program__attach_btf_id(prog, opts);
12022 }
12023 
12024 struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
12025 {
12026 	return bpf_program__attach_btf_id(prog, NULL);
12027 }
12028 
12029 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12030 {
12031 	*link = bpf_program__attach_trace(prog);
12032 	return libbpf_get_error(*link);
12033 }
12034 
12035 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12036 {
12037 	*link = bpf_program__attach_lsm(prog);
12038 	return libbpf_get_error(*link);
12039 }
12040 
12041 static struct bpf_link *
12042 bpf_program_attach_fd(const struct bpf_program *prog,
12043 		      int target_fd, const char *target_name,
12044 		      const struct bpf_link_create_opts *opts)
12045 {
12046 	enum bpf_attach_type attach_type;
12047 	char errmsg[STRERR_BUFSIZE];
12048 	struct bpf_link *link;
12049 	int prog_fd, link_fd;
12050 
12051 	prog_fd = bpf_program__fd(prog);
12052 	if (prog_fd < 0) {
12053 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12054 		return libbpf_err_ptr(-EINVAL);
12055 	}
12056 
12057 	link = calloc(1, sizeof(*link));
12058 	if (!link)
12059 		return libbpf_err_ptr(-ENOMEM);
12060 	link->detach = &bpf_link__detach_fd;
12061 
12062 	attach_type = bpf_program__expected_attach_type(prog);
12063 	link_fd = bpf_link_create(prog_fd, target_fd, attach_type, opts);
12064 	if (link_fd < 0) {
12065 		link_fd = -errno;
12066 		free(link);
12067 		pr_warn("prog '%s': failed to attach to %s: %s\n",
12068 			prog->name, target_name,
12069 			libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
12070 		return libbpf_err_ptr(link_fd);
12071 	}
12072 	link->fd = link_fd;
12073 	return link;
12074 }
12075 
12076 struct bpf_link *
12077 bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
12078 {
12079 	return bpf_program_attach_fd(prog, cgroup_fd, "cgroup", NULL);
12080 }
12081 
12082 struct bpf_link *
12083 bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
12084 {
12085 	return bpf_program_attach_fd(prog, netns_fd, "netns", NULL);
12086 }
12087 
12088 struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
12089 {
12090 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
12091 	return bpf_program_attach_fd(prog, ifindex, "xdp", NULL);
12092 }
12093 
12094 struct bpf_link *
12095 bpf_program__attach_tcx(const struct bpf_program *prog, int ifindex,
12096 			const struct bpf_tcx_opts *opts)
12097 {
12098 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12099 	__u32 relative_id;
12100 	int relative_fd;
12101 
12102 	if (!OPTS_VALID(opts, bpf_tcx_opts))
12103 		return libbpf_err_ptr(-EINVAL);
12104 
12105 	relative_id = OPTS_GET(opts, relative_id, 0);
12106 	relative_fd = OPTS_GET(opts, relative_fd, 0);
12107 
12108 	/* validate we don't have unexpected combinations of non-zero fields */
12109 	if (!ifindex) {
12110 		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
12111 			prog->name);
12112 		return libbpf_err_ptr(-EINVAL);
12113 	}
12114 	if (relative_fd && relative_id) {
12115 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
12116 			prog->name);
12117 		return libbpf_err_ptr(-EINVAL);
12118 	}
12119 
12120 	link_create_opts.tcx.expected_revision = OPTS_GET(opts, expected_revision, 0);
12121 	link_create_opts.tcx.relative_fd = relative_fd;
12122 	link_create_opts.tcx.relative_id = relative_id;
12123 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
12124 
12125 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
12126 	return bpf_program_attach_fd(prog, ifindex, "tcx", &link_create_opts);
12127 }
12128 
12129 struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
12130 					      int target_fd,
12131 					      const char *attach_func_name)
12132 {
12133 	int btf_id;
12134 
12135 	if (!!target_fd != !!attach_func_name) {
12136 		pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
12137 			prog->name);
12138 		return libbpf_err_ptr(-EINVAL);
12139 	}
12140 
12141 	if (prog->type != BPF_PROG_TYPE_EXT) {
12142 		pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace",
12143 			prog->name);
12144 		return libbpf_err_ptr(-EINVAL);
12145 	}
12146 
12147 	if (target_fd) {
12148 		LIBBPF_OPTS(bpf_link_create_opts, target_opts);
12149 
12150 		btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd);
12151 		if (btf_id < 0)
12152 			return libbpf_err_ptr(btf_id);
12153 
12154 		target_opts.target_btf_id = btf_id;
12155 
12156 		return bpf_program_attach_fd(prog, target_fd, "freplace",
12157 					     &target_opts);
12158 	} else {
12159 		/* no target, so use raw_tracepoint_open for compatibility
12160 		 * with old kernels
12161 		 */
12162 		return bpf_program__attach_trace(prog);
12163 	}
12164 }
12165 
12166 struct bpf_link *
12167 bpf_program__attach_iter(const struct bpf_program *prog,
12168 			 const struct bpf_iter_attach_opts *opts)
12169 {
12170 	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12171 	char errmsg[STRERR_BUFSIZE];
12172 	struct bpf_link *link;
12173 	int prog_fd, link_fd;
12174 	__u32 target_fd = 0;
12175 
12176 	if (!OPTS_VALID(opts, bpf_iter_attach_opts))
12177 		return libbpf_err_ptr(-EINVAL);
12178 
12179 	link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
12180 	link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
12181 
12182 	prog_fd = bpf_program__fd(prog);
12183 	if (prog_fd < 0) {
12184 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12185 		return libbpf_err_ptr(-EINVAL);
12186 	}
12187 
12188 	link = calloc(1, sizeof(*link));
12189 	if (!link)
12190 		return libbpf_err_ptr(-ENOMEM);
12191 	link->detach = &bpf_link__detach_fd;
12192 
12193 	link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
12194 				  &link_create_opts);
12195 	if (link_fd < 0) {
12196 		link_fd = -errno;
12197 		free(link);
12198 		pr_warn("prog '%s': failed to attach to iterator: %s\n",
12199 			prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
12200 		return libbpf_err_ptr(link_fd);
12201 	}
12202 	link->fd = link_fd;
12203 	return link;
12204 }
12205 
12206 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12207 {
12208 	*link = bpf_program__attach_iter(prog, NULL);
12209 	return libbpf_get_error(*link);
12210 }
12211 
12212 struct bpf_link *bpf_program__attach_netfilter(const struct bpf_program *prog,
12213 					       const struct bpf_netfilter_opts *opts)
12214 {
12215 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
12216 	struct bpf_link *link;
12217 	int prog_fd, link_fd;
12218 
12219 	if (!OPTS_VALID(opts, bpf_netfilter_opts))
12220 		return libbpf_err_ptr(-EINVAL);
12221 
12222 	prog_fd = bpf_program__fd(prog);
12223 	if (prog_fd < 0) {
12224 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12225 		return libbpf_err_ptr(-EINVAL);
12226 	}
12227 
12228 	link = calloc(1, sizeof(*link));
12229 	if (!link)
12230 		return libbpf_err_ptr(-ENOMEM);
12231 
12232 	link->detach = &bpf_link__detach_fd;
12233 
12234 	lopts.netfilter.pf = OPTS_GET(opts, pf, 0);
12235 	lopts.netfilter.hooknum = OPTS_GET(opts, hooknum, 0);
12236 	lopts.netfilter.priority = OPTS_GET(opts, priority, 0);
12237 	lopts.netfilter.flags = OPTS_GET(opts, flags, 0);
12238 
12239 	link_fd = bpf_link_create(prog_fd, 0, BPF_NETFILTER, &lopts);
12240 	if (link_fd < 0) {
12241 		char errmsg[STRERR_BUFSIZE];
12242 
12243 		link_fd = -errno;
12244 		free(link);
12245 		pr_warn("prog '%s': failed to attach to netfilter: %s\n",
12246 			prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
12247 		return libbpf_err_ptr(link_fd);
12248 	}
12249 	link->fd = link_fd;
12250 
12251 	return link;
12252 }
12253 
12254 struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
12255 {
12256 	struct bpf_link *link = NULL;
12257 	int err;
12258 
12259 	if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
12260 		return libbpf_err_ptr(-EOPNOTSUPP);
12261 
12262 	err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, &link);
12263 	if (err)
12264 		return libbpf_err_ptr(err);
12265 
12266 	/* When calling bpf_program__attach() explicitly, auto-attach support
12267 	 * is expected to work, so NULL returned link is considered an error.
12268 	 * This is different for skeleton's attach, see comment in
12269 	 * bpf_object__attach_skeleton().
12270 	 */
12271 	if (!link)
12272 		return libbpf_err_ptr(-EOPNOTSUPP);
12273 
12274 	return link;
12275 }
12276 
12277 struct bpf_link_struct_ops {
12278 	struct bpf_link link;
12279 	int map_fd;
12280 };
12281 
12282 static int bpf_link__detach_struct_ops(struct bpf_link *link)
12283 {
12284 	struct bpf_link_struct_ops *st_link;
12285 	__u32 zero = 0;
12286 
12287 	st_link = container_of(link, struct bpf_link_struct_ops, link);
12288 
12289 	if (st_link->map_fd < 0)
12290 		/* w/o a real link */
12291 		return bpf_map_delete_elem(link->fd, &zero);
12292 
12293 	return close(link->fd);
12294 }
12295 
12296 struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
12297 {
12298 	struct bpf_link_struct_ops *link;
12299 	__u32 zero = 0;
12300 	int err, fd;
12301 
12302 	if (!bpf_map__is_struct_ops(map) || map->fd == -1)
12303 		return libbpf_err_ptr(-EINVAL);
12304 
12305 	link = calloc(1, sizeof(*link));
12306 	if (!link)
12307 		return libbpf_err_ptr(-EINVAL);
12308 
12309 	/* kern_vdata should be prepared during the loading phase. */
12310 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
12311 	/* It can be EBUSY if the map has been used to create or
12312 	 * update a link before.  We don't allow updating the value of
12313 	 * a struct_ops once it is set.  That ensures that the value
12314 	 * never changed.  So, it is safe to skip EBUSY.
12315 	 */
12316 	if (err && (!(map->def.map_flags & BPF_F_LINK) || err != -EBUSY)) {
12317 		free(link);
12318 		return libbpf_err_ptr(err);
12319 	}
12320 
12321 	link->link.detach = bpf_link__detach_struct_ops;
12322 
12323 	if (!(map->def.map_flags & BPF_F_LINK)) {
12324 		/* w/o a real link */
12325 		link->link.fd = map->fd;
12326 		link->map_fd = -1;
12327 		return &link->link;
12328 	}
12329 
12330 	fd = bpf_link_create(map->fd, 0, BPF_STRUCT_OPS, NULL);
12331 	if (fd < 0) {
12332 		free(link);
12333 		return libbpf_err_ptr(fd);
12334 	}
12335 
12336 	link->link.fd = fd;
12337 	link->map_fd = map->fd;
12338 
12339 	return &link->link;
12340 }
12341 
12342 /*
12343  * Swap the back struct_ops of a link with a new struct_ops map.
12344  */
12345 int bpf_link__update_map(struct bpf_link *link, const struct bpf_map *map)
12346 {
12347 	struct bpf_link_struct_ops *st_ops_link;
12348 	__u32 zero = 0;
12349 	int err;
12350 
12351 	if (!bpf_map__is_struct_ops(map) || map->fd < 0)
12352 		return -EINVAL;
12353 
12354 	st_ops_link = container_of(link, struct bpf_link_struct_ops, link);
12355 	/* Ensure the type of a link is correct */
12356 	if (st_ops_link->map_fd < 0)
12357 		return -EINVAL;
12358 
12359 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
12360 	/* It can be EBUSY if the map has been used to create or
12361 	 * update a link before.  We don't allow updating the value of
12362 	 * a struct_ops once it is set.  That ensures that the value
12363 	 * never changed.  So, it is safe to skip EBUSY.
12364 	 */
12365 	if (err && err != -EBUSY)
12366 		return err;
12367 
12368 	err = bpf_link_update(link->fd, map->fd, NULL);
12369 	if (err < 0)
12370 		return err;
12371 
12372 	st_ops_link->map_fd = map->fd;
12373 
12374 	return 0;
12375 }
12376 
12377 typedef enum bpf_perf_event_ret (*bpf_perf_event_print_t)(struct perf_event_header *hdr,
12378 							  void *private_data);
12379 
12380 static enum bpf_perf_event_ret
12381 perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
12382 		       void **copy_mem, size_t *copy_size,
12383 		       bpf_perf_event_print_t fn, void *private_data)
12384 {
12385 	struct perf_event_mmap_page *header = mmap_mem;
12386 	__u64 data_head = ring_buffer_read_head(header);
12387 	__u64 data_tail = header->data_tail;
12388 	void *base = ((__u8 *)header) + page_size;
12389 	int ret = LIBBPF_PERF_EVENT_CONT;
12390 	struct perf_event_header *ehdr;
12391 	size_t ehdr_size;
12392 
12393 	while (data_head != data_tail) {
12394 		ehdr = base + (data_tail & (mmap_size - 1));
12395 		ehdr_size = ehdr->size;
12396 
12397 		if (((void *)ehdr) + ehdr_size > base + mmap_size) {
12398 			void *copy_start = ehdr;
12399 			size_t len_first = base + mmap_size - copy_start;
12400 			size_t len_secnd = ehdr_size - len_first;
12401 
12402 			if (*copy_size < ehdr_size) {
12403 				free(*copy_mem);
12404 				*copy_mem = malloc(ehdr_size);
12405 				if (!*copy_mem) {
12406 					*copy_size = 0;
12407 					ret = LIBBPF_PERF_EVENT_ERROR;
12408 					break;
12409 				}
12410 				*copy_size = ehdr_size;
12411 			}
12412 
12413 			memcpy(*copy_mem, copy_start, len_first);
12414 			memcpy(*copy_mem + len_first, base, len_secnd);
12415 			ehdr = *copy_mem;
12416 		}
12417 
12418 		ret = fn(ehdr, private_data);
12419 		data_tail += ehdr_size;
12420 		if (ret != LIBBPF_PERF_EVENT_CONT)
12421 			break;
12422 	}
12423 
12424 	ring_buffer_write_tail(header, data_tail);
12425 	return libbpf_err(ret);
12426 }
12427 
12428 struct perf_buffer;
12429 
12430 struct perf_buffer_params {
12431 	struct perf_event_attr *attr;
12432 	/* if event_cb is specified, it takes precendence */
12433 	perf_buffer_event_fn event_cb;
12434 	/* sample_cb and lost_cb are higher-level common-case callbacks */
12435 	perf_buffer_sample_fn sample_cb;
12436 	perf_buffer_lost_fn lost_cb;
12437 	void *ctx;
12438 	int cpu_cnt;
12439 	int *cpus;
12440 	int *map_keys;
12441 };
12442 
12443 struct perf_cpu_buf {
12444 	struct perf_buffer *pb;
12445 	void *base; /* mmap()'ed memory */
12446 	void *buf; /* for reconstructing segmented data */
12447 	size_t buf_size;
12448 	int fd;
12449 	int cpu;
12450 	int map_key;
12451 };
12452 
12453 struct perf_buffer {
12454 	perf_buffer_event_fn event_cb;
12455 	perf_buffer_sample_fn sample_cb;
12456 	perf_buffer_lost_fn lost_cb;
12457 	void *ctx; /* passed into callbacks */
12458 
12459 	size_t page_size;
12460 	size_t mmap_size;
12461 	struct perf_cpu_buf **cpu_bufs;
12462 	struct epoll_event *events;
12463 	int cpu_cnt; /* number of allocated CPU buffers */
12464 	int epoll_fd; /* perf event FD */
12465 	int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
12466 };
12467 
12468 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
12469 				      struct perf_cpu_buf *cpu_buf)
12470 {
12471 	if (!cpu_buf)
12472 		return;
12473 	if (cpu_buf->base &&
12474 	    munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
12475 		pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
12476 	if (cpu_buf->fd >= 0) {
12477 		ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
12478 		close(cpu_buf->fd);
12479 	}
12480 	free(cpu_buf->buf);
12481 	free(cpu_buf);
12482 }
12483 
12484 void perf_buffer__free(struct perf_buffer *pb)
12485 {
12486 	int i;
12487 
12488 	if (IS_ERR_OR_NULL(pb))
12489 		return;
12490 	if (pb->cpu_bufs) {
12491 		for (i = 0; i < pb->cpu_cnt; i++) {
12492 			struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
12493 
12494 			if (!cpu_buf)
12495 				continue;
12496 
12497 			bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
12498 			perf_buffer__free_cpu_buf(pb, cpu_buf);
12499 		}
12500 		free(pb->cpu_bufs);
12501 	}
12502 	if (pb->epoll_fd >= 0)
12503 		close(pb->epoll_fd);
12504 	free(pb->events);
12505 	free(pb);
12506 }
12507 
12508 static struct perf_cpu_buf *
12509 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
12510 			  int cpu, int map_key)
12511 {
12512 	struct perf_cpu_buf *cpu_buf;
12513 	char msg[STRERR_BUFSIZE];
12514 	int err;
12515 
12516 	cpu_buf = calloc(1, sizeof(*cpu_buf));
12517 	if (!cpu_buf)
12518 		return ERR_PTR(-ENOMEM);
12519 
12520 	cpu_buf->pb = pb;
12521 	cpu_buf->cpu = cpu;
12522 	cpu_buf->map_key = map_key;
12523 
12524 	cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
12525 			      -1, PERF_FLAG_FD_CLOEXEC);
12526 	if (cpu_buf->fd < 0) {
12527 		err = -errno;
12528 		pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
12529 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
12530 		goto error;
12531 	}
12532 
12533 	cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
12534 			     PROT_READ | PROT_WRITE, MAP_SHARED,
12535 			     cpu_buf->fd, 0);
12536 	if (cpu_buf->base == MAP_FAILED) {
12537 		cpu_buf->base = NULL;
12538 		err = -errno;
12539 		pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
12540 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
12541 		goto error;
12542 	}
12543 
12544 	if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
12545 		err = -errno;
12546 		pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
12547 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
12548 		goto error;
12549 	}
12550 
12551 	return cpu_buf;
12552 
12553 error:
12554 	perf_buffer__free_cpu_buf(pb, cpu_buf);
12555 	return (struct perf_cpu_buf *)ERR_PTR(err);
12556 }
12557 
12558 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
12559 					      struct perf_buffer_params *p);
12560 
12561 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
12562 				     perf_buffer_sample_fn sample_cb,
12563 				     perf_buffer_lost_fn lost_cb,
12564 				     void *ctx,
12565 				     const struct perf_buffer_opts *opts)
12566 {
12567 	const size_t attr_sz = sizeof(struct perf_event_attr);
12568 	struct perf_buffer_params p = {};
12569 	struct perf_event_attr attr;
12570 	__u32 sample_period;
12571 
12572 	if (!OPTS_VALID(opts, perf_buffer_opts))
12573 		return libbpf_err_ptr(-EINVAL);
12574 
12575 	sample_period = OPTS_GET(opts, sample_period, 1);
12576 	if (!sample_period)
12577 		sample_period = 1;
12578 
12579 	memset(&attr, 0, attr_sz);
12580 	attr.size = attr_sz;
12581 	attr.config = PERF_COUNT_SW_BPF_OUTPUT;
12582 	attr.type = PERF_TYPE_SOFTWARE;
12583 	attr.sample_type = PERF_SAMPLE_RAW;
12584 	attr.sample_period = sample_period;
12585 	attr.wakeup_events = sample_period;
12586 
12587 	p.attr = &attr;
12588 	p.sample_cb = sample_cb;
12589 	p.lost_cb = lost_cb;
12590 	p.ctx = ctx;
12591 
12592 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
12593 }
12594 
12595 struct perf_buffer *perf_buffer__new_raw(int map_fd, size_t page_cnt,
12596 					 struct perf_event_attr *attr,
12597 					 perf_buffer_event_fn event_cb, void *ctx,
12598 					 const struct perf_buffer_raw_opts *opts)
12599 {
12600 	struct perf_buffer_params p = {};
12601 
12602 	if (!attr)
12603 		return libbpf_err_ptr(-EINVAL);
12604 
12605 	if (!OPTS_VALID(opts, perf_buffer_raw_opts))
12606 		return libbpf_err_ptr(-EINVAL);
12607 
12608 	p.attr = attr;
12609 	p.event_cb = event_cb;
12610 	p.ctx = ctx;
12611 	p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
12612 	p.cpus = OPTS_GET(opts, cpus, NULL);
12613 	p.map_keys = OPTS_GET(opts, map_keys, NULL);
12614 
12615 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
12616 }
12617 
12618 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
12619 					      struct perf_buffer_params *p)
12620 {
12621 	const char *online_cpus_file = "/sys/devices/system/cpu/online";
12622 	struct bpf_map_info map;
12623 	char msg[STRERR_BUFSIZE];
12624 	struct perf_buffer *pb;
12625 	bool *online = NULL;
12626 	__u32 map_info_len;
12627 	int err, i, j, n;
12628 
12629 	if (page_cnt == 0 || (page_cnt & (page_cnt - 1))) {
12630 		pr_warn("page count should be power of two, but is %zu\n",
12631 			page_cnt);
12632 		return ERR_PTR(-EINVAL);
12633 	}
12634 
12635 	/* best-effort sanity checks */
12636 	memset(&map, 0, sizeof(map));
12637 	map_info_len = sizeof(map);
12638 	err = bpf_map_get_info_by_fd(map_fd, &map, &map_info_len);
12639 	if (err) {
12640 		err = -errno;
12641 		/* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
12642 		 * -EBADFD, -EFAULT, or -E2BIG on real error
12643 		 */
12644 		if (err != -EINVAL) {
12645 			pr_warn("failed to get map info for map FD %d: %s\n",
12646 				map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
12647 			return ERR_PTR(err);
12648 		}
12649 		pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
12650 			 map_fd);
12651 	} else {
12652 		if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
12653 			pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
12654 				map.name);
12655 			return ERR_PTR(-EINVAL);
12656 		}
12657 	}
12658 
12659 	pb = calloc(1, sizeof(*pb));
12660 	if (!pb)
12661 		return ERR_PTR(-ENOMEM);
12662 
12663 	pb->event_cb = p->event_cb;
12664 	pb->sample_cb = p->sample_cb;
12665 	pb->lost_cb = p->lost_cb;
12666 	pb->ctx = p->ctx;
12667 
12668 	pb->page_size = getpagesize();
12669 	pb->mmap_size = pb->page_size * page_cnt;
12670 	pb->map_fd = map_fd;
12671 
12672 	pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
12673 	if (pb->epoll_fd < 0) {
12674 		err = -errno;
12675 		pr_warn("failed to create epoll instance: %s\n",
12676 			libbpf_strerror_r(err, msg, sizeof(msg)));
12677 		goto error;
12678 	}
12679 
12680 	if (p->cpu_cnt > 0) {
12681 		pb->cpu_cnt = p->cpu_cnt;
12682 	} else {
12683 		pb->cpu_cnt = libbpf_num_possible_cpus();
12684 		if (pb->cpu_cnt < 0) {
12685 			err = pb->cpu_cnt;
12686 			goto error;
12687 		}
12688 		if (map.max_entries && map.max_entries < pb->cpu_cnt)
12689 			pb->cpu_cnt = map.max_entries;
12690 	}
12691 
12692 	pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
12693 	if (!pb->events) {
12694 		err = -ENOMEM;
12695 		pr_warn("failed to allocate events: out of memory\n");
12696 		goto error;
12697 	}
12698 	pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
12699 	if (!pb->cpu_bufs) {
12700 		err = -ENOMEM;
12701 		pr_warn("failed to allocate buffers: out of memory\n");
12702 		goto error;
12703 	}
12704 
12705 	err = parse_cpu_mask_file(online_cpus_file, &online, &n);
12706 	if (err) {
12707 		pr_warn("failed to get online CPU mask: %d\n", err);
12708 		goto error;
12709 	}
12710 
12711 	for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
12712 		struct perf_cpu_buf *cpu_buf;
12713 		int cpu, map_key;
12714 
12715 		cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
12716 		map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
12717 
12718 		/* in case user didn't explicitly requested particular CPUs to
12719 		 * be attached to, skip offline/not present CPUs
12720 		 */
12721 		if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
12722 			continue;
12723 
12724 		cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
12725 		if (IS_ERR(cpu_buf)) {
12726 			err = PTR_ERR(cpu_buf);
12727 			goto error;
12728 		}
12729 
12730 		pb->cpu_bufs[j] = cpu_buf;
12731 
12732 		err = bpf_map_update_elem(pb->map_fd, &map_key,
12733 					  &cpu_buf->fd, 0);
12734 		if (err) {
12735 			err = -errno;
12736 			pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
12737 				cpu, map_key, cpu_buf->fd,
12738 				libbpf_strerror_r(err, msg, sizeof(msg)));
12739 			goto error;
12740 		}
12741 
12742 		pb->events[j].events = EPOLLIN;
12743 		pb->events[j].data.ptr = cpu_buf;
12744 		if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
12745 			      &pb->events[j]) < 0) {
12746 			err = -errno;
12747 			pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
12748 				cpu, cpu_buf->fd,
12749 				libbpf_strerror_r(err, msg, sizeof(msg)));
12750 			goto error;
12751 		}
12752 		j++;
12753 	}
12754 	pb->cpu_cnt = j;
12755 	free(online);
12756 
12757 	return pb;
12758 
12759 error:
12760 	free(online);
12761 	if (pb)
12762 		perf_buffer__free(pb);
12763 	return ERR_PTR(err);
12764 }
12765 
12766 struct perf_sample_raw {
12767 	struct perf_event_header header;
12768 	uint32_t size;
12769 	char data[];
12770 };
12771 
12772 struct perf_sample_lost {
12773 	struct perf_event_header header;
12774 	uint64_t id;
12775 	uint64_t lost;
12776 	uint64_t sample_id;
12777 };
12778 
12779 static enum bpf_perf_event_ret
12780 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
12781 {
12782 	struct perf_cpu_buf *cpu_buf = ctx;
12783 	struct perf_buffer *pb = cpu_buf->pb;
12784 	void *data = e;
12785 
12786 	/* user wants full control over parsing perf event */
12787 	if (pb->event_cb)
12788 		return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
12789 
12790 	switch (e->type) {
12791 	case PERF_RECORD_SAMPLE: {
12792 		struct perf_sample_raw *s = data;
12793 
12794 		if (pb->sample_cb)
12795 			pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
12796 		break;
12797 	}
12798 	case PERF_RECORD_LOST: {
12799 		struct perf_sample_lost *s = data;
12800 
12801 		if (pb->lost_cb)
12802 			pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
12803 		break;
12804 	}
12805 	default:
12806 		pr_warn("unknown perf sample type %d\n", e->type);
12807 		return LIBBPF_PERF_EVENT_ERROR;
12808 	}
12809 	return LIBBPF_PERF_EVENT_CONT;
12810 }
12811 
12812 static int perf_buffer__process_records(struct perf_buffer *pb,
12813 					struct perf_cpu_buf *cpu_buf)
12814 {
12815 	enum bpf_perf_event_ret ret;
12816 
12817 	ret = perf_event_read_simple(cpu_buf->base, pb->mmap_size,
12818 				     pb->page_size, &cpu_buf->buf,
12819 				     &cpu_buf->buf_size,
12820 				     perf_buffer__process_record, cpu_buf);
12821 	if (ret != LIBBPF_PERF_EVENT_CONT)
12822 		return ret;
12823 	return 0;
12824 }
12825 
12826 int perf_buffer__epoll_fd(const struct perf_buffer *pb)
12827 {
12828 	return pb->epoll_fd;
12829 }
12830 
12831 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
12832 {
12833 	int i, cnt, err;
12834 
12835 	cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
12836 	if (cnt < 0)
12837 		return -errno;
12838 
12839 	for (i = 0; i < cnt; i++) {
12840 		struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
12841 
12842 		err = perf_buffer__process_records(pb, cpu_buf);
12843 		if (err) {
12844 			pr_warn("error while processing records: %d\n", err);
12845 			return libbpf_err(err);
12846 		}
12847 	}
12848 	return cnt;
12849 }
12850 
12851 /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
12852  * manager.
12853  */
12854 size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
12855 {
12856 	return pb->cpu_cnt;
12857 }
12858 
12859 /*
12860  * Return perf_event FD of a ring buffer in *buf_idx* slot of
12861  * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
12862  * select()/poll()/epoll() Linux syscalls.
12863  */
12864 int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
12865 {
12866 	struct perf_cpu_buf *cpu_buf;
12867 
12868 	if (buf_idx >= pb->cpu_cnt)
12869 		return libbpf_err(-EINVAL);
12870 
12871 	cpu_buf = pb->cpu_bufs[buf_idx];
12872 	if (!cpu_buf)
12873 		return libbpf_err(-ENOENT);
12874 
12875 	return cpu_buf->fd;
12876 }
12877 
12878 int perf_buffer__buffer(struct perf_buffer *pb, int buf_idx, void **buf, size_t *buf_size)
12879 {
12880 	struct perf_cpu_buf *cpu_buf;
12881 
12882 	if (buf_idx >= pb->cpu_cnt)
12883 		return libbpf_err(-EINVAL);
12884 
12885 	cpu_buf = pb->cpu_bufs[buf_idx];
12886 	if (!cpu_buf)
12887 		return libbpf_err(-ENOENT);
12888 
12889 	*buf = cpu_buf->base;
12890 	*buf_size = pb->mmap_size;
12891 	return 0;
12892 }
12893 
12894 /*
12895  * Consume data from perf ring buffer corresponding to slot *buf_idx* in
12896  * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
12897  * consume, do nothing and return success.
12898  * Returns:
12899  *   - 0 on success;
12900  *   - <0 on failure.
12901  */
12902 int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
12903 {
12904 	struct perf_cpu_buf *cpu_buf;
12905 
12906 	if (buf_idx >= pb->cpu_cnt)
12907 		return libbpf_err(-EINVAL);
12908 
12909 	cpu_buf = pb->cpu_bufs[buf_idx];
12910 	if (!cpu_buf)
12911 		return libbpf_err(-ENOENT);
12912 
12913 	return perf_buffer__process_records(pb, cpu_buf);
12914 }
12915 
12916 int perf_buffer__consume(struct perf_buffer *pb)
12917 {
12918 	int i, err;
12919 
12920 	for (i = 0; i < pb->cpu_cnt; i++) {
12921 		struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
12922 
12923 		if (!cpu_buf)
12924 			continue;
12925 
12926 		err = perf_buffer__process_records(pb, cpu_buf);
12927 		if (err) {
12928 			pr_warn("perf_buffer: failed to process records in buffer #%d: %d\n", i, err);
12929 			return libbpf_err(err);
12930 		}
12931 	}
12932 	return 0;
12933 }
12934 
12935 int bpf_program__set_attach_target(struct bpf_program *prog,
12936 				   int attach_prog_fd,
12937 				   const char *attach_func_name)
12938 {
12939 	int btf_obj_fd = 0, btf_id = 0, err;
12940 
12941 	if (!prog || attach_prog_fd < 0)
12942 		return libbpf_err(-EINVAL);
12943 
12944 	if (prog->obj->loaded)
12945 		return libbpf_err(-EINVAL);
12946 
12947 	if (attach_prog_fd && !attach_func_name) {
12948 		/* remember attach_prog_fd and let bpf_program__load() find
12949 		 * BTF ID during the program load
12950 		 */
12951 		prog->attach_prog_fd = attach_prog_fd;
12952 		return 0;
12953 	}
12954 
12955 	if (attach_prog_fd) {
12956 		btf_id = libbpf_find_prog_btf_id(attach_func_name,
12957 						 attach_prog_fd);
12958 		if (btf_id < 0)
12959 			return libbpf_err(btf_id);
12960 	} else {
12961 		if (!attach_func_name)
12962 			return libbpf_err(-EINVAL);
12963 
12964 		/* load btf_vmlinux, if not yet */
12965 		err = bpf_object__load_vmlinux_btf(prog->obj, true);
12966 		if (err)
12967 			return libbpf_err(err);
12968 		err = find_kernel_btf_id(prog->obj, attach_func_name,
12969 					 prog->expected_attach_type,
12970 					 &btf_obj_fd, &btf_id);
12971 		if (err)
12972 			return libbpf_err(err);
12973 	}
12974 
12975 	prog->attach_btf_id = btf_id;
12976 	prog->attach_btf_obj_fd = btf_obj_fd;
12977 	prog->attach_prog_fd = attach_prog_fd;
12978 	return 0;
12979 }
12980 
12981 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
12982 {
12983 	int err = 0, n, len, start, end = -1;
12984 	bool *tmp;
12985 
12986 	*mask = NULL;
12987 	*mask_sz = 0;
12988 
12989 	/* Each sub string separated by ',' has format \d+-\d+ or \d+ */
12990 	while (*s) {
12991 		if (*s == ',' || *s == '\n') {
12992 			s++;
12993 			continue;
12994 		}
12995 		n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
12996 		if (n <= 0 || n > 2) {
12997 			pr_warn("Failed to get CPU range %s: %d\n", s, n);
12998 			err = -EINVAL;
12999 			goto cleanup;
13000 		} else if (n == 1) {
13001 			end = start;
13002 		}
13003 		if (start < 0 || start > end) {
13004 			pr_warn("Invalid CPU range [%d,%d] in %s\n",
13005 				start, end, s);
13006 			err = -EINVAL;
13007 			goto cleanup;
13008 		}
13009 		tmp = realloc(*mask, end + 1);
13010 		if (!tmp) {
13011 			err = -ENOMEM;
13012 			goto cleanup;
13013 		}
13014 		*mask = tmp;
13015 		memset(tmp + *mask_sz, 0, start - *mask_sz);
13016 		memset(tmp + start, 1, end - start + 1);
13017 		*mask_sz = end + 1;
13018 		s += len;
13019 	}
13020 	if (!*mask_sz) {
13021 		pr_warn("Empty CPU range\n");
13022 		return -EINVAL;
13023 	}
13024 	return 0;
13025 cleanup:
13026 	free(*mask);
13027 	*mask = NULL;
13028 	return err;
13029 }
13030 
13031 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
13032 {
13033 	int fd, err = 0, len;
13034 	char buf[128];
13035 
13036 	fd = open(fcpu, O_RDONLY | O_CLOEXEC);
13037 	if (fd < 0) {
13038 		err = -errno;
13039 		pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
13040 		return err;
13041 	}
13042 	len = read(fd, buf, sizeof(buf));
13043 	close(fd);
13044 	if (len <= 0) {
13045 		err = len ? -errno : -EINVAL;
13046 		pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
13047 		return err;
13048 	}
13049 	if (len >= sizeof(buf)) {
13050 		pr_warn("CPU mask is too big in file %s\n", fcpu);
13051 		return -E2BIG;
13052 	}
13053 	buf[len] = '\0';
13054 
13055 	return parse_cpu_mask_str(buf, mask, mask_sz);
13056 }
13057 
13058 int libbpf_num_possible_cpus(void)
13059 {
13060 	static const char *fcpu = "/sys/devices/system/cpu/possible";
13061 	static int cpus;
13062 	int err, n, i, tmp_cpus;
13063 	bool *mask;
13064 
13065 	tmp_cpus = READ_ONCE(cpus);
13066 	if (tmp_cpus > 0)
13067 		return tmp_cpus;
13068 
13069 	err = parse_cpu_mask_file(fcpu, &mask, &n);
13070 	if (err)
13071 		return libbpf_err(err);
13072 
13073 	tmp_cpus = 0;
13074 	for (i = 0; i < n; i++) {
13075 		if (mask[i])
13076 			tmp_cpus++;
13077 	}
13078 	free(mask);
13079 
13080 	WRITE_ONCE(cpus, tmp_cpus);
13081 	return tmp_cpus;
13082 }
13083 
13084 static int populate_skeleton_maps(const struct bpf_object *obj,
13085 				  struct bpf_map_skeleton *maps,
13086 				  size_t map_cnt)
13087 {
13088 	int i;
13089 
13090 	for (i = 0; i < map_cnt; i++) {
13091 		struct bpf_map **map = maps[i].map;
13092 		const char *name = maps[i].name;
13093 		void **mmaped = maps[i].mmaped;
13094 
13095 		*map = bpf_object__find_map_by_name(obj, name);
13096 		if (!*map) {
13097 			pr_warn("failed to find skeleton map '%s'\n", name);
13098 			return -ESRCH;
13099 		}
13100 
13101 		/* externs shouldn't be pre-setup from user code */
13102 		if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
13103 			*mmaped = (*map)->mmaped;
13104 	}
13105 	return 0;
13106 }
13107 
13108 static int populate_skeleton_progs(const struct bpf_object *obj,
13109 				   struct bpf_prog_skeleton *progs,
13110 				   size_t prog_cnt)
13111 {
13112 	int i;
13113 
13114 	for (i = 0; i < prog_cnt; i++) {
13115 		struct bpf_program **prog = progs[i].prog;
13116 		const char *name = progs[i].name;
13117 
13118 		*prog = bpf_object__find_program_by_name(obj, name);
13119 		if (!*prog) {
13120 			pr_warn("failed to find skeleton program '%s'\n", name);
13121 			return -ESRCH;
13122 		}
13123 	}
13124 	return 0;
13125 }
13126 
13127 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
13128 			      const struct bpf_object_open_opts *opts)
13129 {
13130 	DECLARE_LIBBPF_OPTS(bpf_object_open_opts, skel_opts,
13131 		.object_name = s->name,
13132 	);
13133 	struct bpf_object *obj;
13134 	int err;
13135 
13136 	/* Attempt to preserve opts->object_name, unless overriden by user
13137 	 * explicitly. Overwriting object name for skeletons is discouraged,
13138 	 * as it breaks global data maps, because they contain object name
13139 	 * prefix as their own map name prefix. When skeleton is generated,
13140 	 * bpftool is making an assumption that this name will stay the same.
13141 	 */
13142 	if (opts) {
13143 		memcpy(&skel_opts, opts, sizeof(*opts));
13144 		if (!opts->object_name)
13145 			skel_opts.object_name = s->name;
13146 	}
13147 
13148 	obj = bpf_object__open_mem(s->data, s->data_sz, &skel_opts);
13149 	err = libbpf_get_error(obj);
13150 	if (err) {
13151 		pr_warn("failed to initialize skeleton BPF object '%s': %d\n",
13152 			s->name, err);
13153 		return libbpf_err(err);
13154 	}
13155 
13156 	*s->obj = obj;
13157 	err = populate_skeleton_maps(obj, s->maps, s->map_cnt);
13158 	if (err) {
13159 		pr_warn("failed to populate skeleton maps for '%s': %d\n", s->name, err);
13160 		return libbpf_err(err);
13161 	}
13162 
13163 	err = populate_skeleton_progs(obj, s->progs, s->prog_cnt);
13164 	if (err) {
13165 		pr_warn("failed to populate skeleton progs for '%s': %d\n", s->name, err);
13166 		return libbpf_err(err);
13167 	}
13168 
13169 	return 0;
13170 }
13171 
13172 int bpf_object__open_subskeleton(struct bpf_object_subskeleton *s)
13173 {
13174 	int err, len, var_idx, i;
13175 	const char *var_name;
13176 	const struct bpf_map *map;
13177 	struct btf *btf;
13178 	__u32 map_type_id;
13179 	const struct btf_type *map_type, *var_type;
13180 	const struct bpf_var_skeleton *var_skel;
13181 	struct btf_var_secinfo *var;
13182 
13183 	if (!s->obj)
13184 		return libbpf_err(-EINVAL);
13185 
13186 	btf = bpf_object__btf(s->obj);
13187 	if (!btf) {
13188 		pr_warn("subskeletons require BTF at runtime (object %s)\n",
13189 			bpf_object__name(s->obj));
13190 		return libbpf_err(-errno);
13191 	}
13192 
13193 	err = populate_skeleton_maps(s->obj, s->maps, s->map_cnt);
13194 	if (err) {
13195 		pr_warn("failed to populate subskeleton maps: %d\n", err);
13196 		return libbpf_err(err);
13197 	}
13198 
13199 	err = populate_skeleton_progs(s->obj, s->progs, s->prog_cnt);
13200 	if (err) {
13201 		pr_warn("failed to populate subskeleton maps: %d\n", err);
13202 		return libbpf_err(err);
13203 	}
13204 
13205 	for (var_idx = 0; var_idx < s->var_cnt; var_idx++) {
13206 		var_skel = &s->vars[var_idx];
13207 		map = *var_skel->map;
13208 		map_type_id = bpf_map__btf_value_type_id(map);
13209 		map_type = btf__type_by_id(btf, map_type_id);
13210 
13211 		if (!btf_is_datasec(map_type)) {
13212 			pr_warn("type for map '%1$s' is not a datasec: %2$s",
13213 				bpf_map__name(map),
13214 				__btf_kind_str(btf_kind(map_type)));
13215 			return libbpf_err(-EINVAL);
13216 		}
13217 
13218 		len = btf_vlen(map_type);
13219 		var = btf_var_secinfos(map_type);
13220 		for (i = 0; i < len; i++, var++) {
13221 			var_type = btf__type_by_id(btf, var->type);
13222 			var_name = btf__name_by_offset(btf, var_type->name_off);
13223 			if (strcmp(var_name, var_skel->name) == 0) {
13224 				*var_skel->addr = map->mmaped + var->offset;
13225 				break;
13226 			}
13227 		}
13228 	}
13229 	return 0;
13230 }
13231 
13232 void bpf_object__destroy_subskeleton(struct bpf_object_subskeleton *s)
13233 {
13234 	if (!s)
13235 		return;
13236 	free(s->maps);
13237 	free(s->progs);
13238 	free(s->vars);
13239 	free(s);
13240 }
13241 
13242 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
13243 {
13244 	int i, err;
13245 
13246 	err = bpf_object__load(*s->obj);
13247 	if (err) {
13248 		pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
13249 		return libbpf_err(err);
13250 	}
13251 
13252 	for (i = 0; i < s->map_cnt; i++) {
13253 		struct bpf_map *map = *s->maps[i].map;
13254 		size_t mmap_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
13255 		int prot, map_fd = bpf_map__fd(map);
13256 		void **mmaped = s->maps[i].mmaped;
13257 
13258 		if (!mmaped)
13259 			continue;
13260 
13261 		if (!(map->def.map_flags & BPF_F_MMAPABLE)) {
13262 			*mmaped = NULL;
13263 			continue;
13264 		}
13265 
13266 		if (map->def.map_flags & BPF_F_RDONLY_PROG)
13267 			prot = PROT_READ;
13268 		else
13269 			prot = PROT_READ | PROT_WRITE;
13270 
13271 		/* Remap anonymous mmap()-ed "map initialization image" as
13272 		 * a BPF map-backed mmap()-ed memory, but preserving the same
13273 		 * memory address. This will cause kernel to change process'
13274 		 * page table to point to a different piece of kernel memory,
13275 		 * but from userspace point of view memory address (and its
13276 		 * contents, being identical at this point) will stay the
13277 		 * same. This mapping will be released by bpf_object__close()
13278 		 * as per normal clean up procedure, so we don't need to worry
13279 		 * about it from skeleton's clean up perspective.
13280 		 */
13281 		*mmaped = mmap(map->mmaped, mmap_sz, prot, MAP_SHARED | MAP_FIXED, map_fd, 0);
13282 		if (*mmaped == MAP_FAILED) {
13283 			err = -errno;
13284 			*mmaped = NULL;
13285 			pr_warn("failed to re-mmap() map '%s': %d\n",
13286 				 bpf_map__name(map), err);
13287 			return libbpf_err(err);
13288 		}
13289 	}
13290 
13291 	return 0;
13292 }
13293 
13294 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
13295 {
13296 	int i, err;
13297 
13298 	for (i = 0; i < s->prog_cnt; i++) {
13299 		struct bpf_program *prog = *s->progs[i].prog;
13300 		struct bpf_link **link = s->progs[i].link;
13301 
13302 		if (!prog->autoload || !prog->autoattach)
13303 			continue;
13304 
13305 		/* auto-attaching not supported for this program */
13306 		if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
13307 			continue;
13308 
13309 		/* if user already set the link manually, don't attempt auto-attach */
13310 		if (*link)
13311 			continue;
13312 
13313 		err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, link);
13314 		if (err) {
13315 			pr_warn("prog '%s': failed to auto-attach: %d\n",
13316 				bpf_program__name(prog), err);
13317 			return libbpf_err(err);
13318 		}
13319 
13320 		/* It's possible that for some SEC() definitions auto-attach
13321 		 * is supported in some cases (e.g., if definition completely
13322 		 * specifies target information), but is not in other cases.
13323 		 * SEC("uprobe") is one such case. If user specified target
13324 		 * binary and function name, such BPF program can be
13325 		 * auto-attached. But if not, it shouldn't trigger skeleton's
13326 		 * attach to fail. It should just be skipped.
13327 		 * attach_fn signals such case with returning 0 (no error) and
13328 		 * setting link to NULL.
13329 		 */
13330 	}
13331 
13332 	return 0;
13333 }
13334 
13335 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
13336 {
13337 	int i;
13338 
13339 	for (i = 0; i < s->prog_cnt; i++) {
13340 		struct bpf_link **link = s->progs[i].link;
13341 
13342 		bpf_link__destroy(*link);
13343 		*link = NULL;
13344 	}
13345 }
13346 
13347 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
13348 {
13349 	if (!s)
13350 		return;
13351 
13352 	if (s->progs)
13353 		bpf_object__detach_skeleton(s);
13354 	if (s->obj)
13355 		bpf_object__close(*s->obj);
13356 	free(s->maps);
13357 	free(s->progs);
13358 	free(s);
13359 }
13360