xref: /linux-6.15/tools/lib/bpf/libbpf.c (revision 20e109ea)
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 <[email protected]>
7  * Copyright (C) 2015 Wang Nan <[email protected]>
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 static int map_set_def_max_entries(struct bpf_map *map);
74 
75 static const char * const attach_type_name[] = {
76 	[BPF_CGROUP_INET_INGRESS]	= "cgroup_inet_ingress",
77 	[BPF_CGROUP_INET_EGRESS]	= "cgroup_inet_egress",
78 	[BPF_CGROUP_INET_SOCK_CREATE]	= "cgroup_inet_sock_create",
79 	[BPF_CGROUP_INET_SOCK_RELEASE]	= "cgroup_inet_sock_release",
80 	[BPF_CGROUP_SOCK_OPS]		= "cgroup_sock_ops",
81 	[BPF_CGROUP_DEVICE]		= "cgroup_device",
82 	[BPF_CGROUP_INET4_BIND]		= "cgroup_inet4_bind",
83 	[BPF_CGROUP_INET6_BIND]		= "cgroup_inet6_bind",
84 	[BPF_CGROUP_INET4_CONNECT]	= "cgroup_inet4_connect",
85 	[BPF_CGROUP_INET6_CONNECT]	= "cgroup_inet6_connect",
86 	[BPF_CGROUP_UNIX_CONNECT]       = "cgroup_unix_connect",
87 	[BPF_CGROUP_INET4_POST_BIND]	= "cgroup_inet4_post_bind",
88 	[BPF_CGROUP_INET6_POST_BIND]	= "cgroup_inet6_post_bind",
89 	[BPF_CGROUP_INET4_GETPEERNAME]	= "cgroup_inet4_getpeername",
90 	[BPF_CGROUP_INET6_GETPEERNAME]	= "cgroup_inet6_getpeername",
91 	[BPF_CGROUP_UNIX_GETPEERNAME]	= "cgroup_unix_getpeername",
92 	[BPF_CGROUP_INET4_GETSOCKNAME]	= "cgroup_inet4_getsockname",
93 	[BPF_CGROUP_INET6_GETSOCKNAME]	= "cgroup_inet6_getsockname",
94 	[BPF_CGROUP_UNIX_GETSOCKNAME]	= "cgroup_unix_getsockname",
95 	[BPF_CGROUP_UDP4_SENDMSG]	= "cgroup_udp4_sendmsg",
96 	[BPF_CGROUP_UDP6_SENDMSG]	= "cgroup_udp6_sendmsg",
97 	[BPF_CGROUP_UNIX_SENDMSG]	= "cgroup_unix_sendmsg",
98 	[BPF_CGROUP_SYSCTL]		= "cgroup_sysctl",
99 	[BPF_CGROUP_UDP4_RECVMSG]	= "cgroup_udp4_recvmsg",
100 	[BPF_CGROUP_UDP6_RECVMSG]	= "cgroup_udp6_recvmsg",
101 	[BPF_CGROUP_UNIX_RECVMSG]	= "cgroup_unix_recvmsg",
102 	[BPF_CGROUP_GETSOCKOPT]		= "cgroup_getsockopt",
103 	[BPF_CGROUP_SETSOCKOPT]		= "cgroup_setsockopt",
104 	[BPF_SK_SKB_STREAM_PARSER]	= "sk_skb_stream_parser",
105 	[BPF_SK_SKB_STREAM_VERDICT]	= "sk_skb_stream_verdict",
106 	[BPF_SK_SKB_VERDICT]		= "sk_skb_verdict",
107 	[BPF_SK_MSG_VERDICT]		= "sk_msg_verdict",
108 	[BPF_LIRC_MODE2]		= "lirc_mode2",
109 	[BPF_FLOW_DISSECTOR]		= "flow_dissector",
110 	[BPF_TRACE_RAW_TP]		= "trace_raw_tp",
111 	[BPF_TRACE_FENTRY]		= "trace_fentry",
112 	[BPF_TRACE_FEXIT]		= "trace_fexit",
113 	[BPF_MODIFY_RETURN]		= "modify_return",
114 	[BPF_LSM_MAC]			= "lsm_mac",
115 	[BPF_LSM_CGROUP]		= "lsm_cgroup",
116 	[BPF_SK_LOOKUP]			= "sk_lookup",
117 	[BPF_TRACE_ITER]		= "trace_iter",
118 	[BPF_XDP_DEVMAP]		= "xdp_devmap",
119 	[BPF_XDP_CPUMAP]		= "xdp_cpumap",
120 	[BPF_XDP]			= "xdp",
121 	[BPF_SK_REUSEPORT_SELECT]	= "sk_reuseport_select",
122 	[BPF_SK_REUSEPORT_SELECT_OR_MIGRATE]	= "sk_reuseport_select_or_migrate",
123 	[BPF_PERF_EVENT]		= "perf_event",
124 	[BPF_TRACE_KPROBE_MULTI]	= "trace_kprobe_multi",
125 	[BPF_STRUCT_OPS]		= "struct_ops",
126 	[BPF_NETFILTER]			= "netfilter",
127 	[BPF_TCX_INGRESS]		= "tcx_ingress",
128 	[BPF_TCX_EGRESS]		= "tcx_egress",
129 	[BPF_TRACE_UPROBE_MULTI]	= "trace_uprobe_multi",
130 	[BPF_NETKIT_PRIMARY]		= "netkit_primary",
131 	[BPF_NETKIT_PEER]		= "netkit_peer",
132 };
133 
134 static const char * const link_type_name[] = {
135 	[BPF_LINK_TYPE_UNSPEC]			= "unspec",
136 	[BPF_LINK_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
137 	[BPF_LINK_TYPE_TRACING]			= "tracing",
138 	[BPF_LINK_TYPE_CGROUP]			= "cgroup",
139 	[BPF_LINK_TYPE_ITER]			= "iter",
140 	[BPF_LINK_TYPE_NETNS]			= "netns",
141 	[BPF_LINK_TYPE_XDP]			= "xdp",
142 	[BPF_LINK_TYPE_PERF_EVENT]		= "perf_event",
143 	[BPF_LINK_TYPE_KPROBE_MULTI]		= "kprobe_multi",
144 	[BPF_LINK_TYPE_STRUCT_OPS]		= "struct_ops",
145 	[BPF_LINK_TYPE_NETFILTER]		= "netfilter",
146 	[BPF_LINK_TYPE_TCX]			= "tcx",
147 	[BPF_LINK_TYPE_UPROBE_MULTI]		= "uprobe_multi",
148 	[BPF_LINK_TYPE_NETKIT]			= "netkit",
149 };
150 
151 static const char * const map_type_name[] = {
152 	[BPF_MAP_TYPE_UNSPEC]			= "unspec",
153 	[BPF_MAP_TYPE_HASH]			= "hash",
154 	[BPF_MAP_TYPE_ARRAY]			= "array",
155 	[BPF_MAP_TYPE_PROG_ARRAY]		= "prog_array",
156 	[BPF_MAP_TYPE_PERF_EVENT_ARRAY]		= "perf_event_array",
157 	[BPF_MAP_TYPE_PERCPU_HASH]		= "percpu_hash",
158 	[BPF_MAP_TYPE_PERCPU_ARRAY]		= "percpu_array",
159 	[BPF_MAP_TYPE_STACK_TRACE]		= "stack_trace",
160 	[BPF_MAP_TYPE_CGROUP_ARRAY]		= "cgroup_array",
161 	[BPF_MAP_TYPE_LRU_HASH]			= "lru_hash",
162 	[BPF_MAP_TYPE_LRU_PERCPU_HASH]		= "lru_percpu_hash",
163 	[BPF_MAP_TYPE_LPM_TRIE]			= "lpm_trie",
164 	[BPF_MAP_TYPE_ARRAY_OF_MAPS]		= "array_of_maps",
165 	[BPF_MAP_TYPE_HASH_OF_MAPS]		= "hash_of_maps",
166 	[BPF_MAP_TYPE_DEVMAP]			= "devmap",
167 	[BPF_MAP_TYPE_DEVMAP_HASH]		= "devmap_hash",
168 	[BPF_MAP_TYPE_SOCKMAP]			= "sockmap",
169 	[BPF_MAP_TYPE_CPUMAP]			= "cpumap",
170 	[BPF_MAP_TYPE_XSKMAP]			= "xskmap",
171 	[BPF_MAP_TYPE_SOCKHASH]			= "sockhash",
172 	[BPF_MAP_TYPE_CGROUP_STORAGE]		= "cgroup_storage",
173 	[BPF_MAP_TYPE_REUSEPORT_SOCKARRAY]	= "reuseport_sockarray",
174 	[BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE]	= "percpu_cgroup_storage",
175 	[BPF_MAP_TYPE_QUEUE]			= "queue",
176 	[BPF_MAP_TYPE_STACK]			= "stack",
177 	[BPF_MAP_TYPE_SK_STORAGE]		= "sk_storage",
178 	[BPF_MAP_TYPE_STRUCT_OPS]		= "struct_ops",
179 	[BPF_MAP_TYPE_RINGBUF]			= "ringbuf",
180 	[BPF_MAP_TYPE_INODE_STORAGE]		= "inode_storage",
181 	[BPF_MAP_TYPE_TASK_STORAGE]		= "task_storage",
182 	[BPF_MAP_TYPE_BLOOM_FILTER]		= "bloom_filter",
183 	[BPF_MAP_TYPE_USER_RINGBUF]             = "user_ringbuf",
184 	[BPF_MAP_TYPE_CGRP_STORAGE]		= "cgrp_storage",
185 };
186 
187 static const char * const prog_type_name[] = {
188 	[BPF_PROG_TYPE_UNSPEC]			= "unspec",
189 	[BPF_PROG_TYPE_SOCKET_FILTER]		= "socket_filter",
190 	[BPF_PROG_TYPE_KPROBE]			= "kprobe",
191 	[BPF_PROG_TYPE_SCHED_CLS]		= "sched_cls",
192 	[BPF_PROG_TYPE_SCHED_ACT]		= "sched_act",
193 	[BPF_PROG_TYPE_TRACEPOINT]		= "tracepoint",
194 	[BPF_PROG_TYPE_XDP]			= "xdp",
195 	[BPF_PROG_TYPE_PERF_EVENT]		= "perf_event",
196 	[BPF_PROG_TYPE_CGROUP_SKB]		= "cgroup_skb",
197 	[BPF_PROG_TYPE_CGROUP_SOCK]		= "cgroup_sock",
198 	[BPF_PROG_TYPE_LWT_IN]			= "lwt_in",
199 	[BPF_PROG_TYPE_LWT_OUT]			= "lwt_out",
200 	[BPF_PROG_TYPE_LWT_XMIT]		= "lwt_xmit",
201 	[BPF_PROG_TYPE_SOCK_OPS]		= "sock_ops",
202 	[BPF_PROG_TYPE_SK_SKB]			= "sk_skb",
203 	[BPF_PROG_TYPE_CGROUP_DEVICE]		= "cgroup_device",
204 	[BPF_PROG_TYPE_SK_MSG]			= "sk_msg",
205 	[BPF_PROG_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
206 	[BPF_PROG_TYPE_CGROUP_SOCK_ADDR]	= "cgroup_sock_addr",
207 	[BPF_PROG_TYPE_LWT_SEG6LOCAL]		= "lwt_seg6local",
208 	[BPF_PROG_TYPE_LIRC_MODE2]		= "lirc_mode2",
209 	[BPF_PROG_TYPE_SK_REUSEPORT]		= "sk_reuseport",
210 	[BPF_PROG_TYPE_FLOW_DISSECTOR]		= "flow_dissector",
211 	[BPF_PROG_TYPE_CGROUP_SYSCTL]		= "cgroup_sysctl",
212 	[BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE]	= "raw_tracepoint_writable",
213 	[BPF_PROG_TYPE_CGROUP_SOCKOPT]		= "cgroup_sockopt",
214 	[BPF_PROG_TYPE_TRACING]			= "tracing",
215 	[BPF_PROG_TYPE_STRUCT_OPS]		= "struct_ops",
216 	[BPF_PROG_TYPE_EXT]			= "ext",
217 	[BPF_PROG_TYPE_LSM]			= "lsm",
218 	[BPF_PROG_TYPE_SK_LOOKUP]		= "sk_lookup",
219 	[BPF_PROG_TYPE_SYSCALL]			= "syscall",
220 	[BPF_PROG_TYPE_NETFILTER]		= "netfilter",
221 };
222 
223 static int __base_pr(enum libbpf_print_level level, const char *format,
224 		     va_list args)
225 {
226 	if (level == LIBBPF_DEBUG)
227 		return 0;
228 
229 	return vfprintf(stderr, format, args);
230 }
231 
232 static libbpf_print_fn_t __libbpf_pr = __base_pr;
233 
234 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
235 {
236 	libbpf_print_fn_t old_print_fn;
237 
238 	old_print_fn = __atomic_exchange_n(&__libbpf_pr, fn, __ATOMIC_RELAXED);
239 
240 	return old_print_fn;
241 }
242 
243 __printf(2, 3)
244 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
245 {
246 	va_list args;
247 	int old_errno;
248 	libbpf_print_fn_t print_fn;
249 
250 	print_fn = __atomic_load_n(&__libbpf_pr, __ATOMIC_RELAXED);
251 	if (!print_fn)
252 		return;
253 
254 	old_errno = errno;
255 
256 	va_start(args, format);
257 	__libbpf_pr(level, format, args);
258 	va_end(args);
259 
260 	errno = old_errno;
261 }
262 
263 static void pr_perm_msg(int err)
264 {
265 	struct rlimit limit;
266 	char buf[100];
267 
268 	if (err != -EPERM || geteuid() != 0)
269 		return;
270 
271 	err = getrlimit(RLIMIT_MEMLOCK, &limit);
272 	if (err)
273 		return;
274 
275 	if (limit.rlim_cur == RLIM_INFINITY)
276 		return;
277 
278 	if (limit.rlim_cur < 1024)
279 		snprintf(buf, sizeof(buf), "%zu bytes", (size_t)limit.rlim_cur);
280 	else if (limit.rlim_cur < 1024*1024)
281 		snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
282 	else
283 		snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
284 
285 	pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
286 		buf);
287 }
288 
289 #define STRERR_BUFSIZE  128
290 
291 /* Copied from tools/perf/util/util.h */
292 #ifndef zfree
293 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
294 #endif
295 
296 #ifndef zclose
297 # define zclose(fd) ({			\
298 	int ___err = 0;			\
299 	if ((fd) >= 0)			\
300 		___err = close((fd));	\
301 	fd = -1;			\
302 	___err; })
303 #endif
304 
305 static inline __u64 ptr_to_u64(const void *ptr)
306 {
307 	return (__u64) (unsigned long) ptr;
308 }
309 
310 int libbpf_set_strict_mode(enum libbpf_strict_mode mode)
311 {
312 	/* as of v1.0 libbpf_set_strict_mode() is a no-op */
313 	return 0;
314 }
315 
316 __u32 libbpf_major_version(void)
317 {
318 	return LIBBPF_MAJOR_VERSION;
319 }
320 
321 __u32 libbpf_minor_version(void)
322 {
323 	return LIBBPF_MINOR_VERSION;
324 }
325 
326 const char *libbpf_version_string(void)
327 {
328 #define __S(X) #X
329 #define _S(X) __S(X)
330 	return  "v" _S(LIBBPF_MAJOR_VERSION) "." _S(LIBBPF_MINOR_VERSION);
331 #undef _S
332 #undef __S
333 }
334 
335 enum reloc_type {
336 	RELO_LD64,
337 	RELO_CALL,
338 	RELO_DATA,
339 	RELO_EXTERN_LD64,
340 	RELO_EXTERN_CALL,
341 	RELO_SUBPROG_ADDR,
342 	RELO_CORE,
343 };
344 
345 struct reloc_desc {
346 	enum reloc_type type;
347 	int insn_idx;
348 	union {
349 		const struct bpf_core_relo *core_relo; /* used when type == RELO_CORE */
350 		struct {
351 			int map_idx;
352 			int sym_off;
353 			int ext_idx;
354 		};
355 	};
356 };
357 
358 /* stored as sec_def->cookie for all libbpf-supported SEC()s */
359 enum sec_def_flags {
360 	SEC_NONE = 0,
361 	/* expected_attach_type is optional, if kernel doesn't support that */
362 	SEC_EXP_ATTACH_OPT = 1,
363 	/* legacy, only used by libbpf_get_type_names() and
364 	 * libbpf_attach_type_by_name(), not used by libbpf itself at all.
365 	 * This used to be associated with cgroup (and few other) BPF programs
366 	 * that were attachable through BPF_PROG_ATTACH command. Pretty
367 	 * meaningless nowadays, though.
368 	 */
369 	SEC_ATTACHABLE = 2,
370 	SEC_ATTACHABLE_OPT = SEC_ATTACHABLE | SEC_EXP_ATTACH_OPT,
371 	/* attachment target is specified through BTF ID in either kernel or
372 	 * other BPF program's BTF object
373 	 */
374 	SEC_ATTACH_BTF = 4,
375 	/* BPF program type allows sleeping/blocking in kernel */
376 	SEC_SLEEPABLE = 8,
377 	/* BPF program support non-linear XDP buffer */
378 	SEC_XDP_FRAGS = 16,
379 	/* Setup proper attach type for usdt probes. */
380 	SEC_USDT = 32,
381 };
382 
383 struct bpf_sec_def {
384 	char *sec;
385 	enum bpf_prog_type prog_type;
386 	enum bpf_attach_type expected_attach_type;
387 	long cookie;
388 	int handler_id;
389 
390 	libbpf_prog_setup_fn_t prog_setup_fn;
391 	libbpf_prog_prepare_load_fn_t prog_prepare_load_fn;
392 	libbpf_prog_attach_fn_t prog_attach_fn;
393 };
394 
395 /*
396  * bpf_prog should be a better name but it has been used in
397  * linux/filter.h.
398  */
399 struct bpf_program {
400 	char *name;
401 	char *sec_name;
402 	size_t sec_idx;
403 	const struct bpf_sec_def *sec_def;
404 	/* this program's instruction offset (in number of instructions)
405 	 * within its containing ELF section
406 	 */
407 	size_t sec_insn_off;
408 	/* number of original instructions in ELF section belonging to this
409 	 * program, not taking into account subprogram instructions possible
410 	 * appended later during relocation
411 	 */
412 	size_t sec_insn_cnt;
413 	/* Offset (in number of instructions) of the start of instruction
414 	 * belonging to this BPF program  within its containing main BPF
415 	 * program. For the entry-point (main) BPF program, this is always
416 	 * zero. For a sub-program, this gets reset before each of main BPF
417 	 * programs are processed and relocated and is used to determined
418 	 * whether sub-program was already appended to the main program, and
419 	 * if yes, at which instruction offset.
420 	 */
421 	size_t sub_insn_off;
422 
423 	/* instructions that belong to BPF program; insns[0] is located at
424 	 * sec_insn_off instruction within its ELF section in ELF file, so
425 	 * when mapping ELF file instruction index to the local instruction,
426 	 * one needs to subtract sec_insn_off; and vice versa.
427 	 */
428 	struct bpf_insn *insns;
429 	/* actual number of instruction in this BPF program's image; for
430 	 * entry-point BPF programs this includes the size of main program
431 	 * itself plus all the used sub-programs, appended at the end
432 	 */
433 	size_t insns_cnt;
434 
435 	struct reloc_desc *reloc_desc;
436 	int nr_reloc;
437 
438 	/* BPF verifier log settings */
439 	char *log_buf;
440 	size_t log_size;
441 	__u32 log_level;
442 
443 	struct bpf_object *obj;
444 
445 	int fd;
446 	bool autoload;
447 	bool autoattach;
448 	bool sym_global;
449 	bool mark_btf_static;
450 	enum bpf_prog_type type;
451 	enum bpf_attach_type expected_attach_type;
452 	int exception_cb_idx;
453 
454 	int prog_ifindex;
455 	__u32 attach_btf_obj_fd;
456 	__u32 attach_btf_id;
457 	__u32 attach_prog_fd;
458 
459 	void *func_info;
460 	__u32 func_info_rec_size;
461 	__u32 func_info_cnt;
462 
463 	void *line_info;
464 	__u32 line_info_rec_size;
465 	__u32 line_info_cnt;
466 	__u32 prog_flags;
467 };
468 
469 struct bpf_struct_ops {
470 	const char *tname;
471 	const struct btf_type *type;
472 	struct bpf_program **progs;
473 	__u32 *kern_func_off;
474 	/* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
475 	void *data;
476 	/* e.g. struct bpf_struct_ops_tcp_congestion_ops in
477 	 *      btf_vmlinux's format.
478 	 * struct bpf_struct_ops_tcp_congestion_ops {
479 	 *	[... some other kernel fields ...]
480 	 *	struct tcp_congestion_ops data;
481 	 * }
482 	 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
483 	 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
484 	 * from "data".
485 	 */
486 	void *kern_vdata;
487 	__u32 type_id;
488 };
489 
490 #define DATA_SEC ".data"
491 #define BSS_SEC ".bss"
492 #define RODATA_SEC ".rodata"
493 #define KCONFIG_SEC ".kconfig"
494 #define KSYMS_SEC ".ksyms"
495 #define STRUCT_OPS_SEC ".struct_ops"
496 #define STRUCT_OPS_LINK_SEC ".struct_ops.link"
497 
498 enum libbpf_map_type {
499 	LIBBPF_MAP_UNSPEC,
500 	LIBBPF_MAP_DATA,
501 	LIBBPF_MAP_BSS,
502 	LIBBPF_MAP_RODATA,
503 	LIBBPF_MAP_KCONFIG,
504 };
505 
506 struct bpf_map_def {
507 	unsigned int type;
508 	unsigned int key_size;
509 	unsigned int value_size;
510 	unsigned int max_entries;
511 	unsigned int map_flags;
512 };
513 
514 struct bpf_map {
515 	struct bpf_object *obj;
516 	char *name;
517 	/* real_name is defined for special internal maps (.rodata*,
518 	 * .data*, .bss, .kconfig) and preserves their original ELF section
519 	 * name. This is important to be able to find corresponding BTF
520 	 * DATASEC information.
521 	 */
522 	char *real_name;
523 	int fd;
524 	int sec_idx;
525 	size_t sec_offset;
526 	int map_ifindex;
527 	int inner_map_fd;
528 	struct bpf_map_def def;
529 	__u32 numa_node;
530 	__u32 btf_var_idx;
531 	__u32 btf_key_type_id;
532 	__u32 btf_value_type_id;
533 	__u32 btf_vmlinux_value_type_id;
534 	enum libbpf_map_type libbpf_type;
535 	void *mmaped;
536 	struct bpf_struct_ops *st_ops;
537 	struct bpf_map *inner_map;
538 	void **init_slots;
539 	int init_slots_sz;
540 	char *pin_path;
541 	bool pinned;
542 	bool reused;
543 	bool autocreate;
544 	__u64 map_extra;
545 };
546 
547 enum extern_type {
548 	EXT_UNKNOWN,
549 	EXT_KCFG,
550 	EXT_KSYM,
551 };
552 
553 enum kcfg_type {
554 	KCFG_UNKNOWN,
555 	KCFG_CHAR,
556 	KCFG_BOOL,
557 	KCFG_INT,
558 	KCFG_TRISTATE,
559 	KCFG_CHAR_ARR,
560 };
561 
562 struct extern_desc {
563 	enum extern_type type;
564 	int sym_idx;
565 	int btf_id;
566 	int sec_btf_id;
567 	const char *name;
568 	char *essent_name;
569 	bool is_set;
570 	bool is_weak;
571 	union {
572 		struct {
573 			enum kcfg_type type;
574 			int sz;
575 			int align;
576 			int data_off;
577 			bool is_signed;
578 		} kcfg;
579 		struct {
580 			unsigned long long addr;
581 
582 			/* target btf_id of the corresponding kernel var. */
583 			int kernel_btf_obj_fd;
584 			int kernel_btf_id;
585 
586 			/* local btf_id of the ksym extern's type. */
587 			__u32 type_id;
588 			/* BTF fd index to be patched in for insn->off, this is
589 			 * 0 for vmlinux BTF, index in obj->fd_array for module
590 			 * BTF
591 			 */
592 			__s16 btf_fd_idx;
593 		} ksym;
594 	};
595 };
596 
597 struct module_btf {
598 	struct btf *btf;
599 	char *name;
600 	__u32 id;
601 	int fd;
602 	int fd_array_idx;
603 };
604 
605 enum sec_type {
606 	SEC_UNUSED = 0,
607 	SEC_RELO,
608 	SEC_BSS,
609 	SEC_DATA,
610 	SEC_RODATA,
611 };
612 
613 struct elf_sec_desc {
614 	enum sec_type sec_type;
615 	Elf64_Shdr *shdr;
616 	Elf_Data *data;
617 };
618 
619 struct elf_state {
620 	int fd;
621 	const void *obj_buf;
622 	size_t obj_buf_sz;
623 	Elf *elf;
624 	Elf64_Ehdr *ehdr;
625 	Elf_Data *symbols;
626 	Elf_Data *st_ops_data;
627 	Elf_Data *st_ops_link_data;
628 	size_t shstrndx; /* section index for section name strings */
629 	size_t strtabidx;
630 	struct elf_sec_desc *secs;
631 	size_t sec_cnt;
632 	int btf_maps_shndx;
633 	__u32 btf_maps_sec_btf_id;
634 	int text_shndx;
635 	int symbols_shndx;
636 	int st_ops_shndx;
637 	int st_ops_link_shndx;
638 };
639 
640 struct usdt_manager;
641 
642 struct bpf_object {
643 	char name[BPF_OBJ_NAME_LEN];
644 	char license[64];
645 	__u32 kern_version;
646 
647 	struct bpf_program *programs;
648 	size_t nr_programs;
649 	struct bpf_map *maps;
650 	size_t nr_maps;
651 	size_t maps_cap;
652 
653 	char *kconfig;
654 	struct extern_desc *externs;
655 	int nr_extern;
656 	int kconfig_map_idx;
657 
658 	bool loaded;
659 	bool has_subcalls;
660 	bool has_rodata;
661 
662 	struct bpf_gen *gen_loader;
663 
664 	/* Information when doing ELF related work. Only valid if efile.elf is not NULL */
665 	struct elf_state efile;
666 
667 	struct btf *btf;
668 	struct btf_ext *btf_ext;
669 
670 	/* Parse and load BTF vmlinux if any of the programs in the object need
671 	 * it at load time.
672 	 */
673 	struct btf *btf_vmlinux;
674 	/* Path to the custom BTF to be used for BPF CO-RE relocations as an
675 	 * override for vmlinux BTF.
676 	 */
677 	char *btf_custom_path;
678 	/* vmlinux BTF override for CO-RE relocations */
679 	struct btf *btf_vmlinux_override;
680 	/* Lazily initialized kernel module BTFs */
681 	struct module_btf *btf_modules;
682 	bool btf_modules_loaded;
683 	size_t btf_module_cnt;
684 	size_t btf_module_cap;
685 
686 	/* optional log settings passed to BPF_BTF_LOAD and BPF_PROG_LOAD commands */
687 	char *log_buf;
688 	size_t log_size;
689 	__u32 log_level;
690 
691 	int *fd_array;
692 	size_t fd_array_cap;
693 	size_t fd_array_cnt;
694 
695 	struct usdt_manager *usdt_man;
696 
697 	char path[];
698 };
699 
700 static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
701 static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
702 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
703 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
704 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn);
705 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
706 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
707 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx);
708 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx);
709 
710 void bpf_program__unload(struct bpf_program *prog)
711 {
712 	if (!prog)
713 		return;
714 
715 	zclose(prog->fd);
716 
717 	zfree(&prog->func_info);
718 	zfree(&prog->line_info);
719 }
720 
721 static void bpf_program__exit(struct bpf_program *prog)
722 {
723 	if (!prog)
724 		return;
725 
726 	bpf_program__unload(prog);
727 	zfree(&prog->name);
728 	zfree(&prog->sec_name);
729 	zfree(&prog->insns);
730 	zfree(&prog->reloc_desc);
731 
732 	prog->nr_reloc = 0;
733 	prog->insns_cnt = 0;
734 	prog->sec_idx = -1;
735 }
736 
737 static bool insn_is_subprog_call(const struct bpf_insn *insn)
738 {
739 	return BPF_CLASS(insn->code) == BPF_JMP &&
740 	       BPF_OP(insn->code) == BPF_CALL &&
741 	       BPF_SRC(insn->code) == BPF_K &&
742 	       insn->src_reg == BPF_PSEUDO_CALL &&
743 	       insn->dst_reg == 0 &&
744 	       insn->off == 0;
745 }
746 
747 static bool is_call_insn(const struct bpf_insn *insn)
748 {
749 	return insn->code == (BPF_JMP | BPF_CALL);
750 }
751 
752 static bool insn_is_pseudo_func(struct bpf_insn *insn)
753 {
754 	return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
755 }
756 
757 static int
758 bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
759 		      const char *name, size_t sec_idx, const char *sec_name,
760 		      size_t sec_off, void *insn_data, size_t insn_data_sz)
761 {
762 	if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
763 		pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
764 			sec_name, name, sec_off, insn_data_sz);
765 		return -EINVAL;
766 	}
767 
768 	memset(prog, 0, sizeof(*prog));
769 	prog->obj = obj;
770 
771 	prog->sec_idx = sec_idx;
772 	prog->sec_insn_off = sec_off / BPF_INSN_SZ;
773 	prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
774 	/* insns_cnt can later be increased by appending used subprograms */
775 	prog->insns_cnt = prog->sec_insn_cnt;
776 
777 	prog->type = BPF_PROG_TYPE_UNSPEC;
778 	prog->fd = -1;
779 	prog->exception_cb_idx = -1;
780 
781 	/* libbpf's convention for SEC("?abc...") is that it's just like
782 	 * SEC("abc...") but the corresponding bpf_program starts out with
783 	 * autoload set to false.
784 	 */
785 	if (sec_name[0] == '?') {
786 		prog->autoload = false;
787 		/* from now on forget there was ? in section name */
788 		sec_name++;
789 	} else {
790 		prog->autoload = true;
791 	}
792 
793 	prog->autoattach = true;
794 
795 	/* inherit object's log_level */
796 	prog->log_level = obj->log_level;
797 
798 	prog->sec_name = strdup(sec_name);
799 	if (!prog->sec_name)
800 		goto errout;
801 
802 	prog->name = strdup(name);
803 	if (!prog->name)
804 		goto errout;
805 
806 	prog->insns = malloc(insn_data_sz);
807 	if (!prog->insns)
808 		goto errout;
809 	memcpy(prog->insns, insn_data, insn_data_sz);
810 
811 	return 0;
812 errout:
813 	pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
814 	bpf_program__exit(prog);
815 	return -ENOMEM;
816 }
817 
818 static int
819 bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
820 			 const char *sec_name, int sec_idx)
821 {
822 	Elf_Data *symbols = obj->efile.symbols;
823 	struct bpf_program *prog, *progs;
824 	void *data = sec_data->d_buf;
825 	size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
826 	int nr_progs, err, i;
827 	const char *name;
828 	Elf64_Sym *sym;
829 
830 	progs = obj->programs;
831 	nr_progs = obj->nr_programs;
832 	nr_syms = symbols->d_size / sizeof(Elf64_Sym);
833 
834 	for (i = 0; i < nr_syms; i++) {
835 		sym = elf_sym_by_idx(obj, i);
836 
837 		if (sym->st_shndx != sec_idx)
838 			continue;
839 		if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC)
840 			continue;
841 
842 		prog_sz = sym->st_size;
843 		sec_off = sym->st_value;
844 
845 		name = elf_sym_str(obj, sym->st_name);
846 		if (!name) {
847 			pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
848 				sec_name, sec_off);
849 			return -LIBBPF_ERRNO__FORMAT;
850 		}
851 
852 		if (sec_off + prog_sz > sec_sz) {
853 			pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
854 				sec_name, sec_off);
855 			return -LIBBPF_ERRNO__FORMAT;
856 		}
857 
858 		if (sec_idx != obj->efile.text_shndx && ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
859 			pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
860 			return -ENOTSUP;
861 		}
862 
863 		pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
864 			 sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
865 
866 		progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
867 		if (!progs) {
868 			/*
869 			 * In this case the original obj->programs
870 			 * is still valid, so don't need special treat for
871 			 * bpf_close_object().
872 			 */
873 			pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
874 				sec_name, name);
875 			return -ENOMEM;
876 		}
877 		obj->programs = progs;
878 
879 		prog = &progs[nr_progs];
880 
881 		err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
882 					    sec_off, data + sec_off, prog_sz);
883 		if (err)
884 			return err;
885 
886 		if (ELF64_ST_BIND(sym->st_info) != STB_LOCAL)
887 			prog->sym_global = true;
888 
889 		/* if function is a global/weak symbol, but has restricted
890 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
891 		 * as static to enable more permissive BPF verification mode
892 		 * with more outside context available to BPF verifier
893 		 */
894 		if (prog->sym_global && (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
895 		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL))
896 			prog->mark_btf_static = true;
897 
898 		nr_progs++;
899 		obj->nr_programs = nr_progs;
900 	}
901 
902 	return 0;
903 }
904 
905 static const struct btf_member *
906 find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
907 {
908 	struct btf_member *m;
909 	int i;
910 
911 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
912 		if (btf_member_bit_offset(t, i) == bit_offset)
913 			return m;
914 	}
915 
916 	return NULL;
917 }
918 
919 static const struct btf_member *
920 find_member_by_name(const struct btf *btf, const struct btf_type *t,
921 		    const char *name)
922 {
923 	struct btf_member *m;
924 	int i;
925 
926 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
927 		if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
928 			return m;
929 	}
930 
931 	return NULL;
932 }
933 
934 #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
935 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
936 				   const char *name, __u32 kind);
937 
938 static int
939 find_struct_ops_kern_types(const struct btf *btf, const char *tname,
940 			   const struct btf_type **type, __u32 *type_id,
941 			   const struct btf_type **vtype, __u32 *vtype_id,
942 			   const struct btf_member **data_member)
943 {
944 	const struct btf_type *kern_type, *kern_vtype;
945 	const struct btf_member *kern_data_member;
946 	__s32 kern_vtype_id, kern_type_id;
947 	__u32 i;
948 
949 	kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
950 	if (kern_type_id < 0) {
951 		pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n",
952 			tname);
953 		return kern_type_id;
954 	}
955 	kern_type = btf__type_by_id(btf, kern_type_id);
956 
957 	/* Find the corresponding "map_value" type that will be used
958 	 * in map_update(BPF_MAP_TYPE_STRUCT_OPS).  For example,
959 	 * find "struct bpf_struct_ops_tcp_congestion_ops" from the
960 	 * btf_vmlinux.
961 	 */
962 	kern_vtype_id = find_btf_by_prefix_kind(btf, STRUCT_OPS_VALUE_PREFIX,
963 						tname, BTF_KIND_STRUCT);
964 	if (kern_vtype_id < 0) {
965 		pr_warn("struct_ops init_kern: struct %s%s is not found in kernel BTF\n",
966 			STRUCT_OPS_VALUE_PREFIX, tname);
967 		return kern_vtype_id;
968 	}
969 	kern_vtype = btf__type_by_id(btf, kern_vtype_id);
970 
971 	/* Find "struct tcp_congestion_ops" from
972 	 * struct bpf_struct_ops_tcp_congestion_ops {
973 	 *	[ ... ]
974 	 *	struct tcp_congestion_ops data;
975 	 * }
976 	 */
977 	kern_data_member = btf_members(kern_vtype);
978 	for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
979 		if (kern_data_member->type == kern_type_id)
980 			break;
981 	}
982 	if (i == btf_vlen(kern_vtype)) {
983 		pr_warn("struct_ops init_kern: struct %s data is not found in struct %s%s\n",
984 			tname, STRUCT_OPS_VALUE_PREFIX, tname);
985 		return -EINVAL;
986 	}
987 
988 	*type = kern_type;
989 	*type_id = kern_type_id;
990 	*vtype = kern_vtype;
991 	*vtype_id = kern_vtype_id;
992 	*data_member = kern_data_member;
993 
994 	return 0;
995 }
996 
997 static bool bpf_map__is_struct_ops(const struct bpf_map *map)
998 {
999 	return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
1000 }
1001 
1002 /* Init the map's fields that depend on kern_btf */
1003 static int bpf_map__init_kern_struct_ops(struct bpf_map *map,
1004 					 const struct btf *btf,
1005 					 const struct btf *kern_btf)
1006 {
1007 	const struct btf_member *member, *kern_member, *kern_data_member;
1008 	const struct btf_type *type, *kern_type, *kern_vtype;
1009 	__u32 i, kern_type_id, kern_vtype_id, kern_data_off;
1010 	struct bpf_struct_ops *st_ops;
1011 	void *data, *kern_data;
1012 	const char *tname;
1013 	int err;
1014 
1015 	st_ops = map->st_ops;
1016 	type = st_ops->type;
1017 	tname = st_ops->tname;
1018 	err = find_struct_ops_kern_types(kern_btf, tname,
1019 					 &kern_type, &kern_type_id,
1020 					 &kern_vtype, &kern_vtype_id,
1021 					 &kern_data_member);
1022 	if (err)
1023 		return err;
1024 
1025 	pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
1026 		 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
1027 
1028 	map->def.value_size = kern_vtype->size;
1029 	map->btf_vmlinux_value_type_id = kern_vtype_id;
1030 
1031 	st_ops->kern_vdata = calloc(1, kern_vtype->size);
1032 	if (!st_ops->kern_vdata)
1033 		return -ENOMEM;
1034 
1035 	data = st_ops->data;
1036 	kern_data_off = kern_data_member->offset / 8;
1037 	kern_data = st_ops->kern_vdata + kern_data_off;
1038 
1039 	member = btf_members(type);
1040 	for (i = 0; i < btf_vlen(type); i++, member++) {
1041 		const struct btf_type *mtype, *kern_mtype;
1042 		__u32 mtype_id, kern_mtype_id;
1043 		void *mdata, *kern_mdata;
1044 		__s64 msize, kern_msize;
1045 		__u32 moff, kern_moff;
1046 		__u32 kern_member_idx;
1047 		const char *mname;
1048 
1049 		mname = btf__name_by_offset(btf, member->name_off);
1050 		kern_member = find_member_by_name(kern_btf, kern_type, mname);
1051 		if (!kern_member) {
1052 			pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
1053 				map->name, mname);
1054 			return -ENOTSUP;
1055 		}
1056 
1057 		kern_member_idx = kern_member - btf_members(kern_type);
1058 		if (btf_member_bitfield_size(type, i) ||
1059 		    btf_member_bitfield_size(kern_type, kern_member_idx)) {
1060 			pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
1061 				map->name, mname);
1062 			return -ENOTSUP;
1063 		}
1064 
1065 		moff = member->offset / 8;
1066 		kern_moff = kern_member->offset / 8;
1067 
1068 		mdata = data + moff;
1069 		kern_mdata = kern_data + kern_moff;
1070 
1071 		mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
1072 		kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
1073 						    &kern_mtype_id);
1074 		if (BTF_INFO_KIND(mtype->info) !=
1075 		    BTF_INFO_KIND(kern_mtype->info)) {
1076 			pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
1077 				map->name, mname, BTF_INFO_KIND(mtype->info),
1078 				BTF_INFO_KIND(kern_mtype->info));
1079 			return -ENOTSUP;
1080 		}
1081 
1082 		if (btf_is_ptr(mtype)) {
1083 			struct bpf_program *prog;
1084 
1085 			prog = st_ops->progs[i];
1086 			if (!prog)
1087 				continue;
1088 
1089 			kern_mtype = skip_mods_and_typedefs(kern_btf,
1090 							    kern_mtype->type,
1091 							    &kern_mtype_id);
1092 
1093 			/* mtype->type must be a func_proto which was
1094 			 * guaranteed in bpf_object__collect_st_ops_relos(),
1095 			 * so only check kern_mtype for func_proto here.
1096 			 */
1097 			if (!btf_is_func_proto(kern_mtype)) {
1098 				pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
1099 					map->name, mname);
1100 				return -ENOTSUP;
1101 			}
1102 
1103 			prog->attach_btf_id = kern_type_id;
1104 			prog->expected_attach_type = kern_member_idx;
1105 
1106 			st_ops->kern_func_off[i] = kern_data_off + kern_moff;
1107 
1108 			pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
1109 				 map->name, mname, prog->name, moff,
1110 				 kern_moff);
1111 
1112 			continue;
1113 		}
1114 
1115 		msize = btf__resolve_size(btf, mtype_id);
1116 		kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
1117 		if (msize < 0 || kern_msize < 0 || msize != kern_msize) {
1118 			pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
1119 				map->name, mname, (ssize_t)msize,
1120 				(ssize_t)kern_msize);
1121 			return -ENOTSUP;
1122 		}
1123 
1124 		pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
1125 			 map->name, mname, (unsigned int)msize,
1126 			 moff, kern_moff);
1127 		memcpy(kern_mdata, mdata, msize);
1128 	}
1129 
1130 	return 0;
1131 }
1132 
1133 static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
1134 {
1135 	struct bpf_map *map;
1136 	size_t i;
1137 	int err;
1138 
1139 	for (i = 0; i < obj->nr_maps; i++) {
1140 		map = &obj->maps[i];
1141 
1142 		if (!bpf_map__is_struct_ops(map))
1143 			continue;
1144 
1145 		err = bpf_map__init_kern_struct_ops(map, obj->btf,
1146 						    obj->btf_vmlinux);
1147 		if (err)
1148 			return err;
1149 	}
1150 
1151 	return 0;
1152 }
1153 
1154 static int init_struct_ops_maps(struct bpf_object *obj, const char *sec_name,
1155 				int shndx, Elf_Data *data, __u32 map_flags)
1156 {
1157 	const struct btf_type *type, *datasec;
1158 	const struct btf_var_secinfo *vsi;
1159 	struct bpf_struct_ops *st_ops;
1160 	const char *tname, *var_name;
1161 	__s32 type_id, datasec_id;
1162 	const struct btf *btf;
1163 	struct bpf_map *map;
1164 	__u32 i;
1165 
1166 	if (shndx == -1)
1167 		return 0;
1168 
1169 	btf = obj->btf;
1170 	datasec_id = btf__find_by_name_kind(btf, sec_name,
1171 					    BTF_KIND_DATASEC);
1172 	if (datasec_id < 0) {
1173 		pr_warn("struct_ops init: DATASEC %s not found\n",
1174 			sec_name);
1175 		return -EINVAL;
1176 	}
1177 
1178 	datasec = btf__type_by_id(btf, datasec_id);
1179 	vsi = btf_var_secinfos(datasec);
1180 	for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
1181 		type = btf__type_by_id(obj->btf, vsi->type);
1182 		var_name = btf__name_by_offset(obj->btf, type->name_off);
1183 
1184 		type_id = btf__resolve_type(obj->btf, vsi->type);
1185 		if (type_id < 0) {
1186 			pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
1187 				vsi->type, sec_name);
1188 			return -EINVAL;
1189 		}
1190 
1191 		type = btf__type_by_id(obj->btf, type_id);
1192 		tname = btf__name_by_offset(obj->btf, type->name_off);
1193 		if (!tname[0]) {
1194 			pr_warn("struct_ops init: anonymous type is not supported\n");
1195 			return -ENOTSUP;
1196 		}
1197 		if (!btf_is_struct(type)) {
1198 			pr_warn("struct_ops init: %s is not a struct\n", tname);
1199 			return -EINVAL;
1200 		}
1201 
1202 		map = bpf_object__add_map(obj);
1203 		if (IS_ERR(map))
1204 			return PTR_ERR(map);
1205 
1206 		map->sec_idx = shndx;
1207 		map->sec_offset = vsi->offset;
1208 		map->name = strdup(var_name);
1209 		if (!map->name)
1210 			return -ENOMEM;
1211 
1212 		map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
1213 		map->def.key_size = sizeof(int);
1214 		map->def.value_size = type->size;
1215 		map->def.max_entries = 1;
1216 		map->def.map_flags = map_flags;
1217 
1218 		map->st_ops = calloc(1, sizeof(*map->st_ops));
1219 		if (!map->st_ops)
1220 			return -ENOMEM;
1221 		st_ops = map->st_ops;
1222 		st_ops->data = malloc(type->size);
1223 		st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1224 		st_ops->kern_func_off = malloc(btf_vlen(type) *
1225 					       sizeof(*st_ops->kern_func_off));
1226 		if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1227 			return -ENOMEM;
1228 
1229 		if (vsi->offset + type->size > data->d_size) {
1230 			pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1231 				var_name, sec_name);
1232 			return -EINVAL;
1233 		}
1234 
1235 		memcpy(st_ops->data,
1236 		       data->d_buf + vsi->offset,
1237 		       type->size);
1238 		st_ops->tname = tname;
1239 		st_ops->type = type;
1240 		st_ops->type_id = type_id;
1241 
1242 		pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
1243 			 tname, type_id, var_name, vsi->offset);
1244 	}
1245 
1246 	return 0;
1247 }
1248 
1249 static int bpf_object_init_struct_ops(struct bpf_object *obj)
1250 {
1251 	int err;
1252 
1253 	err = init_struct_ops_maps(obj, STRUCT_OPS_SEC, obj->efile.st_ops_shndx,
1254 				   obj->efile.st_ops_data, 0);
1255 	err = err ?: init_struct_ops_maps(obj, STRUCT_OPS_LINK_SEC,
1256 					  obj->efile.st_ops_link_shndx,
1257 					  obj->efile.st_ops_link_data,
1258 					  BPF_F_LINK);
1259 	return err;
1260 }
1261 
1262 static struct bpf_object *bpf_object__new(const char *path,
1263 					  const void *obj_buf,
1264 					  size_t obj_buf_sz,
1265 					  const char *obj_name)
1266 {
1267 	struct bpf_object *obj;
1268 	char *end;
1269 
1270 	obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1271 	if (!obj) {
1272 		pr_warn("alloc memory failed for %s\n", path);
1273 		return ERR_PTR(-ENOMEM);
1274 	}
1275 
1276 	strcpy(obj->path, path);
1277 	if (obj_name) {
1278 		libbpf_strlcpy(obj->name, obj_name, sizeof(obj->name));
1279 	} else {
1280 		/* Using basename() GNU version which doesn't modify arg. */
1281 		libbpf_strlcpy(obj->name, basename((void *)path), sizeof(obj->name));
1282 		end = strchr(obj->name, '.');
1283 		if (end)
1284 			*end = 0;
1285 	}
1286 
1287 	obj->efile.fd = -1;
1288 	/*
1289 	 * Caller of this function should also call
1290 	 * bpf_object__elf_finish() after data collection to return
1291 	 * obj_buf to user. If not, we should duplicate the buffer to
1292 	 * avoid user freeing them before elf finish.
1293 	 */
1294 	obj->efile.obj_buf = obj_buf;
1295 	obj->efile.obj_buf_sz = obj_buf_sz;
1296 	obj->efile.btf_maps_shndx = -1;
1297 	obj->efile.st_ops_shndx = -1;
1298 	obj->efile.st_ops_link_shndx = -1;
1299 	obj->kconfig_map_idx = -1;
1300 
1301 	obj->kern_version = get_kernel_version();
1302 	obj->loaded = false;
1303 
1304 	return obj;
1305 }
1306 
1307 static void bpf_object__elf_finish(struct bpf_object *obj)
1308 {
1309 	if (!obj->efile.elf)
1310 		return;
1311 
1312 	elf_end(obj->efile.elf);
1313 	obj->efile.elf = NULL;
1314 	obj->efile.symbols = NULL;
1315 	obj->efile.st_ops_data = NULL;
1316 	obj->efile.st_ops_link_data = NULL;
1317 
1318 	zfree(&obj->efile.secs);
1319 	obj->efile.sec_cnt = 0;
1320 	zclose(obj->efile.fd);
1321 	obj->efile.obj_buf = NULL;
1322 	obj->efile.obj_buf_sz = 0;
1323 }
1324 
1325 static int bpf_object__elf_init(struct bpf_object *obj)
1326 {
1327 	Elf64_Ehdr *ehdr;
1328 	int err = 0;
1329 	Elf *elf;
1330 
1331 	if (obj->efile.elf) {
1332 		pr_warn("elf: init internal error\n");
1333 		return -LIBBPF_ERRNO__LIBELF;
1334 	}
1335 
1336 	if (obj->efile.obj_buf_sz > 0) {
1337 		/* obj_buf should have been validated by bpf_object__open_mem(). */
1338 		elf = elf_memory((char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
1339 	} else {
1340 		obj->efile.fd = open(obj->path, O_RDONLY | O_CLOEXEC);
1341 		if (obj->efile.fd < 0) {
1342 			char errmsg[STRERR_BUFSIZE], *cp;
1343 
1344 			err = -errno;
1345 			cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
1346 			pr_warn("elf: failed to open %s: %s\n", obj->path, cp);
1347 			return err;
1348 		}
1349 
1350 		elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1351 	}
1352 
1353 	if (!elf) {
1354 		pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
1355 		err = -LIBBPF_ERRNO__LIBELF;
1356 		goto errout;
1357 	}
1358 
1359 	obj->efile.elf = elf;
1360 
1361 	if (elf_kind(elf) != ELF_K_ELF) {
1362 		err = -LIBBPF_ERRNO__FORMAT;
1363 		pr_warn("elf: '%s' is not a proper ELF object\n", obj->path);
1364 		goto errout;
1365 	}
1366 
1367 	if (gelf_getclass(elf) != ELFCLASS64) {
1368 		err = -LIBBPF_ERRNO__FORMAT;
1369 		pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path);
1370 		goto errout;
1371 	}
1372 
1373 	obj->efile.ehdr = ehdr = elf64_getehdr(elf);
1374 	if (!obj->efile.ehdr) {
1375 		pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
1376 		err = -LIBBPF_ERRNO__FORMAT;
1377 		goto errout;
1378 	}
1379 
1380 	if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
1381 		pr_warn("elf: failed to get section names section index for %s: %s\n",
1382 			obj->path, elf_errmsg(-1));
1383 		err = -LIBBPF_ERRNO__FORMAT;
1384 		goto errout;
1385 	}
1386 
1387 	/* ELF is corrupted/truncated, avoid calling elf_strptr. */
1388 	if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
1389 		pr_warn("elf: failed to get section names strings from %s: %s\n",
1390 			obj->path, elf_errmsg(-1));
1391 		err = -LIBBPF_ERRNO__FORMAT;
1392 		goto errout;
1393 	}
1394 
1395 	/* Old LLVM set e_machine to EM_NONE */
1396 	if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
1397 		pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
1398 		err = -LIBBPF_ERRNO__FORMAT;
1399 		goto errout;
1400 	}
1401 
1402 	return 0;
1403 errout:
1404 	bpf_object__elf_finish(obj);
1405 	return err;
1406 }
1407 
1408 static int bpf_object__check_endianness(struct bpf_object *obj)
1409 {
1410 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1411 	if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2LSB)
1412 		return 0;
1413 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1414 	if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2MSB)
1415 		return 0;
1416 #else
1417 # error "Unrecognized __BYTE_ORDER__"
1418 #endif
1419 	pr_warn("elf: endianness mismatch in %s.\n", obj->path);
1420 	return -LIBBPF_ERRNO__ENDIAN;
1421 }
1422 
1423 static int
1424 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1425 {
1426 	if (!data) {
1427 		pr_warn("invalid license section in %s\n", obj->path);
1428 		return -LIBBPF_ERRNO__FORMAT;
1429 	}
1430 	/* libbpf_strlcpy() only copies first N - 1 bytes, so size + 1 won't
1431 	 * go over allowed ELF data section buffer
1432 	 */
1433 	libbpf_strlcpy(obj->license, data, min(size + 1, sizeof(obj->license)));
1434 	pr_debug("license of %s is %s\n", obj->path, obj->license);
1435 	return 0;
1436 }
1437 
1438 static int
1439 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1440 {
1441 	__u32 kver;
1442 
1443 	if (!data || size != sizeof(kver)) {
1444 		pr_warn("invalid kver section in %s\n", obj->path);
1445 		return -LIBBPF_ERRNO__FORMAT;
1446 	}
1447 	memcpy(&kver, data, sizeof(kver));
1448 	obj->kern_version = kver;
1449 	pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1450 	return 0;
1451 }
1452 
1453 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1454 {
1455 	if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1456 	    type == BPF_MAP_TYPE_HASH_OF_MAPS)
1457 		return true;
1458 	return false;
1459 }
1460 
1461 static int find_elf_sec_sz(const struct bpf_object *obj, const char *name, __u32 *size)
1462 {
1463 	Elf_Data *data;
1464 	Elf_Scn *scn;
1465 
1466 	if (!name)
1467 		return -EINVAL;
1468 
1469 	scn = elf_sec_by_name(obj, name);
1470 	data = elf_sec_data(obj, scn);
1471 	if (data) {
1472 		*size = data->d_size;
1473 		return 0; /* found it */
1474 	}
1475 
1476 	return -ENOENT;
1477 }
1478 
1479 static Elf64_Sym *find_elf_var_sym(const struct bpf_object *obj, const char *name)
1480 {
1481 	Elf_Data *symbols = obj->efile.symbols;
1482 	const char *sname;
1483 	size_t si;
1484 
1485 	for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
1486 		Elf64_Sym *sym = elf_sym_by_idx(obj, si);
1487 
1488 		if (ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)
1489 			continue;
1490 
1491 		if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL &&
1492 		    ELF64_ST_BIND(sym->st_info) != STB_WEAK)
1493 			continue;
1494 
1495 		sname = elf_sym_str(obj, sym->st_name);
1496 		if (!sname) {
1497 			pr_warn("failed to get sym name string for var %s\n", name);
1498 			return ERR_PTR(-EIO);
1499 		}
1500 		if (strcmp(name, sname) == 0)
1501 			return sym;
1502 	}
1503 
1504 	return ERR_PTR(-ENOENT);
1505 }
1506 
1507 static int create_placeholder_fd(void)
1508 {
1509 	int fd;
1510 
1511 	fd = ensure_good_fd(memfd_create("libbpf-placeholder-fd", MFD_CLOEXEC));
1512 	if (fd < 0)
1513 		return -errno;
1514 	return fd;
1515 }
1516 
1517 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1518 {
1519 	struct bpf_map *map;
1520 	int err;
1521 
1522 	err = libbpf_ensure_mem((void **)&obj->maps, &obj->maps_cap,
1523 				sizeof(*obj->maps), obj->nr_maps + 1);
1524 	if (err)
1525 		return ERR_PTR(err);
1526 
1527 	map = &obj->maps[obj->nr_maps++];
1528 	map->obj = obj;
1529 	/* Preallocate map FD without actually creating BPF map just yet.
1530 	 * These map FD "placeholders" will be reused later without changing
1531 	 * FD value when map is actually created in the kernel.
1532 	 *
1533 	 * This is useful to be able to perform BPF program relocations
1534 	 * without having to create BPF maps before that step. This allows us
1535 	 * to finalize and load BTF very late in BPF object's loading phase,
1536 	 * right before BPF maps have to be created and BPF programs have to
1537 	 * be loaded. By having these map FD placeholders we can perform all
1538 	 * the sanitizations, relocations, and any other adjustments before we
1539 	 * start creating actual BPF kernel objects (BTF, maps, progs).
1540 	 */
1541 	map->fd = create_placeholder_fd();
1542 	if (map->fd < 0)
1543 		return ERR_PTR(map->fd);
1544 	map->inner_map_fd = -1;
1545 	map->autocreate = true;
1546 
1547 	return map;
1548 }
1549 
1550 static size_t bpf_map_mmap_sz(unsigned int value_sz, unsigned int max_entries)
1551 {
1552 	const long page_sz = sysconf(_SC_PAGE_SIZE);
1553 	size_t map_sz;
1554 
1555 	map_sz = (size_t)roundup(value_sz, 8) * max_entries;
1556 	map_sz = roundup(map_sz, page_sz);
1557 	return map_sz;
1558 }
1559 
1560 static int bpf_map_mmap_resize(struct bpf_map *map, size_t old_sz, size_t new_sz)
1561 {
1562 	void *mmaped;
1563 
1564 	if (!map->mmaped)
1565 		return -EINVAL;
1566 
1567 	if (old_sz == new_sz)
1568 		return 0;
1569 
1570 	mmaped = mmap(NULL, new_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1571 	if (mmaped == MAP_FAILED)
1572 		return -errno;
1573 
1574 	memcpy(mmaped, map->mmaped, min(old_sz, new_sz));
1575 	munmap(map->mmaped, old_sz);
1576 	map->mmaped = mmaped;
1577 	return 0;
1578 }
1579 
1580 static char *internal_map_name(struct bpf_object *obj, const char *real_name)
1581 {
1582 	char map_name[BPF_OBJ_NAME_LEN], *p;
1583 	int pfx_len, sfx_len = max((size_t)7, strlen(real_name));
1584 
1585 	/* This is one of the more confusing parts of libbpf for various
1586 	 * reasons, some of which are historical. The original idea for naming
1587 	 * internal names was to include as much of BPF object name prefix as
1588 	 * possible, so that it can be distinguished from similar internal
1589 	 * maps of a different BPF object.
1590 	 * As an example, let's say we have bpf_object named 'my_object_name'
1591 	 * and internal map corresponding to '.rodata' ELF section. The final
1592 	 * map name advertised to user and to the kernel will be
1593 	 * 'my_objec.rodata', taking first 8 characters of object name and
1594 	 * entire 7 characters of '.rodata'.
1595 	 * Somewhat confusingly, if internal map ELF section name is shorter
1596 	 * than 7 characters, e.g., '.bss', we still reserve 7 characters
1597 	 * for the suffix, even though we only have 4 actual characters, and
1598 	 * resulting map will be called 'my_objec.bss', not even using all 15
1599 	 * characters allowed by the kernel. Oh well, at least the truncated
1600 	 * object name is somewhat consistent in this case. But if the map
1601 	 * name is '.kconfig', we'll still have entirety of '.kconfig' added
1602 	 * (8 chars) and thus will be left with only first 7 characters of the
1603 	 * object name ('my_obje'). Happy guessing, user, that the final map
1604 	 * name will be "my_obje.kconfig".
1605 	 * Now, with libbpf starting to support arbitrarily named .rodata.*
1606 	 * and .data.* data sections, it's possible that ELF section name is
1607 	 * longer than allowed 15 chars, so we now need to be careful to take
1608 	 * only up to 15 first characters of ELF name, taking no BPF object
1609 	 * name characters at all. So '.rodata.abracadabra' will result in
1610 	 * '.rodata.abracad' kernel and user-visible name.
1611 	 * We need to keep this convoluted logic intact for .data, .bss and
1612 	 * .rodata maps, but for new custom .data.custom and .rodata.custom
1613 	 * maps we use their ELF names as is, not prepending bpf_object name
1614 	 * in front. We still need to truncate them to 15 characters for the
1615 	 * kernel. Full name can be recovered for such maps by using DATASEC
1616 	 * BTF type associated with such map's value type, though.
1617 	 */
1618 	if (sfx_len >= BPF_OBJ_NAME_LEN)
1619 		sfx_len = BPF_OBJ_NAME_LEN - 1;
1620 
1621 	/* if there are two or more dots in map name, it's a custom dot map */
1622 	if (strchr(real_name + 1, '.') != NULL)
1623 		pfx_len = 0;
1624 	else
1625 		pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
1626 
1627 	snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1628 		 sfx_len, real_name);
1629 
1630 	/* sanitise map name to characters allowed by kernel */
1631 	for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1632 		if (!isalnum(*p) && *p != '_' && *p != '.')
1633 			*p = '_';
1634 
1635 	return strdup(map_name);
1636 }
1637 
1638 static int
1639 map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map);
1640 
1641 /* Internal BPF map is mmap()'able only if at least one of corresponding
1642  * DATASEC's VARs are to be exposed through BPF skeleton. I.e., it's a GLOBAL
1643  * variable and it's not marked as __hidden (which turns it into, effectively,
1644  * a STATIC variable).
1645  */
1646 static bool map_is_mmapable(struct bpf_object *obj, struct bpf_map *map)
1647 {
1648 	const struct btf_type *t, *vt;
1649 	struct btf_var_secinfo *vsi;
1650 	int i, n;
1651 
1652 	if (!map->btf_value_type_id)
1653 		return false;
1654 
1655 	t = btf__type_by_id(obj->btf, map->btf_value_type_id);
1656 	if (!btf_is_datasec(t))
1657 		return false;
1658 
1659 	vsi = btf_var_secinfos(t);
1660 	for (i = 0, n = btf_vlen(t); i < n; i++, vsi++) {
1661 		vt = btf__type_by_id(obj->btf, vsi->type);
1662 		if (!btf_is_var(vt))
1663 			continue;
1664 
1665 		if (btf_var(vt)->linkage != BTF_VAR_STATIC)
1666 			return true;
1667 	}
1668 
1669 	return false;
1670 }
1671 
1672 static int
1673 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
1674 			      const char *real_name, int sec_idx, void *data, size_t data_sz)
1675 {
1676 	struct bpf_map_def *def;
1677 	struct bpf_map *map;
1678 	size_t mmap_sz;
1679 	int err;
1680 
1681 	map = bpf_object__add_map(obj);
1682 	if (IS_ERR(map))
1683 		return PTR_ERR(map);
1684 
1685 	map->libbpf_type = type;
1686 	map->sec_idx = sec_idx;
1687 	map->sec_offset = 0;
1688 	map->real_name = strdup(real_name);
1689 	map->name = internal_map_name(obj, real_name);
1690 	if (!map->real_name || !map->name) {
1691 		zfree(&map->real_name);
1692 		zfree(&map->name);
1693 		return -ENOMEM;
1694 	}
1695 
1696 	def = &map->def;
1697 	def->type = BPF_MAP_TYPE_ARRAY;
1698 	def->key_size = sizeof(int);
1699 	def->value_size = data_sz;
1700 	def->max_entries = 1;
1701 	def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
1702 			 ? BPF_F_RDONLY_PROG : 0;
1703 
1704 	/* failures are fine because of maps like .rodata.str1.1 */
1705 	(void) map_fill_btf_type_info(obj, map);
1706 
1707 	if (map_is_mmapable(obj, map))
1708 		def->map_flags |= BPF_F_MMAPABLE;
1709 
1710 	pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
1711 		 map->name, map->sec_idx, map->sec_offset, def->map_flags);
1712 
1713 	mmap_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
1714 	map->mmaped = mmap(NULL, mmap_sz, PROT_READ | PROT_WRITE,
1715 			   MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1716 	if (map->mmaped == MAP_FAILED) {
1717 		err = -errno;
1718 		map->mmaped = NULL;
1719 		pr_warn("failed to alloc map '%s' content buffer: %d\n",
1720 			map->name, err);
1721 		zfree(&map->real_name);
1722 		zfree(&map->name);
1723 		return err;
1724 	}
1725 
1726 	if (data)
1727 		memcpy(map->mmaped, data, data_sz);
1728 
1729 	pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
1730 	return 0;
1731 }
1732 
1733 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
1734 {
1735 	struct elf_sec_desc *sec_desc;
1736 	const char *sec_name;
1737 	int err = 0, sec_idx;
1738 
1739 	/*
1740 	 * Populate obj->maps with libbpf internal maps.
1741 	 */
1742 	for (sec_idx = 1; sec_idx < obj->efile.sec_cnt; sec_idx++) {
1743 		sec_desc = &obj->efile.secs[sec_idx];
1744 
1745 		/* Skip recognized sections with size 0. */
1746 		if (!sec_desc->data || sec_desc->data->d_size == 0)
1747 			continue;
1748 
1749 		switch (sec_desc->sec_type) {
1750 		case SEC_DATA:
1751 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1752 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
1753 							    sec_name, sec_idx,
1754 							    sec_desc->data->d_buf,
1755 							    sec_desc->data->d_size);
1756 			break;
1757 		case SEC_RODATA:
1758 			obj->has_rodata = true;
1759 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1760 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
1761 							    sec_name, sec_idx,
1762 							    sec_desc->data->d_buf,
1763 							    sec_desc->data->d_size);
1764 			break;
1765 		case SEC_BSS:
1766 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1767 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
1768 							    sec_name, sec_idx,
1769 							    NULL,
1770 							    sec_desc->data->d_size);
1771 			break;
1772 		default:
1773 			/* skip */
1774 			break;
1775 		}
1776 		if (err)
1777 			return err;
1778 	}
1779 	return 0;
1780 }
1781 
1782 
1783 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
1784 					       const void *name)
1785 {
1786 	int i;
1787 
1788 	for (i = 0; i < obj->nr_extern; i++) {
1789 		if (strcmp(obj->externs[i].name, name) == 0)
1790 			return &obj->externs[i];
1791 	}
1792 	return NULL;
1793 }
1794 
1795 static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
1796 			      char value)
1797 {
1798 	switch (ext->kcfg.type) {
1799 	case KCFG_BOOL:
1800 		if (value == 'm') {
1801 			pr_warn("extern (kcfg) '%s': value '%c' implies tristate or char type\n",
1802 				ext->name, value);
1803 			return -EINVAL;
1804 		}
1805 		*(bool *)ext_val = value == 'y' ? true : false;
1806 		break;
1807 	case KCFG_TRISTATE:
1808 		if (value == 'y')
1809 			*(enum libbpf_tristate *)ext_val = TRI_YES;
1810 		else if (value == 'm')
1811 			*(enum libbpf_tristate *)ext_val = TRI_MODULE;
1812 		else /* value == 'n' */
1813 			*(enum libbpf_tristate *)ext_val = TRI_NO;
1814 		break;
1815 	case KCFG_CHAR:
1816 		*(char *)ext_val = value;
1817 		break;
1818 	case KCFG_UNKNOWN:
1819 	case KCFG_INT:
1820 	case KCFG_CHAR_ARR:
1821 	default:
1822 		pr_warn("extern (kcfg) '%s': value '%c' implies bool, tristate, or char type\n",
1823 			ext->name, value);
1824 		return -EINVAL;
1825 	}
1826 	ext->is_set = true;
1827 	return 0;
1828 }
1829 
1830 static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
1831 			      const char *value)
1832 {
1833 	size_t len;
1834 
1835 	if (ext->kcfg.type != KCFG_CHAR_ARR) {
1836 		pr_warn("extern (kcfg) '%s': value '%s' implies char array type\n",
1837 			ext->name, value);
1838 		return -EINVAL;
1839 	}
1840 
1841 	len = strlen(value);
1842 	if (value[len - 1] != '"') {
1843 		pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
1844 			ext->name, value);
1845 		return -EINVAL;
1846 	}
1847 
1848 	/* strip quotes */
1849 	len -= 2;
1850 	if (len >= ext->kcfg.sz) {
1851 		pr_warn("extern (kcfg) '%s': long string '%s' of (%zu bytes) truncated to %d bytes\n",
1852 			ext->name, value, len, ext->kcfg.sz - 1);
1853 		len = ext->kcfg.sz - 1;
1854 	}
1855 	memcpy(ext_val, value + 1, len);
1856 	ext_val[len] = '\0';
1857 	ext->is_set = true;
1858 	return 0;
1859 }
1860 
1861 static int parse_u64(const char *value, __u64 *res)
1862 {
1863 	char *value_end;
1864 	int err;
1865 
1866 	errno = 0;
1867 	*res = strtoull(value, &value_end, 0);
1868 	if (errno) {
1869 		err = -errno;
1870 		pr_warn("failed to parse '%s' as integer: %d\n", value, err);
1871 		return err;
1872 	}
1873 	if (*value_end) {
1874 		pr_warn("failed to parse '%s' as integer completely\n", value);
1875 		return -EINVAL;
1876 	}
1877 	return 0;
1878 }
1879 
1880 static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
1881 {
1882 	int bit_sz = ext->kcfg.sz * 8;
1883 
1884 	if (ext->kcfg.sz == 8)
1885 		return true;
1886 
1887 	/* Validate that value stored in u64 fits in integer of `ext->sz`
1888 	 * bytes size without any loss of information. If the target integer
1889 	 * is signed, we rely on the following limits of integer type of
1890 	 * Y bits and subsequent transformation:
1891 	 *
1892 	 *     -2^(Y-1) <= X           <= 2^(Y-1) - 1
1893 	 *            0 <= X + 2^(Y-1) <= 2^Y - 1
1894 	 *            0 <= X + 2^(Y-1) <  2^Y
1895 	 *
1896 	 *  For unsigned target integer, check that all the (64 - Y) bits are
1897 	 *  zero.
1898 	 */
1899 	if (ext->kcfg.is_signed)
1900 		return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
1901 	else
1902 		return (v >> bit_sz) == 0;
1903 }
1904 
1905 static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
1906 			      __u64 value)
1907 {
1908 	if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR &&
1909 	    ext->kcfg.type != KCFG_BOOL) {
1910 		pr_warn("extern (kcfg) '%s': value '%llu' implies integer, char, or boolean type\n",
1911 			ext->name, (unsigned long long)value);
1912 		return -EINVAL;
1913 	}
1914 	if (ext->kcfg.type == KCFG_BOOL && value > 1) {
1915 		pr_warn("extern (kcfg) '%s': value '%llu' isn't boolean compatible\n",
1916 			ext->name, (unsigned long long)value);
1917 		return -EINVAL;
1918 
1919 	}
1920 	if (!is_kcfg_value_in_range(ext, value)) {
1921 		pr_warn("extern (kcfg) '%s': value '%llu' doesn't fit in %d bytes\n",
1922 			ext->name, (unsigned long long)value, ext->kcfg.sz);
1923 		return -ERANGE;
1924 	}
1925 	switch (ext->kcfg.sz) {
1926 	case 1:
1927 		*(__u8 *)ext_val = value;
1928 		break;
1929 	case 2:
1930 		*(__u16 *)ext_val = value;
1931 		break;
1932 	case 4:
1933 		*(__u32 *)ext_val = value;
1934 		break;
1935 	case 8:
1936 		*(__u64 *)ext_val = value;
1937 		break;
1938 	default:
1939 		return -EINVAL;
1940 	}
1941 	ext->is_set = true;
1942 	return 0;
1943 }
1944 
1945 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
1946 					    char *buf, void *data)
1947 {
1948 	struct extern_desc *ext;
1949 	char *sep, *value;
1950 	int len, err = 0;
1951 	void *ext_val;
1952 	__u64 num;
1953 
1954 	if (!str_has_pfx(buf, "CONFIG_"))
1955 		return 0;
1956 
1957 	sep = strchr(buf, '=');
1958 	if (!sep) {
1959 		pr_warn("failed to parse '%s': no separator\n", buf);
1960 		return -EINVAL;
1961 	}
1962 
1963 	/* Trim ending '\n' */
1964 	len = strlen(buf);
1965 	if (buf[len - 1] == '\n')
1966 		buf[len - 1] = '\0';
1967 	/* Split on '=' and ensure that a value is present. */
1968 	*sep = '\0';
1969 	if (!sep[1]) {
1970 		*sep = '=';
1971 		pr_warn("failed to parse '%s': no value\n", buf);
1972 		return -EINVAL;
1973 	}
1974 
1975 	ext = find_extern_by_name(obj, buf);
1976 	if (!ext || ext->is_set)
1977 		return 0;
1978 
1979 	ext_val = data + ext->kcfg.data_off;
1980 	value = sep + 1;
1981 
1982 	switch (*value) {
1983 	case 'y': case 'n': case 'm':
1984 		err = set_kcfg_value_tri(ext, ext_val, *value);
1985 		break;
1986 	case '"':
1987 		err = set_kcfg_value_str(ext, ext_val, value);
1988 		break;
1989 	default:
1990 		/* assume integer */
1991 		err = parse_u64(value, &num);
1992 		if (err) {
1993 			pr_warn("extern (kcfg) '%s': value '%s' isn't a valid integer\n", ext->name, value);
1994 			return err;
1995 		}
1996 		if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
1997 			pr_warn("extern (kcfg) '%s': value '%s' implies integer type\n", ext->name, value);
1998 			return -EINVAL;
1999 		}
2000 		err = set_kcfg_value_num(ext, ext_val, num);
2001 		break;
2002 	}
2003 	if (err)
2004 		return err;
2005 	pr_debug("extern (kcfg) '%s': set to %s\n", ext->name, value);
2006 	return 0;
2007 }
2008 
2009 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
2010 {
2011 	char buf[PATH_MAX];
2012 	struct utsname uts;
2013 	int len, err = 0;
2014 	gzFile file;
2015 
2016 	uname(&uts);
2017 	len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
2018 	if (len < 0)
2019 		return -EINVAL;
2020 	else if (len >= PATH_MAX)
2021 		return -ENAMETOOLONG;
2022 
2023 	/* gzopen also accepts uncompressed files. */
2024 	file = gzopen(buf, "re");
2025 	if (!file)
2026 		file = gzopen("/proc/config.gz", "re");
2027 
2028 	if (!file) {
2029 		pr_warn("failed to open system Kconfig\n");
2030 		return -ENOENT;
2031 	}
2032 
2033 	while (gzgets(file, buf, sizeof(buf))) {
2034 		err = bpf_object__process_kconfig_line(obj, buf, data);
2035 		if (err) {
2036 			pr_warn("error parsing system Kconfig line '%s': %d\n",
2037 				buf, err);
2038 			goto out;
2039 		}
2040 	}
2041 
2042 out:
2043 	gzclose(file);
2044 	return err;
2045 }
2046 
2047 static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
2048 					const char *config, void *data)
2049 {
2050 	char buf[PATH_MAX];
2051 	int err = 0;
2052 	FILE *file;
2053 
2054 	file = fmemopen((void *)config, strlen(config), "r");
2055 	if (!file) {
2056 		err = -errno;
2057 		pr_warn("failed to open in-memory Kconfig: %d\n", err);
2058 		return err;
2059 	}
2060 
2061 	while (fgets(buf, sizeof(buf), file)) {
2062 		err = bpf_object__process_kconfig_line(obj, buf, data);
2063 		if (err) {
2064 			pr_warn("error parsing in-memory Kconfig line '%s': %d\n",
2065 				buf, err);
2066 			break;
2067 		}
2068 	}
2069 
2070 	fclose(file);
2071 	return err;
2072 }
2073 
2074 static int bpf_object__init_kconfig_map(struct bpf_object *obj)
2075 {
2076 	struct extern_desc *last_ext = NULL, *ext;
2077 	size_t map_sz;
2078 	int i, err;
2079 
2080 	for (i = 0; i < obj->nr_extern; i++) {
2081 		ext = &obj->externs[i];
2082 		if (ext->type == EXT_KCFG)
2083 			last_ext = ext;
2084 	}
2085 
2086 	if (!last_ext)
2087 		return 0;
2088 
2089 	map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
2090 	err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
2091 					    ".kconfig", obj->efile.symbols_shndx,
2092 					    NULL, map_sz);
2093 	if (err)
2094 		return err;
2095 
2096 	obj->kconfig_map_idx = obj->nr_maps - 1;
2097 
2098 	return 0;
2099 }
2100 
2101 const struct btf_type *
2102 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
2103 {
2104 	const struct btf_type *t = btf__type_by_id(btf, id);
2105 
2106 	if (res_id)
2107 		*res_id = id;
2108 
2109 	while (btf_is_mod(t) || btf_is_typedef(t)) {
2110 		if (res_id)
2111 			*res_id = t->type;
2112 		t = btf__type_by_id(btf, t->type);
2113 	}
2114 
2115 	return t;
2116 }
2117 
2118 static const struct btf_type *
2119 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
2120 {
2121 	const struct btf_type *t;
2122 
2123 	t = skip_mods_and_typedefs(btf, id, NULL);
2124 	if (!btf_is_ptr(t))
2125 		return NULL;
2126 
2127 	t = skip_mods_and_typedefs(btf, t->type, res_id);
2128 
2129 	return btf_is_func_proto(t) ? t : NULL;
2130 }
2131 
2132 static const char *__btf_kind_str(__u16 kind)
2133 {
2134 	switch (kind) {
2135 	case BTF_KIND_UNKN: return "void";
2136 	case BTF_KIND_INT: return "int";
2137 	case BTF_KIND_PTR: return "ptr";
2138 	case BTF_KIND_ARRAY: return "array";
2139 	case BTF_KIND_STRUCT: return "struct";
2140 	case BTF_KIND_UNION: return "union";
2141 	case BTF_KIND_ENUM: return "enum";
2142 	case BTF_KIND_FWD: return "fwd";
2143 	case BTF_KIND_TYPEDEF: return "typedef";
2144 	case BTF_KIND_VOLATILE: return "volatile";
2145 	case BTF_KIND_CONST: return "const";
2146 	case BTF_KIND_RESTRICT: return "restrict";
2147 	case BTF_KIND_FUNC: return "func";
2148 	case BTF_KIND_FUNC_PROTO: return "func_proto";
2149 	case BTF_KIND_VAR: return "var";
2150 	case BTF_KIND_DATASEC: return "datasec";
2151 	case BTF_KIND_FLOAT: return "float";
2152 	case BTF_KIND_DECL_TAG: return "decl_tag";
2153 	case BTF_KIND_TYPE_TAG: return "type_tag";
2154 	case BTF_KIND_ENUM64: return "enum64";
2155 	default: return "unknown";
2156 	}
2157 }
2158 
2159 const char *btf_kind_str(const struct btf_type *t)
2160 {
2161 	return __btf_kind_str(btf_kind(t));
2162 }
2163 
2164 /*
2165  * Fetch integer attribute of BTF map definition. Such attributes are
2166  * represented using a pointer to an array, in which dimensionality of array
2167  * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2168  * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2169  * type definition, while using only sizeof(void *) space in ELF data section.
2170  */
2171 static bool get_map_field_int(const char *map_name, const struct btf *btf,
2172 			      const struct btf_member *m, __u32 *res)
2173 {
2174 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2175 	const char *name = btf__name_by_offset(btf, m->name_off);
2176 	const struct btf_array *arr_info;
2177 	const struct btf_type *arr_t;
2178 
2179 	if (!btf_is_ptr(t)) {
2180 		pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2181 			map_name, name, btf_kind_str(t));
2182 		return false;
2183 	}
2184 
2185 	arr_t = btf__type_by_id(btf, t->type);
2186 	if (!arr_t) {
2187 		pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2188 			map_name, name, t->type);
2189 		return false;
2190 	}
2191 	if (!btf_is_array(arr_t)) {
2192 		pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2193 			map_name, name, btf_kind_str(arr_t));
2194 		return false;
2195 	}
2196 	arr_info = btf_array(arr_t);
2197 	*res = arr_info->nelems;
2198 	return true;
2199 }
2200 
2201 static int pathname_concat(char *buf, size_t buf_sz, const char *path, const char *name)
2202 {
2203 	int len;
2204 
2205 	len = snprintf(buf, buf_sz, "%s/%s", path, name);
2206 	if (len < 0)
2207 		return -EINVAL;
2208 	if (len >= buf_sz)
2209 		return -ENAMETOOLONG;
2210 
2211 	return 0;
2212 }
2213 
2214 static int build_map_pin_path(struct bpf_map *map, const char *path)
2215 {
2216 	char buf[PATH_MAX];
2217 	int err;
2218 
2219 	if (!path)
2220 		path = "/sys/fs/bpf";
2221 
2222 	err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
2223 	if (err)
2224 		return err;
2225 
2226 	return bpf_map__set_pin_path(map, buf);
2227 }
2228 
2229 /* should match definition in bpf_helpers.h */
2230 enum libbpf_pin_type {
2231 	LIBBPF_PIN_NONE,
2232 	/* PIN_BY_NAME: pin maps by name (in /sys/fs/bpf by default) */
2233 	LIBBPF_PIN_BY_NAME,
2234 };
2235 
2236 int parse_btf_map_def(const char *map_name, struct btf *btf,
2237 		      const struct btf_type *def_t, bool strict,
2238 		      struct btf_map_def *map_def, struct btf_map_def *inner_def)
2239 {
2240 	const struct btf_type *t;
2241 	const struct btf_member *m;
2242 	bool is_inner = inner_def == NULL;
2243 	int vlen, i;
2244 
2245 	vlen = btf_vlen(def_t);
2246 	m = btf_members(def_t);
2247 	for (i = 0; i < vlen; i++, m++) {
2248 		const char *name = btf__name_by_offset(btf, m->name_off);
2249 
2250 		if (!name) {
2251 			pr_warn("map '%s': invalid field #%d.\n", map_name, i);
2252 			return -EINVAL;
2253 		}
2254 		if (strcmp(name, "type") == 0) {
2255 			if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
2256 				return -EINVAL;
2257 			map_def->parts |= MAP_DEF_MAP_TYPE;
2258 		} else if (strcmp(name, "max_entries") == 0) {
2259 			if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
2260 				return -EINVAL;
2261 			map_def->parts |= MAP_DEF_MAX_ENTRIES;
2262 		} else if (strcmp(name, "map_flags") == 0) {
2263 			if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
2264 				return -EINVAL;
2265 			map_def->parts |= MAP_DEF_MAP_FLAGS;
2266 		} else if (strcmp(name, "numa_node") == 0) {
2267 			if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
2268 				return -EINVAL;
2269 			map_def->parts |= MAP_DEF_NUMA_NODE;
2270 		} else if (strcmp(name, "key_size") == 0) {
2271 			__u32 sz;
2272 
2273 			if (!get_map_field_int(map_name, btf, m, &sz))
2274 				return -EINVAL;
2275 			if (map_def->key_size && map_def->key_size != sz) {
2276 				pr_warn("map '%s': conflicting key size %u != %u.\n",
2277 					map_name, map_def->key_size, sz);
2278 				return -EINVAL;
2279 			}
2280 			map_def->key_size = sz;
2281 			map_def->parts |= MAP_DEF_KEY_SIZE;
2282 		} else if (strcmp(name, "key") == 0) {
2283 			__s64 sz;
2284 
2285 			t = btf__type_by_id(btf, m->type);
2286 			if (!t) {
2287 				pr_warn("map '%s': key type [%d] not found.\n",
2288 					map_name, m->type);
2289 				return -EINVAL;
2290 			}
2291 			if (!btf_is_ptr(t)) {
2292 				pr_warn("map '%s': key spec is not PTR: %s.\n",
2293 					map_name, btf_kind_str(t));
2294 				return -EINVAL;
2295 			}
2296 			sz = btf__resolve_size(btf, t->type);
2297 			if (sz < 0) {
2298 				pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2299 					map_name, t->type, (ssize_t)sz);
2300 				return sz;
2301 			}
2302 			if (map_def->key_size && map_def->key_size != sz) {
2303 				pr_warn("map '%s': conflicting key size %u != %zd.\n",
2304 					map_name, map_def->key_size, (ssize_t)sz);
2305 				return -EINVAL;
2306 			}
2307 			map_def->key_size = sz;
2308 			map_def->key_type_id = t->type;
2309 			map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
2310 		} else if (strcmp(name, "value_size") == 0) {
2311 			__u32 sz;
2312 
2313 			if (!get_map_field_int(map_name, btf, m, &sz))
2314 				return -EINVAL;
2315 			if (map_def->value_size && map_def->value_size != sz) {
2316 				pr_warn("map '%s': conflicting value size %u != %u.\n",
2317 					map_name, map_def->value_size, sz);
2318 				return -EINVAL;
2319 			}
2320 			map_def->value_size = sz;
2321 			map_def->parts |= MAP_DEF_VALUE_SIZE;
2322 		} else if (strcmp(name, "value") == 0) {
2323 			__s64 sz;
2324 
2325 			t = btf__type_by_id(btf, m->type);
2326 			if (!t) {
2327 				pr_warn("map '%s': value type [%d] not found.\n",
2328 					map_name, m->type);
2329 				return -EINVAL;
2330 			}
2331 			if (!btf_is_ptr(t)) {
2332 				pr_warn("map '%s': value spec is not PTR: %s.\n",
2333 					map_name, btf_kind_str(t));
2334 				return -EINVAL;
2335 			}
2336 			sz = btf__resolve_size(btf, t->type);
2337 			if (sz < 0) {
2338 				pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2339 					map_name, t->type, (ssize_t)sz);
2340 				return sz;
2341 			}
2342 			if (map_def->value_size && map_def->value_size != sz) {
2343 				pr_warn("map '%s': conflicting value size %u != %zd.\n",
2344 					map_name, map_def->value_size, (ssize_t)sz);
2345 				return -EINVAL;
2346 			}
2347 			map_def->value_size = sz;
2348 			map_def->value_type_id = t->type;
2349 			map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
2350 		}
2351 		else if (strcmp(name, "values") == 0) {
2352 			bool is_map_in_map = bpf_map_type__is_map_in_map(map_def->map_type);
2353 			bool is_prog_array = map_def->map_type == BPF_MAP_TYPE_PROG_ARRAY;
2354 			const char *desc = is_map_in_map ? "map-in-map inner" : "prog-array value";
2355 			char inner_map_name[128];
2356 			int err;
2357 
2358 			if (is_inner) {
2359 				pr_warn("map '%s': multi-level inner maps not supported.\n",
2360 					map_name);
2361 				return -ENOTSUP;
2362 			}
2363 			if (i != vlen - 1) {
2364 				pr_warn("map '%s': '%s' member should be last.\n",
2365 					map_name, name);
2366 				return -EINVAL;
2367 			}
2368 			if (!is_map_in_map && !is_prog_array) {
2369 				pr_warn("map '%s': should be map-in-map or prog-array.\n",
2370 					map_name);
2371 				return -ENOTSUP;
2372 			}
2373 			if (map_def->value_size && map_def->value_size != 4) {
2374 				pr_warn("map '%s': conflicting value size %u != 4.\n",
2375 					map_name, map_def->value_size);
2376 				return -EINVAL;
2377 			}
2378 			map_def->value_size = 4;
2379 			t = btf__type_by_id(btf, m->type);
2380 			if (!t) {
2381 				pr_warn("map '%s': %s type [%d] not found.\n",
2382 					map_name, desc, m->type);
2383 				return -EINVAL;
2384 			}
2385 			if (!btf_is_array(t) || btf_array(t)->nelems) {
2386 				pr_warn("map '%s': %s spec is not a zero-sized array.\n",
2387 					map_name, desc);
2388 				return -EINVAL;
2389 			}
2390 			t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
2391 			if (!btf_is_ptr(t)) {
2392 				pr_warn("map '%s': %s def is of unexpected kind %s.\n",
2393 					map_name, desc, btf_kind_str(t));
2394 				return -EINVAL;
2395 			}
2396 			t = skip_mods_and_typedefs(btf, t->type, NULL);
2397 			if (is_prog_array) {
2398 				if (!btf_is_func_proto(t)) {
2399 					pr_warn("map '%s': prog-array value def is of unexpected kind %s.\n",
2400 						map_name, btf_kind_str(t));
2401 					return -EINVAL;
2402 				}
2403 				continue;
2404 			}
2405 			if (!btf_is_struct(t)) {
2406 				pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2407 					map_name, btf_kind_str(t));
2408 				return -EINVAL;
2409 			}
2410 
2411 			snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2412 			err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
2413 			if (err)
2414 				return err;
2415 
2416 			map_def->parts |= MAP_DEF_INNER_MAP;
2417 		} else if (strcmp(name, "pinning") == 0) {
2418 			__u32 val;
2419 
2420 			if (is_inner) {
2421 				pr_warn("map '%s': inner def can't be pinned.\n", map_name);
2422 				return -EINVAL;
2423 			}
2424 			if (!get_map_field_int(map_name, btf, m, &val))
2425 				return -EINVAL;
2426 			if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
2427 				pr_warn("map '%s': invalid pinning value %u.\n",
2428 					map_name, val);
2429 				return -EINVAL;
2430 			}
2431 			map_def->pinning = val;
2432 			map_def->parts |= MAP_DEF_PINNING;
2433 		} else if (strcmp(name, "map_extra") == 0) {
2434 			__u32 map_extra;
2435 
2436 			if (!get_map_field_int(map_name, btf, m, &map_extra))
2437 				return -EINVAL;
2438 			map_def->map_extra = map_extra;
2439 			map_def->parts |= MAP_DEF_MAP_EXTRA;
2440 		} else {
2441 			if (strict) {
2442 				pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
2443 				return -ENOTSUP;
2444 			}
2445 			pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
2446 		}
2447 	}
2448 
2449 	if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2450 		pr_warn("map '%s': map type isn't specified.\n", map_name);
2451 		return -EINVAL;
2452 	}
2453 
2454 	return 0;
2455 }
2456 
2457 static size_t adjust_ringbuf_sz(size_t sz)
2458 {
2459 	__u32 page_sz = sysconf(_SC_PAGE_SIZE);
2460 	__u32 mul;
2461 
2462 	/* if user forgot to set any size, make sure they see error */
2463 	if (sz == 0)
2464 		return 0;
2465 	/* Kernel expects BPF_MAP_TYPE_RINGBUF's max_entries to be
2466 	 * a power-of-2 multiple of kernel's page size. If user diligently
2467 	 * satisified these conditions, pass the size through.
2468 	 */
2469 	if ((sz % page_sz) == 0 && is_pow_of_2(sz / page_sz))
2470 		return sz;
2471 
2472 	/* Otherwise find closest (page_sz * power_of_2) product bigger than
2473 	 * user-set size to satisfy both user size request and kernel
2474 	 * requirements and substitute correct max_entries for map creation.
2475 	 */
2476 	for (mul = 1; mul <= UINT_MAX / page_sz; mul <<= 1) {
2477 		if (mul * page_sz > sz)
2478 			return mul * page_sz;
2479 	}
2480 
2481 	/* if it's impossible to satisfy the conditions (i.e., user size is
2482 	 * very close to UINT_MAX but is not a power-of-2 multiple of
2483 	 * page_size) then just return original size and let kernel reject it
2484 	 */
2485 	return sz;
2486 }
2487 
2488 static bool map_is_ringbuf(const struct bpf_map *map)
2489 {
2490 	return map->def.type == BPF_MAP_TYPE_RINGBUF ||
2491 	       map->def.type == BPF_MAP_TYPE_USER_RINGBUF;
2492 }
2493 
2494 static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2495 {
2496 	map->def.type = def->map_type;
2497 	map->def.key_size = def->key_size;
2498 	map->def.value_size = def->value_size;
2499 	map->def.max_entries = def->max_entries;
2500 	map->def.map_flags = def->map_flags;
2501 	map->map_extra = def->map_extra;
2502 
2503 	map->numa_node = def->numa_node;
2504 	map->btf_key_type_id = def->key_type_id;
2505 	map->btf_value_type_id = def->value_type_id;
2506 
2507 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
2508 	if (map_is_ringbuf(map))
2509 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
2510 
2511 	if (def->parts & MAP_DEF_MAP_TYPE)
2512 		pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2513 
2514 	if (def->parts & MAP_DEF_KEY_TYPE)
2515 		pr_debug("map '%s': found key [%u], sz = %u.\n",
2516 			 map->name, def->key_type_id, def->key_size);
2517 	else if (def->parts & MAP_DEF_KEY_SIZE)
2518 		pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2519 
2520 	if (def->parts & MAP_DEF_VALUE_TYPE)
2521 		pr_debug("map '%s': found value [%u], sz = %u.\n",
2522 			 map->name, def->value_type_id, def->value_size);
2523 	else if (def->parts & MAP_DEF_VALUE_SIZE)
2524 		pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2525 
2526 	if (def->parts & MAP_DEF_MAX_ENTRIES)
2527 		pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2528 	if (def->parts & MAP_DEF_MAP_FLAGS)
2529 		pr_debug("map '%s': found map_flags = 0x%x.\n", map->name, def->map_flags);
2530 	if (def->parts & MAP_DEF_MAP_EXTRA)
2531 		pr_debug("map '%s': found map_extra = 0x%llx.\n", map->name,
2532 			 (unsigned long long)def->map_extra);
2533 	if (def->parts & MAP_DEF_PINNING)
2534 		pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2535 	if (def->parts & MAP_DEF_NUMA_NODE)
2536 		pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2537 
2538 	if (def->parts & MAP_DEF_INNER_MAP)
2539 		pr_debug("map '%s': found inner map definition.\n", map->name);
2540 }
2541 
2542 static const char *btf_var_linkage_str(__u32 linkage)
2543 {
2544 	switch (linkage) {
2545 	case BTF_VAR_STATIC: return "static";
2546 	case BTF_VAR_GLOBAL_ALLOCATED: return "global";
2547 	case BTF_VAR_GLOBAL_EXTERN: return "extern";
2548 	default: return "unknown";
2549 	}
2550 }
2551 
2552 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2553 					 const struct btf_type *sec,
2554 					 int var_idx, int sec_idx,
2555 					 const Elf_Data *data, bool strict,
2556 					 const char *pin_root_path)
2557 {
2558 	struct btf_map_def map_def = {}, inner_def = {};
2559 	const struct btf_type *var, *def;
2560 	const struct btf_var_secinfo *vi;
2561 	const struct btf_var *var_extra;
2562 	const char *map_name;
2563 	struct bpf_map *map;
2564 	int err;
2565 
2566 	vi = btf_var_secinfos(sec) + var_idx;
2567 	var = btf__type_by_id(obj->btf, vi->type);
2568 	var_extra = btf_var(var);
2569 	map_name = btf__name_by_offset(obj->btf, var->name_off);
2570 
2571 	if (map_name == NULL || map_name[0] == '\0') {
2572 		pr_warn("map #%d: empty name.\n", var_idx);
2573 		return -EINVAL;
2574 	}
2575 	if ((__u64)vi->offset + vi->size > data->d_size) {
2576 		pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2577 		return -EINVAL;
2578 	}
2579 	if (!btf_is_var(var)) {
2580 		pr_warn("map '%s': unexpected var kind %s.\n",
2581 			map_name, btf_kind_str(var));
2582 		return -EINVAL;
2583 	}
2584 	if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
2585 		pr_warn("map '%s': unsupported map linkage %s.\n",
2586 			map_name, btf_var_linkage_str(var_extra->linkage));
2587 		return -EOPNOTSUPP;
2588 	}
2589 
2590 	def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2591 	if (!btf_is_struct(def)) {
2592 		pr_warn("map '%s': unexpected def kind %s.\n",
2593 			map_name, btf_kind_str(var));
2594 		return -EINVAL;
2595 	}
2596 	if (def->size > vi->size) {
2597 		pr_warn("map '%s': invalid def size.\n", map_name);
2598 		return -EINVAL;
2599 	}
2600 
2601 	map = bpf_object__add_map(obj);
2602 	if (IS_ERR(map))
2603 		return PTR_ERR(map);
2604 	map->name = strdup(map_name);
2605 	if (!map->name) {
2606 		pr_warn("map '%s': failed to alloc map name.\n", map_name);
2607 		return -ENOMEM;
2608 	}
2609 	map->libbpf_type = LIBBPF_MAP_UNSPEC;
2610 	map->def.type = BPF_MAP_TYPE_UNSPEC;
2611 	map->sec_idx = sec_idx;
2612 	map->sec_offset = vi->offset;
2613 	map->btf_var_idx = var_idx;
2614 	pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2615 		 map_name, map->sec_idx, map->sec_offset);
2616 
2617 	err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
2618 	if (err)
2619 		return err;
2620 
2621 	fill_map_from_def(map, &map_def);
2622 
2623 	if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
2624 		err = build_map_pin_path(map, pin_root_path);
2625 		if (err) {
2626 			pr_warn("map '%s': couldn't build pin path.\n", map->name);
2627 			return err;
2628 		}
2629 	}
2630 
2631 	if (map_def.parts & MAP_DEF_INNER_MAP) {
2632 		map->inner_map = calloc(1, sizeof(*map->inner_map));
2633 		if (!map->inner_map)
2634 			return -ENOMEM;
2635 		map->inner_map->fd = create_placeholder_fd();
2636 		if (map->inner_map->fd < 0)
2637 			return map->inner_map->fd;
2638 		map->inner_map->sec_idx = sec_idx;
2639 		map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
2640 		if (!map->inner_map->name)
2641 			return -ENOMEM;
2642 		sprintf(map->inner_map->name, "%s.inner", map_name);
2643 
2644 		fill_map_from_def(map->inner_map, &inner_def);
2645 	}
2646 
2647 	err = map_fill_btf_type_info(obj, map);
2648 	if (err)
2649 		return err;
2650 
2651 	return 0;
2652 }
2653 
2654 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
2655 					  const char *pin_root_path)
2656 {
2657 	const struct btf_type *sec = NULL;
2658 	int nr_types, i, vlen, err;
2659 	const struct btf_type *t;
2660 	const char *name;
2661 	Elf_Data *data;
2662 	Elf_Scn *scn;
2663 
2664 	if (obj->efile.btf_maps_shndx < 0)
2665 		return 0;
2666 
2667 	scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
2668 	data = elf_sec_data(obj, scn);
2669 	if (!scn || !data) {
2670 		pr_warn("elf: failed to get %s map definitions for %s\n",
2671 			MAPS_ELF_SEC, obj->path);
2672 		return -EINVAL;
2673 	}
2674 
2675 	nr_types = btf__type_cnt(obj->btf);
2676 	for (i = 1; i < nr_types; i++) {
2677 		t = btf__type_by_id(obj->btf, i);
2678 		if (!btf_is_datasec(t))
2679 			continue;
2680 		name = btf__name_by_offset(obj->btf, t->name_off);
2681 		if (strcmp(name, MAPS_ELF_SEC) == 0) {
2682 			sec = t;
2683 			obj->efile.btf_maps_sec_btf_id = i;
2684 			break;
2685 		}
2686 	}
2687 
2688 	if (!sec) {
2689 		pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
2690 		return -ENOENT;
2691 	}
2692 
2693 	vlen = btf_vlen(sec);
2694 	for (i = 0; i < vlen; i++) {
2695 		err = bpf_object__init_user_btf_map(obj, sec, i,
2696 						    obj->efile.btf_maps_shndx,
2697 						    data, strict,
2698 						    pin_root_path);
2699 		if (err)
2700 			return err;
2701 	}
2702 
2703 	return 0;
2704 }
2705 
2706 static int bpf_object__init_maps(struct bpf_object *obj,
2707 				 const struct bpf_object_open_opts *opts)
2708 {
2709 	const char *pin_root_path;
2710 	bool strict;
2711 	int err = 0;
2712 
2713 	strict = !OPTS_GET(opts, relaxed_maps, false);
2714 	pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
2715 
2716 	err = bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
2717 	err = err ?: bpf_object__init_global_data_maps(obj);
2718 	err = err ?: bpf_object__init_kconfig_map(obj);
2719 	err = err ?: bpf_object_init_struct_ops(obj);
2720 
2721 	return err;
2722 }
2723 
2724 static bool section_have_execinstr(struct bpf_object *obj, int idx)
2725 {
2726 	Elf64_Shdr *sh;
2727 
2728 	sh = elf_sec_hdr(obj, elf_sec_by_idx(obj, idx));
2729 	if (!sh)
2730 		return false;
2731 
2732 	return sh->sh_flags & SHF_EXECINSTR;
2733 }
2734 
2735 static bool btf_needs_sanitization(struct bpf_object *obj)
2736 {
2737 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2738 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2739 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2740 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2741 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2742 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2743 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
2744 
2745 	return !has_func || !has_datasec || !has_func_global || !has_float ||
2746 	       !has_decl_tag || !has_type_tag || !has_enum64;
2747 }
2748 
2749 static int bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *btf)
2750 {
2751 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2752 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2753 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2754 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2755 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2756 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2757 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
2758 	int enum64_placeholder_id = 0;
2759 	struct btf_type *t;
2760 	int i, j, vlen;
2761 
2762 	for (i = 1; i < btf__type_cnt(btf); i++) {
2763 		t = (struct btf_type *)btf__type_by_id(btf, i);
2764 
2765 		if ((!has_datasec && btf_is_var(t)) || (!has_decl_tag && btf_is_decl_tag(t))) {
2766 			/* replace VAR/DECL_TAG with INT */
2767 			t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
2768 			/*
2769 			 * using size = 1 is the safest choice, 4 will be too
2770 			 * big and cause kernel BTF validation failure if
2771 			 * original variable took less than 4 bytes
2772 			 */
2773 			t->size = 1;
2774 			*(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
2775 		} else if (!has_datasec && btf_is_datasec(t)) {
2776 			/* replace DATASEC with STRUCT */
2777 			const struct btf_var_secinfo *v = btf_var_secinfos(t);
2778 			struct btf_member *m = btf_members(t);
2779 			struct btf_type *vt;
2780 			char *name;
2781 
2782 			name = (char *)btf__name_by_offset(btf, t->name_off);
2783 			while (*name) {
2784 				if (*name == '.')
2785 					*name = '_';
2786 				name++;
2787 			}
2788 
2789 			vlen = btf_vlen(t);
2790 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
2791 			for (j = 0; j < vlen; j++, v++, m++) {
2792 				/* order of field assignments is important */
2793 				m->offset = v->offset * 8;
2794 				m->type = v->type;
2795 				/* preserve variable name as member name */
2796 				vt = (void *)btf__type_by_id(btf, v->type);
2797 				m->name_off = vt->name_off;
2798 			}
2799 		} else if (!has_func && btf_is_func_proto(t)) {
2800 			/* replace FUNC_PROTO with ENUM */
2801 			vlen = btf_vlen(t);
2802 			t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
2803 			t->size = sizeof(__u32); /* kernel enforced */
2804 		} else if (!has_func && btf_is_func(t)) {
2805 			/* replace FUNC with TYPEDEF */
2806 			t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
2807 		} else if (!has_func_global && btf_is_func(t)) {
2808 			/* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
2809 			t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
2810 		} else if (!has_float && btf_is_float(t)) {
2811 			/* replace FLOAT with an equally-sized empty STRUCT;
2812 			 * since C compilers do not accept e.g. "float" as a
2813 			 * valid struct name, make it anonymous
2814 			 */
2815 			t->name_off = 0;
2816 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
2817 		} else if (!has_type_tag && btf_is_type_tag(t)) {
2818 			/* replace TYPE_TAG with a CONST */
2819 			t->name_off = 0;
2820 			t->info = BTF_INFO_ENC(BTF_KIND_CONST, 0, 0);
2821 		} else if (!has_enum64 && btf_is_enum(t)) {
2822 			/* clear the kflag */
2823 			t->info = btf_type_info(btf_kind(t), btf_vlen(t), false);
2824 		} else if (!has_enum64 && btf_is_enum64(t)) {
2825 			/* replace ENUM64 with a union */
2826 			struct btf_member *m;
2827 
2828 			if (enum64_placeholder_id == 0) {
2829 				enum64_placeholder_id = btf__add_int(btf, "enum64_placeholder", 1, 0);
2830 				if (enum64_placeholder_id < 0)
2831 					return enum64_placeholder_id;
2832 
2833 				t = (struct btf_type *)btf__type_by_id(btf, i);
2834 			}
2835 
2836 			m = btf_members(t);
2837 			vlen = btf_vlen(t);
2838 			t->info = BTF_INFO_ENC(BTF_KIND_UNION, 0, vlen);
2839 			for (j = 0; j < vlen; j++, m++) {
2840 				m->type = enum64_placeholder_id;
2841 				m->offset = 0;
2842 			}
2843 		}
2844 	}
2845 
2846 	return 0;
2847 }
2848 
2849 static bool libbpf_needs_btf(const struct bpf_object *obj)
2850 {
2851 	return obj->efile.btf_maps_shndx >= 0 ||
2852 	       obj->efile.st_ops_shndx >= 0 ||
2853 	       obj->efile.st_ops_link_shndx >= 0 ||
2854 	       obj->nr_extern > 0;
2855 }
2856 
2857 static bool kernel_needs_btf(const struct bpf_object *obj)
2858 {
2859 	return obj->efile.st_ops_shndx >= 0 || obj->efile.st_ops_link_shndx >= 0;
2860 }
2861 
2862 static int bpf_object__init_btf(struct bpf_object *obj,
2863 				Elf_Data *btf_data,
2864 				Elf_Data *btf_ext_data)
2865 {
2866 	int err = -ENOENT;
2867 
2868 	if (btf_data) {
2869 		obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
2870 		err = libbpf_get_error(obj->btf);
2871 		if (err) {
2872 			obj->btf = NULL;
2873 			pr_warn("Error loading ELF section %s: %d.\n", BTF_ELF_SEC, err);
2874 			goto out;
2875 		}
2876 		/* enforce 8-byte pointers for BPF-targeted BTFs */
2877 		btf__set_pointer_size(obj->btf, 8);
2878 	}
2879 	if (btf_ext_data) {
2880 		struct btf_ext_info *ext_segs[3];
2881 		int seg_num, sec_num;
2882 
2883 		if (!obj->btf) {
2884 			pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
2885 				 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
2886 			goto out;
2887 		}
2888 		obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
2889 		err = libbpf_get_error(obj->btf_ext);
2890 		if (err) {
2891 			pr_warn("Error loading ELF section %s: %d. Ignored and continue.\n",
2892 				BTF_EXT_ELF_SEC, err);
2893 			obj->btf_ext = NULL;
2894 			goto out;
2895 		}
2896 
2897 		/* setup .BTF.ext to ELF section mapping */
2898 		ext_segs[0] = &obj->btf_ext->func_info;
2899 		ext_segs[1] = &obj->btf_ext->line_info;
2900 		ext_segs[2] = &obj->btf_ext->core_relo_info;
2901 		for (seg_num = 0; seg_num < ARRAY_SIZE(ext_segs); seg_num++) {
2902 			struct btf_ext_info *seg = ext_segs[seg_num];
2903 			const struct btf_ext_info_sec *sec;
2904 			const char *sec_name;
2905 			Elf_Scn *scn;
2906 
2907 			if (seg->sec_cnt == 0)
2908 				continue;
2909 
2910 			seg->sec_idxs = calloc(seg->sec_cnt, sizeof(*seg->sec_idxs));
2911 			if (!seg->sec_idxs) {
2912 				err = -ENOMEM;
2913 				goto out;
2914 			}
2915 
2916 			sec_num = 0;
2917 			for_each_btf_ext_sec(seg, sec) {
2918 				/* preventively increment index to avoid doing
2919 				 * this before every continue below
2920 				 */
2921 				sec_num++;
2922 
2923 				sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
2924 				if (str_is_empty(sec_name))
2925 					continue;
2926 				scn = elf_sec_by_name(obj, sec_name);
2927 				if (!scn)
2928 					continue;
2929 
2930 				seg->sec_idxs[sec_num - 1] = elf_ndxscn(scn);
2931 			}
2932 		}
2933 	}
2934 out:
2935 	if (err && libbpf_needs_btf(obj)) {
2936 		pr_warn("BTF is required, but is missing or corrupted.\n");
2937 		return err;
2938 	}
2939 	return 0;
2940 }
2941 
2942 static int compare_vsi_off(const void *_a, const void *_b)
2943 {
2944 	const struct btf_var_secinfo *a = _a;
2945 	const struct btf_var_secinfo *b = _b;
2946 
2947 	return a->offset - b->offset;
2948 }
2949 
2950 static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
2951 			     struct btf_type *t)
2952 {
2953 	__u32 size = 0, i, vars = btf_vlen(t);
2954 	const char *sec_name = btf__name_by_offset(btf, t->name_off);
2955 	struct btf_var_secinfo *vsi;
2956 	bool fixup_offsets = false;
2957 	int err;
2958 
2959 	if (!sec_name) {
2960 		pr_debug("No name found in string section for DATASEC kind.\n");
2961 		return -ENOENT;
2962 	}
2963 
2964 	/* Extern-backing datasecs (.ksyms, .kconfig) have their size and
2965 	 * variable offsets set at the previous step. Further, not every
2966 	 * extern BTF VAR has corresponding ELF symbol preserved, so we skip
2967 	 * all fixups altogether for such sections and go straight to sorting
2968 	 * VARs within their DATASEC.
2969 	 */
2970 	if (strcmp(sec_name, KCONFIG_SEC) == 0 || strcmp(sec_name, KSYMS_SEC) == 0)
2971 		goto sort_vars;
2972 
2973 	/* Clang leaves DATASEC size and VAR offsets as zeroes, so we need to
2974 	 * fix this up. But BPF static linker already fixes this up and fills
2975 	 * all the sizes and offsets during static linking. So this step has
2976 	 * to be optional. But the STV_HIDDEN handling is non-optional for any
2977 	 * non-extern DATASEC, so the variable fixup loop below handles both
2978 	 * functions at the same time, paying the cost of BTF VAR <-> ELF
2979 	 * symbol matching just once.
2980 	 */
2981 	if (t->size == 0) {
2982 		err = find_elf_sec_sz(obj, sec_name, &size);
2983 		if (err || !size) {
2984 			pr_debug("sec '%s': failed to determine size from ELF: size %u, err %d\n",
2985 				 sec_name, size, err);
2986 			return -ENOENT;
2987 		}
2988 
2989 		t->size = size;
2990 		fixup_offsets = true;
2991 	}
2992 
2993 	for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
2994 		const struct btf_type *t_var;
2995 		struct btf_var *var;
2996 		const char *var_name;
2997 		Elf64_Sym *sym;
2998 
2999 		t_var = btf__type_by_id(btf, vsi->type);
3000 		if (!t_var || !btf_is_var(t_var)) {
3001 			pr_debug("sec '%s': unexpected non-VAR type found\n", sec_name);
3002 			return -EINVAL;
3003 		}
3004 
3005 		var = btf_var(t_var);
3006 		if (var->linkage == BTF_VAR_STATIC || var->linkage == BTF_VAR_GLOBAL_EXTERN)
3007 			continue;
3008 
3009 		var_name = btf__name_by_offset(btf, t_var->name_off);
3010 		if (!var_name) {
3011 			pr_debug("sec '%s': failed to find name of DATASEC's member #%d\n",
3012 				 sec_name, i);
3013 			return -ENOENT;
3014 		}
3015 
3016 		sym = find_elf_var_sym(obj, var_name);
3017 		if (IS_ERR(sym)) {
3018 			pr_debug("sec '%s': failed to find ELF symbol for VAR '%s'\n",
3019 				 sec_name, var_name);
3020 			return -ENOENT;
3021 		}
3022 
3023 		if (fixup_offsets)
3024 			vsi->offset = sym->st_value;
3025 
3026 		/* if variable is a global/weak symbol, but has restricted
3027 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF VAR
3028 		 * as static. This follows similar logic for functions (BPF
3029 		 * subprogs) and influences libbpf's further decisions about
3030 		 * whether to make global data BPF array maps as
3031 		 * BPF_F_MMAPABLE.
3032 		 */
3033 		if (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
3034 		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL)
3035 			var->linkage = BTF_VAR_STATIC;
3036 	}
3037 
3038 sort_vars:
3039 	qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
3040 	return 0;
3041 }
3042 
3043 static int bpf_object_fixup_btf(struct bpf_object *obj)
3044 {
3045 	int i, n, err = 0;
3046 
3047 	if (!obj->btf)
3048 		return 0;
3049 
3050 	n = btf__type_cnt(obj->btf);
3051 	for (i = 1; i < n; i++) {
3052 		struct btf_type *t = btf_type_by_id(obj->btf, i);
3053 
3054 		/* Loader needs to fix up some of the things compiler
3055 		 * couldn't get its hands on while emitting BTF. This
3056 		 * is section size and global variable offset. We use
3057 		 * the info from the ELF itself for this purpose.
3058 		 */
3059 		if (btf_is_datasec(t)) {
3060 			err = btf_fixup_datasec(obj, obj->btf, t);
3061 			if (err)
3062 				return err;
3063 		}
3064 	}
3065 
3066 	return 0;
3067 }
3068 
3069 static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
3070 {
3071 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
3072 	    prog->type == BPF_PROG_TYPE_LSM)
3073 		return true;
3074 
3075 	/* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
3076 	 * also need vmlinux BTF
3077 	 */
3078 	if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
3079 		return true;
3080 
3081 	return false;
3082 }
3083 
3084 static bool map_needs_vmlinux_btf(struct bpf_map *map)
3085 {
3086 	return bpf_map__is_struct_ops(map);
3087 }
3088 
3089 static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
3090 {
3091 	struct bpf_program *prog;
3092 	struct bpf_map *map;
3093 	int i;
3094 
3095 	/* CO-RE relocations need kernel BTF, only when btf_custom_path
3096 	 * is not specified
3097 	 */
3098 	if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
3099 		return true;
3100 
3101 	/* Support for typed ksyms needs kernel BTF */
3102 	for (i = 0; i < obj->nr_extern; i++) {
3103 		const struct extern_desc *ext;
3104 
3105 		ext = &obj->externs[i];
3106 		if (ext->type == EXT_KSYM && ext->ksym.type_id)
3107 			return true;
3108 	}
3109 
3110 	bpf_object__for_each_program(prog, obj) {
3111 		if (!prog->autoload)
3112 			continue;
3113 		if (prog_needs_vmlinux_btf(prog))
3114 			return true;
3115 	}
3116 
3117 	bpf_object__for_each_map(map, obj) {
3118 		if (map_needs_vmlinux_btf(map))
3119 			return true;
3120 	}
3121 
3122 	return false;
3123 }
3124 
3125 static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
3126 {
3127 	int err;
3128 
3129 	/* btf_vmlinux could be loaded earlier */
3130 	if (obj->btf_vmlinux || obj->gen_loader)
3131 		return 0;
3132 
3133 	if (!force && !obj_needs_vmlinux_btf(obj))
3134 		return 0;
3135 
3136 	obj->btf_vmlinux = btf__load_vmlinux_btf();
3137 	err = libbpf_get_error(obj->btf_vmlinux);
3138 	if (err) {
3139 		pr_warn("Error loading vmlinux BTF: %d\n", err);
3140 		obj->btf_vmlinux = NULL;
3141 		return err;
3142 	}
3143 	return 0;
3144 }
3145 
3146 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
3147 {
3148 	struct btf *kern_btf = obj->btf;
3149 	bool btf_mandatory, sanitize;
3150 	int i, err = 0;
3151 
3152 	if (!obj->btf)
3153 		return 0;
3154 
3155 	if (!kernel_supports(obj, FEAT_BTF)) {
3156 		if (kernel_needs_btf(obj)) {
3157 			err = -EOPNOTSUPP;
3158 			goto report;
3159 		}
3160 		pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
3161 		return 0;
3162 	}
3163 
3164 	/* Even though some subprogs are global/weak, user might prefer more
3165 	 * permissive BPF verification process that BPF verifier performs for
3166 	 * static functions, taking into account more context from the caller
3167 	 * functions. In such case, they need to mark such subprogs with
3168 	 * __attribute__((visibility("hidden"))) and libbpf will adjust
3169 	 * corresponding FUNC BTF type to be marked as static and trigger more
3170 	 * involved BPF verification process.
3171 	 */
3172 	for (i = 0; i < obj->nr_programs; i++) {
3173 		struct bpf_program *prog = &obj->programs[i];
3174 		struct btf_type *t;
3175 		const char *name;
3176 		int j, n;
3177 
3178 		if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
3179 			continue;
3180 
3181 		n = btf__type_cnt(obj->btf);
3182 		for (j = 1; j < n; j++) {
3183 			t = btf_type_by_id(obj->btf, j);
3184 			if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
3185 				continue;
3186 
3187 			name = btf__str_by_offset(obj->btf, t->name_off);
3188 			if (strcmp(name, prog->name) != 0)
3189 				continue;
3190 
3191 			t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
3192 			break;
3193 		}
3194 	}
3195 
3196 	sanitize = btf_needs_sanitization(obj);
3197 	if (sanitize) {
3198 		const void *raw_data;
3199 		__u32 sz;
3200 
3201 		/* clone BTF to sanitize a copy and leave the original intact */
3202 		raw_data = btf__raw_data(obj->btf, &sz);
3203 		kern_btf = btf__new(raw_data, sz);
3204 		err = libbpf_get_error(kern_btf);
3205 		if (err)
3206 			return err;
3207 
3208 		/* enforce 8-byte pointers for BPF-targeted BTFs */
3209 		btf__set_pointer_size(obj->btf, 8);
3210 		err = bpf_object__sanitize_btf(obj, kern_btf);
3211 		if (err)
3212 			return err;
3213 	}
3214 
3215 	if (obj->gen_loader) {
3216 		__u32 raw_size = 0;
3217 		const void *raw_data = btf__raw_data(kern_btf, &raw_size);
3218 
3219 		if (!raw_data)
3220 			return -ENOMEM;
3221 		bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
3222 		/* Pretend to have valid FD to pass various fd >= 0 checks.
3223 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
3224 		 */
3225 		btf__set_fd(kern_btf, 0);
3226 	} else {
3227 		/* currently BPF_BTF_LOAD only supports log_level 1 */
3228 		err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
3229 					   obj->log_level ? 1 : 0);
3230 	}
3231 	if (sanitize) {
3232 		if (!err) {
3233 			/* move fd to libbpf's BTF */
3234 			btf__set_fd(obj->btf, btf__fd(kern_btf));
3235 			btf__set_fd(kern_btf, -1);
3236 		}
3237 		btf__free(kern_btf);
3238 	}
3239 report:
3240 	if (err) {
3241 		btf_mandatory = kernel_needs_btf(obj);
3242 		pr_warn("Error loading .BTF into kernel: %d. %s\n", err,
3243 			btf_mandatory ? "BTF is mandatory, can't proceed."
3244 				      : "BTF is optional, ignoring.");
3245 		if (!btf_mandatory)
3246 			err = 0;
3247 	}
3248 	return err;
3249 }
3250 
3251 static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
3252 {
3253 	const char *name;
3254 
3255 	name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
3256 	if (!name) {
3257 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3258 			off, obj->path, elf_errmsg(-1));
3259 		return NULL;
3260 	}
3261 
3262 	return name;
3263 }
3264 
3265 static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
3266 {
3267 	const char *name;
3268 
3269 	name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
3270 	if (!name) {
3271 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3272 			off, obj->path, elf_errmsg(-1));
3273 		return NULL;
3274 	}
3275 
3276 	return name;
3277 }
3278 
3279 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
3280 {
3281 	Elf_Scn *scn;
3282 
3283 	scn = elf_getscn(obj->efile.elf, idx);
3284 	if (!scn) {
3285 		pr_warn("elf: failed to get section(%zu) from %s: %s\n",
3286 			idx, obj->path, elf_errmsg(-1));
3287 		return NULL;
3288 	}
3289 	return scn;
3290 }
3291 
3292 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
3293 {
3294 	Elf_Scn *scn = NULL;
3295 	Elf *elf = obj->efile.elf;
3296 	const char *sec_name;
3297 
3298 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3299 		sec_name = elf_sec_name(obj, scn);
3300 		if (!sec_name)
3301 			return NULL;
3302 
3303 		if (strcmp(sec_name, name) != 0)
3304 			continue;
3305 
3306 		return scn;
3307 	}
3308 	return NULL;
3309 }
3310 
3311 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn)
3312 {
3313 	Elf64_Shdr *shdr;
3314 
3315 	if (!scn)
3316 		return NULL;
3317 
3318 	shdr = elf64_getshdr(scn);
3319 	if (!shdr) {
3320 		pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
3321 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3322 		return NULL;
3323 	}
3324 
3325 	return shdr;
3326 }
3327 
3328 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
3329 {
3330 	const char *name;
3331 	Elf64_Shdr *sh;
3332 
3333 	if (!scn)
3334 		return NULL;
3335 
3336 	sh = elf_sec_hdr(obj, scn);
3337 	if (!sh)
3338 		return NULL;
3339 
3340 	name = elf_sec_str(obj, sh->sh_name);
3341 	if (!name) {
3342 		pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
3343 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3344 		return NULL;
3345 	}
3346 
3347 	return name;
3348 }
3349 
3350 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
3351 {
3352 	Elf_Data *data;
3353 
3354 	if (!scn)
3355 		return NULL;
3356 
3357 	data = elf_getdata(scn, 0);
3358 	if (!data) {
3359 		pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
3360 			elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
3361 			obj->path, elf_errmsg(-1));
3362 		return NULL;
3363 	}
3364 
3365 	return data;
3366 }
3367 
3368 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx)
3369 {
3370 	if (idx >= obj->efile.symbols->d_size / sizeof(Elf64_Sym))
3371 		return NULL;
3372 
3373 	return (Elf64_Sym *)obj->efile.symbols->d_buf + idx;
3374 }
3375 
3376 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx)
3377 {
3378 	if (idx >= data->d_size / sizeof(Elf64_Rel))
3379 		return NULL;
3380 
3381 	return (Elf64_Rel *)data->d_buf + idx;
3382 }
3383 
3384 static bool is_sec_name_dwarf(const char *name)
3385 {
3386 	/* approximation, but the actual list is too long */
3387 	return str_has_pfx(name, ".debug_");
3388 }
3389 
3390 static bool ignore_elf_section(Elf64_Shdr *hdr, const char *name)
3391 {
3392 	/* no special handling of .strtab */
3393 	if (hdr->sh_type == SHT_STRTAB)
3394 		return true;
3395 
3396 	/* ignore .llvm_addrsig section as well */
3397 	if (hdr->sh_type == SHT_LLVM_ADDRSIG)
3398 		return true;
3399 
3400 	/* no subprograms will lead to an empty .text section, ignore it */
3401 	if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
3402 	    strcmp(name, ".text") == 0)
3403 		return true;
3404 
3405 	/* DWARF sections */
3406 	if (is_sec_name_dwarf(name))
3407 		return true;
3408 
3409 	if (str_has_pfx(name, ".rel")) {
3410 		name += sizeof(".rel") - 1;
3411 		/* DWARF section relocations */
3412 		if (is_sec_name_dwarf(name))
3413 			return true;
3414 
3415 		/* .BTF and .BTF.ext don't need relocations */
3416 		if (strcmp(name, BTF_ELF_SEC) == 0 ||
3417 		    strcmp(name, BTF_EXT_ELF_SEC) == 0)
3418 			return true;
3419 	}
3420 
3421 	return false;
3422 }
3423 
3424 static int cmp_progs(const void *_a, const void *_b)
3425 {
3426 	const struct bpf_program *a = _a;
3427 	const struct bpf_program *b = _b;
3428 
3429 	if (a->sec_idx != b->sec_idx)
3430 		return a->sec_idx < b->sec_idx ? -1 : 1;
3431 
3432 	/* sec_insn_off can't be the same within the section */
3433 	return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
3434 }
3435 
3436 static int bpf_object__elf_collect(struct bpf_object *obj)
3437 {
3438 	struct elf_sec_desc *sec_desc;
3439 	Elf *elf = obj->efile.elf;
3440 	Elf_Data *btf_ext_data = NULL;
3441 	Elf_Data *btf_data = NULL;
3442 	int idx = 0, err = 0;
3443 	const char *name;
3444 	Elf_Data *data;
3445 	Elf_Scn *scn;
3446 	Elf64_Shdr *sh;
3447 
3448 	/* ELF section indices are 0-based, but sec #0 is special "invalid"
3449 	 * section. Since section count retrieved by elf_getshdrnum() does
3450 	 * include sec #0, it is already the necessary size of an array to keep
3451 	 * all the sections.
3452 	 */
3453 	if (elf_getshdrnum(obj->efile.elf, &obj->efile.sec_cnt)) {
3454 		pr_warn("elf: failed to get the number of sections for %s: %s\n",
3455 			obj->path, elf_errmsg(-1));
3456 		return -LIBBPF_ERRNO__FORMAT;
3457 	}
3458 	obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs));
3459 	if (!obj->efile.secs)
3460 		return -ENOMEM;
3461 
3462 	/* a bunch of ELF parsing functionality depends on processing symbols,
3463 	 * so do the first pass and find the symbol table
3464 	 */
3465 	scn = NULL;
3466 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3467 		sh = elf_sec_hdr(obj, scn);
3468 		if (!sh)
3469 			return -LIBBPF_ERRNO__FORMAT;
3470 
3471 		if (sh->sh_type == SHT_SYMTAB) {
3472 			if (obj->efile.symbols) {
3473 				pr_warn("elf: multiple symbol tables in %s\n", obj->path);
3474 				return -LIBBPF_ERRNO__FORMAT;
3475 			}
3476 
3477 			data = elf_sec_data(obj, scn);
3478 			if (!data)
3479 				return -LIBBPF_ERRNO__FORMAT;
3480 
3481 			idx = elf_ndxscn(scn);
3482 
3483 			obj->efile.symbols = data;
3484 			obj->efile.symbols_shndx = idx;
3485 			obj->efile.strtabidx = sh->sh_link;
3486 		}
3487 	}
3488 
3489 	if (!obj->efile.symbols) {
3490 		pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
3491 			obj->path);
3492 		return -ENOENT;
3493 	}
3494 
3495 	scn = NULL;
3496 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3497 		idx = elf_ndxscn(scn);
3498 		sec_desc = &obj->efile.secs[idx];
3499 
3500 		sh = elf_sec_hdr(obj, scn);
3501 		if (!sh)
3502 			return -LIBBPF_ERRNO__FORMAT;
3503 
3504 		name = elf_sec_str(obj, sh->sh_name);
3505 		if (!name)
3506 			return -LIBBPF_ERRNO__FORMAT;
3507 
3508 		if (ignore_elf_section(sh, name))
3509 			continue;
3510 
3511 		data = elf_sec_data(obj, scn);
3512 		if (!data)
3513 			return -LIBBPF_ERRNO__FORMAT;
3514 
3515 		pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
3516 			 idx, name, (unsigned long)data->d_size,
3517 			 (int)sh->sh_link, (unsigned long)sh->sh_flags,
3518 			 (int)sh->sh_type);
3519 
3520 		if (strcmp(name, "license") == 0) {
3521 			err = bpf_object__init_license(obj, data->d_buf, data->d_size);
3522 			if (err)
3523 				return err;
3524 		} else if (strcmp(name, "version") == 0) {
3525 			err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
3526 			if (err)
3527 				return err;
3528 		} else if (strcmp(name, "maps") == 0) {
3529 			pr_warn("elf: legacy map definitions in 'maps' section are not supported by libbpf v1.0+\n");
3530 			return -ENOTSUP;
3531 		} else if (strcmp(name, MAPS_ELF_SEC) == 0) {
3532 			obj->efile.btf_maps_shndx = idx;
3533 		} else if (strcmp(name, BTF_ELF_SEC) == 0) {
3534 			if (sh->sh_type != SHT_PROGBITS)
3535 				return -LIBBPF_ERRNO__FORMAT;
3536 			btf_data = data;
3537 		} else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
3538 			if (sh->sh_type != SHT_PROGBITS)
3539 				return -LIBBPF_ERRNO__FORMAT;
3540 			btf_ext_data = data;
3541 		} else if (sh->sh_type == SHT_SYMTAB) {
3542 			/* already processed during the first pass above */
3543 		} else if (sh->sh_type == SHT_PROGBITS && data->d_size > 0) {
3544 			if (sh->sh_flags & SHF_EXECINSTR) {
3545 				if (strcmp(name, ".text") == 0)
3546 					obj->efile.text_shndx = idx;
3547 				err = bpf_object__add_programs(obj, data, name, idx);
3548 				if (err)
3549 					return err;
3550 			} else if (strcmp(name, DATA_SEC) == 0 ||
3551 				   str_has_pfx(name, DATA_SEC ".")) {
3552 				sec_desc->sec_type = SEC_DATA;
3553 				sec_desc->shdr = sh;
3554 				sec_desc->data = data;
3555 			} else if (strcmp(name, RODATA_SEC) == 0 ||
3556 				   str_has_pfx(name, RODATA_SEC ".")) {
3557 				sec_desc->sec_type = SEC_RODATA;
3558 				sec_desc->shdr = sh;
3559 				sec_desc->data = data;
3560 			} else if (strcmp(name, STRUCT_OPS_SEC) == 0) {
3561 				obj->efile.st_ops_data = data;
3562 				obj->efile.st_ops_shndx = idx;
3563 			} else if (strcmp(name, STRUCT_OPS_LINK_SEC) == 0) {
3564 				obj->efile.st_ops_link_data = data;
3565 				obj->efile.st_ops_link_shndx = idx;
3566 			} else {
3567 				pr_info("elf: skipping unrecognized data section(%d) %s\n",
3568 					idx, name);
3569 			}
3570 		} else if (sh->sh_type == SHT_REL) {
3571 			int targ_sec_idx = sh->sh_info; /* points to other section */
3572 
3573 			if (sh->sh_entsize != sizeof(Elf64_Rel) ||
3574 			    targ_sec_idx >= obj->efile.sec_cnt)
3575 				return -LIBBPF_ERRNO__FORMAT;
3576 
3577 			/* Only do relo for section with exec instructions */
3578 			if (!section_have_execinstr(obj, targ_sec_idx) &&
3579 			    strcmp(name, ".rel" STRUCT_OPS_SEC) &&
3580 			    strcmp(name, ".rel" STRUCT_OPS_LINK_SEC) &&
3581 			    strcmp(name, ".rel" MAPS_ELF_SEC)) {
3582 				pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
3583 					idx, name, targ_sec_idx,
3584 					elf_sec_name(obj, elf_sec_by_idx(obj, targ_sec_idx)) ?: "<?>");
3585 				continue;
3586 			}
3587 
3588 			sec_desc->sec_type = SEC_RELO;
3589 			sec_desc->shdr = sh;
3590 			sec_desc->data = data;
3591 		} else if (sh->sh_type == SHT_NOBITS && (strcmp(name, BSS_SEC) == 0 ||
3592 							 str_has_pfx(name, BSS_SEC "."))) {
3593 			sec_desc->sec_type = SEC_BSS;
3594 			sec_desc->shdr = sh;
3595 			sec_desc->data = data;
3596 		} else {
3597 			pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
3598 				(size_t)sh->sh_size);
3599 		}
3600 	}
3601 
3602 	if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
3603 		pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
3604 		return -LIBBPF_ERRNO__FORMAT;
3605 	}
3606 
3607 	/* sort BPF programs by section name and in-section instruction offset
3608 	 * for faster search
3609 	 */
3610 	if (obj->nr_programs)
3611 		qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
3612 
3613 	return bpf_object__init_btf(obj, btf_data, btf_ext_data);
3614 }
3615 
3616 static bool sym_is_extern(const Elf64_Sym *sym)
3617 {
3618 	int bind = ELF64_ST_BIND(sym->st_info);
3619 	/* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
3620 	return sym->st_shndx == SHN_UNDEF &&
3621 	       (bind == STB_GLOBAL || bind == STB_WEAK) &&
3622 	       ELF64_ST_TYPE(sym->st_info) == STT_NOTYPE;
3623 }
3624 
3625 static bool sym_is_subprog(const Elf64_Sym *sym, int text_shndx)
3626 {
3627 	int bind = ELF64_ST_BIND(sym->st_info);
3628 	int type = ELF64_ST_TYPE(sym->st_info);
3629 
3630 	/* in .text section */
3631 	if (sym->st_shndx != text_shndx)
3632 		return false;
3633 
3634 	/* local function */
3635 	if (bind == STB_LOCAL && type == STT_SECTION)
3636 		return true;
3637 
3638 	/* global function */
3639 	return bind == STB_GLOBAL && type == STT_FUNC;
3640 }
3641 
3642 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
3643 {
3644 	const struct btf_type *t;
3645 	const char *tname;
3646 	int i, n;
3647 
3648 	if (!btf)
3649 		return -ESRCH;
3650 
3651 	n = btf__type_cnt(btf);
3652 	for (i = 1; i < n; i++) {
3653 		t = btf__type_by_id(btf, i);
3654 
3655 		if (!btf_is_var(t) && !btf_is_func(t))
3656 			continue;
3657 
3658 		tname = btf__name_by_offset(btf, t->name_off);
3659 		if (strcmp(tname, ext_name))
3660 			continue;
3661 
3662 		if (btf_is_var(t) &&
3663 		    btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
3664 			return -EINVAL;
3665 
3666 		if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
3667 			return -EINVAL;
3668 
3669 		return i;
3670 	}
3671 
3672 	return -ENOENT;
3673 }
3674 
3675 static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
3676 	const struct btf_var_secinfo *vs;
3677 	const struct btf_type *t;
3678 	int i, j, n;
3679 
3680 	if (!btf)
3681 		return -ESRCH;
3682 
3683 	n = btf__type_cnt(btf);
3684 	for (i = 1; i < n; i++) {
3685 		t = btf__type_by_id(btf, i);
3686 
3687 		if (!btf_is_datasec(t))
3688 			continue;
3689 
3690 		vs = btf_var_secinfos(t);
3691 		for (j = 0; j < btf_vlen(t); j++, vs++) {
3692 			if (vs->type == ext_btf_id)
3693 				return i;
3694 		}
3695 	}
3696 
3697 	return -ENOENT;
3698 }
3699 
3700 static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
3701 				     bool *is_signed)
3702 {
3703 	const struct btf_type *t;
3704 	const char *name;
3705 
3706 	t = skip_mods_and_typedefs(btf, id, NULL);
3707 	name = btf__name_by_offset(btf, t->name_off);
3708 
3709 	if (is_signed)
3710 		*is_signed = false;
3711 	switch (btf_kind(t)) {
3712 	case BTF_KIND_INT: {
3713 		int enc = btf_int_encoding(t);
3714 
3715 		if (enc & BTF_INT_BOOL)
3716 			return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
3717 		if (is_signed)
3718 			*is_signed = enc & BTF_INT_SIGNED;
3719 		if (t->size == 1)
3720 			return KCFG_CHAR;
3721 		if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
3722 			return KCFG_UNKNOWN;
3723 		return KCFG_INT;
3724 	}
3725 	case BTF_KIND_ENUM:
3726 		if (t->size != 4)
3727 			return KCFG_UNKNOWN;
3728 		if (strcmp(name, "libbpf_tristate"))
3729 			return KCFG_UNKNOWN;
3730 		return KCFG_TRISTATE;
3731 	case BTF_KIND_ENUM64:
3732 		if (strcmp(name, "libbpf_tristate"))
3733 			return KCFG_UNKNOWN;
3734 		return KCFG_TRISTATE;
3735 	case BTF_KIND_ARRAY:
3736 		if (btf_array(t)->nelems == 0)
3737 			return KCFG_UNKNOWN;
3738 		if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
3739 			return KCFG_UNKNOWN;
3740 		return KCFG_CHAR_ARR;
3741 	default:
3742 		return KCFG_UNKNOWN;
3743 	}
3744 }
3745 
3746 static int cmp_externs(const void *_a, const void *_b)
3747 {
3748 	const struct extern_desc *a = _a;
3749 	const struct extern_desc *b = _b;
3750 
3751 	if (a->type != b->type)
3752 		return a->type < b->type ? -1 : 1;
3753 
3754 	if (a->type == EXT_KCFG) {
3755 		/* descending order by alignment requirements */
3756 		if (a->kcfg.align != b->kcfg.align)
3757 			return a->kcfg.align > b->kcfg.align ? -1 : 1;
3758 		/* ascending order by size, within same alignment class */
3759 		if (a->kcfg.sz != b->kcfg.sz)
3760 			return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
3761 	}
3762 
3763 	/* resolve ties by name */
3764 	return strcmp(a->name, b->name);
3765 }
3766 
3767 static int find_int_btf_id(const struct btf *btf)
3768 {
3769 	const struct btf_type *t;
3770 	int i, n;
3771 
3772 	n = btf__type_cnt(btf);
3773 	for (i = 1; i < n; i++) {
3774 		t = btf__type_by_id(btf, i);
3775 
3776 		if (btf_is_int(t) && btf_int_bits(t) == 32)
3777 			return i;
3778 	}
3779 
3780 	return 0;
3781 }
3782 
3783 static int add_dummy_ksym_var(struct btf *btf)
3784 {
3785 	int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
3786 	const struct btf_var_secinfo *vs;
3787 	const struct btf_type *sec;
3788 
3789 	if (!btf)
3790 		return 0;
3791 
3792 	sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
3793 					    BTF_KIND_DATASEC);
3794 	if (sec_btf_id < 0)
3795 		return 0;
3796 
3797 	sec = btf__type_by_id(btf, sec_btf_id);
3798 	vs = btf_var_secinfos(sec);
3799 	for (i = 0; i < btf_vlen(sec); i++, vs++) {
3800 		const struct btf_type *vt;
3801 
3802 		vt = btf__type_by_id(btf, vs->type);
3803 		if (btf_is_func(vt))
3804 			break;
3805 	}
3806 
3807 	/* No func in ksyms sec.  No need to add dummy var. */
3808 	if (i == btf_vlen(sec))
3809 		return 0;
3810 
3811 	int_btf_id = find_int_btf_id(btf);
3812 	dummy_var_btf_id = btf__add_var(btf,
3813 					"dummy_ksym",
3814 					BTF_VAR_GLOBAL_ALLOCATED,
3815 					int_btf_id);
3816 	if (dummy_var_btf_id < 0)
3817 		pr_warn("cannot create a dummy_ksym var\n");
3818 
3819 	return dummy_var_btf_id;
3820 }
3821 
3822 static int bpf_object__collect_externs(struct bpf_object *obj)
3823 {
3824 	struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
3825 	const struct btf_type *t;
3826 	struct extern_desc *ext;
3827 	int i, n, off, dummy_var_btf_id;
3828 	const char *ext_name, *sec_name;
3829 	size_t ext_essent_len;
3830 	Elf_Scn *scn;
3831 	Elf64_Shdr *sh;
3832 
3833 	if (!obj->efile.symbols)
3834 		return 0;
3835 
3836 	scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
3837 	sh = elf_sec_hdr(obj, scn);
3838 	if (!sh || sh->sh_entsize != sizeof(Elf64_Sym))
3839 		return -LIBBPF_ERRNO__FORMAT;
3840 
3841 	dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
3842 	if (dummy_var_btf_id < 0)
3843 		return dummy_var_btf_id;
3844 
3845 	n = sh->sh_size / sh->sh_entsize;
3846 	pr_debug("looking for externs among %d symbols...\n", n);
3847 
3848 	for (i = 0; i < n; i++) {
3849 		Elf64_Sym *sym = elf_sym_by_idx(obj, i);
3850 
3851 		if (!sym)
3852 			return -LIBBPF_ERRNO__FORMAT;
3853 		if (!sym_is_extern(sym))
3854 			continue;
3855 		ext_name = elf_sym_str(obj, sym->st_name);
3856 		if (!ext_name || !ext_name[0])
3857 			continue;
3858 
3859 		ext = obj->externs;
3860 		ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
3861 		if (!ext)
3862 			return -ENOMEM;
3863 		obj->externs = ext;
3864 		ext = &ext[obj->nr_extern];
3865 		memset(ext, 0, sizeof(*ext));
3866 		obj->nr_extern++;
3867 
3868 		ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
3869 		if (ext->btf_id <= 0) {
3870 			pr_warn("failed to find BTF for extern '%s': %d\n",
3871 				ext_name, ext->btf_id);
3872 			return ext->btf_id;
3873 		}
3874 		t = btf__type_by_id(obj->btf, ext->btf_id);
3875 		ext->name = btf__name_by_offset(obj->btf, t->name_off);
3876 		ext->sym_idx = i;
3877 		ext->is_weak = ELF64_ST_BIND(sym->st_info) == STB_WEAK;
3878 
3879 		ext_essent_len = bpf_core_essential_name_len(ext->name);
3880 		ext->essent_name = NULL;
3881 		if (ext_essent_len != strlen(ext->name)) {
3882 			ext->essent_name = strndup(ext->name, ext_essent_len);
3883 			if (!ext->essent_name)
3884 				return -ENOMEM;
3885 		}
3886 
3887 		ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
3888 		if (ext->sec_btf_id <= 0) {
3889 			pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
3890 				ext_name, ext->btf_id, ext->sec_btf_id);
3891 			return ext->sec_btf_id;
3892 		}
3893 		sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
3894 		sec_name = btf__name_by_offset(obj->btf, sec->name_off);
3895 
3896 		if (strcmp(sec_name, KCONFIG_SEC) == 0) {
3897 			if (btf_is_func(t)) {
3898 				pr_warn("extern function %s is unsupported under %s section\n",
3899 					ext->name, KCONFIG_SEC);
3900 				return -ENOTSUP;
3901 			}
3902 			kcfg_sec = sec;
3903 			ext->type = EXT_KCFG;
3904 			ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
3905 			if (ext->kcfg.sz <= 0) {
3906 				pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
3907 					ext_name, ext->kcfg.sz);
3908 				return ext->kcfg.sz;
3909 			}
3910 			ext->kcfg.align = btf__align_of(obj->btf, t->type);
3911 			if (ext->kcfg.align <= 0) {
3912 				pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
3913 					ext_name, ext->kcfg.align);
3914 				return -EINVAL;
3915 			}
3916 			ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
3917 							&ext->kcfg.is_signed);
3918 			if (ext->kcfg.type == KCFG_UNKNOWN) {
3919 				pr_warn("extern (kcfg) '%s': type is unsupported\n", ext_name);
3920 				return -ENOTSUP;
3921 			}
3922 		} else if (strcmp(sec_name, KSYMS_SEC) == 0) {
3923 			ksym_sec = sec;
3924 			ext->type = EXT_KSYM;
3925 			skip_mods_and_typedefs(obj->btf, t->type,
3926 					       &ext->ksym.type_id);
3927 		} else {
3928 			pr_warn("unrecognized extern section '%s'\n", sec_name);
3929 			return -ENOTSUP;
3930 		}
3931 	}
3932 	pr_debug("collected %d externs total\n", obj->nr_extern);
3933 
3934 	if (!obj->nr_extern)
3935 		return 0;
3936 
3937 	/* sort externs by type, for kcfg ones also by (align, size, name) */
3938 	qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
3939 
3940 	/* for .ksyms section, we need to turn all externs into allocated
3941 	 * variables in BTF to pass kernel verification; we do this by
3942 	 * pretending that each extern is a 8-byte variable
3943 	 */
3944 	if (ksym_sec) {
3945 		/* find existing 4-byte integer type in BTF to use for fake
3946 		 * extern variables in DATASEC
3947 		 */
3948 		int int_btf_id = find_int_btf_id(obj->btf);
3949 		/* For extern function, a dummy_var added earlier
3950 		 * will be used to replace the vs->type and
3951 		 * its name string will be used to refill
3952 		 * the missing param's name.
3953 		 */
3954 		const struct btf_type *dummy_var;
3955 
3956 		dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
3957 		for (i = 0; i < obj->nr_extern; i++) {
3958 			ext = &obj->externs[i];
3959 			if (ext->type != EXT_KSYM)
3960 				continue;
3961 			pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
3962 				 i, ext->sym_idx, ext->name);
3963 		}
3964 
3965 		sec = ksym_sec;
3966 		n = btf_vlen(sec);
3967 		for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
3968 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3969 			struct btf_type *vt;
3970 
3971 			vt = (void *)btf__type_by_id(obj->btf, vs->type);
3972 			ext_name = btf__name_by_offset(obj->btf, vt->name_off);
3973 			ext = find_extern_by_name(obj, ext_name);
3974 			if (!ext) {
3975 				pr_warn("failed to find extern definition for BTF %s '%s'\n",
3976 					btf_kind_str(vt), ext_name);
3977 				return -ESRCH;
3978 			}
3979 			if (btf_is_func(vt)) {
3980 				const struct btf_type *func_proto;
3981 				struct btf_param *param;
3982 				int j;
3983 
3984 				func_proto = btf__type_by_id(obj->btf,
3985 							     vt->type);
3986 				param = btf_params(func_proto);
3987 				/* Reuse the dummy_var string if the
3988 				 * func proto does not have param name.
3989 				 */
3990 				for (j = 0; j < btf_vlen(func_proto); j++)
3991 					if (param[j].type && !param[j].name_off)
3992 						param[j].name_off =
3993 							dummy_var->name_off;
3994 				vs->type = dummy_var_btf_id;
3995 				vt->info &= ~0xffff;
3996 				vt->info |= BTF_FUNC_GLOBAL;
3997 			} else {
3998 				btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3999 				vt->type = int_btf_id;
4000 			}
4001 			vs->offset = off;
4002 			vs->size = sizeof(int);
4003 		}
4004 		sec->size = off;
4005 	}
4006 
4007 	if (kcfg_sec) {
4008 		sec = kcfg_sec;
4009 		/* for kcfg externs calculate their offsets within a .kconfig map */
4010 		off = 0;
4011 		for (i = 0; i < obj->nr_extern; i++) {
4012 			ext = &obj->externs[i];
4013 			if (ext->type != EXT_KCFG)
4014 				continue;
4015 
4016 			ext->kcfg.data_off = roundup(off, ext->kcfg.align);
4017 			off = ext->kcfg.data_off + ext->kcfg.sz;
4018 			pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
4019 				 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
4020 		}
4021 		sec->size = off;
4022 		n = btf_vlen(sec);
4023 		for (i = 0; i < n; i++) {
4024 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4025 
4026 			t = btf__type_by_id(obj->btf, vs->type);
4027 			ext_name = btf__name_by_offset(obj->btf, t->name_off);
4028 			ext = find_extern_by_name(obj, ext_name);
4029 			if (!ext) {
4030 				pr_warn("failed to find extern definition for BTF var '%s'\n",
4031 					ext_name);
4032 				return -ESRCH;
4033 			}
4034 			btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4035 			vs->offset = ext->kcfg.data_off;
4036 		}
4037 	}
4038 	return 0;
4039 }
4040 
4041 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog)
4042 {
4043 	return prog->sec_idx == obj->efile.text_shndx && obj->nr_programs > 1;
4044 }
4045 
4046 struct bpf_program *
4047 bpf_object__find_program_by_name(const struct bpf_object *obj,
4048 				 const char *name)
4049 {
4050 	struct bpf_program *prog;
4051 
4052 	bpf_object__for_each_program(prog, obj) {
4053 		if (prog_is_subprog(obj, prog))
4054 			continue;
4055 		if (!strcmp(prog->name, name))
4056 			return prog;
4057 	}
4058 	return errno = ENOENT, NULL;
4059 }
4060 
4061 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
4062 				      int shndx)
4063 {
4064 	switch (obj->efile.secs[shndx].sec_type) {
4065 	case SEC_BSS:
4066 	case SEC_DATA:
4067 	case SEC_RODATA:
4068 		return true;
4069 	default:
4070 		return false;
4071 	}
4072 }
4073 
4074 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
4075 				      int shndx)
4076 {
4077 	return shndx == obj->efile.btf_maps_shndx;
4078 }
4079 
4080 static enum libbpf_map_type
4081 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
4082 {
4083 	if (shndx == obj->efile.symbols_shndx)
4084 		return LIBBPF_MAP_KCONFIG;
4085 
4086 	switch (obj->efile.secs[shndx].sec_type) {
4087 	case SEC_BSS:
4088 		return LIBBPF_MAP_BSS;
4089 	case SEC_DATA:
4090 		return LIBBPF_MAP_DATA;
4091 	case SEC_RODATA:
4092 		return LIBBPF_MAP_RODATA;
4093 	default:
4094 		return LIBBPF_MAP_UNSPEC;
4095 	}
4096 }
4097 
4098 static int bpf_program__record_reloc(struct bpf_program *prog,
4099 				     struct reloc_desc *reloc_desc,
4100 				     __u32 insn_idx, const char *sym_name,
4101 				     const Elf64_Sym *sym, const Elf64_Rel *rel)
4102 {
4103 	struct bpf_insn *insn = &prog->insns[insn_idx];
4104 	size_t map_idx, nr_maps = prog->obj->nr_maps;
4105 	struct bpf_object *obj = prog->obj;
4106 	__u32 shdr_idx = sym->st_shndx;
4107 	enum libbpf_map_type type;
4108 	const char *sym_sec_name;
4109 	struct bpf_map *map;
4110 
4111 	if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
4112 		pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n",
4113 			prog->name, sym_name, insn_idx, insn->code);
4114 		return -LIBBPF_ERRNO__RELOC;
4115 	}
4116 
4117 	if (sym_is_extern(sym)) {
4118 		int sym_idx = ELF64_R_SYM(rel->r_info);
4119 		int i, n = obj->nr_extern;
4120 		struct extern_desc *ext;
4121 
4122 		for (i = 0; i < n; i++) {
4123 			ext = &obj->externs[i];
4124 			if (ext->sym_idx == sym_idx)
4125 				break;
4126 		}
4127 		if (i >= n) {
4128 			pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
4129 				prog->name, sym_name, sym_idx);
4130 			return -LIBBPF_ERRNO__RELOC;
4131 		}
4132 		pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
4133 			 prog->name, i, ext->name, ext->sym_idx, insn_idx);
4134 		if (insn->code == (BPF_JMP | BPF_CALL))
4135 			reloc_desc->type = RELO_EXTERN_CALL;
4136 		else
4137 			reloc_desc->type = RELO_EXTERN_LD64;
4138 		reloc_desc->insn_idx = insn_idx;
4139 		reloc_desc->ext_idx = i;
4140 		return 0;
4141 	}
4142 
4143 	/* sub-program call relocation */
4144 	if (is_call_insn(insn)) {
4145 		if (insn->src_reg != BPF_PSEUDO_CALL) {
4146 			pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
4147 			return -LIBBPF_ERRNO__RELOC;
4148 		}
4149 		/* text_shndx can be 0, if no default "main" program exists */
4150 		if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
4151 			sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4152 			pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
4153 				prog->name, sym_name, sym_sec_name);
4154 			return -LIBBPF_ERRNO__RELOC;
4155 		}
4156 		if (sym->st_value % BPF_INSN_SZ) {
4157 			pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
4158 				prog->name, sym_name, (size_t)sym->st_value);
4159 			return -LIBBPF_ERRNO__RELOC;
4160 		}
4161 		reloc_desc->type = RELO_CALL;
4162 		reloc_desc->insn_idx = insn_idx;
4163 		reloc_desc->sym_off = sym->st_value;
4164 		return 0;
4165 	}
4166 
4167 	if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
4168 		pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
4169 			prog->name, sym_name, shdr_idx);
4170 		return -LIBBPF_ERRNO__RELOC;
4171 	}
4172 
4173 	/* loading subprog addresses */
4174 	if (sym_is_subprog(sym, obj->efile.text_shndx)) {
4175 		/* global_func: sym->st_value = offset in the section, insn->imm = 0.
4176 		 * local_func: sym->st_value = 0, insn->imm = offset in the section.
4177 		 */
4178 		if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
4179 			pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
4180 				prog->name, sym_name, (size_t)sym->st_value, insn->imm);
4181 			return -LIBBPF_ERRNO__RELOC;
4182 		}
4183 
4184 		reloc_desc->type = RELO_SUBPROG_ADDR;
4185 		reloc_desc->insn_idx = insn_idx;
4186 		reloc_desc->sym_off = sym->st_value;
4187 		return 0;
4188 	}
4189 
4190 	type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
4191 	sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4192 
4193 	/* generic map reference relocation */
4194 	if (type == LIBBPF_MAP_UNSPEC) {
4195 		if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
4196 			pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
4197 				prog->name, sym_name, sym_sec_name);
4198 			return -LIBBPF_ERRNO__RELOC;
4199 		}
4200 		for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4201 			map = &obj->maps[map_idx];
4202 			if (map->libbpf_type != type ||
4203 			    map->sec_idx != sym->st_shndx ||
4204 			    map->sec_offset != sym->st_value)
4205 				continue;
4206 			pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n",
4207 				 prog->name, map_idx, map->name, map->sec_idx,
4208 				 map->sec_offset, insn_idx);
4209 			break;
4210 		}
4211 		if (map_idx >= nr_maps) {
4212 			pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
4213 				prog->name, sym_sec_name, (size_t)sym->st_value);
4214 			return -LIBBPF_ERRNO__RELOC;
4215 		}
4216 		reloc_desc->type = RELO_LD64;
4217 		reloc_desc->insn_idx = insn_idx;
4218 		reloc_desc->map_idx = map_idx;
4219 		reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
4220 		return 0;
4221 	}
4222 
4223 	/* global data map relocation */
4224 	if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
4225 		pr_warn("prog '%s': bad data relo against section '%s'\n",
4226 			prog->name, sym_sec_name);
4227 		return -LIBBPF_ERRNO__RELOC;
4228 	}
4229 	for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4230 		map = &obj->maps[map_idx];
4231 		if (map->libbpf_type != type || map->sec_idx != sym->st_shndx)
4232 			continue;
4233 		pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n",
4234 			 prog->name, map_idx, map->name, map->sec_idx,
4235 			 map->sec_offset, insn_idx);
4236 		break;
4237 	}
4238 	if (map_idx >= nr_maps) {
4239 		pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
4240 			prog->name, sym_sec_name);
4241 		return -LIBBPF_ERRNO__RELOC;
4242 	}
4243 
4244 	reloc_desc->type = RELO_DATA;
4245 	reloc_desc->insn_idx = insn_idx;
4246 	reloc_desc->map_idx = map_idx;
4247 	reloc_desc->sym_off = sym->st_value;
4248 	return 0;
4249 }
4250 
4251 static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
4252 {
4253 	return insn_idx >= prog->sec_insn_off &&
4254 	       insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
4255 }
4256 
4257 static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
4258 						 size_t sec_idx, size_t insn_idx)
4259 {
4260 	int l = 0, r = obj->nr_programs - 1, m;
4261 	struct bpf_program *prog;
4262 
4263 	if (!obj->nr_programs)
4264 		return NULL;
4265 
4266 	while (l < r) {
4267 		m = l + (r - l + 1) / 2;
4268 		prog = &obj->programs[m];
4269 
4270 		if (prog->sec_idx < sec_idx ||
4271 		    (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
4272 			l = m;
4273 		else
4274 			r = m - 1;
4275 	}
4276 	/* matching program could be at index l, but it still might be the
4277 	 * wrong one, so we need to double check conditions for the last time
4278 	 */
4279 	prog = &obj->programs[l];
4280 	if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
4281 		return prog;
4282 	return NULL;
4283 }
4284 
4285 static int
4286 bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
4287 {
4288 	const char *relo_sec_name, *sec_name;
4289 	size_t sec_idx = shdr->sh_info, sym_idx;
4290 	struct bpf_program *prog;
4291 	struct reloc_desc *relos;
4292 	int err, i, nrels;
4293 	const char *sym_name;
4294 	__u32 insn_idx;
4295 	Elf_Scn *scn;
4296 	Elf_Data *scn_data;
4297 	Elf64_Sym *sym;
4298 	Elf64_Rel *rel;
4299 
4300 	if (sec_idx >= obj->efile.sec_cnt)
4301 		return -EINVAL;
4302 
4303 	scn = elf_sec_by_idx(obj, sec_idx);
4304 	scn_data = elf_sec_data(obj, scn);
4305 	if (!scn_data)
4306 		return -LIBBPF_ERRNO__FORMAT;
4307 
4308 	relo_sec_name = elf_sec_str(obj, shdr->sh_name);
4309 	sec_name = elf_sec_name(obj, scn);
4310 	if (!relo_sec_name || !sec_name)
4311 		return -EINVAL;
4312 
4313 	pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
4314 		 relo_sec_name, sec_idx, sec_name);
4315 	nrels = shdr->sh_size / shdr->sh_entsize;
4316 
4317 	for (i = 0; i < nrels; i++) {
4318 		rel = elf_rel_by_idx(data, i);
4319 		if (!rel) {
4320 			pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
4321 			return -LIBBPF_ERRNO__FORMAT;
4322 		}
4323 
4324 		sym_idx = ELF64_R_SYM(rel->r_info);
4325 		sym = elf_sym_by_idx(obj, sym_idx);
4326 		if (!sym) {
4327 			pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
4328 				relo_sec_name, sym_idx, i);
4329 			return -LIBBPF_ERRNO__FORMAT;
4330 		}
4331 
4332 		if (sym->st_shndx >= obj->efile.sec_cnt) {
4333 			pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
4334 				relo_sec_name, sym_idx, (size_t)sym->st_shndx, i);
4335 			return -LIBBPF_ERRNO__FORMAT;
4336 		}
4337 
4338 		if (rel->r_offset % BPF_INSN_SZ || rel->r_offset >= scn_data->d_size) {
4339 			pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
4340 				relo_sec_name, (size_t)rel->r_offset, i);
4341 			return -LIBBPF_ERRNO__FORMAT;
4342 		}
4343 
4344 		insn_idx = rel->r_offset / BPF_INSN_SZ;
4345 		/* relocations against static functions are recorded as
4346 		 * relocations against the section that contains a function;
4347 		 * in such case, symbol will be STT_SECTION and sym.st_name
4348 		 * will point to empty string (0), so fetch section name
4349 		 * instead
4350 		 */
4351 		if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
4352 			sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx));
4353 		else
4354 			sym_name = elf_sym_str(obj, sym->st_name);
4355 		sym_name = sym_name ?: "<?";
4356 
4357 		pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
4358 			 relo_sec_name, i, insn_idx, sym_name);
4359 
4360 		prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
4361 		if (!prog) {
4362 			pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
4363 				relo_sec_name, i, sec_name, insn_idx);
4364 			continue;
4365 		}
4366 
4367 		relos = libbpf_reallocarray(prog->reloc_desc,
4368 					    prog->nr_reloc + 1, sizeof(*relos));
4369 		if (!relos)
4370 			return -ENOMEM;
4371 		prog->reloc_desc = relos;
4372 
4373 		/* adjust insn_idx to local BPF program frame of reference */
4374 		insn_idx -= prog->sec_insn_off;
4375 		err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
4376 						insn_idx, sym_name, sym, rel);
4377 		if (err)
4378 			return err;
4379 
4380 		prog->nr_reloc++;
4381 	}
4382 	return 0;
4383 }
4384 
4385 static int map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map)
4386 {
4387 	int id;
4388 
4389 	if (!obj->btf)
4390 		return -ENOENT;
4391 
4392 	/* if it's BTF-defined map, we don't need to search for type IDs.
4393 	 * For struct_ops map, it does not need btf_key_type_id and
4394 	 * btf_value_type_id.
4395 	 */
4396 	if (map->sec_idx == obj->efile.btf_maps_shndx || bpf_map__is_struct_ops(map))
4397 		return 0;
4398 
4399 	/*
4400 	 * LLVM annotates global data differently in BTF, that is,
4401 	 * only as '.data', '.bss' or '.rodata'.
4402 	 */
4403 	if (!bpf_map__is_internal(map))
4404 		return -ENOENT;
4405 
4406 	id = btf__find_by_name(obj->btf, map->real_name);
4407 	if (id < 0)
4408 		return id;
4409 
4410 	map->btf_key_type_id = 0;
4411 	map->btf_value_type_id = id;
4412 	return 0;
4413 }
4414 
4415 static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
4416 {
4417 	char file[PATH_MAX], buff[4096];
4418 	FILE *fp;
4419 	__u32 val;
4420 	int err;
4421 
4422 	snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
4423 	memset(info, 0, sizeof(*info));
4424 
4425 	fp = fopen(file, "re");
4426 	if (!fp) {
4427 		err = -errno;
4428 		pr_warn("failed to open %s: %d. No procfs support?\n", file,
4429 			err);
4430 		return err;
4431 	}
4432 
4433 	while (fgets(buff, sizeof(buff), fp)) {
4434 		if (sscanf(buff, "map_type:\t%u", &val) == 1)
4435 			info->type = val;
4436 		else if (sscanf(buff, "key_size:\t%u", &val) == 1)
4437 			info->key_size = val;
4438 		else if (sscanf(buff, "value_size:\t%u", &val) == 1)
4439 			info->value_size = val;
4440 		else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
4441 			info->max_entries = val;
4442 		else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
4443 			info->map_flags = val;
4444 	}
4445 
4446 	fclose(fp);
4447 
4448 	return 0;
4449 }
4450 
4451 bool bpf_map__autocreate(const struct bpf_map *map)
4452 {
4453 	return map->autocreate;
4454 }
4455 
4456 int bpf_map__set_autocreate(struct bpf_map *map, bool autocreate)
4457 {
4458 	if (map->obj->loaded)
4459 		return libbpf_err(-EBUSY);
4460 
4461 	map->autocreate = autocreate;
4462 	return 0;
4463 }
4464 
4465 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
4466 {
4467 	struct bpf_map_info info;
4468 	__u32 len = sizeof(info), name_len;
4469 	int new_fd, err;
4470 	char *new_name;
4471 
4472 	memset(&info, 0, len);
4473 	err = bpf_map_get_info_by_fd(fd, &info, &len);
4474 	if (err && errno == EINVAL)
4475 		err = bpf_get_map_info_from_fdinfo(fd, &info);
4476 	if (err)
4477 		return libbpf_err(err);
4478 
4479 	name_len = strlen(info.name);
4480 	if (name_len == BPF_OBJ_NAME_LEN - 1 && strncmp(map->name, info.name, name_len) == 0)
4481 		new_name = strdup(map->name);
4482 	else
4483 		new_name = strdup(info.name);
4484 
4485 	if (!new_name)
4486 		return libbpf_err(-errno);
4487 
4488 	/*
4489 	 * Like dup(), but make sure new FD is >= 3 and has O_CLOEXEC set.
4490 	 * This is similar to what we do in ensure_good_fd(), but without
4491 	 * closing original FD.
4492 	 */
4493 	new_fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
4494 	if (new_fd < 0) {
4495 		err = -errno;
4496 		goto err_free_new_name;
4497 	}
4498 
4499 	err = reuse_fd(map->fd, new_fd);
4500 	if (err)
4501 		goto err_free_new_name;
4502 
4503 	free(map->name);
4504 
4505 	map->name = new_name;
4506 	map->def.type = info.type;
4507 	map->def.key_size = info.key_size;
4508 	map->def.value_size = info.value_size;
4509 	map->def.max_entries = info.max_entries;
4510 	map->def.map_flags = info.map_flags;
4511 	map->btf_key_type_id = info.btf_key_type_id;
4512 	map->btf_value_type_id = info.btf_value_type_id;
4513 	map->reused = true;
4514 	map->map_extra = info.map_extra;
4515 
4516 	return 0;
4517 
4518 err_free_new_name:
4519 	free(new_name);
4520 	return libbpf_err(err);
4521 }
4522 
4523 __u32 bpf_map__max_entries(const struct bpf_map *map)
4524 {
4525 	return map->def.max_entries;
4526 }
4527 
4528 struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
4529 {
4530 	if (!bpf_map_type__is_map_in_map(map->def.type))
4531 		return errno = EINVAL, NULL;
4532 
4533 	return map->inner_map;
4534 }
4535 
4536 int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
4537 {
4538 	if (map->obj->loaded)
4539 		return libbpf_err(-EBUSY);
4540 
4541 	map->def.max_entries = max_entries;
4542 
4543 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
4544 	if (map_is_ringbuf(map))
4545 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
4546 
4547 	return 0;
4548 }
4549 
4550 static int
4551 bpf_object__probe_loading(struct bpf_object *obj)
4552 {
4553 	char *cp, errmsg[STRERR_BUFSIZE];
4554 	struct bpf_insn insns[] = {
4555 		BPF_MOV64_IMM(BPF_REG_0, 0),
4556 		BPF_EXIT_INSN(),
4557 	};
4558 	int ret, insn_cnt = ARRAY_SIZE(insns);
4559 
4560 	if (obj->gen_loader)
4561 		return 0;
4562 
4563 	ret = bump_rlimit_memlock();
4564 	if (ret)
4565 		pr_warn("Failed to bump RLIMIT_MEMLOCK (err = %d), you might need to do it explicitly!\n", ret);
4566 
4567 	/* make sure basic loading works */
4568 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4569 	if (ret < 0)
4570 		ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
4571 	if (ret < 0) {
4572 		ret = errno;
4573 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4574 		pr_warn("Error in %s():%s(%d). Couldn't load trivial BPF "
4575 			"program. Make sure your kernel supports BPF "
4576 			"(CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is "
4577 			"set to big enough value.\n", __func__, cp, ret);
4578 		return -ret;
4579 	}
4580 	close(ret);
4581 
4582 	return 0;
4583 }
4584 
4585 static int probe_fd(int fd)
4586 {
4587 	if (fd >= 0)
4588 		close(fd);
4589 	return fd >= 0;
4590 }
4591 
4592 static int probe_kern_prog_name(void)
4593 {
4594 	const size_t attr_sz = offsetofend(union bpf_attr, prog_name);
4595 	struct bpf_insn insns[] = {
4596 		BPF_MOV64_IMM(BPF_REG_0, 0),
4597 		BPF_EXIT_INSN(),
4598 	};
4599 	union bpf_attr attr;
4600 	int ret;
4601 
4602 	memset(&attr, 0, attr_sz);
4603 	attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
4604 	attr.license = ptr_to_u64("GPL");
4605 	attr.insns = ptr_to_u64(insns);
4606 	attr.insn_cnt = (__u32)ARRAY_SIZE(insns);
4607 	libbpf_strlcpy(attr.prog_name, "libbpf_nametest", sizeof(attr.prog_name));
4608 
4609 	/* make sure loading with name works */
4610 	ret = sys_bpf_prog_load(&attr, attr_sz, PROG_LOAD_ATTEMPTS);
4611 	return probe_fd(ret);
4612 }
4613 
4614 static int probe_kern_global_data(void)
4615 {
4616 	char *cp, errmsg[STRERR_BUFSIZE];
4617 	struct bpf_insn insns[] = {
4618 		BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
4619 		BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
4620 		BPF_MOV64_IMM(BPF_REG_0, 0),
4621 		BPF_EXIT_INSN(),
4622 	};
4623 	int ret, map, insn_cnt = ARRAY_SIZE(insns);
4624 
4625 	map = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_global", sizeof(int), 32, 1, NULL);
4626 	if (map < 0) {
4627 		ret = -errno;
4628 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4629 		pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4630 			__func__, cp, -ret);
4631 		return ret;
4632 	}
4633 
4634 	insns[0].imm = map;
4635 
4636 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4637 	close(map);
4638 	return probe_fd(ret);
4639 }
4640 
4641 static int probe_kern_btf(void)
4642 {
4643 	static const char strs[] = "\0int";
4644 	__u32 types[] = {
4645 		/* int */
4646 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4647 	};
4648 
4649 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4650 					     strs, sizeof(strs)));
4651 }
4652 
4653 static int probe_kern_btf_func(void)
4654 {
4655 	static const char strs[] = "\0int\0x\0a";
4656 	/* void x(int a) {} */
4657 	__u32 types[] = {
4658 		/* int */
4659 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4660 		/* FUNC_PROTO */                                /* [2] */
4661 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4662 		BTF_PARAM_ENC(7, 1),
4663 		/* FUNC x */                                    /* [3] */
4664 		BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
4665 	};
4666 
4667 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4668 					     strs, sizeof(strs)));
4669 }
4670 
4671 static int probe_kern_btf_func_global(void)
4672 {
4673 	static const char strs[] = "\0int\0x\0a";
4674 	/* static void x(int a) {} */
4675 	__u32 types[] = {
4676 		/* int */
4677 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4678 		/* FUNC_PROTO */                                /* [2] */
4679 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4680 		BTF_PARAM_ENC(7, 1),
4681 		/* FUNC x BTF_FUNC_GLOBAL */                    /* [3] */
4682 		BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, BTF_FUNC_GLOBAL), 2),
4683 	};
4684 
4685 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4686 					     strs, sizeof(strs)));
4687 }
4688 
4689 static int probe_kern_btf_datasec(void)
4690 {
4691 	static const char strs[] = "\0x\0.data";
4692 	/* static int a; */
4693 	__u32 types[] = {
4694 		/* int */
4695 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4696 		/* VAR x */                                     /* [2] */
4697 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4698 		BTF_VAR_STATIC,
4699 		/* DATASEC val */                               /* [3] */
4700 		BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
4701 		BTF_VAR_SECINFO_ENC(2, 0, 4),
4702 	};
4703 
4704 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4705 					     strs, sizeof(strs)));
4706 }
4707 
4708 static int probe_kern_btf_float(void)
4709 {
4710 	static const char strs[] = "\0float";
4711 	__u32 types[] = {
4712 		/* float */
4713 		BTF_TYPE_FLOAT_ENC(1, 4),
4714 	};
4715 
4716 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4717 					     strs, sizeof(strs)));
4718 }
4719 
4720 static int probe_kern_btf_decl_tag(void)
4721 {
4722 	static const char strs[] = "\0tag";
4723 	__u32 types[] = {
4724 		/* int */
4725 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4726 		/* VAR x */                                     /* [2] */
4727 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4728 		BTF_VAR_STATIC,
4729 		/* attr */
4730 		BTF_TYPE_DECL_TAG_ENC(1, 2, -1),
4731 	};
4732 
4733 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4734 					     strs, sizeof(strs)));
4735 }
4736 
4737 static int probe_kern_btf_type_tag(void)
4738 {
4739 	static const char strs[] = "\0tag";
4740 	__u32 types[] = {
4741 		/* int */
4742 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),		/* [1] */
4743 		/* attr */
4744 		BTF_TYPE_TYPE_TAG_ENC(1, 1),				/* [2] */
4745 		/* ptr */
4746 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_PTR, 0, 0), 2),	/* [3] */
4747 	};
4748 
4749 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4750 					     strs, sizeof(strs)));
4751 }
4752 
4753 static int probe_kern_array_mmap(void)
4754 {
4755 	LIBBPF_OPTS(bpf_map_create_opts, opts, .map_flags = BPF_F_MMAPABLE);
4756 	int fd;
4757 
4758 	fd = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_mmap", sizeof(int), sizeof(int), 1, &opts);
4759 	return probe_fd(fd);
4760 }
4761 
4762 static int probe_kern_exp_attach_type(void)
4763 {
4764 	LIBBPF_OPTS(bpf_prog_load_opts, opts, .expected_attach_type = BPF_CGROUP_INET_SOCK_CREATE);
4765 	struct bpf_insn insns[] = {
4766 		BPF_MOV64_IMM(BPF_REG_0, 0),
4767 		BPF_EXIT_INSN(),
4768 	};
4769 	int fd, insn_cnt = ARRAY_SIZE(insns);
4770 
4771 	/* use any valid combination of program type and (optional)
4772 	 * non-zero expected attach type (i.e., not a BPF_CGROUP_INET_INGRESS)
4773 	 * to see if kernel supports expected_attach_type field for
4774 	 * BPF_PROG_LOAD command
4775 	 */
4776 	fd = bpf_prog_load(BPF_PROG_TYPE_CGROUP_SOCK, NULL, "GPL", insns, insn_cnt, &opts);
4777 	return probe_fd(fd);
4778 }
4779 
4780 static int probe_kern_probe_read_kernel(void)
4781 {
4782 	struct bpf_insn insns[] = {
4783 		BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),	/* r1 = r10 (fp) */
4784 		BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -8),	/* r1 += -8 */
4785 		BPF_MOV64_IMM(BPF_REG_2, 8),		/* r2 = 8 */
4786 		BPF_MOV64_IMM(BPF_REG_3, 0),		/* r3 = 0 */
4787 		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_probe_read_kernel),
4788 		BPF_EXIT_INSN(),
4789 	};
4790 	int fd, insn_cnt = ARRAY_SIZE(insns);
4791 
4792 	fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
4793 	return probe_fd(fd);
4794 }
4795 
4796 static int probe_prog_bind_map(void)
4797 {
4798 	char *cp, errmsg[STRERR_BUFSIZE];
4799 	struct bpf_insn insns[] = {
4800 		BPF_MOV64_IMM(BPF_REG_0, 0),
4801 		BPF_EXIT_INSN(),
4802 	};
4803 	int ret, map, prog, insn_cnt = ARRAY_SIZE(insns);
4804 
4805 	map = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_det_bind", sizeof(int), 32, 1, NULL);
4806 	if (map < 0) {
4807 		ret = -errno;
4808 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4809 		pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4810 			__func__, cp, -ret);
4811 		return ret;
4812 	}
4813 
4814 	prog = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4815 	if (prog < 0) {
4816 		close(map);
4817 		return 0;
4818 	}
4819 
4820 	ret = bpf_prog_bind_map(prog, map, NULL);
4821 
4822 	close(map);
4823 	close(prog);
4824 
4825 	return ret >= 0;
4826 }
4827 
4828 static int probe_module_btf(void)
4829 {
4830 	static const char strs[] = "\0int";
4831 	__u32 types[] = {
4832 		/* int */
4833 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4834 	};
4835 	struct bpf_btf_info info;
4836 	__u32 len = sizeof(info);
4837 	char name[16];
4838 	int fd, err;
4839 
4840 	fd = libbpf__load_raw_btf((char *)types, sizeof(types), strs, sizeof(strs));
4841 	if (fd < 0)
4842 		return 0; /* BTF not supported at all */
4843 
4844 	memset(&info, 0, sizeof(info));
4845 	info.name = ptr_to_u64(name);
4846 	info.name_len = sizeof(name);
4847 
4848 	/* check that BPF_OBJ_GET_INFO_BY_FD supports specifying name pointer;
4849 	 * kernel's module BTF support coincides with support for
4850 	 * name/name_len fields in struct bpf_btf_info.
4851 	 */
4852 	err = bpf_btf_get_info_by_fd(fd, &info, &len);
4853 	close(fd);
4854 	return !err;
4855 }
4856 
4857 static int probe_perf_link(void)
4858 {
4859 	struct bpf_insn insns[] = {
4860 		BPF_MOV64_IMM(BPF_REG_0, 0),
4861 		BPF_EXIT_INSN(),
4862 	};
4863 	int prog_fd, link_fd, err;
4864 
4865 	prog_fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL",
4866 				insns, ARRAY_SIZE(insns), NULL);
4867 	if (prog_fd < 0)
4868 		return -errno;
4869 
4870 	/* use invalid perf_event FD to get EBADF, if link is supported;
4871 	 * otherwise EINVAL should be returned
4872 	 */
4873 	link_fd = bpf_link_create(prog_fd, -1, BPF_PERF_EVENT, NULL);
4874 	err = -errno; /* close() can clobber errno */
4875 
4876 	if (link_fd >= 0)
4877 		close(link_fd);
4878 	close(prog_fd);
4879 
4880 	return link_fd < 0 && err == -EBADF;
4881 }
4882 
4883 static int probe_uprobe_multi_link(void)
4884 {
4885 	LIBBPF_OPTS(bpf_prog_load_opts, load_opts,
4886 		.expected_attach_type = BPF_TRACE_UPROBE_MULTI,
4887 	);
4888 	LIBBPF_OPTS(bpf_link_create_opts, link_opts);
4889 	struct bpf_insn insns[] = {
4890 		BPF_MOV64_IMM(BPF_REG_0, 0),
4891 		BPF_EXIT_INSN(),
4892 	};
4893 	int prog_fd, link_fd, err;
4894 	unsigned long offset = 0;
4895 
4896 	prog_fd = bpf_prog_load(BPF_PROG_TYPE_KPROBE, NULL, "GPL",
4897 				insns, ARRAY_SIZE(insns), &load_opts);
4898 	if (prog_fd < 0)
4899 		return -errno;
4900 
4901 	/* Creating uprobe in '/' binary should fail with -EBADF. */
4902 	link_opts.uprobe_multi.path = "/";
4903 	link_opts.uprobe_multi.offsets = &offset;
4904 	link_opts.uprobe_multi.cnt = 1;
4905 
4906 	link_fd = bpf_link_create(prog_fd, -1, BPF_TRACE_UPROBE_MULTI, &link_opts);
4907 	err = -errno; /* close() can clobber errno */
4908 
4909 	if (link_fd >= 0)
4910 		close(link_fd);
4911 	close(prog_fd);
4912 
4913 	return link_fd < 0 && err == -EBADF;
4914 }
4915 
4916 static int probe_kern_bpf_cookie(void)
4917 {
4918 	struct bpf_insn insns[] = {
4919 		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_get_attach_cookie),
4920 		BPF_EXIT_INSN(),
4921 	};
4922 	int ret, insn_cnt = ARRAY_SIZE(insns);
4923 
4924 	ret = bpf_prog_load(BPF_PROG_TYPE_KPROBE, NULL, "GPL", insns, insn_cnt, NULL);
4925 	return probe_fd(ret);
4926 }
4927 
4928 static int probe_kern_btf_enum64(void)
4929 {
4930 	static const char strs[] = "\0enum64";
4931 	__u32 types[] = {
4932 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_ENUM64, 0, 0), 8),
4933 	};
4934 
4935 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4936 					     strs, sizeof(strs)));
4937 }
4938 
4939 static int probe_kern_syscall_wrapper(void);
4940 
4941 enum kern_feature_result {
4942 	FEAT_UNKNOWN = 0,
4943 	FEAT_SUPPORTED = 1,
4944 	FEAT_MISSING = 2,
4945 };
4946 
4947 typedef int (*feature_probe_fn)(void);
4948 
4949 static struct kern_feature_desc {
4950 	const char *desc;
4951 	feature_probe_fn probe;
4952 	enum kern_feature_result res;
4953 } feature_probes[__FEAT_CNT] = {
4954 	[FEAT_PROG_NAME] = {
4955 		"BPF program name", probe_kern_prog_name,
4956 	},
4957 	[FEAT_GLOBAL_DATA] = {
4958 		"global variables", probe_kern_global_data,
4959 	},
4960 	[FEAT_BTF] = {
4961 		"minimal BTF", probe_kern_btf,
4962 	},
4963 	[FEAT_BTF_FUNC] = {
4964 		"BTF functions", probe_kern_btf_func,
4965 	},
4966 	[FEAT_BTF_GLOBAL_FUNC] = {
4967 		"BTF global function", probe_kern_btf_func_global,
4968 	},
4969 	[FEAT_BTF_DATASEC] = {
4970 		"BTF data section and variable", probe_kern_btf_datasec,
4971 	},
4972 	[FEAT_ARRAY_MMAP] = {
4973 		"ARRAY map mmap()", probe_kern_array_mmap,
4974 	},
4975 	[FEAT_EXP_ATTACH_TYPE] = {
4976 		"BPF_PROG_LOAD expected_attach_type attribute",
4977 		probe_kern_exp_attach_type,
4978 	},
4979 	[FEAT_PROBE_READ_KERN] = {
4980 		"bpf_probe_read_kernel() helper", probe_kern_probe_read_kernel,
4981 	},
4982 	[FEAT_PROG_BIND_MAP] = {
4983 		"BPF_PROG_BIND_MAP support", probe_prog_bind_map,
4984 	},
4985 	[FEAT_MODULE_BTF] = {
4986 		"module BTF support", probe_module_btf,
4987 	},
4988 	[FEAT_BTF_FLOAT] = {
4989 		"BTF_KIND_FLOAT support", probe_kern_btf_float,
4990 	},
4991 	[FEAT_PERF_LINK] = {
4992 		"BPF perf link support", probe_perf_link,
4993 	},
4994 	[FEAT_BTF_DECL_TAG] = {
4995 		"BTF_KIND_DECL_TAG support", probe_kern_btf_decl_tag,
4996 	},
4997 	[FEAT_BTF_TYPE_TAG] = {
4998 		"BTF_KIND_TYPE_TAG support", probe_kern_btf_type_tag,
4999 	},
5000 	[FEAT_MEMCG_ACCOUNT] = {
5001 		"memcg-based memory accounting", probe_memcg_account,
5002 	},
5003 	[FEAT_BPF_COOKIE] = {
5004 		"BPF cookie support", probe_kern_bpf_cookie,
5005 	},
5006 	[FEAT_BTF_ENUM64] = {
5007 		"BTF_KIND_ENUM64 support", probe_kern_btf_enum64,
5008 	},
5009 	[FEAT_SYSCALL_WRAPPER] = {
5010 		"Kernel using syscall wrapper", probe_kern_syscall_wrapper,
5011 	},
5012 	[FEAT_UPROBE_MULTI_LINK] = {
5013 		"BPF multi-uprobe link support", probe_uprobe_multi_link,
5014 	},
5015 };
5016 
5017 bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
5018 {
5019 	struct kern_feature_desc *feat = &feature_probes[feat_id];
5020 	int ret;
5021 
5022 	if (obj && obj->gen_loader)
5023 		/* To generate loader program assume the latest kernel
5024 		 * to avoid doing extra prog_load, map_create syscalls.
5025 		 */
5026 		return true;
5027 
5028 	if (READ_ONCE(feat->res) == FEAT_UNKNOWN) {
5029 		ret = feat->probe();
5030 		if (ret > 0) {
5031 			WRITE_ONCE(feat->res, FEAT_SUPPORTED);
5032 		} else if (ret == 0) {
5033 			WRITE_ONCE(feat->res, FEAT_MISSING);
5034 		} else {
5035 			pr_warn("Detection of kernel %s support failed: %d\n", feat->desc, ret);
5036 			WRITE_ONCE(feat->res, FEAT_MISSING);
5037 		}
5038 	}
5039 
5040 	return READ_ONCE(feat->res) == FEAT_SUPPORTED;
5041 }
5042 
5043 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
5044 {
5045 	struct bpf_map_info map_info;
5046 	char msg[STRERR_BUFSIZE];
5047 	__u32 map_info_len = sizeof(map_info);
5048 	int err;
5049 
5050 	memset(&map_info, 0, map_info_len);
5051 	err = bpf_map_get_info_by_fd(map_fd, &map_info, &map_info_len);
5052 	if (err && errno == EINVAL)
5053 		err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
5054 	if (err) {
5055 		pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
5056 			libbpf_strerror_r(errno, msg, sizeof(msg)));
5057 		return false;
5058 	}
5059 
5060 	return (map_info.type == map->def.type &&
5061 		map_info.key_size == map->def.key_size &&
5062 		map_info.value_size == map->def.value_size &&
5063 		map_info.max_entries == map->def.max_entries &&
5064 		map_info.map_flags == map->def.map_flags &&
5065 		map_info.map_extra == map->map_extra);
5066 }
5067 
5068 static int
5069 bpf_object__reuse_map(struct bpf_map *map)
5070 {
5071 	char *cp, errmsg[STRERR_BUFSIZE];
5072 	int err, pin_fd;
5073 
5074 	pin_fd = bpf_obj_get(map->pin_path);
5075 	if (pin_fd < 0) {
5076 		err = -errno;
5077 		if (err == -ENOENT) {
5078 			pr_debug("found no pinned map to reuse at '%s'\n",
5079 				 map->pin_path);
5080 			return 0;
5081 		}
5082 
5083 		cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
5084 		pr_warn("couldn't retrieve pinned map '%s': %s\n",
5085 			map->pin_path, cp);
5086 		return err;
5087 	}
5088 
5089 	if (!map_is_reuse_compat(map, pin_fd)) {
5090 		pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
5091 			map->pin_path);
5092 		close(pin_fd);
5093 		return -EINVAL;
5094 	}
5095 
5096 	err = bpf_map__reuse_fd(map, pin_fd);
5097 	close(pin_fd);
5098 	if (err)
5099 		return err;
5100 
5101 	map->pinned = true;
5102 	pr_debug("reused pinned map at '%s'\n", map->pin_path);
5103 
5104 	return 0;
5105 }
5106 
5107 static int
5108 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
5109 {
5110 	enum libbpf_map_type map_type = map->libbpf_type;
5111 	char *cp, errmsg[STRERR_BUFSIZE];
5112 	int err, zero = 0;
5113 
5114 	if (obj->gen_loader) {
5115 		bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
5116 					 map->mmaped, map->def.value_size);
5117 		if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
5118 			bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
5119 		return 0;
5120 	}
5121 	err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
5122 	if (err) {
5123 		err = -errno;
5124 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5125 		pr_warn("Error setting initial map(%s) contents: %s\n",
5126 			map->name, cp);
5127 		return err;
5128 	}
5129 
5130 	/* Freeze .rodata and .kconfig map as read-only from syscall side. */
5131 	if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
5132 		err = bpf_map_freeze(map->fd);
5133 		if (err) {
5134 			err = -errno;
5135 			cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5136 			pr_warn("Error freezing map(%s) as read-only: %s\n",
5137 				map->name, cp);
5138 			return err;
5139 		}
5140 	}
5141 	return 0;
5142 }
5143 
5144 static void bpf_map__destroy(struct bpf_map *map);
5145 
5146 static bool map_is_created(const struct bpf_map *map)
5147 {
5148 	return map->obj->loaded || map->reused;
5149 }
5150 
5151 static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
5152 {
5153 	LIBBPF_OPTS(bpf_map_create_opts, create_attr);
5154 	struct bpf_map_def *def = &map->def;
5155 	const char *map_name = NULL;
5156 	int err = 0, map_fd;
5157 
5158 	if (kernel_supports(obj, FEAT_PROG_NAME))
5159 		map_name = map->name;
5160 	create_attr.map_ifindex = map->map_ifindex;
5161 	create_attr.map_flags = def->map_flags;
5162 	create_attr.numa_node = map->numa_node;
5163 	create_attr.map_extra = map->map_extra;
5164 
5165 	if (bpf_map__is_struct_ops(map))
5166 		create_attr.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
5167 
5168 	if (obj->btf && btf__fd(obj->btf) >= 0) {
5169 		create_attr.btf_fd = btf__fd(obj->btf);
5170 		create_attr.btf_key_type_id = map->btf_key_type_id;
5171 		create_attr.btf_value_type_id = map->btf_value_type_id;
5172 	}
5173 
5174 	if (bpf_map_type__is_map_in_map(def->type)) {
5175 		if (map->inner_map) {
5176 			err = map_set_def_max_entries(map->inner_map);
5177 			if (err)
5178 				return err;
5179 			err = bpf_object__create_map(obj, map->inner_map, true);
5180 			if (err) {
5181 				pr_warn("map '%s': failed to create inner map: %d\n",
5182 					map->name, err);
5183 				return err;
5184 			}
5185 			map->inner_map_fd = map->inner_map->fd;
5186 		}
5187 		if (map->inner_map_fd >= 0)
5188 			create_attr.inner_map_fd = map->inner_map_fd;
5189 	}
5190 
5191 	switch (def->type) {
5192 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5193 	case BPF_MAP_TYPE_CGROUP_ARRAY:
5194 	case BPF_MAP_TYPE_STACK_TRACE:
5195 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5196 	case BPF_MAP_TYPE_HASH_OF_MAPS:
5197 	case BPF_MAP_TYPE_DEVMAP:
5198 	case BPF_MAP_TYPE_DEVMAP_HASH:
5199 	case BPF_MAP_TYPE_CPUMAP:
5200 	case BPF_MAP_TYPE_XSKMAP:
5201 	case BPF_MAP_TYPE_SOCKMAP:
5202 	case BPF_MAP_TYPE_SOCKHASH:
5203 	case BPF_MAP_TYPE_QUEUE:
5204 	case BPF_MAP_TYPE_STACK:
5205 		create_attr.btf_fd = 0;
5206 		create_attr.btf_key_type_id = 0;
5207 		create_attr.btf_value_type_id = 0;
5208 		map->btf_key_type_id = 0;
5209 		map->btf_value_type_id = 0;
5210 	default:
5211 		break;
5212 	}
5213 
5214 	if (obj->gen_loader) {
5215 		bpf_gen__map_create(obj->gen_loader, def->type, map_name,
5216 				    def->key_size, def->value_size, def->max_entries,
5217 				    &create_attr, is_inner ? -1 : map - obj->maps);
5218 		/* We keep pretenting we have valid FD to pass various fd >= 0
5219 		 * checks by just keeping original placeholder FDs in place.
5220 		 * See bpf_object__add_map() comment.
5221 		 * This placeholder fd will not be used with any syscall and
5222 		 * will be reset to -1 eventually.
5223 		 */
5224 		map_fd = map->fd;
5225 	} else {
5226 		map_fd = bpf_map_create(def->type, map_name,
5227 					def->key_size, def->value_size,
5228 					def->max_entries, &create_attr);
5229 	}
5230 	if (map_fd < 0 && (create_attr.btf_key_type_id || create_attr.btf_value_type_id)) {
5231 		char *cp, errmsg[STRERR_BUFSIZE];
5232 
5233 		err = -errno;
5234 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5235 		pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
5236 			map->name, cp, err);
5237 		create_attr.btf_fd = 0;
5238 		create_attr.btf_key_type_id = 0;
5239 		create_attr.btf_value_type_id = 0;
5240 		map->btf_key_type_id = 0;
5241 		map->btf_value_type_id = 0;
5242 		map_fd = bpf_map_create(def->type, map_name,
5243 					def->key_size, def->value_size,
5244 					def->max_entries, &create_attr);
5245 	}
5246 
5247 	if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
5248 		if (obj->gen_loader)
5249 			map->inner_map->fd = -1;
5250 		bpf_map__destroy(map->inner_map);
5251 		zfree(&map->inner_map);
5252 	}
5253 
5254 	if (map_fd < 0)
5255 		return map_fd;
5256 
5257 	/* obj->gen_loader case, prevent reuse_fd() from closing map_fd */
5258 	if (map->fd == map_fd)
5259 		return 0;
5260 
5261 	/* Keep placeholder FD value but now point it to the BPF map object.
5262 	 * This way everything that relied on this map's FD (e.g., relocated
5263 	 * ldimm64 instructions) will stay valid and won't need adjustments.
5264 	 * map->fd stays valid but now point to what map_fd points to.
5265 	 */
5266 	return reuse_fd(map->fd, map_fd);
5267 }
5268 
5269 static int init_map_in_map_slots(struct bpf_object *obj, struct bpf_map *map)
5270 {
5271 	const struct bpf_map *targ_map;
5272 	unsigned int i;
5273 	int fd, err = 0;
5274 
5275 	for (i = 0; i < map->init_slots_sz; i++) {
5276 		if (!map->init_slots[i])
5277 			continue;
5278 
5279 		targ_map = map->init_slots[i];
5280 		fd = targ_map->fd;
5281 
5282 		if (obj->gen_loader) {
5283 			bpf_gen__populate_outer_map(obj->gen_loader,
5284 						    map - obj->maps, i,
5285 						    targ_map - obj->maps);
5286 		} else {
5287 			err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5288 		}
5289 		if (err) {
5290 			err = -errno;
5291 			pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %d\n",
5292 				map->name, i, targ_map->name, fd, err);
5293 			return err;
5294 		}
5295 		pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
5296 			 map->name, i, targ_map->name, fd);
5297 	}
5298 
5299 	zfree(&map->init_slots);
5300 	map->init_slots_sz = 0;
5301 
5302 	return 0;
5303 }
5304 
5305 static int init_prog_array_slots(struct bpf_object *obj, struct bpf_map *map)
5306 {
5307 	const struct bpf_program *targ_prog;
5308 	unsigned int i;
5309 	int fd, err;
5310 
5311 	if (obj->gen_loader)
5312 		return -ENOTSUP;
5313 
5314 	for (i = 0; i < map->init_slots_sz; i++) {
5315 		if (!map->init_slots[i])
5316 			continue;
5317 
5318 		targ_prog = map->init_slots[i];
5319 		fd = bpf_program__fd(targ_prog);
5320 
5321 		err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5322 		if (err) {
5323 			err = -errno;
5324 			pr_warn("map '%s': failed to initialize slot [%d] to prog '%s' fd=%d: %d\n",
5325 				map->name, i, targ_prog->name, fd, err);
5326 			return err;
5327 		}
5328 		pr_debug("map '%s': slot [%d] set to prog '%s' fd=%d\n",
5329 			 map->name, i, targ_prog->name, fd);
5330 	}
5331 
5332 	zfree(&map->init_slots);
5333 	map->init_slots_sz = 0;
5334 
5335 	return 0;
5336 }
5337 
5338 static int bpf_object_init_prog_arrays(struct bpf_object *obj)
5339 {
5340 	struct bpf_map *map;
5341 	int i, err;
5342 
5343 	for (i = 0; i < obj->nr_maps; i++) {
5344 		map = &obj->maps[i];
5345 
5346 		if (!map->init_slots_sz || map->def.type != BPF_MAP_TYPE_PROG_ARRAY)
5347 			continue;
5348 
5349 		err = init_prog_array_slots(obj, map);
5350 		if (err < 0)
5351 			return err;
5352 	}
5353 	return 0;
5354 }
5355 
5356 static int map_set_def_max_entries(struct bpf_map *map)
5357 {
5358 	if (map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !map->def.max_entries) {
5359 		int nr_cpus;
5360 
5361 		nr_cpus = libbpf_num_possible_cpus();
5362 		if (nr_cpus < 0) {
5363 			pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
5364 				map->name, nr_cpus);
5365 			return nr_cpus;
5366 		}
5367 		pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
5368 		map->def.max_entries = nr_cpus;
5369 	}
5370 
5371 	return 0;
5372 }
5373 
5374 static int
5375 bpf_object__create_maps(struct bpf_object *obj)
5376 {
5377 	struct bpf_map *map;
5378 	char *cp, errmsg[STRERR_BUFSIZE];
5379 	unsigned int i, j;
5380 	int err;
5381 	bool retried;
5382 
5383 	for (i = 0; i < obj->nr_maps; i++) {
5384 		map = &obj->maps[i];
5385 
5386 		/* To support old kernels, we skip creating global data maps
5387 		 * (.rodata, .data, .kconfig, etc); later on, during program
5388 		 * loading, if we detect that at least one of the to-be-loaded
5389 		 * programs is referencing any global data map, we'll error
5390 		 * out with program name and relocation index logged.
5391 		 * This approach allows to accommodate Clang emitting
5392 		 * unnecessary .rodata.str1.1 sections for string literals,
5393 		 * but also it allows to have CO-RE applications that use
5394 		 * global variables in some of BPF programs, but not others.
5395 		 * If those global variable-using programs are not loaded at
5396 		 * runtime due to bpf_program__set_autoload(prog, false),
5397 		 * bpf_object loading will succeed just fine even on old
5398 		 * kernels.
5399 		 */
5400 		if (bpf_map__is_internal(map) && !kernel_supports(obj, FEAT_GLOBAL_DATA))
5401 			map->autocreate = false;
5402 
5403 		if (!map->autocreate) {
5404 			pr_debug("map '%s': skipped auto-creating...\n", map->name);
5405 			continue;
5406 		}
5407 
5408 		err = map_set_def_max_entries(map);
5409 		if (err)
5410 			goto err_out;
5411 
5412 		retried = false;
5413 retry:
5414 		if (map->pin_path) {
5415 			err = bpf_object__reuse_map(map);
5416 			if (err) {
5417 				pr_warn("map '%s': error reusing pinned map\n",
5418 					map->name);
5419 				goto err_out;
5420 			}
5421 			if (retried && map->fd < 0) {
5422 				pr_warn("map '%s': cannot find pinned map\n",
5423 					map->name);
5424 				err = -ENOENT;
5425 				goto err_out;
5426 			}
5427 		}
5428 
5429 		if (map->reused) {
5430 			pr_debug("map '%s': skipping creation (preset fd=%d)\n",
5431 				 map->name, map->fd);
5432 		} else {
5433 			err = bpf_object__create_map(obj, map, false);
5434 			if (err)
5435 				goto err_out;
5436 
5437 			pr_debug("map '%s': created successfully, fd=%d\n",
5438 				 map->name, map->fd);
5439 
5440 			if (bpf_map__is_internal(map)) {
5441 				err = bpf_object__populate_internal_map(obj, map);
5442 				if (err < 0)
5443 					goto err_out;
5444 			}
5445 
5446 			if (map->init_slots_sz && map->def.type != BPF_MAP_TYPE_PROG_ARRAY) {
5447 				err = init_map_in_map_slots(obj, map);
5448 				if (err < 0)
5449 					goto err_out;
5450 			}
5451 		}
5452 
5453 		if (map->pin_path && !map->pinned) {
5454 			err = bpf_map__pin(map, NULL);
5455 			if (err) {
5456 				if (!retried && err == -EEXIST) {
5457 					retried = true;
5458 					goto retry;
5459 				}
5460 				pr_warn("map '%s': failed to auto-pin at '%s': %d\n",
5461 					map->name, map->pin_path, err);
5462 				goto err_out;
5463 			}
5464 		}
5465 	}
5466 
5467 	return 0;
5468 
5469 err_out:
5470 	cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5471 	pr_warn("map '%s': failed to create: %s(%d)\n", map->name, cp, err);
5472 	pr_perm_msg(err);
5473 	for (j = 0; j < i; j++)
5474 		zclose(obj->maps[j].fd);
5475 	return err;
5476 }
5477 
5478 static bool bpf_core_is_flavor_sep(const char *s)
5479 {
5480 	/* check X___Y name pattern, where X and Y are not underscores */
5481 	return s[0] != '_' &&				      /* X */
5482 	       s[1] == '_' && s[2] == '_' && s[3] == '_' &&   /* ___ */
5483 	       s[4] != '_';				      /* Y */
5484 }
5485 
5486 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
5487  * before last triple underscore. Struct name part after last triple
5488  * underscore is ignored by BPF CO-RE relocation during relocation matching.
5489  */
5490 size_t bpf_core_essential_name_len(const char *name)
5491 {
5492 	size_t n = strlen(name);
5493 	int i;
5494 
5495 	for (i = n - 5; i >= 0; i--) {
5496 		if (bpf_core_is_flavor_sep(name + i))
5497 			return i + 1;
5498 	}
5499 	return n;
5500 }
5501 
5502 void bpf_core_free_cands(struct bpf_core_cand_list *cands)
5503 {
5504 	if (!cands)
5505 		return;
5506 
5507 	free(cands->cands);
5508 	free(cands);
5509 }
5510 
5511 int bpf_core_add_cands(struct bpf_core_cand *local_cand,
5512 		       size_t local_essent_len,
5513 		       const struct btf *targ_btf,
5514 		       const char *targ_btf_name,
5515 		       int targ_start_id,
5516 		       struct bpf_core_cand_list *cands)
5517 {
5518 	struct bpf_core_cand *new_cands, *cand;
5519 	const struct btf_type *t, *local_t;
5520 	const char *targ_name, *local_name;
5521 	size_t targ_essent_len;
5522 	int n, i;
5523 
5524 	local_t = btf__type_by_id(local_cand->btf, local_cand->id);
5525 	local_name = btf__str_by_offset(local_cand->btf, local_t->name_off);
5526 
5527 	n = btf__type_cnt(targ_btf);
5528 	for (i = targ_start_id; i < n; i++) {
5529 		t = btf__type_by_id(targ_btf, i);
5530 		if (!btf_kind_core_compat(t, local_t))
5531 			continue;
5532 
5533 		targ_name = btf__name_by_offset(targ_btf, t->name_off);
5534 		if (str_is_empty(targ_name))
5535 			continue;
5536 
5537 		targ_essent_len = bpf_core_essential_name_len(targ_name);
5538 		if (targ_essent_len != local_essent_len)
5539 			continue;
5540 
5541 		if (strncmp(local_name, targ_name, local_essent_len) != 0)
5542 			continue;
5543 
5544 		pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s in [%s]\n",
5545 			 local_cand->id, btf_kind_str(local_t),
5546 			 local_name, i, btf_kind_str(t), targ_name,
5547 			 targ_btf_name);
5548 		new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
5549 					      sizeof(*cands->cands));
5550 		if (!new_cands)
5551 			return -ENOMEM;
5552 
5553 		cand = &new_cands[cands->len];
5554 		cand->btf = targ_btf;
5555 		cand->id = i;
5556 
5557 		cands->cands = new_cands;
5558 		cands->len++;
5559 	}
5560 	return 0;
5561 }
5562 
5563 static int load_module_btfs(struct bpf_object *obj)
5564 {
5565 	struct bpf_btf_info info;
5566 	struct module_btf *mod_btf;
5567 	struct btf *btf;
5568 	char name[64];
5569 	__u32 id = 0, len;
5570 	int err, fd;
5571 
5572 	if (obj->btf_modules_loaded)
5573 		return 0;
5574 
5575 	if (obj->gen_loader)
5576 		return 0;
5577 
5578 	/* don't do this again, even if we find no module BTFs */
5579 	obj->btf_modules_loaded = true;
5580 
5581 	/* kernel too old to support module BTFs */
5582 	if (!kernel_supports(obj, FEAT_MODULE_BTF))
5583 		return 0;
5584 
5585 	while (true) {
5586 		err = bpf_btf_get_next_id(id, &id);
5587 		if (err && errno == ENOENT)
5588 			return 0;
5589 		if (err && errno == EPERM) {
5590 			pr_debug("skipping module BTFs loading, missing privileges\n");
5591 			return 0;
5592 		}
5593 		if (err) {
5594 			err = -errno;
5595 			pr_warn("failed to iterate BTF objects: %d\n", err);
5596 			return err;
5597 		}
5598 
5599 		fd = bpf_btf_get_fd_by_id(id);
5600 		if (fd < 0) {
5601 			if (errno == ENOENT)
5602 				continue; /* expected race: BTF was unloaded */
5603 			err = -errno;
5604 			pr_warn("failed to get BTF object #%d FD: %d\n", id, err);
5605 			return err;
5606 		}
5607 
5608 		len = sizeof(info);
5609 		memset(&info, 0, sizeof(info));
5610 		info.name = ptr_to_u64(name);
5611 		info.name_len = sizeof(name);
5612 
5613 		err = bpf_btf_get_info_by_fd(fd, &info, &len);
5614 		if (err) {
5615 			err = -errno;
5616 			pr_warn("failed to get BTF object #%d info: %d\n", id, err);
5617 			goto err_out;
5618 		}
5619 
5620 		/* ignore non-module BTFs */
5621 		if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
5622 			close(fd);
5623 			continue;
5624 		}
5625 
5626 		btf = btf_get_from_fd(fd, obj->btf_vmlinux);
5627 		err = libbpf_get_error(btf);
5628 		if (err) {
5629 			pr_warn("failed to load module [%s]'s BTF object #%d: %d\n",
5630 				name, id, err);
5631 			goto err_out;
5632 		}
5633 
5634 		err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
5635 					sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
5636 		if (err)
5637 			goto err_out;
5638 
5639 		mod_btf = &obj->btf_modules[obj->btf_module_cnt++];
5640 
5641 		mod_btf->btf = btf;
5642 		mod_btf->id = id;
5643 		mod_btf->fd = fd;
5644 		mod_btf->name = strdup(name);
5645 		if (!mod_btf->name) {
5646 			err = -ENOMEM;
5647 			goto err_out;
5648 		}
5649 		continue;
5650 
5651 err_out:
5652 		close(fd);
5653 		return err;
5654 	}
5655 
5656 	return 0;
5657 }
5658 
5659 static struct bpf_core_cand_list *
5660 bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
5661 {
5662 	struct bpf_core_cand local_cand = {};
5663 	struct bpf_core_cand_list *cands;
5664 	const struct btf *main_btf;
5665 	const struct btf_type *local_t;
5666 	const char *local_name;
5667 	size_t local_essent_len;
5668 	int err, i;
5669 
5670 	local_cand.btf = local_btf;
5671 	local_cand.id = local_type_id;
5672 	local_t = btf__type_by_id(local_btf, local_type_id);
5673 	if (!local_t)
5674 		return ERR_PTR(-EINVAL);
5675 
5676 	local_name = btf__name_by_offset(local_btf, local_t->name_off);
5677 	if (str_is_empty(local_name))
5678 		return ERR_PTR(-EINVAL);
5679 	local_essent_len = bpf_core_essential_name_len(local_name);
5680 
5681 	cands = calloc(1, sizeof(*cands));
5682 	if (!cands)
5683 		return ERR_PTR(-ENOMEM);
5684 
5685 	/* Attempt to find target candidates in vmlinux BTF first */
5686 	main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
5687 	err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
5688 	if (err)
5689 		goto err_out;
5690 
5691 	/* if vmlinux BTF has any candidate, don't got for module BTFs */
5692 	if (cands->len)
5693 		return cands;
5694 
5695 	/* if vmlinux BTF was overridden, don't attempt to load module BTFs */
5696 	if (obj->btf_vmlinux_override)
5697 		return cands;
5698 
5699 	/* now look through module BTFs, trying to still find candidates */
5700 	err = load_module_btfs(obj);
5701 	if (err)
5702 		goto err_out;
5703 
5704 	for (i = 0; i < obj->btf_module_cnt; i++) {
5705 		err = bpf_core_add_cands(&local_cand, local_essent_len,
5706 					 obj->btf_modules[i].btf,
5707 					 obj->btf_modules[i].name,
5708 					 btf__type_cnt(obj->btf_vmlinux),
5709 					 cands);
5710 		if (err)
5711 			goto err_out;
5712 	}
5713 
5714 	return cands;
5715 err_out:
5716 	bpf_core_free_cands(cands);
5717 	return ERR_PTR(err);
5718 }
5719 
5720 /* Check local and target types for compatibility. This check is used for
5721  * type-based CO-RE relocations and follow slightly different rules than
5722  * field-based relocations. This function assumes that root types were already
5723  * checked for name match. Beyond that initial root-level name check, names
5724  * are completely ignored. Compatibility rules are as follows:
5725  *   - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
5726  *     kind should match for local and target types (i.e., STRUCT is not
5727  *     compatible with UNION);
5728  *   - for ENUMs, the size is ignored;
5729  *   - for INT, size and signedness are ignored;
5730  *   - for ARRAY, dimensionality is ignored, element types are checked for
5731  *     compatibility recursively;
5732  *   - CONST/VOLATILE/RESTRICT modifiers are ignored;
5733  *   - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
5734  *   - FUNC_PROTOs are compatible if they have compatible signature: same
5735  *     number of input args and compatible return and argument types.
5736  * These rules are not set in stone and probably will be adjusted as we get
5737  * more experience with using BPF CO-RE relocations.
5738  */
5739 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
5740 			      const struct btf *targ_btf, __u32 targ_id)
5741 {
5742 	return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id, 32);
5743 }
5744 
5745 int bpf_core_types_match(const struct btf *local_btf, __u32 local_id,
5746 			 const struct btf *targ_btf, __u32 targ_id)
5747 {
5748 	return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false, 32);
5749 }
5750 
5751 static size_t bpf_core_hash_fn(const long key, void *ctx)
5752 {
5753 	return key;
5754 }
5755 
5756 static bool bpf_core_equal_fn(const long k1, const long k2, void *ctx)
5757 {
5758 	return k1 == k2;
5759 }
5760 
5761 static int record_relo_core(struct bpf_program *prog,
5762 			    const struct bpf_core_relo *core_relo, int insn_idx)
5763 {
5764 	struct reloc_desc *relos, *relo;
5765 
5766 	relos = libbpf_reallocarray(prog->reloc_desc,
5767 				    prog->nr_reloc + 1, sizeof(*relos));
5768 	if (!relos)
5769 		return -ENOMEM;
5770 	relo = &relos[prog->nr_reloc];
5771 	relo->type = RELO_CORE;
5772 	relo->insn_idx = insn_idx;
5773 	relo->core_relo = core_relo;
5774 	prog->reloc_desc = relos;
5775 	prog->nr_reloc++;
5776 	return 0;
5777 }
5778 
5779 static const struct bpf_core_relo *find_relo_core(struct bpf_program *prog, int insn_idx)
5780 {
5781 	struct reloc_desc *relo;
5782 	int i;
5783 
5784 	for (i = 0; i < prog->nr_reloc; i++) {
5785 		relo = &prog->reloc_desc[i];
5786 		if (relo->type != RELO_CORE || relo->insn_idx != insn_idx)
5787 			continue;
5788 
5789 		return relo->core_relo;
5790 	}
5791 
5792 	return NULL;
5793 }
5794 
5795 static int bpf_core_resolve_relo(struct bpf_program *prog,
5796 				 const struct bpf_core_relo *relo,
5797 				 int relo_idx,
5798 				 const struct btf *local_btf,
5799 				 struct hashmap *cand_cache,
5800 				 struct bpf_core_relo_res *targ_res)
5801 {
5802 	struct bpf_core_spec specs_scratch[3] = {};
5803 	struct bpf_core_cand_list *cands = NULL;
5804 	const char *prog_name = prog->name;
5805 	const struct btf_type *local_type;
5806 	const char *local_name;
5807 	__u32 local_id = relo->type_id;
5808 	int err;
5809 
5810 	local_type = btf__type_by_id(local_btf, local_id);
5811 	if (!local_type)
5812 		return -EINVAL;
5813 
5814 	local_name = btf__name_by_offset(local_btf, local_type->name_off);
5815 	if (!local_name)
5816 		return -EINVAL;
5817 
5818 	if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
5819 	    !hashmap__find(cand_cache, local_id, &cands)) {
5820 		cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
5821 		if (IS_ERR(cands)) {
5822 			pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n",
5823 				prog_name, relo_idx, local_id, btf_kind_str(local_type),
5824 				local_name, PTR_ERR(cands));
5825 			return PTR_ERR(cands);
5826 		}
5827 		err = hashmap__set(cand_cache, local_id, cands, NULL, NULL);
5828 		if (err) {
5829 			bpf_core_free_cands(cands);
5830 			return err;
5831 		}
5832 	}
5833 
5834 	return bpf_core_calc_relo_insn(prog_name, relo, relo_idx, local_btf, cands, specs_scratch,
5835 				       targ_res);
5836 }
5837 
5838 static int
5839 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
5840 {
5841 	const struct btf_ext_info_sec *sec;
5842 	struct bpf_core_relo_res targ_res;
5843 	const struct bpf_core_relo *rec;
5844 	const struct btf_ext_info *seg;
5845 	struct hashmap_entry *entry;
5846 	struct hashmap *cand_cache = NULL;
5847 	struct bpf_program *prog;
5848 	struct bpf_insn *insn;
5849 	const char *sec_name;
5850 	int i, err = 0, insn_idx, sec_idx, sec_num;
5851 
5852 	if (obj->btf_ext->core_relo_info.len == 0)
5853 		return 0;
5854 
5855 	if (targ_btf_path) {
5856 		obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
5857 		err = libbpf_get_error(obj->btf_vmlinux_override);
5858 		if (err) {
5859 			pr_warn("failed to parse target BTF: %d\n", err);
5860 			return err;
5861 		}
5862 	}
5863 
5864 	cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
5865 	if (IS_ERR(cand_cache)) {
5866 		err = PTR_ERR(cand_cache);
5867 		goto out;
5868 	}
5869 
5870 	seg = &obj->btf_ext->core_relo_info;
5871 	sec_num = 0;
5872 	for_each_btf_ext_sec(seg, sec) {
5873 		sec_idx = seg->sec_idxs[sec_num];
5874 		sec_num++;
5875 
5876 		sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
5877 		if (str_is_empty(sec_name)) {
5878 			err = -EINVAL;
5879 			goto out;
5880 		}
5881 
5882 		pr_debug("sec '%s': found %d CO-RE relocations\n", sec_name, sec->num_info);
5883 
5884 		for_each_btf_ext_rec(seg, sec, i, rec) {
5885 			if (rec->insn_off % BPF_INSN_SZ)
5886 				return -EINVAL;
5887 			insn_idx = rec->insn_off / BPF_INSN_SZ;
5888 			prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
5889 			if (!prog) {
5890 				/* When __weak subprog is "overridden" by another instance
5891 				 * of the subprog from a different object file, linker still
5892 				 * appends all the .BTF.ext info that used to belong to that
5893 				 * eliminated subprogram.
5894 				 * This is similar to what x86-64 linker does for relocations.
5895 				 * So just ignore such relocations just like we ignore
5896 				 * subprog instructions when discovering subprograms.
5897 				 */
5898 				pr_debug("sec '%s': skipping CO-RE relocation #%d for insn #%d belonging to eliminated weak subprogram\n",
5899 					 sec_name, i, insn_idx);
5900 				continue;
5901 			}
5902 			/* no need to apply CO-RE relocation if the program is
5903 			 * not going to be loaded
5904 			 */
5905 			if (!prog->autoload)
5906 				continue;
5907 
5908 			/* adjust insn_idx from section frame of reference to the local
5909 			 * program's frame of reference; (sub-)program code is not yet
5910 			 * relocated, so it's enough to just subtract in-section offset
5911 			 */
5912 			insn_idx = insn_idx - prog->sec_insn_off;
5913 			if (insn_idx >= prog->insns_cnt)
5914 				return -EINVAL;
5915 			insn = &prog->insns[insn_idx];
5916 
5917 			err = record_relo_core(prog, rec, insn_idx);
5918 			if (err) {
5919 				pr_warn("prog '%s': relo #%d: failed to record relocation: %d\n",
5920 					prog->name, i, err);
5921 				goto out;
5922 			}
5923 
5924 			if (prog->obj->gen_loader)
5925 				continue;
5926 
5927 			err = bpf_core_resolve_relo(prog, rec, i, obj->btf, cand_cache, &targ_res);
5928 			if (err) {
5929 				pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
5930 					prog->name, i, err);
5931 				goto out;
5932 			}
5933 
5934 			err = bpf_core_patch_insn(prog->name, insn, insn_idx, rec, i, &targ_res);
5935 			if (err) {
5936 				pr_warn("prog '%s': relo #%d: failed to patch insn #%u: %d\n",
5937 					prog->name, i, insn_idx, err);
5938 				goto out;
5939 			}
5940 		}
5941 	}
5942 
5943 out:
5944 	/* obj->btf_vmlinux and module BTFs are freed after object load */
5945 	btf__free(obj->btf_vmlinux_override);
5946 	obj->btf_vmlinux_override = NULL;
5947 
5948 	if (!IS_ERR_OR_NULL(cand_cache)) {
5949 		hashmap__for_each_entry(cand_cache, entry, i) {
5950 			bpf_core_free_cands(entry->pvalue);
5951 		}
5952 		hashmap__free(cand_cache);
5953 	}
5954 	return err;
5955 }
5956 
5957 /* base map load ldimm64 special constant, used also for log fixup logic */
5958 #define POISON_LDIMM64_MAP_BASE 2001000000
5959 #define POISON_LDIMM64_MAP_PFX "200100"
5960 
5961 static void poison_map_ldimm64(struct bpf_program *prog, int relo_idx,
5962 			       int insn_idx, struct bpf_insn *insn,
5963 			       int map_idx, const struct bpf_map *map)
5964 {
5965 	int i;
5966 
5967 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that loads map #%d '%s'\n",
5968 		 prog->name, relo_idx, insn_idx, map_idx, map->name);
5969 
5970 	/* we turn single ldimm64 into two identical invalid calls */
5971 	for (i = 0; i < 2; i++) {
5972 		insn->code = BPF_JMP | BPF_CALL;
5973 		insn->dst_reg = 0;
5974 		insn->src_reg = 0;
5975 		insn->off = 0;
5976 		/* if this instruction is reachable (not a dead code),
5977 		 * verifier will complain with something like:
5978 		 * invalid func unknown#2001000123
5979 		 * where lower 123 is map index into obj->maps[] array
5980 		 */
5981 		insn->imm = POISON_LDIMM64_MAP_BASE + map_idx;
5982 
5983 		insn++;
5984 	}
5985 }
5986 
5987 /* unresolved kfunc call special constant, used also for log fixup logic */
5988 #define POISON_CALL_KFUNC_BASE 2002000000
5989 #define POISON_CALL_KFUNC_PFX "2002"
5990 
5991 static void poison_kfunc_call(struct bpf_program *prog, int relo_idx,
5992 			      int insn_idx, struct bpf_insn *insn,
5993 			      int ext_idx, const struct extern_desc *ext)
5994 {
5995 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that calls kfunc '%s'\n",
5996 		 prog->name, relo_idx, insn_idx, ext->name);
5997 
5998 	/* we turn kfunc call into invalid helper call with identifiable constant */
5999 	insn->code = BPF_JMP | BPF_CALL;
6000 	insn->dst_reg = 0;
6001 	insn->src_reg = 0;
6002 	insn->off = 0;
6003 	/* if this instruction is reachable (not a dead code),
6004 	 * verifier will complain with something like:
6005 	 * invalid func unknown#2001000123
6006 	 * where lower 123 is extern index into obj->externs[] array
6007 	 */
6008 	insn->imm = POISON_CALL_KFUNC_BASE + ext_idx;
6009 }
6010 
6011 /* Relocate data references within program code:
6012  *  - map references;
6013  *  - global variable references;
6014  *  - extern references.
6015  */
6016 static int
6017 bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
6018 {
6019 	int i;
6020 
6021 	for (i = 0; i < prog->nr_reloc; i++) {
6022 		struct reloc_desc *relo = &prog->reloc_desc[i];
6023 		struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6024 		const struct bpf_map *map;
6025 		struct extern_desc *ext;
6026 
6027 		switch (relo->type) {
6028 		case RELO_LD64:
6029 			map = &obj->maps[relo->map_idx];
6030 			if (obj->gen_loader) {
6031 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
6032 				insn[0].imm = relo->map_idx;
6033 			} else if (map->autocreate) {
6034 				insn[0].src_reg = BPF_PSEUDO_MAP_FD;
6035 				insn[0].imm = map->fd;
6036 			} else {
6037 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6038 						   relo->map_idx, map);
6039 			}
6040 			break;
6041 		case RELO_DATA:
6042 			map = &obj->maps[relo->map_idx];
6043 			insn[1].imm = insn[0].imm + relo->sym_off;
6044 			if (obj->gen_loader) {
6045 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6046 				insn[0].imm = relo->map_idx;
6047 			} else if (map->autocreate) {
6048 				insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6049 				insn[0].imm = map->fd;
6050 			} else {
6051 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6052 						   relo->map_idx, map);
6053 			}
6054 			break;
6055 		case RELO_EXTERN_LD64:
6056 			ext = &obj->externs[relo->ext_idx];
6057 			if (ext->type == EXT_KCFG) {
6058 				if (obj->gen_loader) {
6059 					insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6060 					insn[0].imm = obj->kconfig_map_idx;
6061 				} else {
6062 					insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6063 					insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
6064 				}
6065 				insn[1].imm = ext->kcfg.data_off;
6066 			} else /* EXT_KSYM */ {
6067 				if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
6068 					insn[0].src_reg = BPF_PSEUDO_BTF_ID;
6069 					insn[0].imm = ext->ksym.kernel_btf_id;
6070 					insn[1].imm = ext->ksym.kernel_btf_obj_fd;
6071 				} else { /* typeless ksyms or unresolved typed ksyms */
6072 					insn[0].imm = (__u32)ext->ksym.addr;
6073 					insn[1].imm = ext->ksym.addr >> 32;
6074 				}
6075 			}
6076 			break;
6077 		case RELO_EXTERN_CALL:
6078 			ext = &obj->externs[relo->ext_idx];
6079 			insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
6080 			if (ext->is_set) {
6081 				insn[0].imm = ext->ksym.kernel_btf_id;
6082 				insn[0].off = ext->ksym.btf_fd_idx;
6083 			} else { /* unresolved weak kfunc call */
6084 				poison_kfunc_call(prog, i, relo->insn_idx, insn,
6085 						  relo->ext_idx, ext);
6086 			}
6087 			break;
6088 		case RELO_SUBPROG_ADDR:
6089 			if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
6090 				pr_warn("prog '%s': relo #%d: bad insn\n",
6091 					prog->name, i);
6092 				return -EINVAL;
6093 			}
6094 			/* handled already */
6095 			break;
6096 		case RELO_CALL:
6097 			/* handled already */
6098 			break;
6099 		case RELO_CORE:
6100 			/* will be handled by bpf_program_record_relos() */
6101 			break;
6102 		default:
6103 			pr_warn("prog '%s': relo #%d: bad relo type %d\n",
6104 				prog->name, i, relo->type);
6105 			return -EINVAL;
6106 		}
6107 	}
6108 
6109 	return 0;
6110 }
6111 
6112 static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
6113 				    const struct bpf_program *prog,
6114 				    const struct btf_ext_info *ext_info,
6115 				    void **prog_info, __u32 *prog_rec_cnt,
6116 				    __u32 *prog_rec_sz)
6117 {
6118 	void *copy_start = NULL, *copy_end = NULL;
6119 	void *rec, *rec_end, *new_prog_info;
6120 	const struct btf_ext_info_sec *sec;
6121 	size_t old_sz, new_sz;
6122 	int i, sec_num, sec_idx, off_adj;
6123 
6124 	sec_num = 0;
6125 	for_each_btf_ext_sec(ext_info, sec) {
6126 		sec_idx = ext_info->sec_idxs[sec_num];
6127 		sec_num++;
6128 		if (prog->sec_idx != sec_idx)
6129 			continue;
6130 
6131 		for_each_btf_ext_rec(ext_info, sec, i, rec) {
6132 			__u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
6133 
6134 			if (insn_off < prog->sec_insn_off)
6135 				continue;
6136 			if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
6137 				break;
6138 
6139 			if (!copy_start)
6140 				copy_start = rec;
6141 			copy_end = rec + ext_info->rec_size;
6142 		}
6143 
6144 		if (!copy_start)
6145 			return -ENOENT;
6146 
6147 		/* append func/line info of a given (sub-)program to the main
6148 		 * program func/line info
6149 		 */
6150 		old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
6151 		new_sz = old_sz + (copy_end - copy_start);
6152 		new_prog_info = realloc(*prog_info, new_sz);
6153 		if (!new_prog_info)
6154 			return -ENOMEM;
6155 		*prog_info = new_prog_info;
6156 		*prog_rec_cnt = new_sz / ext_info->rec_size;
6157 		memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
6158 
6159 		/* Kernel instruction offsets are in units of 8-byte
6160 		 * instructions, while .BTF.ext instruction offsets generated
6161 		 * by Clang are in units of bytes. So convert Clang offsets
6162 		 * into kernel offsets and adjust offset according to program
6163 		 * relocated position.
6164 		 */
6165 		off_adj = prog->sub_insn_off - prog->sec_insn_off;
6166 		rec = new_prog_info + old_sz;
6167 		rec_end = new_prog_info + new_sz;
6168 		for (; rec < rec_end; rec += ext_info->rec_size) {
6169 			__u32 *insn_off = rec;
6170 
6171 			*insn_off = *insn_off / BPF_INSN_SZ + off_adj;
6172 		}
6173 		*prog_rec_sz = ext_info->rec_size;
6174 		return 0;
6175 	}
6176 
6177 	return -ENOENT;
6178 }
6179 
6180 static int
6181 reloc_prog_func_and_line_info(const struct bpf_object *obj,
6182 			      struct bpf_program *main_prog,
6183 			      const struct bpf_program *prog)
6184 {
6185 	int err;
6186 
6187 	/* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
6188 	 * support func/line info
6189 	 */
6190 	if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
6191 		return 0;
6192 
6193 	/* only attempt func info relocation if main program's func_info
6194 	 * relocation was successful
6195 	 */
6196 	if (main_prog != prog && !main_prog->func_info)
6197 		goto line_info;
6198 
6199 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
6200 				       &main_prog->func_info,
6201 				       &main_prog->func_info_cnt,
6202 				       &main_prog->func_info_rec_size);
6203 	if (err) {
6204 		if (err != -ENOENT) {
6205 			pr_warn("prog '%s': error relocating .BTF.ext function info: %d\n",
6206 				prog->name, err);
6207 			return err;
6208 		}
6209 		if (main_prog->func_info) {
6210 			/*
6211 			 * Some info has already been found but has problem
6212 			 * in the last btf_ext reloc. Must have to error out.
6213 			 */
6214 			pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
6215 			return err;
6216 		}
6217 		/* Have problem loading the very first info. Ignore the rest. */
6218 		pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
6219 			prog->name);
6220 	}
6221 
6222 line_info:
6223 	/* don't relocate line info if main program's relocation failed */
6224 	if (main_prog != prog && !main_prog->line_info)
6225 		return 0;
6226 
6227 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
6228 				       &main_prog->line_info,
6229 				       &main_prog->line_info_cnt,
6230 				       &main_prog->line_info_rec_size);
6231 	if (err) {
6232 		if (err != -ENOENT) {
6233 			pr_warn("prog '%s': error relocating .BTF.ext line info: %d\n",
6234 				prog->name, err);
6235 			return err;
6236 		}
6237 		if (main_prog->line_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 line 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 line info for the main program, skipping all of .BTF.ext line info.\n",
6247 			prog->name);
6248 	}
6249 	return 0;
6250 }
6251 
6252 static int cmp_relo_by_insn_idx(const void *key, const void *elem)
6253 {
6254 	size_t insn_idx = *(const size_t *)key;
6255 	const struct reloc_desc *relo = elem;
6256 
6257 	if (insn_idx == relo->insn_idx)
6258 		return 0;
6259 	return insn_idx < relo->insn_idx ? -1 : 1;
6260 }
6261 
6262 static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
6263 {
6264 	if (!prog->nr_reloc)
6265 		return NULL;
6266 	return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
6267 		       sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
6268 }
6269 
6270 static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
6271 {
6272 	int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
6273 	struct reloc_desc *relos;
6274 	int i;
6275 
6276 	if (main_prog == subprog)
6277 		return 0;
6278 	relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
6279 	/* if new count is zero, reallocarray can return a valid NULL result;
6280 	 * in this case the previous pointer will be freed, so we *have to*
6281 	 * reassign old pointer to the new value (even if it's NULL)
6282 	 */
6283 	if (!relos && new_cnt)
6284 		return -ENOMEM;
6285 	if (subprog->nr_reloc)
6286 		memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
6287 		       sizeof(*relos) * subprog->nr_reloc);
6288 
6289 	for (i = main_prog->nr_reloc; i < new_cnt; i++)
6290 		relos[i].insn_idx += subprog->sub_insn_off;
6291 	/* After insn_idx adjustment the 'relos' array is still sorted
6292 	 * by insn_idx and doesn't break bsearch.
6293 	 */
6294 	main_prog->reloc_desc = relos;
6295 	main_prog->nr_reloc = new_cnt;
6296 	return 0;
6297 }
6298 
6299 static int
6300 bpf_object__append_subprog_code(struct bpf_object *obj, struct bpf_program *main_prog,
6301 				struct bpf_program *subprog)
6302 {
6303        struct bpf_insn *insns;
6304        size_t new_cnt;
6305        int err;
6306 
6307        subprog->sub_insn_off = main_prog->insns_cnt;
6308 
6309        new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
6310        insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
6311        if (!insns) {
6312                pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
6313                return -ENOMEM;
6314        }
6315        main_prog->insns = insns;
6316        main_prog->insns_cnt = new_cnt;
6317 
6318        memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
6319               subprog->insns_cnt * sizeof(*insns));
6320 
6321        pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
6322                 main_prog->name, subprog->insns_cnt, subprog->name);
6323 
6324        /* The subprog insns are now appended. Append its relos too. */
6325        err = append_subprog_relos(main_prog, subprog);
6326        if (err)
6327                return err;
6328        return 0;
6329 }
6330 
6331 static int
6332 bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
6333 		       struct bpf_program *prog)
6334 {
6335 	size_t sub_insn_idx, insn_idx;
6336 	struct bpf_program *subprog;
6337 	struct reloc_desc *relo;
6338 	struct bpf_insn *insn;
6339 	int err;
6340 
6341 	err = reloc_prog_func_and_line_info(obj, main_prog, prog);
6342 	if (err)
6343 		return err;
6344 
6345 	for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
6346 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6347 		if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
6348 			continue;
6349 
6350 		relo = find_prog_insn_relo(prog, insn_idx);
6351 		if (relo && relo->type == RELO_EXTERN_CALL)
6352 			/* kfunc relocations will be handled later
6353 			 * in bpf_object__relocate_data()
6354 			 */
6355 			continue;
6356 		if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
6357 			pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
6358 				prog->name, insn_idx, relo->type);
6359 			return -LIBBPF_ERRNO__RELOC;
6360 		}
6361 		if (relo) {
6362 			/* sub-program instruction index is a combination of
6363 			 * an offset of a symbol pointed to by relocation and
6364 			 * call instruction's imm field; for global functions,
6365 			 * call always has imm = -1, but for static functions
6366 			 * relocation is against STT_SECTION and insn->imm
6367 			 * points to a start of a static function
6368 			 *
6369 			 * for subprog addr relocation, the relo->sym_off + insn->imm is
6370 			 * the byte offset in the corresponding section.
6371 			 */
6372 			if (relo->type == RELO_CALL)
6373 				sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
6374 			else
6375 				sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
6376 		} else if (insn_is_pseudo_func(insn)) {
6377 			/*
6378 			 * RELO_SUBPROG_ADDR relo is always emitted even if both
6379 			 * functions are in the same section, so it shouldn't reach here.
6380 			 */
6381 			pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
6382 				prog->name, insn_idx);
6383 			return -LIBBPF_ERRNO__RELOC;
6384 		} else {
6385 			/* if subprogram call is to a static function within
6386 			 * the same ELF section, there won't be any relocation
6387 			 * emitted, but it also means there is no additional
6388 			 * offset necessary, insns->imm is relative to
6389 			 * instruction's original position within the section
6390 			 */
6391 			sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
6392 		}
6393 
6394 		/* we enforce that sub-programs should be in .text section */
6395 		subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
6396 		if (!subprog) {
6397 			pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
6398 				prog->name);
6399 			return -LIBBPF_ERRNO__RELOC;
6400 		}
6401 
6402 		/* if it's the first call instruction calling into this
6403 		 * subprogram (meaning this subprog hasn't been processed
6404 		 * yet) within the context of current main program:
6405 		 *   - append it at the end of main program's instructions blog;
6406 		 *   - process is recursively, while current program is put on hold;
6407 		 *   - if that subprogram calls some other not yet processes
6408 		 *   subprogram, same thing will happen recursively until
6409 		 *   there are no more unprocesses subprograms left to append
6410 		 *   and relocate.
6411 		 */
6412 		if (subprog->sub_insn_off == 0) {
6413 			err = bpf_object__append_subprog_code(obj, main_prog, subprog);
6414 			if (err)
6415 				return err;
6416 			err = bpf_object__reloc_code(obj, main_prog, subprog);
6417 			if (err)
6418 				return err;
6419 		}
6420 
6421 		/* main_prog->insns memory could have been re-allocated, so
6422 		 * calculate pointer again
6423 		 */
6424 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6425 		/* calculate correct instruction position within current main
6426 		 * prog; each main prog can have a different set of
6427 		 * subprograms appended (potentially in different order as
6428 		 * well), so position of any subprog can be different for
6429 		 * different main programs
6430 		 */
6431 		insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
6432 
6433 		pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
6434 			 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
6435 	}
6436 
6437 	return 0;
6438 }
6439 
6440 /*
6441  * Relocate sub-program calls.
6442  *
6443  * Algorithm operates as follows. Each entry-point BPF program (referred to as
6444  * main prog) is processed separately. For each subprog (non-entry functions,
6445  * that can be called from either entry progs or other subprogs) gets their
6446  * sub_insn_off reset to zero. This serves as indicator that this subprogram
6447  * hasn't been yet appended and relocated within current main prog. Once its
6448  * relocated, sub_insn_off will point at the position within current main prog
6449  * where given subprog was appended. This will further be used to relocate all
6450  * the call instructions jumping into this subprog.
6451  *
6452  * We start with main program and process all call instructions. If the call
6453  * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
6454  * is zero), subprog instructions are appended at the end of main program's
6455  * instruction array. Then main program is "put on hold" while we recursively
6456  * process newly appended subprogram. If that subprogram calls into another
6457  * subprogram that hasn't been appended, new subprogram is appended again to
6458  * the *main* prog's instructions (subprog's instructions are always left
6459  * untouched, as they need to be in unmodified state for subsequent main progs
6460  * and subprog instructions are always sent only as part of a main prog) and
6461  * the process continues recursively. Once all the subprogs called from a main
6462  * prog or any of its subprogs are appended (and relocated), all their
6463  * positions within finalized instructions array are known, so it's easy to
6464  * rewrite call instructions with correct relative offsets, corresponding to
6465  * desired target subprog.
6466  *
6467  * Its important to realize that some subprogs might not be called from some
6468  * main prog and any of its called/used subprogs. Those will keep their
6469  * subprog->sub_insn_off as zero at all times and won't be appended to current
6470  * main prog and won't be relocated within the context of current main prog.
6471  * They might still be used from other main progs later.
6472  *
6473  * Visually this process can be shown as below. Suppose we have two main
6474  * programs mainA and mainB and BPF object contains three subprogs: subA,
6475  * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
6476  * subC both call subB:
6477  *
6478  *        +--------+ +-------+
6479  *        |        v v       |
6480  *     +--+---+ +--+-+-+ +---+--+
6481  *     | subA | | subB | | subC |
6482  *     +--+---+ +------+ +---+--+
6483  *        ^                  ^
6484  *        |                  |
6485  *    +---+-------+   +------+----+
6486  *    |   mainA   |   |   mainB   |
6487  *    +-----------+   +-----------+
6488  *
6489  * We'll start relocating mainA, will find subA, append it and start
6490  * processing sub A recursively:
6491  *
6492  *    +-----------+------+
6493  *    |   mainA   | subA |
6494  *    +-----------+------+
6495  *
6496  * At this point we notice that subB is used from subA, so we append it and
6497  * relocate (there are no further subcalls from subB):
6498  *
6499  *    +-----------+------+------+
6500  *    |   mainA   | subA | subB |
6501  *    +-----------+------+------+
6502  *
6503  * At this point, we relocate subA calls, then go one level up and finish with
6504  * relocatin mainA calls. mainA is done.
6505  *
6506  * For mainB process is similar but results in different order. We start with
6507  * mainB and skip subA and subB, as mainB never calls them (at least
6508  * directly), but we see subC is needed, so we append and start processing it:
6509  *
6510  *    +-----------+------+
6511  *    |   mainB   | subC |
6512  *    +-----------+------+
6513  * Now we see subC needs subB, so we go back to it, append and relocate it:
6514  *
6515  *    +-----------+------+------+
6516  *    |   mainB   | subC | subB |
6517  *    +-----------+------+------+
6518  *
6519  * At this point we unwind recursion, relocate calls in subC, then in mainB.
6520  */
6521 static int
6522 bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
6523 {
6524 	struct bpf_program *subprog;
6525 	int i, err;
6526 
6527 	/* mark all subprogs as not relocated (yet) within the context of
6528 	 * current main program
6529 	 */
6530 	for (i = 0; i < obj->nr_programs; i++) {
6531 		subprog = &obj->programs[i];
6532 		if (!prog_is_subprog(obj, subprog))
6533 			continue;
6534 
6535 		subprog->sub_insn_off = 0;
6536 	}
6537 
6538 	err = bpf_object__reloc_code(obj, prog, prog);
6539 	if (err)
6540 		return err;
6541 
6542 	return 0;
6543 }
6544 
6545 static void
6546 bpf_object__free_relocs(struct bpf_object *obj)
6547 {
6548 	struct bpf_program *prog;
6549 	int i;
6550 
6551 	/* free up relocation descriptors */
6552 	for (i = 0; i < obj->nr_programs; i++) {
6553 		prog = &obj->programs[i];
6554 		zfree(&prog->reloc_desc);
6555 		prog->nr_reloc = 0;
6556 	}
6557 }
6558 
6559 static int cmp_relocs(const void *_a, const void *_b)
6560 {
6561 	const struct reloc_desc *a = _a;
6562 	const struct reloc_desc *b = _b;
6563 
6564 	if (a->insn_idx != b->insn_idx)
6565 		return a->insn_idx < b->insn_idx ? -1 : 1;
6566 
6567 	/* no two relocations should have the same insn_idx, but ... */
6568 	if (a->type != b->type)
6569 		return a->type < b->type ? -1 : 1;
6570 
6571 	return 0;
6572 }
6573 
6574 static void bpf_object__sort_relos(struct bpf_object *obj)
6575 {
6576 	int i;
6577 
6578 	for (i = 0; i < obj->nr_programs; i++) {
6579 		struct bpf_program *p = &obj->programs[i];
6580 
6581 		if (!p->nr_reloc)
6582 			continue;
6583 
6584 		qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
6585 	}
6586 }
6587 
6588 static int bpf_prog_assign_exc_cb(struct bpf_object *obj, struct bpf_program *prog)
6589 {
6590 	const char *str = "exception_callback:";
6591 	size_t pfx_len = strlen(str);
6592 	int i, j, n;
6593 
6594 	if (!obj->btf || !kernel_supports(obj, FEAT_BTF_DECL_TAG))
6595 		return 0;
6596 
6597 	n = btf__type_cnt(obj->btf);
6598 	for (i = 1; i < n; i++) {
6599 		const char *name;
6600 		struct btf_type *t;
6601 
6602 		t = btf_type_by_id(obj->btf, i);
6603 		if (!btf_is_decl_tag(t) || btf_decl_tag(t)->component_idx != -1)
6604 			continue;
6605 
6606 		name = btf__str_by_offset(obj->btf, t->name_off);
6607 		if (strncmp(name, str, pfx_len) != 0)
6608 			continue;
6609 
6610 		t = btf_type_by_id(obj->btf, t->type);
6611 		if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
6612 			pr_warn("prog '%s': exception_callback:<value> decl tag not applied to the main program\n",
6613 				prog->name);
6614 			return -EINVAL;
6615 		}
6616 		if (strcmp(prog->name, btf__str_by_offset(obj->btf, t->name_off)) != 0)
6617 			continue;
6618 		/* Multiple callbacks are specified for the same prog,
6619 		 * the verifier will eventually return an error for this
6620 		 * case, hence simply skip appending a subprog.
6621 		 */
6622 		if (prog->exception_cb_idx >= 0) {
6623 			prog->exception_cb_idx = -1;
6624 			break;
6625 		}
6626 
6627 		name += pfx_len;
6628 		if (str_is_empty(name)) {
6629 			pr_warn("prog '%s': exception_callback:<value> decl tag contains empty value\n",
6630 				prog->name);
6631 			return -EINVAL;
6632 		}
6633 
6634 		for (j = 0; j < obj->nr_programs; j++) {
6635 			struct bpf_program *subprog = &obj->programs[j];
6636 
6637 			if (!prog_is_subprog(obj, subprog))
6638 				continue;
6639 			if (strcmp(name, subprog->name) != 0)
6640 				continue;
6641 			/* Enforce non-hidden, as from verifier point of
6642 			 * view it expects global functions, whereas the
6643 			 * mark_btf_static fixes up linkage as static.
6644 			 */
6645 			if (!subprog->sym_global || subprog->mark_btf_static) {
6646 				pr_warn("prog '%s': exception callback %s must be a global non-hidden function\n",
6647 					prog->name, subprog->name);
6648 				return -EINVAL;
6649 			}
6650 			/* Let's see if we already saw a static exception callback with the same name */
6651 			if (prog->exception_cb_idx >= 0) {
6652 				pr_warn("prog '%s': multiple subprogs with same name as exception callback '%s'\n",
6653 					prog->name, subprog->name);
6654 				return -EINVAL;
6655 			}
6656 			prog->exception_cb_idx = j;
6657 			break;
6658 		}
6659 
6660 		if (prog->exception_cb_idx >= 0)
6661 			continue;
6662 
6663 		pr_warn("prog '%s': cannot find exception callback '%s'\n", prog->name, name);
6664 		return -ENOENT;
6665 	}
6666 
6667 	return 0;
6668 }
6669 
6670 static struct {
6671 	enum bpf_prog_type prog_type;
6672 	const char *ctx_name;
6673 } global_ctx_map[] = {
6674 	{ BPF_PROG_TYPE_CGROUP_DEVICE,           "bpf_cgroup_dev_ctx" },
6675 	{ BPF_PROG_TYPE_CGROUP_SKB,              "__sk_buff" },
6676 	{ BPF_PROG_TYPE_CGROUP_SOCK,             "bpf_sock" },
6677 	{ BPF_PROG_TYPE_CGROUP_SOCK_ADDR,        "bpf_sock_addr" },
6678 	{ BPF_PROG_TYPE_CGROUP_SOCKOPT,          "bpf_sockopt" },
6679 	{ BPF_PROG_TYPE_CGROUP_SYSCTL,           "bpf_sysctl" },
6680 	{ BPF_PROG_TYPE_FLOW_DISSECTOR,          "__sk_buff" },
6681 	{ BPF_PROG_TYPE_KPROBE,                  "bpf_user_pt_regs_t" },
6682 	{ BPF_PROG_TYPE_LWT_IN,                  "__sk_buff" },
6683 	{ BPF_PROG_TYPE_LWT_OUT,                 "__sk_buff" },
6684 	{ BPF_PROG_TYPE_LWT_SEG6LOCAL,           "__sk_buff" },
6685 	{ BPF_PROG_TYPE_LWT_XMIT,                "__sk_buff" },
6686 	{ BPF_PROG_TYPE_NETFILTER,               "bpf_nf_ctx" },
6687 	{ BPF_PROG_TYPE_PERF_EVENT,              "bpf_perf_event_data" },
6688 	{ BPF_PROG_TYPE_RAW_TRACEPOINT,          "bpf_raw_tracepoint_args" },
6689 	{ BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE, "bpf_raw_tracepoint_args" },
6690 	{ BPF_PROG_TYPE_SCHED_ACT,               "__sk_buff" },
6691 	{ BPF_PROG_TYPE_SCHED_CLS,               "__sk_buff" },
6692 	{ BPF_PROG_TYPE_SK_LOOKUP,               "bpf_sk_lookup" },
6693 	{ BPF_PROG_TYPE_SK_MSG,                  "sk_msg_md" },
6694 	{ BPF_PROG_TYPE_SK_REUSEPORT,            "sk_reuseport_md" },
6695 	{ BPF_PROG_TYPE_SK_SKB,                  "__sk_buff" },
6696 	{ BPF_PROG_TYPE_SOCK_OPS,                "bpf_sock_ops" },
6697 	{ BPF_PROG_TYPE_SOCKET_FILTER,           "__sk_buff" },
6698 	{ BPF_PROG_TYPE_XDP,                     "xdp_md" },
6699 	/* all other program types don't have "named" context structs */
6700 };
6701 
6702 static bool need_func_arg_type_fixup(const struct btf *btf, const struct bpf_program *prog,
6703 				     const char *subprog_name, int arg_idx,
6704 				     int arg_type_id, const char *ctx_name)
6705 {
6706 	const struct btf_type *t;
6707 	const char *tname;
6708 
6709 	/* check if existing parameter already matches verifier expectations */
6710 	t = skip_mods_and_typedefs(btf, arg_type_id, NULL);
6711 	if (!btf_is_ptr(t))
6712 		goto out_warn;
6713 
6714 	/* typedef bpf_user_pt_regs_t is a special PITA case, valid for kprobe
6715 	 * and perf_event programs, so check this case early on and forget
6716 	 * about it for subsequent checks
6717 	 */
6718 	while (btf_is_mod(t))
6719 		t = btf__type_by_id(btf, t->type);
6720 	if (btf_is_typedef(t) &&
6721 	    (prog->type == BPF_PROG_TYPE_KPROBE || prog->type == BPF_PROG_TYPE_PERF_EVENT)) {
6722 		tname = btf__str_by_offset(btf, t->name_off) ?: "<anon>";
6723 		if (strcmp(tname, "bpf_user_pt_regs_t") == 0)
6724 			return false; /* canonical type for kprobe/perf_event */
6725 	}
6726 
6727 	/* now we can ignore typedefs moving forward */
6728 	t = skip_mods_and_typedefs(btf, t->type, NULL);
6729 
6730 	/* if it's `void *`, definitely fix up BTF info */
6731 	if (btf_is_void(t))
6732 		return true;
6733 
6734 	/* if it's already proper canonical type, no need to fix up */
6735 	tname = btf__str_by_offset(btf, t->name_off) ?: "<anon>";
6736 	if (btf_is_struct(t) && strcmp(tname, ctx_name) == 0)
6737 		return false;
6738 
6739 	/* special cases */
6740 	switch (prog->type) {
6741 	case BPF_PROG_TYPE_KPROBE:
6742 	case BPF_PROG_TYPE_PERF_EVENT:
6743 		/* `struct pt_regs *` is expected, but we need to fix up */
6744 		if (btf_is_struct(t) && strcmp(tname, "pt_regs") == 0)
6745 			return true;
6746 		break;
6747 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
6748 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
6749 		/* allow u64* as ctx */
6750 		if (btf_is_int(t) && t->size == 8)
6751 			return true;
6752 		break;
6753 	default:
6754 		break;
6755 	}
6756 
6757 out_warn:
6758 	pr_warn("prog '%s': subprog '%s' arg#%d is expected to be of `struct %s *` type\n",
6759 		prog->name, subprog_name, arg_idx, ctx_name);
6760 	return false;
6761 }
6762 
6763 static int clone_func_btf_info(struct btf *btf, int orig_fn_id, struct bpf_program *prog)
6764 {
6765 	int fn_id, fn_proto_id, ret_type_id, orig_proto_id;
6766 	int i, err, arg_cnt, fn_name_off, linkage;
6767 	struct btf_type *fn_t, *fn_proto_t, *t;
6768 	struct btf_param *p;
6769 
6770 	/* caller already validated FUNC -> FUNC_PROTO validity */
6771 	fn_t = btf_type_by_id(btf, orig_fn_id);
6772 	fn_proto_t = btf_type_by_id(btf, fn_t->type);
6773 
6774 	/* Note that each btf__add_xxx() operation invalidates
6775 	 * all btf_type and string pointers, so we need to be
6776 	 * very careful when cloning BTF types. BTF type
6777 	 * pointers have to be always refetched. And to avoid
6778 	 * problems with invalidated string pointers, we
6779 	 * add empty strings initially, then just fix up
6780 	 * name_off offsets in place. Offsets are stable for
6781 	 * existing strings, so that works out.
6782 	 */
6783 	fn_name_off = fn_t->name_off; /* we are about to invalidate fn_t */
6784 	linkage = btf_func_linkage(fn_t);
6785 	orig_proto_id = fn_t->type; /* original FUNC_PROTO ID */
6786 	ret_type_id = fn_proto_t->type; /* fn_proto_t will be invalidated */
6787 	arg_cnt = btf_vlen(fn_proto_t);
6788 
6789 	/* clone FUNC_PROTO and its params */
6790 	fn_proto_id = btf__add_func_proto(btf, ret_type_id);
6791 	if (fn_proto_id < 0)
6792 		return -EINVAL;
6793 
6794 	for (i = 0; i < arg_cnt; i++) {
6795 		int name_off;
6796 
6797 		/* copy original parameter data */
6798 		t = btf_type_by_id(btf, orig_proto_id);
6799 		p = &btf_params(t)[i];
6800 		name_off = p->name_off;
6801 
6802 		err = btf__add_func_param(btf, "", p->type);
6803 		if (err)
6804 			return err;
6805 
6806 		fn_proto_t = btf_type_by_id(btf, fn_proto_id);
6807 		p = &btf_params(fn_proto_t)[i];
6808 		p->name_off = name_off; /* use remembered str offset */
6809 	}
6810 
6811 	/* clone FUNC now, btf__add_func() enforces non-empty name, so use
6812 	 * entry program's name as a placeholder, which we replace immediately
6813 	 * with original name_off
6814 	 */
6815 	fn_id = btf__add_func(btf, prog->name, linkage, fn_proto_id);
6816 	if (fn_id < 0)
6817 		return -EINVAL;
6818 
6819 	fn_t = btf_type_by_id(btf, fn_id);
6820 	fn_t->name_off = fn_name_off; /* reuse original string */
6821 
6822 	return fn_id;
6823 }
6824 
6825 static int probe_kern_arg_ctx_tag(void)
6826 {
6827 	/* To minimize merge conflicts with BPF token series that refactors
6828 	 * feature detection code a lot, we don't integrate
6829 	 * probe_kern_arg_ctx_tag() into kernel_supports() feature-detection
6830 	 * framework yet, doing our own caching internally.
6831 	 * This will be cleaned up a bit later when bpf/bpf-next trees settle.
6832 	 */
6833 	static int cached_result = -1;
6834 	static const char strs[] = "\0a\0b\0arg:ctx\0";
6835 	const __u32 types[] = {
6836 		/* [1] INT */
6837 		BTF_TYPE_INT_ENC(1 /* "a" */, BTF_INT_SIGNED, 0, 32, 4),
6838 		/* [2] PTR -> VOID */
6839 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_PTR, 0, 0), 0),
6840 		/* [3] FUNC_PROTO `int(void *a)` */
6841 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 1),
6842 		BTF_PARAM_ENC(1 /* "a" */, 2),
6843 		/* [4] FUNC 'a' -> FUNC_PROTO (main prog) */
6844 		BTF_TYPE_ENC(1 /* "a" */, BTF_INFO_ENC(BTF_KIND_FUNC, 0, BTF_FUNC_GLOBAL), 3),
6845 		/* [5] FUNC_PROTO `int(void *b __arg_ctx)` */
6846 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 1),
6847 		BTF_PARAM_ENC(3 /* "b" */, 2),
6848 		/* [6] FUNC 'b' -> FUNC_PROTO (subprog) */
6849 		BTF_TYPE_ENC(3 /* "b" */, BTF_INFO_ENC(BTF_KIND_FUNC, 0, BTF_FUNC_GLOBAL), 5),
6850 		/* [7] DECL_TAG 'arg:ctx' -> func 'b' arg 'b' */
6851 		BTF_TYPE_DECL_TAG_ENC(5 /* "arg:ctx" */, 6, 0),
6852 	};
6853 	const struct bpf_insn insns[] = {
6854 		/* main prog */
6855 		BPF_CALL_REL(+1),
6856 		BPF_EXIT_INSN(),
6857 		/* global subprog */
6858 		BPF_EMIT_CALL(BPF_FUNC_get_func_ip), /* needs PTR_TO_CTX */
6859 		BPF_EXIT_INSN(),
6860 	};
6861 	const struct bpf_func_info_min func_infos[] = {
6862 		{ 0, 4 }, /* main prog -> FUNC 'a' */
6863 		{ 2, 6 }, /* subprog -> FUNC 'b' */
6864 	};
6865 	LIBBPF_OPTS(bpf_prog_load_opts, opts);
6866 	int prog_fd, btf_fd, insn_cnt = ARRAY_SIZE(insns);
6867 
6868 	if (cached_result >= 0)
6869 		return cached_result;
6870 
6871 	btf_fd = libbpf__load_raw_btf((char *)types, sizeof(types), strs, sizeof(strs));
6872 	if (btf_fd < 0)
6873 		return 0;
6874 
6875 	opts.prog_btf_fd = btf_fd;
6876 	opts.func_info = &func_infos;
6877 	opts.func_info_cnt = ARRAY_SIZE(func_infos);
6878 	opts.func_info_rec_size = sizeof(func_infos[0]);
6879 
6880 	prog_fd = bpf_prog_load(BPF_PROG_TYPE_KPROBE, "det_arg_ctx",
6881 				"GPL", insns, insn_cnt, &opts);
6882 	close(btf_fd);
6883 
6884 	cached_result = probe_fd(prog_fd);
6885 	return cached_result;
6886 }
6887 
6888 /* Check if main program or global subprog's function prototype has `arg:ctx`
6889  * argument tags, and, if necessary, substitute correct type to match what BPF
6890  * verifier would expect, taking into account specific program type. This
6891  * allows to support __arg_ctx tag transparently on old kernels that don't yet
6892  * have a native support for it in the verifier, making user's life much
6893  * easier.
6894  */
6895 static int bpf_program_fixup_func_info(struct bpf_object *obj, struct bpf_program *prog)
6896 {
6897 	const char *ctx_name = NULL, *ctx_tag = "arg:ctx", *fn_name;
6898 	struct bpf_func_info_min *func_rec;
6899 	struct btf_type *fn_t, *fn_proto_t;
6900 	struct btf *btf = obj->btf;
6901 	const struct btf_type *t;
6902 	struct btf_param *p;
6903 	int ptr_id = 0, struct_id, tag_id, orig_fn_id;
6904 	int i, n, arg_idx, arg_cnt, err, rec_idx;
6905 	int *orig_ids;
6906 
6907 	/* no .BTF.ext, no problem */
6908 	if (!obj->btf_ext || !prog->func_info)
6909 		return 0;
6910 
6911 	/* don't do any fix ups if kernel natively supports __arg_ctx */
6912 	if (probe_kern_arg_ctx_tag() > 0)
6913 		return 0;
6914 
6915 	/* some BPF program types just don't have named context structs, so
6916 	 * this fallback mechanism doesn't work for them
6917 	 */
6918 	for (i = 0; i < ARRAY_SIZE(global_ctx_map); i++) {
6919 		if (global_ctx_map[i].prog_type != prog->type)
6920 			continue;
6921 		ctx_name = global_ctx_map[i].ctx_name;
6922 		break;
6923 	}
6924 	if (!ctx_name)
6925 		return 0;
6926 
6927 	/* remember original func BTF IDs to detect if we already cloned them */
6928 	orig_ids = calloc(prog->func_info_cnt, sizeof(*orig_ids));
6929 	if (!orig_ids)
6930 		return -ENOMEM;
6931 	for (i = 0; i < prog->func_info_cnt; i++) {
6932 		func_rec = prog->func_info + prog->func_info_rec_size * i;
6933 		orig_ids[i] = func_rec->type_id;
6934 	}
6935 
6936 	/* go through each DECL_TAG with "arg:ctx" and see if it points to one
6937 	 * of our subprogs; if yes and subprog is global and needs adjustment,
6938 	 * clone and adjust FUNC -> FUNC_PROTO combo
6939 	 */
6940 	for (i = 1, n = btf__type_cnt(btf); i < n; i++) {
6941 		/* only DECL_TAG with "arg:ctx" value are interesting */
6942 		t = btf__type_by_id(btf, i);
6943 		if (!btf_is_decl_tag(t))
6944 			continue;
6945 		if (strcmp(btf__str_by_offset(btf, t->name_off), ctx_tag) != 0)
6946 			continue;
6947 
6948 		/* only global funcs need adjustment, if at all */
6949 		orig_fn_id = t->type;
6950 		fn_t = btf_type_by_id(btf, orig_fn_id);
6951 		if (!btf_is_func(fn_t) || btf_func_linkage(fn_t) != BTF_FUNC_GLOBAL)
6952 			continue;
6953 
6954 		/* sanity check FUNC -> FUNC_PROTO chain, just in case */
6955 		fn_proto_t = btf_type_by_id(btf, fn_t->type);
6956 		if (!fn_proto_t || !btf_is_func_proto(fn_proto_t))
6957 			continue;
6958 
6959 		/* find corresponding func_info record */
6960 		func_rec = NULL;
6961 		for (rec_idx = 0; rec_idx < prog->func_info_cnt; rec_idx++) {
6962 			if (orig_ids[rec_idx] == t->type) {
6963 				func_rec = prog->func_info + prog->func_info_rec_size * rec_idx;
6964 				break;
6965 			}
6966 		}
6967 		/* current main program doesn't call into this subprog */
6968 		if (!func_rec)
6969 			continue;
6970 
6971 		/* some more sanity checking of DECL_TAG */
6972 		arg_cnt = btf_vlen(fn_proto_t);
6973 		arg_idx = btf_decl_tag(t)->component_idx;
6974 		if (arg_idx < 0 || arg_idx >= arg_cnt)
6975 			continue;
6976 
6977 		/* check if we should fix up argument type */
6978 		p = &btf_params(fn_proto_t)[arg_idx];
6979 		fn_name = btf__str_by_offset(btf, fn_t->name_off) ?: "<anon>";
6980 		if (!need_func_arg_type_fixup(btf, prog, fn_name, arg_idx, p->type, ctx_name))
6981 			continue;
6982 
6983 		/* clone fn/fn_proto, unless we already did it for another arg */
6984 		if (func_rec->type_id == orig_fn_id) {
6985 			int fn_id;
6986 
6987 			fn_id = clone_func_btf_info(btf, orig_fn_id, prog);
6988 			if (fn_id < 0) {
6989 				err = fn_id;
6990 				goto err_out;
6991 			}
6992 
6993 			/* point func_info record to a cloned FUNC type */
6994 			func_rec->type_id = fn_id;
6995 		}
6996 
6997 		/* create PTR -> STRUCT type chain to mark PTR_TO_CTX argument;
6998 		 * we do it just once per main BPF program, as all global
6999 		 * funcs share the same program type, so need only PTR ->
7000 		 * STRUCT type chain
7001 		 */
7002 		if (ptr_id == 0) {
7003 			struct_id = btf__add_struct(btf, ctx_name, 0);
7004 			ptr_id = btf__add_ptr(btf, struct_id);
7005 			if (ptr_id < 0 || struct_id < 0) {
7006 				err = -EINVAL;
7007 				goto err_out;
7008 			}
7009 		}
7010 
7011 		/* for completeness, clone DECL_TAG and point it to cloned param */
7012 		tag_id = btf__add_decl_tag(btf, ctx_tag, func_rec->type_id, arg_idx);
7013 		if (tag_id < 0) {
7014 			err = -EINVAL;
7015 			goto err_out;
7016 		}
7017 
7018 		/* all the BTF manipulations invalidated pointers, refetch them */
7019 		fn_t = btf_type_by_id(btf, func_rec->type_id);
7020 		fn_proto_t = btf_type_by_id(btf, fn_t->type);
7021 
7022 		/* fix up type ID pointed to by param */
7023 		p = &btf_params(fn_proto_t)[arg_idx];
7024 		p->type = ptr_id;
7025 	}
7026 
7027 	free(orig_ids);
7028 	return 0;
7029 err_out:
7030 	free(orig_ids);
7031 	return err;
7032 }
7033 
7034 static int bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
7035 {
7036 	struct bpf_program *prog;
7037 	size_t i, j;
7038 	int err;
7039 
7040 	if (obj->btf_ext) {
7041 		err = bpf_object__relocate_core(obj, targ_btf_path);
7042 		if (err) {
7043 			pr_warn("failed to perform CO-RE relocations: %d\n",
7044 				err);
7045 			return err;
7046 		}
7047 		bpf_object__sort_relos(obj);
7048 	}
7049 
7050 	/* Before relocating calls pre-process relocations and mark
7051 	 * few ld_imm64 instructions that points to subprogs.
7052 	 * Otherwise bpf_object__reloc_code() later would have to consider
7053 	 * all ld_imm64 insns as relocation candidates. That would
7054 	 * reduce relocation speed, since amount of find_prog_insn_relo()
7055 	 * would increase and most of them will fail to find a relo.
7056 	 */
7057 	for (i = 0; i < obj->nr_programs; i++) {
7058 		prog = &obj->programs[i];
7059 		for (j = 0; j < prog->nr_reloc; j++) {
7060 			struct reloc_desc *relo = &prog->reloc_desc[j];
7061 			struct bpf_insn *insn = &prog->insns[relo->insn_idx];
7062 
7063 			/* mark the insn, so it's recognized by insn_is_pseudo_func() */
7064 			if (relo->type == RELO_SUBPROG_ADDR)
7065 				insn[0].src_reg = BPF_PSEUDO_FUNC;
7066 		}
7067 	}
7068 
7069 	/* relocate subprogram calls and append used subprograms to main
7070 	 * programs; each copy of subprogram code needs to be relocated
7071 	 * differently for each main program, because its code location might
7072 	 * have changed.
7073 	 * Append subprog relos to main programs to allow data relos to be
7074 	 * processed after text is completely relocated.
7075 	 */
7076 	for (i = 0; i < obj->nr_programs; i++) {
7077 		prog = &obj->programs[i];
7078 		/* sub-program's sub-calls are relocated within the context of
7079 		 * its main program only
7080 		 */
7081 		if (prog_is_subprog(obj, prog))
7082 			continue;
7083 		if (!prog->autoload)
7084 			continue;
7085 
7086 		err = bpf_object__relocate_calls(obj, prog);
7087 		if (err) {
7088 			pr_warn("prog '%s': failed to relocate calls: %d\n",
7089 				prog->name, err);
7090 			return err;
7091 		}
7092 
7093 		err = bpf_prog_assign_exc_cb(obj, prog);
7094 		if (err)
7095 			return err;
7096 		/* Now, also append exception callback if it has not been done already. */
7097 		if (prog->exception_cb_idx >= 0) {
7098 			struct bpf_program *subprog = &obj->programs[prog->exception_cb_idx];
7099 
7100 			/* Calling exception callback directly is disallowed, which the
7101 			 * verifier will reject later. In case it was processed already,
7102 			 * we can skip this step, otherwise for all other valid cases we
7103 			 * have to append exception callback now.
7104 			 */
7105 			if (subprog->sub_insn_off == 0) {
7106 				err = bpf_object__append_subprog_code(obj, prog, subprog);
7107 				if (err)
7108 					return err;
7109 				err = bpf_object__reloc_code(obj, prog, subprog);
7110 				if (err)
7111 					return err;
7112 			}
7113 		}
7114 	}
7115 	for (i = 0; i < obj->nr_programs; i++) {
7116 		prog = &obj->programs[i];
7117 		if (prog_is_subprog(obj, prog))
7118 			continue;
7119 		if (!prog->autoload)
7120 			continue;
7121 
7122 		/* Process data relos for main programs */
7123 		err = bpf_object__relocate_data(obj, prog);
7124 		if (err) {
7125 			pr_warn("prog '%s': failed to relocate data references: %d\n",
7126 				prog->name, err);
7127 			return err;
7128 		}
7129 
7130 		/* Fix up .BTF.ext information, if necessary */
7131 		err = bpf_program_fixup_func_info(obj, prog);
7132 		if (err) {
7133 			pr_warn("prog '%s': failed to perform .BTF.ext fix ups: %d\n",
7134 				prog->name, err);
7135 			return err;
7136 		}
7137 	}
7138 
7139 	return 0;
7140 }
7141 
7142 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
7143 					    Elf64_Shdr *shdr, Elf_Data *data);
7144 
7145 static int bpf_object__collect_map_relos(struct bpf_object *obj,
7146 					 Elf64_Shdr *shdr, Elf_Data *data)
7147 {
7148 	const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
7149 	int i, j, nrels, new_sz;
7150 	const struct btf_var_secinfo *vi = NULL;
7151 	const struct btf_type *sec, *var, *def;
7152 	struct bpf_map *map = NULL, *targ_map = NULL;
7153 	struct bpf_program *targ_prog = NULL;
7154 	bool is_prog_array, is_map_in_map;
7155 	const struct btf_member *member;
7156 	const char *name, *mname, *type;
7157 	unsigned int moff;
7158 	Elf64_Sym *sym;
7159 	Elf64_Rel *rel;
7160 	void *tmp;
7161 
7162 	if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
7163 		return -EINVAL;
7164 	sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
7165 	if (!sec)
7166 		return -EINVAL;
7167 
7168 	nrels = shdr->sh_size / shdr->sh_entsize;
7169 	for (i = 0; i < nrels; i++) {
7170 		rel = elf_rel_by_idx(data, i);
7171 		if (!rel) {
7172 			pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
7173 			return -LIBBPF_ERRNO__FORMAT;
7174 		}
7175 
7176 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
7177 		if (!sym) {
7178 			pr_warn(".maps relo #%d: symbol %zx not found\n",
7179 				i, (size_t)ELF64_R_SYM(rel->r_info));
7180 			return -LIBBPF_ERRNO__FORMAT;
7181 		}
7182 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
7183 
7184 		pr_debug(".maps relo #%d: for %zd value %zd rel->r_offset %zu name %d ('%s')\n",
7185 			 i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
7186 			 (size_t)rel->r_offset, sym->st_name, name);
7187 
7188 		for (j = 0; j < obj->nr_maps; j++) {
7189 			map = &obj->maps[j];
7190 			if (map->sec_idx != obj->efile.btf_maps_shndx)
7191 				continue;
7192 
7193 			vi = btf_var_secinfos(sec) + map->btf_var_idx;
7194 			if (vi->offset <= rel->r_offset &&
7195 			    rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size)
7196 				break;
7197 		}
7198 		if (j == obj->nr_maps) {
7199 			pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
7200 				i, name, (size_t)rel->r_offset);
7201 			return -EINVAL;
7202 		}
7203 
7204 		is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
7205 		is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
7206 		type = is_map_in_map ? "map" : "prog";
7207 		if (is_map_in_map) {
7208 			if (sym->st_shndx != obj->efile.btf_maps_shndx) {
7209 				pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
7210 					i, name);
7211 				return -LIBBPF_ERRNO__RELOC;
7212 			}
7213 			if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
7214 			    map->def.key_size != sizeof(int)) {
7215 				pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
7216 					i, map->name, sizeof(int));
7217 				return -EINVAL;
7218 			}
7219 			targ_map = bpf_object__find_map_by_name(obj, name);
7220 			if (!targ_map) {
7221 				pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
7222 					i, name);
7223 				return -ESRCH;
7224 			}
7225 		} else if (is_prog_array) {
7226 			targ_prog = bpf_object__find_program_by_name(obj, name);
7227 			if (!targ_prog) {
7228 				pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
7229 					i, name);
7230 				return -ESRCH;
7231 			}
7232 			if (targ_prog->sec_idx != sym->st_shndx ||
7233 			    targ_prog->sec_insn_off * 8 != sym->st_value ||
7234 			    prog_is_subprog(obj, targ_prog)) {
7235 				pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
7236 					i, name);
7237 				return -LIBBPF_ERRNO__RELOC;
7238 			}
7239 		} else {
7240 			return -EINVAL;
7241 		}
7242 
7243 		var = btf__type_by_id(obj->btf, vi->type);
7244 		def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
7245 		if (btf_vlen(def) == 0)
7246 			return -EINVAL;
7247 		member = btf_members(def) + btf_vlen(def) - 1;
7248 		mname = btf__name_by_offset(obj->btf, member->name_off);
7249 		if (strcmp(mname, "values"))
7250 			return -EINVAL;
7251 
7252 		moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
7253 		if (rel->r_offset - vi->offset < moff)
7254 			return -EINVAL;
7255 
7256 		moff = rel->r_offset - vi->offset - moff;
7257 		/* here we use BPF pointer size, which is always 64 bit, as we
7258 		 * are parsing ELF that was built for BPF target
7259 		 */
7260 		if (moff % bpf_ptr_sz)
7261 			return -EINVAL;
7262 		moff /= bpf_ptr_sz;
7263 		if (moff >= map->init_slots_sz) {
7264 			new_sz = moff + 1;
7265 			tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
7266 			if (!tmp)
7267 				return -ENOMEM;
7268 			map->init_slots = tmp;
7269 			memset(map->init_slots + map->init_slots_sz, 0,
7270 			       (new_sz - map->init_slots_sz) * host_ptr_sz);
7271 			map->init_slots_sz = new_sz;
7272 		}
7273 		map->init_slots[moff] = is_map_in_map ? (void *)targ_map : (void *)targ_prog;
7274 
7275 		pr_debug(".maps relo #%d: map '%s' slot [%d] points to %s '%s'\n",
7276 			 i, map->name, moff, type, name);
7277 	}
7278 
7279 	return 0;
7280 }
7281 
7282 static int bpf_object__collect_relos(struct bpf_object *obj)
7283 {
7284 	int i, err;
7285 
7286 	for (i = 0; i < obj->efile.sec_cnt; i++) {
7287 		struct elf_sec_desc *sec_desc = &obj->efile.secs[i];
7288 		Elf64_Shdr *shdr;
7289 		Elf_Data *data;
7290 		int idx;
7291 
7292 		if (sec_desc->sec_type != SEC_RELO)
7293 			continue;
7294 
7295 		shdr = sec_desc->shdr;
7296 		data = sec_desc->data;
7297 		idx = shdr->sh_info;
7298 
7299 		if (shdr->sh_type != SHT_REL) {
7300 			pr_warn("internal error at %d\n", __LINE__);
7301 			return -LIBBPF_ERRNO__INTERNAL;
7302 		}
7303 
7304 		if (idx == obj->efile.st_ops_shndx || idx == obj->efile.st_ops_link_shndx)
7305 			err = bpf_object__collect_st_ops_relos(obj, shdr, data);
7306 		else if (idx == obj->efile.btf_maps_shndx)
7307 			err = bpf_object__collect_map_relos(obj, shdr, data);
7308 		else
7309 			err = bpf_object__collect_prog_relos(obj, shdr, data);
7310 		if (err)
7311 			return err;
7312 	}
7313 
7314 	bpf_object__sort_relos(obj);
7315 	return 0;
7316 }
7317 
7318 static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
7319 {
7320 	if (BPF_CLASS(insn->code) == BPF_JMP &&
7321 	    BPF_OP(insn->code) == BPF_CALL &&
7322 	    BPF_SRC(insn->code) == BPF_K &&
7323 	    insn->src_reg == 0 &&
7324 	    insn->dst_reg == 0) {
7325 		    *func_id = insn->imm;
7326 		    return true;
7327 	}
7328 	return false;
7329 }
7330 
7331 static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
7332 {
7333 	struct bpf_insn *insn = prog->insns;
7334 	enum bpf_func_id func_id;
7335 	int i;
7336 
7337 	if (obj->gen_loader)
7338 		return 0;
7339 
7340 	for (i = 0; i < prog->insns_cnt; i++, insn++) {
7341 		if (!insn_is_helper_call(insn, &func_id))
7342 			continue;
7343 
7344 		/* on kernels that don't yet support
7345 		 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
7346 		 * to bpf_probe_read() which works well for old kernels
7347 		 */
7348 		switch (func_id) {
7349 		case BPF_FUNC_probe_read_kernel:
7350 		case BPF_FUNC_probe_read_user:
7351 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
7352 				insn->imm = BPF_FUNC_probe_read;
7353 			break;
7354 		case BPF_FUNC_probe_read_kernel_str:
7355 		case BPF_FUNC_probe_read_user_str:
7356 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
7357 				insn->imm = BPF_FUNC_probe_read_str;
7358 			break;
7359 		default:
7360 			break;
7361 		}
7362 	}
7363 	return 0;
7364 }
7365 
7366 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
7367 				     int *btf_obj_fd, int *btf_type_id);
7368 
7369 /* this is called as prog->sec_def->prog_prepare_load_fn for libbpf-supported sec_defs */
7370 static int libbpf_prepare_prog_load(struct bpf_program *prog,
7371 				    struct bpf_prog_load_opts *opts, long cookie)
7372 {
7373 	enum sec_def_flags def = cookie;
7374 
7375 	/* old kernels might not support specifying expected_attach_type */
7376 	if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
7377 		opts->expected_attach_type = 0;
7378 
7379 	if (def & SEC_SLEEPABLE)
7380 		opts->prog_flags |= BPF_F_SLEEPABLE;
7381 
7382 	if (prog->type == BPF_PROG_TYPE_XDP && (def & SEC_XDP_FRAGS))
7383 		opts->prog_flags |= BPF_F_XDP_HAS_FRAGS;
7384 
7385 	/* special check for usdt to use uprobe_multi link */
7386 	if ((def & SEC_USDT) && kernel_supports(prog->obj, FEAT_UPROBE_MULTI_LINK))
7387 		prog->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
7388 
7389 	if ((def & SEC_ATTACH_BTF) && !prog->attach_btf_id) {
7390 		int btf_obj_fd = 0, btf_type_id = 0, err;
7391 		const char *attach_name;
7392 
7393 		attach_name = strchr(prog->sec_name, '/');
7394 		if (!attach_name) {
7395 			/* if BPF program is annotated with just SEC("fentry")
7396 			 * (or similar) without declaratively specifying
7397 			 * target, then it is expected that target will be
7398 			 * specified with bpf_program__set_attach_target() at
7399 			 * runtime before BPF object load step. If not, then
7400 			 * there is nothing to load into the kernel as BPF
7401 			 * verifier won't be able to validate BPF program
7402 			 * correctness anyways.
7403 			 */
7404 			pr_warn("prog '%s': no BTF-based attach target is specified, use bpf_program__set_attach_target()\n",
7405 				prog->name);
7406 			return -EINVAL;
7407 		}
7408 		attach_name++; /* skip over / */
7409 
7410 		err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
7411 		if (err)
7412 			return err;
7413 
7414 		/* cache resolved BTF FD and BTF type ID in the prog */
7415 		prog->attach_btf_obj_fd = btf_obj_fd;
7416 		prog->attach_btf_id = btf_type_id;
7417 
7418 		/* but by now libbpf common logic is not utilizing
7419 		 * prog->atach_btf_obj_fd/prog->attach_btf_id anymore because
7420 		 * this callback is called after opts were populated by
7421 		 * libbpf, so this callback has to update opts explicitly here
7422 		 */
7423 		opts->attach_btf_obj_fd = btf_obj_fd;
7424 		opts->attach_btf_id = btf_type_id;
7425 	}
7426 	return 0;
7427 }
7428 
7429 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz);
7430 
7431 static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
7432 				struct bpf_insn *insns, int insns_cnt,
7433 				const char *license, __u32 kern_version, int *prog_fd)
7434 {
7435 	LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
7436 	const char *prog_name = NULL;
7437 	char *cp, errmsg[STRERR_BUFSIZE];
7438 	size_t log_buf_size = 0;
7439 	char *log_buf = NULL, *tmp;
7440 	int btf_fd, ret, err;
7441 	bool own_log_buf = true;
7442 	__u32 log_level = prog->log_level;
7443 
7444 	if (prog->type == BPF_PROG_TYPE_UNSPEC) {
7445 		/*
7446 		 * The program type must be set.  Most likely we couldn't find a proper
7447 		 * section definition at load time, and thus we didn't infer the type.
7448 		 */
7449 		pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
7450 			prog->name, prog->sec_name);
7451 		return -EINVAL;
7452 	}
7453 
7454 	if (!insns || !insns_cnt)
7455 		return -EINVAL;
7456 
7457 	if (kernel_supports(obj, FEAT_PROG_NAME))
7458 		prog_name = prog->name;
7459 	load_attr.attach_prog_fd = prog->attach_prog_fd;
7460 	load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
7461 	load_attr.attach_btf_id = prog->attach_btf_id;
7462 	load_attr.kern_version = kern_version;
7463 	load_attr.prog_ifindex = prog->prog_ifindex;
7464 
7465 	/* specify func_info/line_info only if kernel supports them */
7466 	btf_fd = btf__fd(obj->btf);
7467 	if (btf_fd >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
7468 		load_attr.prog_btf_fd = btf_fd;
7469 		load_attr.func_info = prog->func_info;
7470 		load_attr.func_info_rec_size = prog->func_info_rec_size;
7471 		load_attr.func_info_cnt = prog->func_info_cnt;
7472 		load_attr.line_info = prog->line_info;
7473 		load_attr.line_info_rec_size = prog->line_info_rec_size;
7474 		load_attr.line_info_cnt = prog->line_info_cnt;
7475 	}
7476 	load_attr.log_level = log_level;
7477 	load_attr.prog_flags = prog->prog_flags;
7478 	load_attr.fd_array = obj->fd_array;
7479 
7480 	/* adjust load_attr if sec_def provides custom preload callback */
7481 	if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
7482 		err = prog->sec_def->prog_prepare_load_fn(prog, &load_attr, prog->sec_def->cookie);
7483 		if (err < 0) {
7484 			pr_warn("prog '%s': failed to prepare load attributes: %d\n",
7485 				prog->name, err);
7486 			return err;
7487 		}
7488 		insns = prog->insns;
7489 		insns_cnt = prog->insns_cnt;
7490 	}
7491 
7492 	/* allow prog_prepare_load_fn to change expected_attach_type */
7493 	load_attr.expected_attach_type = prog->expected_attach_type;
7494 
7495 	if (obj->gen_loader) {
7496 		bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
7497 				   license, insns, insns_cnt, &load_attr,
7498 				   prog - obj->programs);
7499 		*prog_fd = -1;
7500 		return 0;
7501 	}
7502 
7503 retry_load:
7504 	/* if log_level is zero, we don't request logs initially even if
7505 	 * custom log_buf is specified; if the program load fails, then we'll
7506 	 * bump log_level to 1 and use either custom log_buf or we'll allocate
7507 	 * our own and retry the load to get details on what failed
7508 	 */
7509 	if (log_level) {
7510 		if (prog->log_buf) {
7511 			log_buf = prog->log_buf;
7512 			log_buf_size = prog->log_size;
7513 			own_log_buf = false;
7514 		} else if (obj->log_buf) {
7515 			log_buf = obj->log_buf;
7516 			log_buf_size = obj->log_size;
7517 			own_log_buf = false;
7518 		} else {
7519 			log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
7520 			tmp = realloc(log_buf, log_buf_size);
7521 			if (!tmp) {
7522 				ret = -ENOMEM;
7523 				goto out;
7524 			}
7525 			log_buf = tmp;
7526 			log_buf[0] = '\0';
7527 			own_log_buf = true;
7528 		}
7529 	}
7530 
7531 	load_attr.log_buf = log_buf;
7532 	load_attr.log_size = log_buf_size;
7533 	load_attr.log_level = log_level;
7534 
7535 	ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
7536 	if (ret >= 0) {
7537 		if (log_level && own_log_buf) {
7538 			pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
7539 				 prog->name, log_buf);
7540 		}
7541 
7542 		if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
7543 			struct bpf_map *map;
7544 			int i;
7545 
7546 			for (i = 0; i < obj->nr_maps; i++) {
7547 				map = &prog->obj->maps[i];
7548 				if (map->libbpf_type != LIBBPF_MAP_RODATA)
7549 					continue;
7550 
7551 				if (bpf_prog_bind_map(ret, map->fd, NULL)) {
7552 					cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
7553 					pr_warn("prog '%s': failed to bind map '%s': %s\n",
7554 						prog->name, map->real_name, cp);
7555 					/* Don't fail hard if can't bind rodata. */
7556 				}
7557 			}
7558 		}
7559 
7560 		*prog_fd = ret;
7561 		ret = 0;
7562 		goto out;
7563 	}
7564 
7565 	if (log_level == 0) {
7566 		log_level = 1;
7567 		goto retry_load;
7568 	}
7569 	/* On ENOSPC, increase log buffer size and retry, unless custom
7570 	 * log_buf is specified.
7571 	 * Be careful to not overflow u32, though. Kernel's log buf size limit
7572 	 * isn't part of UAPI so it can always be bumped to full 4GB. So don't
7573 	 * multiply by 2 unless we are sure we'll fit within 32 bits.
7574 	 * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
7575 	 */
7576 	if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
7577 		goto retry_load;
7578 
7579 	ret = -errno;
7580 
7581 	/* post-process verifier log to improve error descriptions */
7582 	fixup_verifier_log(prog, log_buf, log_buf_size);
7583 
7584 	cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
7585 	pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, cp);
7586 	pr_perm_msg(ret);
7587 
7588 	if (own_log_buf && log_buf && log_buf[0] != '\0') {
7589 		pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
7590 			prog->name, log_buf);
7591 	}
7592 
7593 out:
7594 	if (own_log_buf)
7595 		free(log_buf);
7596 	return ret;
7597 }
7598 
7599 static char *find_prev_line(char *buf, char *cur)
7600 {
7601 	char *p;
7602 
7603 	if (cur == buf) /* end of a log buf */
7604 		return NULL;
7605 
7606 	p = cur - 1;
7607 	while (p - 1 >= buf && *(p - 1) != '\n')
7608 		p--;
7609 
7610 	return p;
7611 }
7612 
7613 static void patch_log(char *buf, size_t buf_sz, size_t log_sz,
7614 		      char *orig, size_t orig_sz, const char *patch)
7615 {
7616 	/* size of the remaining log content to the right from the to-be-replaced part */
7617 	size_t rem_sz = (buf + log_sz) - (orig + orig_sz);
7618 	size_t patch_sz = strlen(patch);
7619 
7620 	if (patch_sz != orig_sz) {
7621 		/* If patch line(s) are longer than original piece of verifier log,
7622 		 * shift log contents by (patch_sz - orig_sz) bytes to the right
7623 		 * starting from after to-be-replaced part of the log.
7624 		 *
7625 		 * If patch line(s) are shorter than original piece of verifier log,
7626 		 * shift log contents by (orig_sz - patch_sz) bytes to the left
7627 		 * starting from after to-be-replaced part of the log
7628 		 *
7629 		 * We need to be careful about not overflowing available
7630 		 * buf_sz capacity. If that's the case, we'll truncate the end
7631 		 * of the original log, as necessary.
7632 		 */
7633 		if (patch_sz > orig_sz) {
7634 			if (orig + patch_sz >= buf + buf_sz) {
7635 				/* patch is big enough to cover remaining space completely */
7636 				patch_sz -= (orig + patch_sz) - (buf + buf_sz) + 1;
7637 				rem_sz = 0;
7638 			} else if (patch_sz - orig_sz > buf_sz - log_sz) {
7639 				/* patch causes part of remaining log to be truncated */
7640 				rem_sz -= (patch_sz - orig_sz) - (buf_sz - log_sz);
7641 			}
7642 		}
7643 		/* shift remaining log to the right by calculated amount */
7644 		memmove(orig + patch_sz, orig + orig_sz, rem_sz);
7645 	}
7646 
7647 	memcpy(orig, patch, patch_sz);
7648 }
7649 
7650 static void fixup_log_failed_core_relo(struct bpf_program *prog,
7651 				       char *buf, size_t buf_sz, size_t log_sz,
7652 				       char *line1, char *line2, char *line3)
7653 {
7654 	/* Expected log for failed and not properly guarded CO-RE relocation:
7655 	 * line1 -> 123: (85) call unknown#195896080
7656 	 * line2 -> invalid func unknown#195896080
7657 	 * line3 -> <anything else or end of buffer>
7658 	 *
7659 	 * "123" is the index of the instruction that was poisoned. We extract
7660 	 * instruction index to find corresponding CO-RE relocation and
7661 	 * replace this part of the log with more relevant information about
7662 	 * failed CO-RE relocation.
7663 	 */
7664 	const struct bpf_core_relo *relo;
7665 	struct bpf_core_spec spec;
7666 	char patch[512], spec_buf[256];
7667 	int insn_idx, err, spec_len;
7668 
7669 	if (sscanf(line1, "%d: (%*d) call unknown#195896080\n", &insn_idx) != 1)
7670 		return;
7671 
7672 	relo = find_relo_core(prog, insn_idx);
7673 	if (!relo)
7674 		return;
7675 
7676 	err = bpf_core_parse_spec(prog->name, prog->obj->btf, relo, &spec);
7677 	if (err)
7678 		return;
7679 
7680 	spec_len = bpf_core_format_spec(spec_buf, sizeof(spec_buf), &spec);
7681 	snprintf(patch, sizeof(patch),
7682 		 "%d: <invalid CO-RE relocation>\n"
7683 		 "failed to resolve CO-RE relocation %s%s\n",
7684 		 insn_idx, spec_buf, spec_len >= sizeof(spec_buf) ? "..." : "");
7685 
7686 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7687 }
7688 
7689 static void fixup_log_missing_map_load(struct bpf_program *prog,
7690 				       char *buf, size_t buf_sz, size_t log_sz,
7691 				       char *line1, char *line2, char *line3)
7692 {
7693 	/* Expected log for failed and not properly guarded map reference:
7694 	 * line1 -> 123: (85) call unknown#2001000345
7695 	 * line2 -> invalid func unknown#2001000345
7696 	 * line3 -> <anything else or end of buffer>
7697 	 *
7698 	 * "123" is the index of the instruction that was poisoned.
7699 	 * "345" in "2001000345" is a map index in obj->maps to fetch map name.
7700 	 */
7701 	struct bpf_object *obj = prog->obj;
7702 	const struct bpf_map *map;
7703 	int insn_idx, map_idx;
7704 	char patch[128];
7705 
7706 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &map_idx) != 2)
7707 		return;
7708 
7709 	map_idx -= POISON_LDIMM64_MAP_BASE;
7710 	if (map_idx < 0 || map_idx >= obj->nr_maps)
7711 		return;
7712 	map = &obj->maps[map_idx];
7713 
7714 	snprintf(patch, sizeof(patch),
7715 		 "%d: <invalid BPF map reference>\n"
7716 		 "BPF map '%s' is referenced but wasn't created\n",
7717 		 insn_idx, map->name);
7718 
7719 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7720 }
7721 
7722 static void fixup_log_missing_kfunc_call(struct bpf_program *prog,
7723 					 char *buf, size_t buf_sz, size_t log_sz,
7724 					 char *line1, char *line2, char *line3)
7725 {
7726 	/* Expected log for failed and not properly guarded kfunc call:
7727 	 * line1 -> 123: (85) call unknown#2002000345
7728 	 * line2 -> invalid func unknown#2002000345
7729 	 * line3 -> <anything else or end of buffer>
7730 	 *
7731 	 * "123" is the index of the instruction that was poisoned.
7732 	 * "345" in "2002000345" is an extern index in obj->externs to fetch kfunc name.
7733 	 */
7734 	struct bpf_object *obj = prog->obj;
7735 	const struct extern_desc *ext;
7736 	int insn_idx, ext_idx;
7737 	char patch[128];
7738 
7739 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &ext_idx) != 2)
7740 		return;
7741 
7742 	ext_idx -= POISON_CALL_KFUNC_BASE;
7743 	if (ext_idx < 0 || ext_idx >= obj->nr_extern)
7744 		return;
7745 	ext = &obj->externs[ext_idx];
7746 
7747 	snprintf(patch, sizeof(patch),
7748 		 "%d: <invalid kfunc call>\n"
7749 		 "kfunc '%s' is referenced but wasn't resolved\n",
7750 		 insn_idx, ext->name);
7751 
7752 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7753 }
7754 
7755 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz)
7756 {
7757 	/* look for familiar error patterns in last N lines of the log */
7758 	const size_t max_last_line_cnt = 10;
7759 	char *prev_line, *cur_line, *next_line;
7760 	size_t log_sz;
7761 	int i;
7762 
7763 	if (!buf)
7764 		return;
7765 
7766 	log_sz = strlen(buf) + 1;
7767 	next_line = buf + log_sz - 1;
7768 
7769 	for (i = 0; i < max_last_line_cnt; i++, next_line = cur_line) {
7770 		cur_line = find_prev_line(buf, next_line);
7771 		if (!cur_line)
7772 			return;
7773 
7774 		if (str_has_pfx(cur_line, "invalid func unknown#195896080\n")) {
7775 			prev_line = find_prev_line(buf, cur_line);
7776 			if (!prev_line)
7777 				continue;
7778 
7779 			/* failed CO-RE relocation case */
7780 			fixup_log_failed_core_relo(prog, buf, buf_sz, log_sz,
7781 						   prev_line, cur_line, next_line);
7782 			return;
7783 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_LDIMM64_MAP_PFX)) {
7784 			prev_line = find_prev_line(buf, cur_line);
7785 			if (!prev_line)
7786 				continue;
7787 
7788 			/* reference to uncreated BPF map */
7789 			fixup_log_missing_map_load(prog, buf, buf_sz, log_sz,
7790 						   prev_line, cur_line, next_line);
7791 			return;
7792 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_CALL_KFUNC_PFX)) {
7793 			prev_line = find_prev_line(buf, cur_line);
7794 			if (!prev_line)
7795 				continue;
7796 
7797 			/* reference to unresolved kfunc */
7798 			fixup_log_missing_kfunc_call(prog, buf, buf_sz, log_sz,
7799 						     prev_line, cur_line, next_line);
7800 			return;
7801 		}
7802 	}
7803 }
7804 
7805 static int bpf_program_record_relos(struct bpf_program *prog)
7806 {
7807 	struct bpf_object *obj = prog->obj;
7808 	int i;
7809 
7810 	for (i = 0; i < prog->nr_reloc; i++) {
7811 		struct reloc_desc *relo = &prog->reloc_desc[i];
7812 		struct extern_desc *ext = &obj->externs[relo->ext_idx];
7813 		int kind;
7814 
7815 		switch (relo->type) {
7816 		case RELO_EXTERN_LD64:
7817 			if (ext->type != EXT_KSYM)
7818 				continue;
7819 			kind = btf_is_var(btf__type_by_id(obj->btf, ext->btf_id)) ?
7820 				BTF_KIND_VAR : BTF_KIND_FUNC;
7821 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7822 					       ext->is_weak, !ext->ksym.type_id,
7823 					       true, kind, relo->insn_idx);
7824 			break;
7825 		case RELO_EXTERN_CALL:
7826 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7827 					       ext->is_weak, false, false, BTF_KIND_FUNC,
7828 					       relo->insn_idx);
7829 			break;
7830 		case RELO_CORE: {
7831 			struct bpf_core_relo cr = {
7832 				.insn_off = relo->insn_idx * 8,
7833 				.type_id = relo->core_relo->type_id,
7834 				.access_str_off = relo->core_relo->access_str_off,
7835 				.kind = relo->core_relo->kind,
7836 			};
7837 
7838 			bpf_gen__record_relo_core(obj->gen_loader, &cr);
7839 			break;
7840 		}
7841 		default:
7842 			continue;
7843 		}
7844 	}
7845 	return 0;
7846 }
7847 
7848 static int
7849 bpf_object__load_progs(struct bpf_object *obj, int log_level)
7850 {
7851 	struct bpf_program *prog;
7852 	size_t i;
7853 	int err;
7854 
7855 	for (i = 0; i < obj->nr_programs; i++) {
7856 		prog = &obj->programs[i];
7857 		err = bpf_object__sanitize_prog(obj, prog);
7858 		if (err)
7859 			return err;
7860 	}
7861 
7862 	for (i = 0; i < obj->nr_programs; i++) {
7863 		prog = &obj->programs[i];
7864 		if (prog_is_subprog(obj, prog))
7865 			continue;
7866 		if (!prog->autoload) {
7867 			pr_debug("prog '%s': skipped loading\n", prog->name);
7868 			continue;
7869 		}
7870 		prog->log_level |= log_level;
7871 
7872 		if (obj->gen_loader)
7873 			bpf_program_record_relos(prog);
7874 
7875 		err = bpf_object_load_prog(obj, prog, prog->insns, prog->insns_cnt,
7876 					   obj->license, obj->kern_version, &prog->fd);
7877 		if (err) {
7878 			pr_warn("prog '%s': failed to load: %d\n", prog->name, err);
7879 			return err;
7880 		}
7881 	}
7882 
7883 	bpf_object__free_relocs(obj);
7884 	return 0;
7885 }
7886 
7887 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
7888 
7889 static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
7890 {
7891 	struct bpf_program *prog;
7892 	int err;
7893 
7894 	bpf_object__for_each_program(prog, obj) {
7895 		prog->sec_def = find_sec_def(prog->sec_name);
7896 		if (!prog->sec_def) {
7897 			/* couldn't guess, but user might manually specify */
7898 			pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
7899 				prog->name, prog->sec_name);
7900 			continue;
7901 		}
7902 
7903 		prog->type = prog->sec_def->prog_type;
7904 		prog->expected_attach_type = prog->sec_def->expected_attach_type;
7905 
7906 		/* sec_def can have custom callback which should be called
7907 		 * after bpf_program is initialized to adjust its properties
7908 		 */
7909 		if (prog->sec_def->prog_setup_fn) {
7910 			err = prog->sec_def->prog_setup_fn(prog, prog->sec_def->cookie);
7911 			if (err < 0) {
7912 				pr_warn("prog '%s': failed to initialize: %d\n",
7913 					prog->name, err);
7914 				return err;
7915 			}
7916 		}
7917 	}
7918 
7919 	return 0;
7920 }
7921 
7922 static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
7923 					  const struct bpf_object_open_opts *opts)
7924 {
7925 	const char *obj_name, *kconfig, *btf_tmp_path;
7926 	struct bpf_object *obj;
7927 	char tmp_name[64];
7928 	int err;
7929 	char *log_buf;
7930 	size_t log_size;
7931 	__u32 log_level;
7932 
7933 	if (elf_version(EV_CURRENT) == EV_NONE) {
7934 		pr_warn("failed to init libelf for %s\n",
7935 			path ? : "(mem buf)");
7936 		return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
7937 	}
7938 
7939 	if (!OPTS_VALID(opts, bpf_object_open_opts))
7940 		return ERR_PTR(-EINVAL);
7941 
7942 	obj_name = OPTS_GET(opts, object_name, NULL);
7943 	if (obj_buf) {
7944 		if (!obj_name) {
7945 			snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
7946 				 (unsigned long)obj_buf,
7947 				 (unsigned long)obj_buf_sz);
7948 			obj_name = tmp_name;
7949 		}
7950 		path = obj_name;
7951 		pr_debug("loading object '%s' from buffer\n", obj_name);
7952 	}
7953 
7954 	log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
7955 	log_size = OPTS_GET(opts, kernel_log_size, 0);
7956 	log_level = OPTS_GET(opts, kernel_log_level, 0);
7957 	if (log_size > UINT_MAX)
7958 		return ERR_PTR(-EINVAL);
7959 	if (log_size && !log_buf)
7960 		return ERR_PTR(-EINVAL);
7961 
7962 	obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
7963 	if (IS_ERR(obj))
7964 		return obj;
7965 
7966 	obj->log_buf = log_buf;
7967 	obj->log_size = log_size;
7968 	obj->log_level = log_level;
7969 
7970 	btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
7971 	if (btf_tmp_path) {
7972 		if (strlen(btf_tmp_path) >= PATH_MAX) {
7973 			err = -ENAMETOOLONG;
7974 			goto out;
7975 		}
7976 		obj->btf_custom_path = strdup(btf_tmp_path);
7977 		if (!obj->btf_custom_path) {
7978 			err = -ENOMEM;
7979 			goto out;
7980 		}
7981 	}
7982 
7983 	kconfig = OPTS_GET(opts, kconfig, NULL);
7984 	if (kconfig) {
7985 		obj->kconfig = strdup(kconfig);
7986 		if (!obj->kconfig) {
7987 			err = -ENOMEM;
7988 			goto out;
7989 		}
7990 	}
7991 
7992 	err = bpf_object__elf_init(obj);
7993 	err = err ? : bpf_object__check_endianness(obj);
7994 	err = err ? : bpf_object__elf_collect(obj);
7995 	err = err ? : bpf_object__collect_externs(obj);
7996 	err = err ? : bpf_object_fixup_btf(obj);
7997 	err = err ? : bpf_object__init_maps(obj, opts);
7998 	err = err ? : bpf_object_init_progs(obj, opts);
7999 	err = err ? : bpf_object__collect_relos(obj);
8000 	if (err)
8001 		goto out;
8002 
8003 	bpf_object__elf_finish(obj);
8004 
8005 	return obj;
8006 out:
8007 	bpf_object__close(obj);
8008 	return ERR_PTR(err);
8009 }
8010 
8011 struct bpf_object *
8012 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
8013 {
8014 	if (!path)
8015 		return libbpf_err_ptr(-EINVAL);
8016 
8017 	pr_debug("loading %s\n", path);
8018 
8019 	return libbpf_ptr(bpf_object_open(path, NULL, 0, opts));
8020 }
8021 
8022 struct bpf_object *bpf_object__open(const char *path)
8023 {
8024 	return bpf_object__open_file(path, NULL);
8025 }
8026 
8027 struct bpf_object *
8028 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
8029 		     const struct bpf_object_open_opts *opts)
8030 {
8031 	if (!obj_buf || obj_buf_sz == 0)
8032 		return libbpf_err_ptr(-EINVAL);
8033 
8034 	return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, opts));
8035 }
8036 
8037 static int bpf_object_unload(struct bpf_object *obj)
8038 {
8039 	size_t i;
8040 
8041 	if (!obj)
8042 		return libbpf_err(-EINVAL);
8043 
8044 	for (i = 0; i < obj->nr_maps; i++) {
8045 		zclose(obj->maps[i].fd);
8046 		if (obj->maps[i].st_ops)
8047 			zfree(&obj->maps[i].st_ops->kern_vdata);
8048 	}
8049 
8050 	for (i = 0; i < obj->nr_programs; i++)
8051 		bpf_program__unload(&obj->programs[i]);
8052 
8053 	return 0;
8054 }
8055 
8056 static int bpf_object__sanitize_maps(struct bpf_object *obj)
8057 {
8058 	struct bpf_map *m;
8059 
8060 	bpf_object__for_each_map(m, obj) {
8061 		if (!bpf_map__is_internal(m))
8062 			continue;
8063 		if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
8064 			m->def.map_flags &= ~BPF_F_MMAPABLE;
8065 	}
8066 
8067 	return 0;
8068 }
8069 
8070 int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
8071 {
8072 	char sym_type, sym_name[500];
8073 	unsigned long long sym_addr;
8074 	int ret, err = 0;
8075 	FILE *f;
8076 
8077 	f = fopen("/proc/kallsyms", "re");
8078 	if (!f) {
8079 		err = -errno;
8080 		pr_warn("failed to open /proc/kallsyms: %d\n", err);
8081 		return err;
8082 	}
8083 
8084 	while (true) {
8085 		ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
8086 			     &sym_addr, &sym_type, sym_name);
8087 		if (ret == EOF && feof(f))
8088 			break;
8089 		if (ret != 3) {
8090 			pr_warn("failed to read kallsyms entry: %d\n", ret);
8091 			err = -EINVAL;
8092 			break;
8093 		}
8094 
8095 		err = cb(sym_addr, sym_type, sym_name, ctx);
8096 		if (err)
8097 			break;
8098 	}
8099 
8100 	fclose(f);
8101 	return err;
8102 }
8103 
8104 static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
8105 		       const char *sym_name, void *ctx)
8106 {
8107 	struct bpf_object *obj = ctx;
8108 	const struct btf_type *t;
8109 	struct extern_desc *ext;
8110 
8111 	ext = find_extern_by_name(obj, sym_name);
8112 	if (!ext || ext->type != EXT_KSYM)
8113 		return 0;
8114 
8115 	t = btf__type_by_id(obj->btf, ext->btf_id);
8116 	if (!btf_is_var(t))
8117 		return 0;
8118 
8119 	if (ext->is_set && ext->ksym.addr != sym_addr) {
8120 		pr_warn("extern (ksym) '%s': resolution is ambiguous: 0x%llx or 0x%llx\n",
8121 			sym_name, ext->ksym.addr, sym_addr);
8122 		return -EINVAL;
8123 	}
8124 	if (!ext->is_set) {
8125 		ext->is_set = true;
8126 		ext->ksym.addr = sym_addr;
8127 		pr_debug("extern (ksym) '%s': set to 0x%llx\n", sym_name, sym_addr);
8128 	}
8129 	return 0;
8130 }
8131 
8132 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
8133 {
8134 	return libbpf_kallsyms_parse(kallsyms_cb, obj);
8135 }
8136 
8137 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
8138 			    __u16 kind, struct btf **res_btf,
8139 			    struct module_btf **res_mod_btf)
8140 {
8141 	struct module_btf *mod_btf;
8142 	struct btf *btf;
8143 	int i, id, err;
8144 
8145 	btf = obj->btf_vmlinux;
8146 	mod_btf = NULL;
8147 	id = btf__find_by_name_kind(btf, ksym_name, kind);
8148 
8149 	if (id == -ENOENT) {
8150 		err = load_module_btfs(obj);
8151 		if (err)
8152 			return err;
8153 
8154 		for (i = 0; i < obj->btf_module_cnt; i++) {
8155 			/* we assume module_btf's BTF FD is always >0 */
8156 			mod_btf = &obj->btf_modules[i];
8157 			btf = mod_btf->btf;
8158 			id = btf__find_by_name_kind_own(btf, ksym_name, kind);
8159 			if (id != -ENOENT)
8160 				break;
8161 		}
8162 	}
8163 	if (id <= 0)
8164 		return -ESRCH;
8165 
8166 	*res_btf = btf;
8167 	*res_mod_btf = mod_btf;
8168 	return id;
8169 }
8170 
8171 static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
8172 					       struct extern_desc *ext)
8173 {
8174 	const struct btf_type *targ_var, *targ_type;
8175 	__u32 targ_type_id, local_type_id;
8176 	struct module_btf *mod_btf = NULL;
8177 	const char *targ_var_name;
8178 	struct btf *btf = NULL;
8179 	int id, err;
8180 
8181 	id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
8182 	if (id < 0) {
8183 		if (id == -ESRCH && ext->is_weak)
8184 			return 0;
8185 		pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
8186 			ext->name);
8187 		return id;
8188 	}
8189 
8190 	/* find local type_id */
8191 	local_type_id = ext->ksym.type_id;
8192 
8193 	/* find target type_id */
8194 	targ_var = btf__type_by_id(btf, id);
8195 	targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
8196 	targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
8197 
8198 	err = bpf_core_types_are_compat(obj->btf, local_type_id,
8199 					btf, targ_type_id);
8200 	if (err <= 0) {
8201 		const struct btf_type *local_type;
8202 		const char *targ_name, *local_name;
8203 
8204 		local_type = btf__type_by_id(obj->btf, local_type_id);
8205 		local_name = btf__name_by_offset(obj->btf, local_type->name_off);
8206 		targ_name = btf__name_by_offset(btf, targ_type->name_off);
8207 
8208 		pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
8209 			ext->name, local_type_id,
8210 			btf_kind_str(local_type), local_name, targ_type_id,
8211 			btf_kind_str(targ_type), targ_name);
8212 		return -EINVAL;
8213 	}
8214 
8215 	ext->is_set = true;
8216 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
8217 	ext->ksym.kernel_btf_id = id;
8218 	pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
8219 		 ext->name, id, btf_kind_str(targ_var), targ_var_name);
8220 
8221 	return 0;
8222 }
8223 
8224 static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
8225 						struct extern_desc *ext)
8226 {
8227 	int local_func_proto_id, kfunc_proto_id, kfunc_id;
8228 	struct module_btf *mod_btf = NULL;
8229 	const struct btf_type *kern_func;
8230 	struct btf *kern_btf = NULL;
8231 	int ret;
8232 
8233 	local_func_proto_id = ext->ksym.type_id;
8234 
8235 	kfunc_id = find_ksym_btf_id(obj, ext->essent_name ?: ext->name, BTF_KIND_FUNC, &kern_btf,
8236 				    &mod_btf);
8237 	if (kfunc_id < 0) {
8238 		if (kfunc_id == -ESRCH && ext->is_weak)
8239 			return 0;
8240 		pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
8241 			ext->name);
8242 		return kfunc_id;
8243 	}
8244 
8245 	kern_func = btf__type_by_id(kern_btf, kfunc_id);
8246 	kfunc_proto_id = kern_func->type;
8247 
8248 	ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
8249 					kern_btf, kfunc_proto_id);
8250 	if (ret <= 0) {
8251 		if (ext->is_weak)
8252 			return 0;
8253 
8254 		pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with %s [%d]\n",
8255 			ext->name, local_func_proto_id,
8256 			mod_btf ? mod_btf->name : "vmlinux", kfunc_proto_id);
8257 		return -EINVAL;
8258 	}
8259 
8260 	/* set index for module BTF fd in fd_array, if unset */
8261 	if (mod_btf && !mod_btf->fd_array_idx) {
8262 		/* insn->off is s16 */
8263 		if (obj->fd_array_cnt == INT16_MAX) {
8264 			pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
8265 				ext->name, mod_btf->fd_array_idx);
8266 			return -E2BIG;
8267 		}
8268 		/* Cannot use index 0 for module BTF fd */
8269 		if (!obj->fd_array_cnt)
8270 			obj->fd_array_cnt = 1;
8271 
8272 		ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
8273 					obj->fd_array_cnt + 1);
8274 		if (ret)
8275 			return ret;
8276 		mod_btf->fd_array_idx = obj->fd_array_cnt;
8277 		/* we assume module BTF FD is always >0 */
8278 		obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
8279 	}
8280 
8281 	ext->is_set = true;
8282 	ext->ksym.kernel_btf_id = kfunc_id;
8283 	ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
8284 	/* Also set kernel_btf_obj_fd to make sure that bpf_object__relocate_data()
8285 	 * populates FD into ld_imm64 insn when it's used to point to kfunc.
8286 	 * {kernel_btf_id, btf_fd_idx} -> fixup bpf_call.
8287 	 * {kernel_btf_id, kernel_btf_obj_fd} -> fixup ld_imm64.
8288 	 */
8289 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
8290 	pr_debug("extern (func ksym) '%s': resolved to %s [%d]\n",
8291 		 ext->name, mod_btf ? mod_btf->name : "vmlinux", kfunc_id);
8292 
8293 	return 0;
8294 }
8295 
8296 static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
8297 {
8298 	const struct btf_type *t;
8299 	struct extern_desc *ext;
8300 	int i, err;
8301 
8302 	for (i = 0; i < obj->nr_extern; i++) {
8303 		ext = &obj->externs[i];
8304 		if (ext->type != EXT_KSYM || !ext->ksym.type_id)
8305 			continue;
8306 
8307 		if (obj->gen_loader) {
8308 			ext->is_set = true;
8309 			ext->ksym.kernel_btf_obj_fd = 0;
8310 			ext->ksym.kernel_btf_id = 0;
8311 			continue;
8312 		}
8313 		t = btf__type_by_id(obj->btf, ext->btf_id);
8314 		if (btf_is_var(t))
8315 			err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
8316 		else
8317 			err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
8318 		if (err)
8319 			return err;
8320 	}
8321 	return 0;
8322 }
8323 
8324 static int bpf_object__resolve_externs(struct bpf_object *obj,
8325 				       const char *extra_kconfig)
8326 {
8327 	bool need_config = false, need_kallsyms = false;
8328 	bool need_vmlinux_btf = false;
8329 	struct extern_desc *ext;
8330 	void *kcfg_data = NULL;
8331 	int err, i;
8332 
8333 	if (obj->nr_extern == 0)
8334 		return 0;
8335 
8336 	if (obj->kconfig_map_idx >= 0)
8337 		kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
8338 
8339 	for (i = 0; i < obj->nr_extern; i++) {
8340 		ext = &obj->externs[i];
8341 
8342 		if (ext->type == EXT_KSYM) {
8343 			if (ext->ksym.type_id)
8344 				need_vmlinux_btf = true;
8345 			else
8346 				need_kallsyms = true;
8347 			continue;
8348 		} else if (ext->type == EXT_KCFG) {
8349 			void *ext_ptr = kcfg_data + ext->kcfg.data_off;
8350 			__u64 value = 0;
8351 
8352 			/* Kconfig externs need actual /proc/config.gz */
8353 			if (str_has_pfx(ext->name, "CONFIG_")) {
8354 				need_config = true;
8355 				continue;
8356 			}
8357 
8358 			/* Virtual kcfg externs are customly handled by libbpf */
8359 			if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
8360 				value = get_kernel_version();
8361 				if (!value) {
8362 					pr_warn("extern (kcfg) '%s': failed to get kernel version\n", ext->name);
8363 					return -EINVAL;
8364 				}
8365 			} else if (strcmp(ext->name, "LINUX_HAS_BPF_COOKIE") == 0) {
8366 				value = kernel_supports(obj, FEAT_BPF_COOKIE);
8367 			} else if (strcmp(ext->name, "LINUX_HAS_SYSCALL_WRAPPER") == 0) {
8368 				value = kernel_supports(obj, FEAT_SYSCALL_WRAPPER);
8369 			} else if (!str_has_pfx(ext->name, "LINUX_") || !ext->is_weak) {
8370 				/* Currently libbpf supports only CONFIG_ and LINUX_ prefixed
8371 				 * __kconfig externs, where LINUX_ ones are virtual and filled out
8372 				 * customly by libbpf (their values don't come from Kconfig).
8373 				 * If LINUX_xxx variable is not recognized by libbpf, but is marked
8374 				 * __weak, it defaults to zero value, just like for CONFIG_xxx
8375 				 * externs.
8376 				 */
8377 				pr_warn("extern (kcfg) '%s': unrecognized virtual extern\n", ext->name);
8378 				return -EINVAL;
8379 			}
8380 
8381 			err = set_kcfg_value_num(ext, ext_ptr, value);
8382 			if (err)
8383 				return err;
8384 			pr_debug("extern (kcfg) '%s': set to 0x%llx\n",
8385 				 ext->name, (long long)value);
8386 		} else {
8387 			pr_warn("extern '%s': unrecognized extern kind\n", ext->name);
8388 			return -EINVAL;
8389 		}
8390 	}
8391 	if (need_config && extra_kconfig) {
8392 		err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
8393 		if (err)
8394 			return -EINVAL;
8395 		need_config = false;
8396 		for (i = 0; i < obj->nr_extern; i++) {
8397 			ext = &obj->externs[i];
8398 			if (ext->type == EXT_KCFG && !ext->is_set) {
8399 				need_config = true;
8400 				break;
8401 			}
8402 		}
8403 	}
8404 	if (need_config) {
8405 		err = bpf_object__read_kconfig_file(obj, kcfg_data);
8406 		if (err)
8407 			return -EINVAL;
8408 	}
8409 	if (need_kallsyms) {
8410 		err = bpf_object__read_kallsyms_file(obj);
8411 		if (err)
8412 			return -EINVAL;
8413 	}
8414 	if (need_vmlinux_btf) {
8415 		err = bpf_object__resolve_ksyms_btf_id(obj);
8416 		if (err)
8417 			return -EINVAL;
8418 	}
8419 	for (i = 0; i < obj->nr_extern; i++) {
8420 		ext = &obj->externs[i];
8421 
8422 		if (!ext->is_set && !ext->is_weak) {
8423 			pr_warn("extern '%s' (strong): not resolved\n", ext->name);
8424 			return -ESRCH;
8425 		} else if (!ext->is_set) {
8426 			pr_debug("extern '%s' (weak): not resolved, defaulting to zero\n",
8427 				 ext->name);
8428 		}
8429 	}
8430 
8431 	return 0;
8432 }
8433 
8434 static void bpf_map_prepare_vdata(const struct bpf_map *map)
8435 {
8436 	struct bpf_struct_ops *st_ops;
8437 	__u32 i;
8438 
8439 	st_ops = map->st_ops;
8440 	for (i = 0; i < btf_vlen(st_ops->type); i++) {
8441 		struct bpf_program *prog = st_ops->progs[i];
8442 		void *kern_data;
8443 		int prog_fd;
8444 
8445 		if (!prog)
8446 			continue;
8447 
8448 		prog_fd = bpf_program__fd(prog);
8449 		kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
8450 		*(unsigned long *)kern_data = prog_fd;
8451 	}
8452 }
8453 
8454 static int bpf_object_prepare_struct_ops(struct bpf_object *obj)
8455 {
8456 	int i;
8457 
8458 	for (i = 0; i < obj->nr_maps; i++)
8459 		if (bpf_map__is_struct_ops(&obj->maps[i]))
8460 			bpf_map_prepare_vdata(&obj->maps[i]);
8461 
8462 	return 0;
8463 }
8464 
8465 static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
8466 {
8467 	int err, i;
8468 
8469 	if (!obj)
8470 		return libbpf_err(-EINVAL);
8471 
8472 	if (obj->loaded) {
8473 		pr_warn("object '%s': load can't be attempted twice\n", obj->name);
8474 		return libbpf_err(-EINVAL);
8475 	}
8476 
8477 	if (obj->gen_loader)
8478 		bpf_gen__init(obj->gen_loader, extra_log_level, obj->nr_programs, obj->nr_maps);
8479 
8480 	err = bpf_object__probe_loading(obj);
8481 	err = err ? : bpf_object__load_vmlinux_btf(obj, false);
8482 	err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
8483 	err = err ? : bpf_object__sanitize_maps(obj);
8484 	err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
8485 	err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
8486 	err = err ? : bpf_object__sanitize_and_load_btf(obj);
8487 	err = err ? : bpf_object__create_maps(obj);
8488 	err = err ? : bpf_object__load_progs(obj, extra_log_level);
8489 	err = err ? : bpf_object_init_prog_arrays(obj);
8490 	err = err ? : bpf_object_prepare_struct_ops(obj);
8491 
8492 	if (obj->gen_loader) {
8493 		/* reset FDs */
8494 		if (obj->btf)
8495 			btf__set_fd(obj->btf, -1);
8496 		if (!err)
8497 			err = bpf_gen__finish(obj->gen_loader, obj->nr_programs, obj->nr_maps);
8498 	}
8499 
8500 	/* clean up fd_array */
8501 	zfree(&obj->fd_array);
8502 
8503 	/* clean up module BTFs */
8504 	for (i = 0; i < obj->btf_module_cnt; i++) {
8505 		close(obj->btf_modules[i].fd);
8506 		btf__free(obj->btf_modules[i].btf);
8507 		free(obj->btf_modules[i].name);
8508 	}
8509 	free(obj->btf_modules);
8510 
8511 	/* clean up vmlinux BTF */
8512 	btf__free(obj->btf_vmlinux);
8513 	obj->btf_vmlinux = NULL;
8514 
8515 	obj->loaded = true; /* doesn't matter if successfully or not */
8516 
8517 	if (err)
8518 		goto out;
8519 
8520 	return 0;
8521 out:
8522 	/* unpin any maps that were auto-pinned during load */
8523 	for (i = 0; i < obj->nr_maps; i++)
8524 		if (obj->maps[i].pinned && !obj->maps[i].reused)
8525 			bpf_map__unpin(&obj->maps[i], NULL);
8526 
8527 	bpf_object_unload(obj);
8528 	pr_warn("failed to load object '%s'\n", obj->path);
8529 	return libbpf_err(err);
8530 }
8531 
8532 int bpf_object__load(struct bpf_object *obj)
8533 {
8534 	return bpf_object_load(obj, 0, NULL);
8535 }
8536 
8537 static int make_parent_dir(const char *path)
8538 {
8539 	char *cp, errmsg[STRERR_BUFSIZE];
8540 	char *dname, *dir;
8541 	int err = 0;
8542 
8543 	dname = strdup(path);
8544 	if (dname == NULL)
8545 		return -ENOMEM;
8546 
8547 	dir = dirname(dname);
8548 	if (mkdir(dir, 0700) && errno != EEXIST)
8549 		err = -errno;
8550 
8551 	free(dname);
8552 	if (err) {
8553 		cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
8554 		pr_warn("failed to mkdir %s: %s\n", path, cp);
8555 	}
8556 	return err;
8557 }
8558 
8559 static int check_path(const char *path)
8560 {
8561 	char *cp, errmsg[STRERR_BUFSIZE];
8562 	struct statfs st_fs;
8563 	char *dname, *dir;
8564 	int err = 0;
8565 
8566 	if (path == NULL)
8567 		return -EINVAL;
8568 
8569 	dname = strdup(path);
8570 	if (dname == NULL)
8571 		return -ENOMEM;
8572 
8573 	dir = dirname(dname);
8574 	if (statfs(dir, &st_fs)) {
8575 		cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
8576 		pr_warn("failed to statfs %s: %s\n", dir, cp);
8577 		err = -errno;
8578 	}
8579 	free(dname);
8580 
8581 	if (!err && st_fs.f_type != BPF_FS_MAGIC) {
8582 		pr_warn("specified path %s is not on BPF FS\n", path);
8583 		err = -EINVAL;
8584 	}
8585 
8586 	return err;
8587 }
8588 
8589 int bpf_program__pin(struct bpf_program *prog, const char *path)
8590 {
8591 	char *cp, errmsg[STRERR_BUFSIZE];
8592 	int err;
8593 
8594 	if (prog->fd < 0) {
8595 		pr_warn("prog '%s': can't pin program that wasn't loaded\n", prog->name);
8596 		return libbpf_err(-EINVAL);
8597 	}
8598 
8599 	err = make_parent_dir(path);
8600 	if (err)
8601 		return libbpf_err(err);
8602 
8603 	err = check_path(path);
8604 	if (err)
8605 		return libbpf_err(err);
8606 
8607 	if (bpf_obj_pin(prog->fd, path)) {
8608 		err = -errno;
8609 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
8610 		pr_warn("prog '%s': failed to pin at '%s': %s\n", prog->name, path, cp);
8611 		return libbpf_err(err);
8612 	}
8613 
8614 	pr_debug("prog '%s': pinned at '%s'\n", prog->name, path);
8615 	return 0;
8616 }
8617 
8618 int bpf_program__unpin(struct bpf_program *prog, const char *path)
8619 {
8620 	int err;
8621 
8622 	if (prog->fd < 0) {
8623 		pr_warn("prog '%s': can't unpin program that wasn't loaded\n", prog->name);
8624 		return libbpf_err(-EINVAL);
8625 	}
8626 
8627 	err = check_path(path);
8628 	if (err)
8629 		return libbpf_err(err);
8630 
8631 	err = unlink(path);
8632 	if (err)
8633 		return libbpf_err(-errno);
8634 
8635 	pr_debug("prog '%s': unpinned from '%s'\n", prog->name, path);
8636 	return 0;
8637 }
8638 
8639 int bpf_map__pin(struct bpf_map *map, const char *path)
8640 {
8641 	char *cp, errmsg[STRERR_BUFSIZE];
8642 	int err;
8643 
8644 	if (map == NULL) {
8645 		pr_warn("invalid map pointer\n");
8646 		return libbpf_err(-EINVAL);
8647 	}
8648 
8649 	if (map->pin_path) {
8650 		if (path && strcmp(path, map->pin_path)) {
8651 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8652 				bpf_map__name(map), map->pin_path, path);
8653 			return libbpf_err(-EINVAL);
8654 		} else if (map->pinned) {
8655 			pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
8656 				 bpf_map__name(map), map->pin_path);
8657 			return 0;
8658 		}
8659 	} else {
8660 		if (!path) {
8661 			pr_warn("missing a path to pin map '%s' at\n",
8662 				bpf_map__name(map));
8663 			return libbpf_err(-EINVAL);
8664 		} else if (map->pinned) {
8665 			pr_warn("map '%s' already pinned\n", bpf_map__name(map));
8666 			return libbpf_err(-EEXIST);
8667 		}
8668 
8669 		map->pin_path = strdup(path);
8670 		if (!map->pin_path) {
8671 			err = -errno;
8672 			goto out_err;
8673 		}
8674 	}
8675 
8676 	err = make_parent_dir(map->pin_path);
8677 	if (err)
8678 		return libbpf_err(err);
8679 
8680 	err = check_path(map->pin_path);
8681 	if (err)
8682 		return libbpf_err(err);
8683 
8684 	if (bpf_obj_pin(map->fd, map->pin_path)) {
8685 		err = -errno;
8686 		goto out_err;
8687 	}
8688 
8689 	map->pinned = true;
8690 	pr_debug("pinned map '%s'\n", map->pin_path);
8691 
8692 	return 0;
8693 
8694 out_err:
8695 	cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
8696 	pr_warn("failed to pin map: %s\n", cp);
8697 	return libbpf_err(err);
8698 }
8699 
8700 int bpf_map__unpin(struct bpf_map *map, const char *path)
8701 {
8702 	int err;
8703 
8704 	if (map == NULL) {
8705 		pr_warn("invalid map pointer\n");
8706 		return libbpf_err(-EINVAL);
8707 	}
8708 
8709 	if (map->pin_path) {
8710 		if (path && strcmp(path, map->pin_path)) {
8711 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8712 				bpf_map__name(map), map->pin_path, path);
8713 			return libbpf_err(-EINVAL);
8714 		}
8715 		path = map->pin_path;
8716 	} else if (!path) {
8717 		pr_warn("no path to unpin map '%s' from\n",
8718 			bpf_map__name(map));
8719 		return libbpf_err(-EINVAL);
8720 	}
8721 
8722 	err = check_path(path);
8723 	if (err)
8724 		return libbpf_err(err);
8725 
8726 	err = unlink(path);
8727 	if (err != 0)
8728 		return libbpf_err(-errno);
8729 
8730 	map->pinned = false;
8731 	pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
8732 
8733 	return 0;
8734 }
8735 
8736 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
8737 {
8738 	char *new = NULL;
8739 
8740 	if (path) {
8741 		new = strdup(path);
8742 		if (!new)
8743 			return libbpf_err(-errno);
8744 	}
8745 
8746 	free(map->pin_path);
8747 	map->pin_path = new;
8748 	return 0;
8749 }
8750 
8751 __alias(bpf_map__pin_path)
8752 const char *bpf_map__get_pin_path(const struct bpf_map *map);
8753 
8754 const char *bpf_map__pin_path(const struct bpf_map *map)
8755 {
8756 	return map->pin_path;
8757 }
8758 
8759 bool bpf_map__is_pinned(const struct bpf_map *map)
8760 {
8761 	return map->pinned;
8762 }
8763 
8764 static void sanitize_pin_path(char *s)
8765 {
8766 	/* bpffs disallows periods in path names */
8767 	while (*s) {
8768 		if (*s == '.')
8769 			*s = '_';
8770 		s++;
8771 	}
8772 }
8773 
8774 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
8775 {
8776 	struct bpf_map *map;
8777 	int err;
8778 
8779 	if (!obj)
8780 		return libbpf_err(-ENOENT);
8781 
8782 	if (!obj->loaded) {
8783 		pr_warn("object not yet loaded; load it first\n");
8784 		return libbpf_err(-ENOENT);
8785 	}
8786 
8787 	bpf_object__for_each_map(map, obj) {
8788 		char *pin_path = NULL;
8789 		char buf[PATH_MAX];
8790 
8791 		if (!map->autocreate)
8792 			continue;
8793 
8794 		if (path) {
8795 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8796 			if (err)
8797 				goto err_unpin_maps;
8798 			sanitize_pin_path(buf);
8799 			pin_path = buf;
8800 		} else if (!map->pin_path) {
8801 			continue;
8802 		}
8803 
8804 		err = bpf_map__pin(map, pin_path);
8805 		if (err)
8806 			goto err_unpin_maps;
8807 	}
8808 
8809 	return 0;
8810 
8811 err_unpin_maps:
8812 	while ((map = bpf_object__prev_map(obj, map))) {
8813 		if (!map->pin_path)
8814 			continue;
8815 
8816 		bpf_map__unpin(map, NULL);
8817 	}
8818 
8819 	return libbpf_err(err);
8820 }
8821 
8822 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
8823 {
8824 	struct bpf_map *map;
8825 	int err;
8826 
8827 	if (!obj)
8828 		return libbpf_err(-ENOENT);
8829 
8830 	bpf_object__for_each_map(map, obj) {
8831 		char *pin_path = NULL;
8832 		char buf[PATH_MAX];
8833 
8834 		if (path) {
8835 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8836 			if (err)
8837 				return libbpf_err(err);
8838 			sanitize_pin_path(buf);
8839 			pin_path = buf;
8840 		} else if (!map->pin_path) {
8841 			continue;
8842 		}
8843 
8844 		err = bpf_map__unpin(map, pin_path);
8845 		if (err)
8846 			return libbpf_err(err);
8847 	}
8848 
8849 	return 0;
8850 }
8851 
8852 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
8853 {
8854 	struct bpf_program *prog;
8855 	char buf[PATH_MAX];
8856 	int err;
8857 
8858 	if (!obj)
8859 		return libbpf_err(-ENOENT);
8860 
8861 	if (!obj->loaded) {
8862 		pr_warn("object not yet loaded; load it first\n");
8863 		return libbpf_err(-ENOENT);
8864 	}
8865 
8866 	bpf_object__for_each_program(prog, obj) {
8867 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
8868 		if (err)
8869 			goto err_unpin_programs;
8870 
8871 		err = bpf_program__pin(prog, buf);
8872 		if (err)
8873 			goto err_unpin_programs;
8874 	}
8875 
8876 	return 0;
8877 
8878 err_unpin_programs:
8879 	while ((prog = bpf_object__prev_program(obj, prog))) {
8880 		if (pathname_concat(buf, sizeof(buf), path, prog->name))
8881 			continue;
8882 
8883 		bpf_program__unpin(prog, buf);
8884 	}
8885 
8886 	return libbpf_err(err);
8887 }
8888 
8889 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
8890 {
8891 	struct bpf_program *prog;
8892 	int err;
8893 
8894 	if (!obj)
8895 		return libbpf_err(-ENOENT);
8896 
8897 	bpf_object__for_each_program(prog, obj) {
8898 		char buf[PATH_MAX];
8899 
8900 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
8901 		if (err)
8902 			return libbpf_err(err);
8903 
8904 		err = bpf_program__unpin(prog, buf);
8905 		if (err)
8906 			return libbpf_err(err);
8907 	}
8908 
8909 	return 0;
8910 }
8911 
8912 int bpf_object__pin(struct bpf_object *obj, const char *path)
8913 {
8914 	int err;
8915 
8916 	err = bpf_object__pin_maps(obj, path);
8917 	if (err)
8918 		return libbpf_err(err);
8919 
8920 	err = bpf_object__pin_programs(obj, path);
8921 	if (err) {
8922 		bpf_object__unpin_maps(obj, path);
8923 		return libbpf_err(err);
8924 	}
8925 
8926 	return 0;
8927 }
8928 
8929 int bpf_object__unpin(struct bpf_object *obj, const char *path)
8930 {
8931 	int err;
8932 
8933 	err = bpf_object__unpin_programs(obj, path);
8934 	if (err)
8935 		return libbpf_err(err);
8936 
8937 	err = bpf_object__unpin_maps(obj, path);
8938 	if (err)
8939 		return libbpf_err(err);
8940 
8941 	return 0;
8942 }
8943 
8944 static void bpf_map__destroy(struct bpf_map *map)
8945 {
8946 	if (map->inner_map) {
8947 		bpf_map__destroy(map->inner_map);
8948 		zfree(&map->inner_map);
8949 	}
8950 
8951 	zfree(&map->init_slots);
8952 	map->init_slots_sz = 0;
8953 
8954 	if (map->mmaped) {
8955 		size_t mmap_sz;
8956 
8957 		mmap_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
8958 		munmap(map->mmaped, mmap_sz);
8959 		map->mmaped = NULL;
8960 	}
8961 
8962 	if (map->st_ops) {
8963 		zfree(&map->st_ops->data);
8964 		zfree(&map->st_ops->progs);
8965 		zfree(&map->st_ops->kern_func_off);
8966 		zfree(&map->st_ops);
8967 	}
8968 
8969 	zfree(&map->name);
8970 	zfree(&map->real_name);
8971 	zfree(&map->pin_path);
8972 
8973 	if (map->fd >= 0)
8974 		zclose(map->fd);
8975 }
8976 
8977 void bpf_object__close(struct bpf_object *obj)
8978 {
8979 	size_t i;
8980 
8981 	if (IS_ERR_OR_NULL(obj))
8982 		return;
8983 
8984 	usdt_manager_free(obj->usdt_man);
8985 	obj->usdt_man = NULL;
8986 
8987 	bpf_gen__free(obj->gen_loader);
8988 	bpf_object__elf_finish(obj);
8989 	bpf_object_unload(obj);
8990 	btf__free(obj->btf);
8991 	btf__free(obj->btf_vmlinux);
8992 	btf_ext__free(obj->btf_ext);
8993 
8994 	for (i = 0; i < obj->nr_maps; i++)
8995 		bpf_map__destroy(&obj->maps[i]);
8996 
8997 	zfree(&obj->btf_custom_path);
8998 	zfree(&obj->kconfig);
8999 
9000 	for (i = 0; i < obj->nr_extern; i++)
9001 		zfree(&obj->externs[i].essent_name);
9002 
9003 	zfree(&obj->externs);
9004 	obj->nr_extern = 0;
9005 
9006 	zfree(&obj->maps);
9007 	obj->nr_maps = 0;
9008 
9009 	if (obj->programs && obj->nr_programs) {
9010 		for (i = 0; i < obj->nr_programs; i++)
9011 			bpf_program__exit(&obj->programs[i]);
9012 	}
9013 	zfree(&obj->programs);
9014 
9015 	free(obj);
9016 }
9017 
9018 const char *bpf_object__name(const struct bpf_object *obj)
9019 {
9020 	return obj ? obj->name : libbpf_err_ptr(-EINVAL);
9021 }
9022 
9023 unsigned int bpf_object__kversion(const struct bpf_object *obj)
9024 {
9025 	return obj ? obj->kern_version : 0;
9026 }
9027 
9028 struct btf *bpf_object__btf(const struct bpf_object *obj)
9029 {
9030 	return obj ? obj->btf : NULL;
9031 }
9032 
9033 int bpf_object__btf_fd(const struct bpf_object *obj)
9034 {
9035 	return obj->btf ? btf__fd(obj->btf) : -1;
9036 }
9037 
9038 int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
9039 {
9040 	if (obj->loaded)
9041 		return libbpf_err(-EINVAL);
9042 
9043 	obj->kern_version = kern_version;
9044 
9045 	return 0;
9046 }
9047 
9048 int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
9049 {
9050 	struct bpf_gen *gen;
9051 
9052 	if (!opts)
9053 		return -EFAULT;
9054 	if (!OPTS_VALID(opts, gen_loader_opts))
9055 		return -EINVAL;
9056 	gen = calloc(sizeof(*gen), 1);
9057 	if (!gen)
9058 		return -ENOMEM;
9059 	gen->opts = opts;
9060 	obj->gen_loader = gen;
9061 	return 0;
9062 }
9063 
9064 static struct bpf_program *
9065 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
9066 		    bool forward)
9067 {
9068 	size_t nr_programs = obj->nr_programs;
9069 	ssize_t idx;
9070 
9071 	if (!nr_programs)
9072 		return NULL;
9073 
9074 	if (!p)
9075 		/* Iter from the beginning */
9076 		return forward ? &obj->programs[0] :
9077 			&obj->programs[nr_programs - 1];
9078 
9079 	if (p->obj != obj) {
9080 		pr_warn("error: program handler doesn't match object\n");
9081 		return errno = EINVAL, NULL;
9082 	}
9083 
9084 	idx = (p - obj->programs) + (forward ? 1 : -1);
9085 	if (idx >= obj->nr_programs || idx < 0)
9086 		return NULL;
9087 	return &obj->programs[idx];
9088 }
9089 
9090 struct bpf_program *
9091 bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
9092 {
9093 	struct bpf_program *prog = prev;
9094 
9095 	do {
9096 		prog = __bpf_program__iter(prog, obj, true);
9097 	} while (prog && prog_is_subprog(obj, prog));
9098 
9099 	return prog;
9100 }
9101 
9102 struct bpf_program *
9103 bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
9104 {
9105 	struct bpf_program *prog = next;
9106 
9107 	do {
9108 		prog = __bpf_program__iter(prog, obj, false);
9109 	} while (prog && prog_is_subprog(obj, prog));
9110 
9111 	return prog;
9112 }
9113 
9114 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
9115 {
9116 	prog->prog_ifindex = ifindex;
9117 }
9118 
9119 const char *bpf_program__name(const struct bpf_program *prog)
9120 {
9121 	return prog->name;
9122 }
9123 
9124 const char *bpf_program__section_name(const struct bpf_program *prog)
9125 {
9126 	return prog->sec_name;
9127 }
9128 
9129 bool bpf_program__autoload(const struct bpf_program *prog)
9130 {
9131 	return prog->autoload;
9132 }
9133 
9134 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
9135 {
9136 	if (prog->obj->loaded)
9137 		return libbpf_err(-EINVAL);
9138 
9139 	prog->autoload = autoload;
9140 	return 0;
9141 }
9142 
9143 bool bpf_program__autoattach(const struct bpf_program *prog)
9144 {
9145 	return prog->autoattach;
9146 }
9147 
9148 void bpf_program__set_autoattach(struct bpf_program *prog, bool autoattach)
9149 {
9150 	prog->autoattach = autoattach;
9151 }
9152 
9153 const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
9154 {
9155 	return prog->insns;
9156 }
9157 
9158 size_t bpf_program__insn_cnt(const struct bpf_program *prog)
9159 {
9160 	return prog->insns_cnt;
9161 }
9162 
9163 int bpf_program__set_insns(struct bpf_program *prog,
9164 			   struct bpf_insn *new_insns, size_t new_insn_cnt)
9165 {
9166 	struct bpf_insn *insns;
9167 
9168 	if (prog->obj->loaded)
9169 		return -EBUSY;
9170 
9171 	insns = libbpf_reallocarray(prog->insns, new_insn_cnt, sizeof(*insns));
9172 	/* NULL is a valid return from reallocarray if the new count is zero */
9173 	if (!insns && new_insn_cnt) {
9174 		pr_warn("prog '%s': failed to realloc prog code\n", prog->name);
9175 		return -ENOMEM;
9176 	}
9177 	memcpy(insns, new_insns, new_insn_cnt * sizeof(*insns));
9178 
9179 	prog->insns = insns;
9180 	prog->insns_cnt = new_insn_cnt;
9181 	return 0;
9182 }
9183 
9184 int bpf_program__fd(const struct bpf_program *prog)
9185 {
9186 	if (!prog)
9187 		return libbpf_err(-EINVAL);
9188 
9189 	if (prog->fd < 0)
9190 		return libbpf_err(-ENOENT);
9191 
9192 	return prog->fd;
9193 }
9194 
9195 __alias(bpf_program__type)
9196 enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog);
9197 
9198 enum bpf_prog_type bpf_program__type(const struct bpf_program *prog)
9199 {
9200 	return prog->type;
9201 }
9202 
9203 static size_t custom_sec_def_cnt;
9204 static struct bpf_sec_def *custom_sec_defs;
9205 static struct bpf_sec_def custom_fallback_def;
9206 static bool has_custom_fallback_def;
9207 static int last_custom_sec_def_handler_id;
9208 
9209 int bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
9210 {
9211 	if (prog->obj->loaded)
9212 		return libbpf_err(-EBUSY);
9213 
9214 	/* if type is not changed, do nothing */
9215 	if (prog->type == type)
9216 		return 0;
9217 
9218 	prog->type = type;
9219 
9220 	/* If a program type was changed, we need to reset associated SEC()
9221 	 * handler, as it will be invalid now. The only exception is a generic
9222 	 * fallback handler, which by definition is program type-agnostic and
9223 	 * is a catch-all custom handler, optionally set by the application,
9224 	 * so should be able to handle any type of BPF program.
9225 	 */
9226 	if (prog->sec_def != &custom_fallback_def)
9227 		prog->sec_def = NULL;
9228 	return 0;
9229 }
9230 
9231 __alias(bpf_program__expected_attach_type)
9232 enum bpf_attach_type bpf_program__get_expected_attach_type(const struct bpf_program *prog);
9233 
9234 enum bpf_attach_type bpf_program__expected_attach_type(const struct bpf_program *prog)
9235 {
9236 	return prog->expected_attach_type;
9237 }
9238 
9239 int bpf_program__set_expected_attach_type(struct bpf_program *prog,
9240 					   enum bpf_attach_type type)
9241 {
9242 	if (prog->obj->loaded)
9243 		return libbpf_err(-EBUSY);
9244 
9245 	prog->expected_attach_type = type;
9246 	return 0;
9247 }
9248 
9249 __u32 bpf_program__flags(const struct bpf_program *prog)
9250 {
9251 	return prog->prog_flags;
9252 }
9253 
9254 int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
9255 {
9256 	if (prog->obj->loaded)
9257 		return libbpf_err(-EBUSY);
9258 
9259 	prog->prog_flags = flags;
9260 	return 0;
9261 }
9262 
9263 __u32 bpf_program__log_level(const struct bpf_program *prog)
9264 {
9265 	return prog->log_level;
9266 }
9267 
9268 int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
9269 {
9270 	if (prog->obj->loaded)
9271 		return libbpf_err(-EBUSY);
9272 
9273 	prog->log_level = log_level;
9274 	return 0;
9275 }
9276 
9277 const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
9278 {
9279 	*log_size = prog->log_size;
9280 	return prog->log_buf;
9281 }
9282 
9283 int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
9284 {
9285 	if (log_size && !log_buf)
9286 		return -EINVAL;
9287 	if (prog->log_size > UINT_MAX)
9288 		return -EINVAL;
9289 	if (prog->obj->loaded)
9290 		return -EBUSY;
9291 
9292 	prog->log_buf = log_buf;
9293 	prog->log_size = log_size;
9294 	return 0;
9295 }
9296 
9297 #define SEC_DEF(sec_pfx, ptype, atype, flags, ...) {			    \
9298 	.sec = (char *)sec_pfx,						    \
9299 	.prog_type = BPF_PROG_TYPE_##ptype,				    \
9300 	.expected_attach_type = atype,					    \
9301 	.cookie = (long)(flags),					    \
9302 	.prog_prepare_load_fn = libbpf_prepare_prog_load,		    \
9303 	__VA_ARGS__							    \
9304 }
9305 
9306 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9307 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9308 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9309 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9310 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9311 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9312 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9313 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9314 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9315 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9316 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9317 
9318 static const struct bpf_sec_def section_defs[] = {
9319 	SEC_DEF("socket",		SOCKET_FILTER, 0, SEC_NONE),
9320 	SEC_DEF("sk_reuseport/migrate",	SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE),
9321 	SEC_DEF("sk_reuseport",		SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE),
9322 	SEC_DEF("kprobe+",		KPROBE,	0, SEC_NONE, attach_kprobe),
9323 	SEC_DEF("uprobe+",		KPROBE,	0, SEC_NONE, attach_uprobe),
9324 	SEC_DEF("uprobe.s+",		KPROBE,	0, SEC_SLEEPABLE, attach_uprobe),
9325 	SEC_DEF("kretprobe+",		KPROBE, 0, SEC_NONE, attach_kprobe),
9326 	SEC_DEF("uretprobe+",		KPROBE, 0, SEC_NONE, attach_uprobe),
9327 	SEC_DEF("uretprobe.s+",		KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
9328 	SEC_DEF("kprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
9329 	SEC_DEF("kretprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
9330 	SEC_DEF("uprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
9331 	SEC_DEF("uretprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
9332 	SEC_DEF("uprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
9333 	SEC_DEF("uretprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
9334 	SEC_DEF("ksyscall+",		KPROBE,	0, SEC_NONE, attach_ksyscall),
9335 	SEC_DEF("kretsyscall+",		KPROBE, 0, SEC_NONE, attach_ksyscall),
9336 	SEC_DEF("usdt+",		KPROBE,	0, SEC_USDT, attach_usdt),
9337 	SEC_DEF("usdt.s+",		KPROBE,	0, SEC_USDT | SEC_SLEEPABLE, attach_usdt),
9338 	SEC_DEF("tc/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE), /* alias for tcx */
9339 	SEC_DEF("tc/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),  /* alias for tcx */
9340 	SEC_DEF("tcx/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE),
9341 	SEC_DEF("tcx/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),
9342 	SEC_DEF("tc",			SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
9343 	SEC_DEF("classifier",		SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
9344 	SEC_DEF("action",		SCHED_ACT, 0, SEC_NONE), /* deprecated / legacy, use tcx */
9345 	SEC_DEF("netkit/primary",	SCHED_CLS, BPF_NETKIT_PRIMARY, SEC_NONE),
9346 	SEC_DEF("netkit/peer",		SCHED_CLS, BPF_NETKIT_PEER, SEC_NONE),
9347 	SEC_DEF("tracepoint+",		TRACEPOINT, 0, SEC_NONE, attach_tp),
9348 	SEC_DEF("tp+",			TRACEPOINT, 0, SEC_NONE, attach_tp),
9349 	SEC_DEF("raw_tracepoint+",	RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
9350 	SEC_DEF("raw_tp+",		RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
9351 	SEC_DEF("raw_tracepoint.w+",	RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
9352 	SEC_DEF("raw_tp.w+",		RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
9353 	SEC_DEF("tp_btf+",		TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
9354 	SEC_DEF("fentry+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
9355 	SEC_DEF("fmod_ret+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
9356 	SEC_DEF("fexit+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
9357 	SEC_DEF("fentry.s+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
9358 	SEC_DEF("fmod_ret.s+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
9359 	SEC_DEF("fexit.s+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
9360 	SEC_DEF("freplace+",		EXT, 0, SEC_ATTACH_BTF, attach_trace),
9361 	SEC_DEF("lsm+",			LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
9362 	SEC_DEF("lsm.s+",		LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
9363 	SEC_DEF("lsm_cgroup+",		LSM, BPF_LSM_CGROUP, SEC_ATTACH_BTF),
9364 	SEC_DEF("iter+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
9365 	SEC_DEF("iter.s+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_iter),
9366 	SEC_DEF("syscall",		SYSCALL, 0, SEC_SLEEPABLE),
9367 	SEC_DEF("xdp.frags/devmap",	XDP, BPF_XDP_DEVMAP, SEC_XDP_FRAGS),
9368 	SEC_DEF("xdp/devmap",		XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
9369 	SEC_DEF("xdp.frags/cpumap",	XDP, BPF_XDP_CPUMAP, SEC_XDP_FRAGS),
9370 	SEC_DEF("xdp/cpumap",		XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
9371 	SEC_DEF("xdp.frags",		XDP, BPF_XDP, SEC_XDP_FRAGS),
9372 	SEC_DEF("xdp",			XDP, BPF_XDP, SEC_ATTACHABLE_OPT),
9373 	SEC_DEF("perf_event",		PERF_EVENT, 0, SEC_NONE),
9374 	SEC_DEF("lwt_in",		LWT_IN, 0, SEC_NONE),
9375 	SEC_DEF("lwt_out",		LWT_OUT, 0, SEC_NONE),
9376 	SEC_DEF("lwt_xmit",		LWT_XMIT, 0, SEC_NONE),
9377 	SEC_DEF("lwt_seg6local",	LWT_SEG6LOCAL, 0, SEC_NONE),
9378 	SEC_DEF("sockops",		SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT),
9379 	SEC_DEF("sk_skb/stream_parser",	SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT),
9380 	SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT),
9381 	SEC_DEF("sk_skb",		SK_SKB, 0, SEC_NONE),
9382 	SEC_DEF("sk_msg",		SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT),
9383 	SEC_DEF("lirc_mode2",		LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT),
9384 	SEC_DEF("flow_dissector",	FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT),
9385 	SEC_DEF("cgroup_skb/ingress",	CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT),
9386 	SEC_DEF("cgroup_skb/egress",	CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT),
9387 	SEC_DEF("cgroup/skb",		CGROUP_SKB, 0, SEC_NONE),
9388 	SEC_DEF("cgroup/sock_create",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE),
9389 	SEC_DEF("cgroup/sock_release",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE),
9390 	SEC_DEF("cgroup/sock",		CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT),
9391 	SEC_DEF("cgroup/post_bind4",	CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE),
9392 	SEC_DEF("cgroup/post_bind6",	CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE),
9393 	SEC_DEF("cgroup/bind4",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE),
9394 	SEC_DEF("cgroup/bind6",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE),
9395 	SEC_DEF("cgroup/connect4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE),
9396 	SEC_DEF("cgroup/connect6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE),
9397 	SEC_DEF("cgroup/connect_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_CONNECT, SEC_ATTACHABLE),
9398 	SEC_DEF("cgroup/sendmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE),
9399 	SEC_DEF("cgroup/sendmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE),
9400 	SEC_DEF("cgroup/sendmsg_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_SENDMSG, SEC_ATTACHABLE),
9401 	SEC_DEF("cgroup/recvmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE),
9402 	SEC_DEF("cgroup/recvmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE),
9403 	SEC_DEF("cgroup/recvmsg_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_RECVMSG, SEC_ATTACHABLE),
9404 	SEC_DEF("cgroup/getpeername4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE),
9405 	SEC_DEF("cgroup/getpeername6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE),
9406 	SEC_DEF("cgroup/getpeername_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETPEERNAME, SEC_ATTACHABLE),
9407 	SEC_DEF("cgroup/getsockname4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE),
9408 	SEC_DEF("cgroup/getsockname6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE),
9409 	SEC_DEF("cgroup/getsockname_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETSOCKNAME, SEC_ATTACHABLE),
9410 	SEC_DEF("cgroup/sysctl",	CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE),
9411 	SEC_DEF("cgroup/getsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE),
9412 	SEC_DEF("cgroup/setsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE),
9413 	SEC_DEF("cgroup/dev",		CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT),
9414 	SEC_DEF("struct_ops+",		STRUCT_OPS, 0, SEC_NONE),
9415 	SEC_DEF("struct_ops.s+",	STRUCT_OPS, 0, SEC_SLEEPABLE),
9416 	SEC_DEF("sk_lookup",		SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE),
9417 	SEC_DEF("netfilter",		NETFILTER, BPF_NETFILTER, SEC_NONE),
9418 };
9419 
9420 int libbpf_register_prog_handler(const char *sec,
9421 				 enum bpf_prog_type prog_type,
9422 				 enum bpf_attach_type exp_attach_type,
9423 				 const struct libbpf_prog_handler_opts *opts)
9424 {
9425 	struct bpf_sec_def *sec_def;
9426 
9427 	if (!OPTS_VALID(opts, libbpf_prog_handler_opts))
9428 		return libbpf_err(-EINVAL);
9429 
9430 	if (last_custom_sec_def_handler_id == INT_MAX) /* prevent overflow */
9431 		return libbpf_err(-E2BIG);
9432 
9433 	if (sec) {
9434 		sec_def = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt + 1,
9435 					      sizeof(*sec_def));
9436 		if (!sec_def)
9437 			return libbpf_err(-ENOMEM);
9438 
9439 		custom_sec_defs = sec_def;
9440 		sec_def = &custom_sec_defs[custom_sec_def_cnt];
9441 	} else {
9442 		if (has_custom_fallback_def)
9443 			return libbpf_err(-EBUSY);
9444 
9445 		sec_def = &custom_fallback_def;
9446 	}
9447 
9448 	sec_def->sec = sec ? strdup(sec) : NULL;
9449 	if (sec && !sec_def->sec)
9450 		return libbpf_err(-ENOMEM);
9451 
9452 	sec_def->prog_type = prog_type;
9453 	sec_def->expected_attach_type = exp_attach_type;
9454 	sec_def->cookie = OPTS_GET(opts, cookie, 0);
9455 
9456 	sec_def->prog_setup_fn = OPTS_GET(opts, prog_setup_fn, NULL);
9457 	sec_def->prog_prepare_load_fn = OPTS_GET(opts, prog_prepare_load_fn, NULL);
9458 	sec_def->prog_attach_fn = OPTS_GET(opts, prog_attach_fn, NULL);
9459 
9460 	sec_def->handler_id = ++last_custom_sec_def_handler_id;
9461 
9462 	if (sec)
9463 		custom_sec_def_cnt++;
9464 	else
9465 		has_custom_fallback_def = true;
9466 
9467 	return sec_def->handler_id;
9468 }
9469 
9470 int libbpf_unregister_prog_handler(int handler_id)
9471 {
9472 	struct bpf_sec_def *sec_defs;
9473 	int i;
9474 
9475 	if (handler_id <= 0)
9476 		return libbpf_err(-EINVAL);
9477 
9478 	if (has_custom_fallback_def && custom_fallback_def.handler_id == handler_id) {
9479 		memset(&custom_fallback_def, 0, sizeof(custom_fallback_def));
9480 		has_custom_fallback_def = false;
9481 		return 0;
9482 	}
9483 
9484 	for (i = 0; i < custom_sec_def_cnt; i++) {
9485 		if (custom_sec_defs[i].handler_id == handler_id)
9486 			break;
9487 	}
9488 
9489 	if (i == custom_sec_def_cnt)
9490 		return libbpf_err(-ENOENT);
9491 
9492 	free(custom_sec_defs[i].sec);
9493 	for (i = i + 1; i < custom_sec_def_cnt; i++)
9494 		custom_sec_defs[i - 1] = custom_sec_defs[i];
9495 	custom_sec_def_cnt--;
9496 
9497 	/* try to shrink the array, but it's ok if we couldn't */
9498 	sec_defs = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt, sizeof(*sec_defs));
9499 	/* if new count is zero, reallocarray can return a valid NULL result;
9500 	 * in this case the previous pointer will be freed, so we *have to*
9501 	 * reassign old pointer to the new value (even if it's NULL)
9502 	 */
9503 	if (sec_defs || custom_sec_def_cnt == 0)
9504 		custom_sec_defs = sec_defs;
9505 
9506 	return 0;
9507 }
9508 
9509 static bool sec_def_matches(const struct bpf_sec_def *sec_def, const char *sec_name)
9510 {
9511 	size_t len = strlen(sec_def->sec);
9512 
9513 	/* "type/" always has to have proper SEC("type/extras") form */
9514 	if (sec_def->sec[len - 1] == '/') {
9515 		if (str_has_pfx(sec_name, sec_def->sec))
9516 			return true;
9517 		return false;
9518 	}
9519 
9520 	/* "type+" means it can be either exact SEC("type") or
9521 	 * well-formed SEC("type/extras") with proper '/' separator
9522 	 */
9523 	if (sec_def->sec[len - 1] == '+') {
9524 		len--;
9525 		/* not even a prefix */
9526 		if (strncmp(sec_name, sec_def->sec, len) != 0)
9527 			return false;
9528 		/* exact match or has '/' separator */
9529 		if (sec_name[len] == '\0' || sec_name[len] == '/')
9530 			return true;
9531 		return false;
9532 	}
9533 
9534 	return strcmp(sec_name, sec_def->sec) == 0;
9535 }
9536 
9537 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
9538 {
9539 	const struct bpf_sec_def *sec_def;
9540 	int i, n;
9541 
9542 	n = custom_sec_def_cnt;
9543 	for (i = 0; i < n; i++) {
9544 		sec_def = &custom_sec_defs[i];
9545 		if (sec_def_matches(sec_def, sec_name))
9546 			return sec_def;
9547 	}
9548 
9549 	n = ARRAY_SIZE(section_defs);
9550 	for (i = 0; i < n; i++) {
9551 		sec_def = &section_defs[i];
9552 		if (sec_def_matches(sec_def, sec_name))
9553 			return sec_def;
9554 	}
9555 
9556 	if (has_custom_fallback_def)
9557 		return &custom_fallback_def;
9558 
9559 	return NULL;
9560 }
9561 
9562 #define MAX_TYPE_NAME_SIZE 32
9563 
9564 static char *libbpf_get_type_names(bool attach_type)
9565 {
9566 	int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
9567 	char *buf;
9568 
9569 	buf = malloc(len);
9570 	if (!buf)
9571 		return NULL;
9572 
9573 	buf[0] = '\0';
9574 	/* Forge string buf with all available names */
9575 	for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
9576 		const struct bpf_sec_def *sec_def = &section_defs[i];
9577 
9578 		if (attach_type) {
9579 			if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
9580 				continue;
9581 
9582 			if (!(sec_def->cookie & SEC_ATTACHABLE))
9583 				continue;
9584 		}
9585 
9586 		if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
9587 			free(buf);
9588 			return NULL;
9589 		}
9590 		strcat(buf, " ");
9591 		strcat(buf, section_defs[i].sec);
9592 	}
9593 
9594 	return buf;
9595 }
9596 
9597 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
9598 			     enum bpf_attach_type *expected_attach_type)
9599 {
9600 	const struct bpf_sec_def *sec_def;
9601 	char *type_names;
9602 
9603 	if (!name)
9604 		return libbpf_err(-EINVAL);
9605 
9606 	sec_def = find_sec_def(name);
9607 	if (sec_def) {
9608 		*prog_type = sec_def->prog_type;
9609 		*expected_attach_type = sec_def->expected_attach_type;
9610 		return 0;
9611 	}
9612 
9613 	pr_debug("failed to guess program type from ELF section '%s'\n", name);
9614 	type_names = libbpf_get_type_names(false);
9615 	if (type_names != NULL) {
9616 		pr_debug("supported section(type) names are:%s\n", type_names);
9617 		free(type_names);
9618 	}
9619 
9620 	return libbpf_err(-ESRCH);
9621 }
9622 
9623 const char *libbpf_bpf_attach_type_str(enum bpf_attach_type t)
9624 {
9625 	if (t < 0 || t >= ARRAY_SIZE(attach_type_name))
9626 		return NULL;
9627 
9628 	return attach_type_name[t];
9629 }
9630 
9631 const char *libbpf_bpf_link_type_str(enum bpf_link_type t)
9632 {
9633 	if (t < 0 || t >= ARRAY_SIZE(link_type_name))
9634 		return NULL;
9635 
9636 	return link_type_name[t];
9637 }
9638 
9639 const char *libbpf_bpf_map_type_str(enum bpf_map_type t)
9640 {
9641 	if (t < 0 || t >= ARRAY_SIZE(map_type_name))
9642 		return NULL;
9643 
9644 	return map_type_name[t];
9645 }
9646 
9647 const char *libbpf_bpf_prog_type_str(enum bpf_prog_type t)
9648 {
9649 	if (t < 0 || t >= ARRAY_SIZE(prog_type_name))
9650 		return NULL;
9651 
9652 	return prog_type_name[t];
9653 }
9654 
9655 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
9656 						     int sec_idx,
9657 						     size_t offset)
9658 {
9659 	struct bpf_map *map;
9660 	size_t i;
9661 
9662 	for (i = 0; i < obj->nr_maps; i++) {
9663 		map = &obj->maps[i];
9664 		if (!bpf_map__is_struct_ops(map))
9665 			continue;
9666 		if (map->sec_idx == sec_idx &&
9667 		    map->sec_offset <= offset &&
9668 		    offset - map->sec_offset < map->def.value_size)
9669 			return map;
9670 	}
9671 
9672 	return NULL;
9673 }
9674 
9675 /* Collect the reloc from ELF and populate the st_ops->progs[] */
9676 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
9677 					    Elf64_Shdr *shdr, Elf_Data *data)
9678 {
9679 	const struct btf_member *member;
9680 	struct bpf_struct_ops *st_ops;
9681 	struct bpf_program *prog;
9682 	unsigned int shdr_idx;
9683 	const struct btf *btf;
9684 	struct bpf_map *map;
9685 	unsigned int moff, insn_idx;
9686 	const char *name;
9687 	__u32 member_idx;
9688 	Elf64_Sym *sym;
9689 	Elf64_Rel *rel;
9690 	int i, nrels;
9691 
9692 	btf = obj->btf;
9693 	nrels = shdr->sh_size / shdr->sh_entsize;
9694 	for (i = 0; i < nrels; i++) {
9695 		rel = elf_rel_by_idx(data, i);
9696 		if (!rel) {
9697 			pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
9698 			return -LIBBPF_ERRNO__FORMAT;
9699 		}
9700 
9701 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
9702 		if (!sym) {
9703 			pr_warn("struct_ops reloc: symbol %zx not found\n",
9704 				(size_t)ELF64_R_SYM(rel->r_info));
9705 			return -LIBBPF_ERRNO__FORMAT;
9706 		}
9707 
9708 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
9709 		map = find_struct_ops_map_by_offset(obj, shdr->sh_info, rel->r_offset);
9710 		if (!map) {
9711 			pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
9712 				(size_t)rel->r_offset);
9713 			return -EINVAL;
9714 		}
9715 
9716 		moff = rel->r_offset - map->sec_offset;
9717 		shdr_idx = sym->st_shndx;
9718 		st_ops = map->st_ops;
9719 		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",
9720 			 map->name,
9721 			 (long long)(rel->r_info >> 32),
9722 			 (long long)sym->st_value,
9723 			 shdr_idx, (size_t)rel->r_offset,
9724 			 map->sec_offset, sym->st_name, name);
9725 
9726 		if (shdr_idx >= SHN_LORESERVE) {
9727 			pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
9728 				map->name, (size_t)rel->r_offset, shdr_idx);
9729 			return -LIBBPF_ERRNO__RELOC;
9730 		}
9731 		if (sym->st_value % BPF_INSN_SZ) {
9732 			pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
9733 				map->name, (unsigned long long)sym->st_value);
9734 			return -LIBBPF_ERRNO__FORMAT;
9735 		}
9736 		insn_idx = sym->st_value / BPF_INSN_SZ;
9737 
9738 		member = find_member_by_offset(st_ops->type, moff * 8);
9739 		if (!member) {
9740 			pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
9741 				map->name, moff);
9742 			return -EINVAL;
9743 		}
9744 		member_idx = member - btf_members(st_ops->type);
9745 		name = btf__name_by_offset(btf, member->name_off);
9746 
9747 		if (!resolve_func_ptr(btf, member->type, NULL)) {
9748 			pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
9749 				map->name, name);
9750 			return -EINVAL;
9751 		}
9752 
9753 		prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
9754 		if (!prog) {
9755 			pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
9756 				map->name, shdr_idx, name);
9757 			return -EINVAL;
9758 		}
9759 
9760 		/* prevent the use of BPF prog with invalid type */
9761 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
9762 			pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
9763 				map->name, prog->name);
9764 			return -EINVAL;
9765 		}
9766 
9767 		/* if we haven't yet processed this BPF program, record proper
9768 		 * attach_btf_id and member_idx
9769 		 */
9770 		if (!prog->attach_btf_id) {
9771 			prog->attach_btf_id = st_ops->type_id;
9772 			prog->expected_attach_type = member_idx;
9773 		}
9774 
9775 		/* struct_ops BPF prog can be re-used between multiple
9776 		 * .struct_ops & .struct_ops.link as long as it's the
9777 		 * same struct_ops struct definition and the same
9778 		 * function pointer field
9779 		 */
9780 		if (prog->attach_btf_id != st_ops->type_id ||
9781 		    prog->expected_attach_type != member_idx) {
9782 			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",
9783 				map->name, prog->name, prog->sec_name, prog->type,
9784 				prog->attach_btf_id, prog->expected_attach_type, name);
9785 			return -EINVAL;
9786 		}
9787 
9788 		st_ops->progs[member_idx] = prog;
9789 	}
9790 
9791 	return 0;
9792 }
9793 
9794 #define BTF_TRACE_PREFIX "btf_trace_"
9795 #define BTF_LSM_PREFIX "bpf_lsm_"
9796 #define BTF_ITER_PREFIX "bpf_iter_"
9797 #define BTF_MAX_NAME_SIZE 128
9798 
9799 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
9800 				const char **prefix, int *kind)
9801 {
9802 	switch (attach_type) {
9803 	case BPF_TRACE_RAW_TP:
9804 		*prefix = BTF_TRACE_PREFIX;
9805 		*kind = BTF_KIND_TYPEDEF;
9806 		break;
9807 	case BPF_LSM_MAC:
9808 	case BPF_LSM_CGROUP:
9809 		*prefix = BTF_LSM_PREFIX;
9810 		*kind = BTF_KIND_FUNC;
9811 		break;
9812 	case BPF_TRACE_ITER:
9813 		*prefix = BTF_ITER_PREFIX;
9814 		*kind = BTF_KIND_FUNC;
9815 		break;
9816 	default:
9817 		*prefix = "";
9818 		*kind = BTF_KIND_FUNC;
9819 	}
9820 }
9821 
9822 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
9823 				   const char *name, __u32 kind)
9824 {
9825 	char btf_type_name[BTF_MAX_NAME_SIZE];
9826 	int ret;
9827 
9828 	ret = snprintf(btf_type_name, sizeof(btf_type_name),
9829 		       "%s%s", prefix, name);
9830 	/* snprintf returns the number of characters written excluding the
9831 	 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
9832 	 * indicates truncation.
9833 	 */
9834 	if (ret < 0 || ret >= sizeof(btf_type_name))
9835 		return -ENAMETOOLONG;
9836 	return btf__find_by_name_kind(btf, btf_type_name, kind);
9837 }
9838 
9839 static inline int find_attach_btf_id(struct btf *btf, const char *name,
9840 				     enum bpf_attach_type attach_type)
9841 {
9842 	const char *prefix;
9843 	int kind;
9844 
9845 	btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
9846 	return find_btf_by_prefix_kind(btf, prefix, name, kind);
9847 }
9848 
9849 int libbpf_find_vmlinux_btf_id(const char *name,
9850 			       enum bpf_attach_type attach_type)
9851 {
9852 	struct btf *btf;
9853 	int err;
9854 
9855 	btf = btf__load_vmlinux_btf();
9856 	err = libbpf_get_error(btf);
9857 	if (err) {
9858 		pr_warn("vmlinux BTF is not found\n");
9859 		return libbpf_err(err);
9860 	}
9861 
9862 	err = find_attach_btf_id(btf, name, attach_type);
9863 	if (err <= 0)
9864 		pr_warn("%s is not found in vmlinux BTF\n", name);
9865 
9866 	btf__free(btf);
9867 	return libbpf_err(err);
9868 }
9869 
9870 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
9871 {
9872 	struct bpf_prog_info info;
9873 	__u32 info_len = sizeof(info);
9874 	struct btf *btf;
9875 	int err;
9876 
9877 	memset(&info, 0, info_len);
9878 	err = bpf_prog_get_info_by_fd(attach_prog_fd, &info, &info_len);
9879 	if (err) {
9880 		pr_warn("failed bpf_prog_get_info_by_fd for FD %d: %d\n",
9881 			attach_prog_fd, err);
9882 		return err;
9883 	}
9884 
9885 	err = -EINVAL;
9886 	if (!info.btf_id) {
9887 		pr_warn("The target program doesn't have BTF\n");
9888 		goto out;
9889 	}
9890 	btf = btf__load_from_kernel_by_id(info.btf_id);
9891 	err = libbpf_get_error(btf);
9892 	if (err) {
9893 		pr_warn("Failed to get BTF %d of the program: %d\n", info.btf_id, err);
9894 		goto out;
9895 	}
9896 	err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
9897 	btf__free(btf);
9898 	if (err <= 0) {
9899 		pr_warn("%s is not found in prog's BTF\n", name);
9900 		goto out;
9901 	}
9902 out:
9903 	return err;
9904 }
9905 
9906 static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
9907 			      enum bpf_attach_type attach_type,
9908 			      int *btf_obj_fd, int *btf_type_id)
9909 {
9910 	int ret, i;
9911 
9912 	ret = find_attach_btf_id(obj->btf_vmlinux, attach_name, attach_type);
9913 	if (ret > 0) {
9914 		*btf_obj_fd = 0; /* vmlinux BTF */
9915 		*btf_type_id = ret;
9916 		return 0;
9917 	}
9918 	if (ret != -ENOENT)
9919 		return ret;
9920 
9921 	ret = load_module_btfs(obj);
9922 	if (ret)
9923 		return ret;
9924 
9925 	for (i = 0; i < obj->btf_module_cnt; i++) {
9926 		const struct module_btf *mod = &obj->btf_modules[i];
9927 
9928 		ret = find_attach_btf_id(mod->btf, attach_name, attach_type);
9929 		if (ret > 0) {
9930 			*btf_obj_fd = mod->fd;
9931 			*btf_type_id = ret;
9932 			return 0;
9933 		}
9934 		if (ret == -ENOENT)
9935 			continue;
9936 
9937 		return ret;
9938 	}
9939 
9940 	return -ESRCH;
9941 }
9942 
9943 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
9944 				     int *btf_obj_fd, int *btf_type_id)
9945 {
9946 	enum bpf_attach_type attach_type = prog->expected_attach_type;
9947 	__u32 attach_prog_fd = prog->attach_prog_fd;
9948 	int err = 0;
9949 
9950 	/* BPF program's BTF ID */
9951 	if (prog->type == BPF_PROG_TYPE_EXT || attach_prog_fd) {
9952 		if (!attach_prog_fd) {
9953 			pr_warn("prog '%s': attach program FD is not set\n", prog->name);
9954 			return -EINVAL;
9955 		}
9956 		err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd);
9957 		if (err < 0) {
9958 			pr_warn("prog '%s': failed to find BPF program (FD %d) BTF ID for '%s': %d\n",
9959 				 prog->name, attach_prog_fd, attach_name, err);
9960 			return err;
9961 		}
9962 		*btf_obj_fd = 0;
9963 		*btf_type_id = err;
9964 		return 0;
9965 	}
9966 
9967 	/* kernel/module BTF ID */
9968 	if (prog->obj->gen_loader) {
9969 		bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
9970 		*btf_obj_fd = 0;
9971 		*btf_type_id = 1;
9972 	} else {
9973 		err = find_kernel_btf_id(prog->obj, attach_name, attach_type, btf_obj_fd, btf_type_id);
9974 	}
9975 	if (err) {
9976 		pr_warn("prog '%s': failed to find kernel BTF type ID of '%s': %d\n",
9977 			prog->name, attach_name, err);
9978 		return err;
9979 	}
9980 	return 0;
9981 }
9982 
9983 int libbpf_attach_type_by_name(const char *name,
9984 			       enum bpf_attach_type *attach_type)
9985 {
9986 	char *type_names;
9987 	const struct bpf_sec_def *sec_def;
9988 
9989 	if (!name)
9990 		return libbpf_err(-EINVAL);
9991 
9992 	sec_def = find_sec_def(name);
9993 	if (!sec_def) {
9994 		pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
9995 		type_names = libbpf_get_type_names(true);
9996 		if (type_names != NULL) {
9997 			pr_debug("attachable section(type) names are:%s\n", type_names);
9998 			free(type_names);
9999 		}
10000 
10001 		return libbpf_err(-EINVAL);
10002 	}
10003 
10004 	if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
10005 		return libbpf_err(-EINVAL);
10006 	if (!(sec_def->cookie & SEC_ATTACHABLE))
10007 		return libbpf_err(-EINVAL);
10008 
10009 	*attach_type = sec_def->expected_attach_type;
10010 	return 0;
10011 }
10012 
10013 int bpf_map__fd(const struct bpf_map *map)
10014 {
10015 	if (!map)
10016 		return libbpf_err(-EINVAL);
10017 	if (!map_is_created(map))
10018 		return -1;
10019 	return map->fd;
10020 }
10021 
10022 static bool map_uses_real_name(const struct bpf_map *map)
10023 {
10024 	/* Since libbpf started to support custom .data.* and .rodata.* maps,
10025 	 * their user-visible name differs from kernel-visible name. Users see
10026 	 * such map's corresponding ELF section name as a map name.
10027 	 * This check distinguishes .data/.rodata from .data.* and .rodata.*
10028 	 * maps to know which name has to be returned to the user.
10029 	 */
10030 	if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
10031 		return true;
10032 	if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
10033 		return true;
10034 	return false;
10035 }
10036 
10037 const char *bpf_map__name(const struct bpf_map *map)
10038 {
10039 	if (!map)
10040 		return NULL;
10041 
10042 	if (map_uses_real_name(map))
10043 		return map->real_name;
10044 
10045 	return map->name;
10046 }
10047 
10048 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
10049 {
10050 	return map->def.type;
10051 }
10052 
10053 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
10054 {
10055 	if (map_is_created(map))
10056 		return libbpf_err(-EBUSY);
10057 	map->def.type = type;
10058 	return 0;
10059 }
10060 
10061 __u32 bpf_map__map_flags(const struct bpf_map *map)
10062 {
10063 	return map->def.map_flags;
10064 }
10065 
10066 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
10067 {
10068 	if (map_is_created(map))
10069 		return libbpf_err(-EBUSY);
10070 	map->def.map_flags = flags;
10071 	return 0;
10072 }
10073 
10074 __u64 bpf_map__map_extra(const struct bpf_map *map)
10075 {
10076 	return map->map_extra;
10077 }
10078 
10079 int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
10080 {
10081 	if (map_is_created(map))
10082 		return libbpf_err(-EBUSY);
10083 	map->map_extra = map_extra;
10084 	return 0;
10085 }
10086 
10087 __u32 bpf_map__numa_node(const struct bpf_map *map)
10088 {
10089 	return map->numa_node;
10090 }
10091 
10092 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
10093 {
10094 	if (map_is_created(map))
10095 		return libbpf_err(-EBUSY);
10096 	map->numa_node = numa_node;
10097 	return 0;
10098 }
10099 
10100 __u32 bpf_map__key_size(const struct bpf_map *map)
10101 {
10102 	return map->def.key_size;
10103 }
10104 
10105 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
10106 {
10107 	if (map_is_created(map))
10108 		return libbpf_err(-EBUSY);
10109 	map->def.key_size = size;
10110 	return 0;
10111 }
10112 
10113 __u32 bpf_map__value_size(const struct bpf_map *map)
10114 {
10115 	return map->def.value_size;
10116 }
10117 
10118 static int map_btf_datasec_resize(struct bpf_map *map, __u32 size)
10119 {
10120 	struct btf *btf;
10121 	struct btf_type *datasec_type, *var_type;
10122 	struct btf_var_secinfo *var;
10123 	const struct btf_type *array_type;
10124 	const struct btf_array *array;
10125 	int vlen, element_sz, new_array_id;
10126 	__u32 nr_elements;
10127 
10128 	/* check btf existence */
10129 	btf = bpf_object__btf(map->obj);
10130 	if (!btf)
10131 		return -ENOENT;
10132 
10133 	/* verify map is datasec */
10134 	datasec_type = btf_type_by_id(btf, bpf_map__btf_value_type_id(map));
10135 	if (!btf_is_datasec(datasec_type)) {
10136 		pr_warn("map '%s': cannot be resized, map value type is not a datasec\n",
10137 			bpf_map__name(map));
10138 		return -EINVAL;
10139 	}
10140 
10141 	/* verify datasec has at least one var */
10142 	vlen = btf_vlen(datasec_type);
10143 	if (vlen == 0) {
10144 		pr_warn("map '%s': cannot be resized, map value datasec is empty\n",
10145 			bpf_map__name(map));
10146 		return -EINVAL;
10147 	}
10148 
10149 	/* verify last var in the datasec is an array */
10150 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
10151 	var_type = btf_type_by_id(btf, var->type);
10152 	array_type = skip_mods_and_typedefs(btf, var_type->type, NULL);
10153 	if (!btf_is_array(array_type)) {
10154 		pr_warn("map '%s': cannot be resized, last var must be an array\n",
10155 			bpf_map__name(map));
10156 		return -EINVAL;
10157 	}
10158 
10159 	/* verify request size aligns with array */
10160 	array = btf_array(array_type);
10161 	element_sz = btf__resolve_size(btf, array->type);
10162 	if (element_sz <= 0 || (size - var->offset) % element_sz != 0) {
10163 		pr_warn("map '%s': cannot be resized, element size (%d) doesn't align with new total size (%u)\n",
10164 			bpf_map__name(map), element_sz, size);
10165 		return -EINVAL;
10166 	}
10167 
10168 	/* create a new array based on the existing array, but with new length */
10169 	nr_elements = (size - var->offset) / element_sz;
10170 	new_array_id = btf__add_array(btf, array->index_type, array->type, nr_elements);
10171 	if (new_array_id < 0)
10172 		return new_array_id;
10173 
10174 	/* adding a new btf type invalidates existing pointers to btf objects,
10175 	 * so refresh pointers before proceeding
10176 	 */
10177 	datasec_type = btf_type_by_id(btf, map->btf_value_type_id);
10178 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
10179 	var_type = btf_type_by_id(btf, var->type);
10180 
10181 	/* finally update btf info */
10182 	datasec_type->size = size;
10183 	var->size = size - var->offset;
10184 	var_type->type = new_array_id;
10185 
10186 	return 0;
10187 }
10188 
10189 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
10190 {
10191 	if (map->obj->loaded || map->reused)
10192 		return libbpf_err(-EBUSY);
10193 
10194 	if (map->mmaped) {
10195 		int err;
10196 		size_t mmap_old_sz, mmap_new_sz;
10197 
10198 		mmap_old_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
10199 		mmap_new_sz = bpf_map_mmap_sz(size, map->def.max_entries);
10200 		err = bpf_map_mmap_resize(map, mmap_old_sz, mmap_new_sz);
10201 		if (err) {
10202 			pr_warn("map '%s': failed to resize memory-mapped region: %d\n",
10203 				bpf_map__name(map), err);
10204 			return err;
10205 		}
10206 		err = map_btf_datasec_resize(map, size);
10207 		if (err && err != -ENOENT) {
10208 			pr_warn("map '%s': failed to adjust resized BTF, clearing BTF key/value info: %d\n",
10209 				bpf_map__name(map), err);
10210 			map->btf_value_type_id = 0;
10211 			map->btf_key_type_id = 0;
10212 		}
10213 	}
10214 
10215 	map->def.value_size = size;
10216 	return 0;
10217 }
10218 
10219 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
10220 {
10221 	return map ? map->btf_key_type_id : 0;
10222 }
10223 
10224 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
10225 {
10226 	return map ? map->btf_value_type_id : 0;
10227 }
10228 
10229 int bpf_map__set_initial_value(struct bpf_map *map,
10230 			       const void *data, size_t size)
10231 {
10232 	if (map->obj->loaded || map->reused)
10233 		return libbpf_err(-EBUSY);
10234 
10235 	if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG ||
10236 	    size != map->def.value_size)
10237 		return libbpf_err(-EINVAL);
10238 
10239 	memcpy(map->mmaped, data, size);
10240 	return 0;
10241 }
10242 
10243 void *bpf_map__initial_value(struct bpf_map *map, size_t *psize)
10244 {
10245 	if (!map->mmaped)
10246 		return NULL;
10247 	*psize = map->def.value_size;
10248 	return map->mmaped;
10249 }
10250 
10251 bool bpf_map__is_internal(const struct bpf_map *map)
10252 {
10253 	return map->libbpf_type != LIBBPF_MAP_UNSPEC;
10254 }
10255 
10256 __u32 bpf_map__ifindex(const struct bpf_map *map)
10257 {
10258 	return map->map_ifindex;
10259 }
10260 
10261 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
10262 {
10263 	if (map_is_created(map))
10264 		return libbpf_err(-EBUSY);
10265 	map->map_ifindex = ifindex;
10266 	return 0;
10267 }
10268 
10269 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
10270 {
10271 	if (!bpf_map_type__is_map_in_map(map->def.type)) {
10272 		pr_warn("error: unsupported map type\n");
10273 		return libbpf_err(-EINVAL);
10274 	}
10275 	if (map->inner_map_fd != -1) {
10276 		pr_warn("error: inner_map_fd already specified\n");
10277 		return libbpf_err(-EINVAL);
10278 	}
10279 	if (map->inner_map) {
10280 		bpf_map__destroy(map->inner_map);
10281 		zfree(&map->inner_map);
10282 	}
10283 	map->inner_map_fd = fd;
10284 	return 0;
10285 }
10286 
10287 static struct bpf_map *
10288 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
10289 {
10290 	ssize_t idx;
10291 	struct bpf_map *s, *e;
10292 
10293 	if (!obj || !obj->maps)
10294 		return errno = EINVAL, NULL;
10295 
10296 	s = obj->maps;
10297 	e = obj->maps + obj->nr_maps;
10298 
10299 	if ((m < s) || (m >= e)) {
10300 		pr_warn("error in %s: map handler doesn't belong to object\n",
10301 			 __func__);
10302 		return errno = EINVAL, NULL;
10303 	}
10304 
10305 	idx = (m - obj->maps) + i;
10306 	if (idx >= obj->nr_maps || idx < 0)
10307 		return NULL;
10308 	return &obj->maps[idx];
10309 }
10310 
10311 struct bpf_map *
10312 bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
10313 {
10314 	if (prev == NULL)
10315 		return obj->maps;
10316 
10317 	return __bpf_map__iter(prev, obj, 1);
10318 }
10319 
10320 struct bpf_map *
10321 bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
10322 {
10323 	if (next == NULL) {
10324 		if (!obj->nr_maps)
10325 			return NULL;
10326 		return obj->maps + obj->nr_maps - 1;
10327 	}
10328 
10329 	return __bpf_map__iter(next, obj, -1);
10330 }
10331 
10332 struct bpf_map *
10333 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
10334 {
10335 	struct bpf_map *pos;
10336 
10337 	bpf_object__for_each_map(pos, obj) {
10338 		/* if it's a special internal map name (which always starts
10339 		 * with dot) then check if that special name matches the
10340 		 * real map name (ELF section name)
10341 		 */
10342 		if (name[0] == '.') {
10343 			if (pos->real_name && strcmp(pos->real_name, name) == 0)
10344 				return pos;
10345 			continue;
10346 		}
10347 		/* otherwise map name has to be an exact match */
10348 		if (map_uses_real_name(pos)) {
10349 			if (strcmp(pos->real_name, name) == 0)
10350 				return pos;
10351 			continue;
10352 		}
10353 		if (strcmp(pos->name, name) == 0)
10354 			return pos;
10355 	}
10356 	return errno = ENOENT, NULL;
10357 }
10358 
10359 int
10360 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
10361 {
10362 	return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
10363 }
10364 
10365 static int validate_map_op(const struct bpf_map *map, size_t key_sz,
10366 			   size_t value_sz, bool check_value_sz)
10367 {
10368 	if (!map_is_created(map)) /* map is not yet created */
10369 		return -ENOENT;
10370 
10371 	if (map->def.key_size != key_sz) {
10372 		pr_warn("map '%s': unexpected key size %zu provided, expected %u\n",
10373 			map->name, key_sz, map->def.key_size);
10374 		return -EINVAL;
10375 	}
10376 
10377 	if (!check_value_sz)
10378 		return 0;
10379 
10380 	switch (map->def.type) {
10381 	case BPF_MAP_TYPE_PERCPU_ARRAY:
10382 	case BPF_MAP_TYPE_PERCPU_HASH:
10383 	case BPF_MAP_TYPE_LRU_PERCPU_HASH:
10384 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: {
10385 		int num_cpu = libbpf_num_possible_cpus();
10386 		size_t elem_sz = roundup(map->def.value_size, 8);
10387 
10388 		if (value_sz != num_cpu * elem_sz) {
10389 			pr_warn("map '%s': unexpected value size %zu provided for per-CPU map, expected %d * %zu = %zd\n",
10390 				map->name, value_sz, num_cpu, elem_sz, num_cpu * elem_sz);
10391 			return -EINVAL;
10392 		}
10393 		break;
10394 	}
10395 	default:
10396 		if (map->def.value_size != value_sz) {
10397 			pr_warn("map '%s': unexpected value size %zu provided, expected %u\n",
10398 				map->name, value_sz, map->def.value_size);
10399 			return -EINVAL;
10400 		}
10401 		break;
10402 	}
10403 	return 0;
10404 }
10405 
10406 int bpf_map__lookup_elem(const struct bpf_map *map,
10407 			 const void *key, size_t key_sz,
10408 			 void *value, size_t value_sz, __u64 flags)
10409 {
10410 	int err;
10411 
10412 	err = validate_map_op(map, key_sz, value_sz, true);
10413 	if (err)
10414 		return libbpf_err(err);
10415 
10416 	return bpf_map_lookup_elem_flags(map->fd, key, value, flags);
10417 }
10418 
10419 int bpf_map__update_elem(const struct bpf_map *map,
10420 			 const void *key, size_t key_sz,
10421 			 const void *value, size_t value_sz, __u64 flags)
10422 {
10423 	int err;
10424 
10425 	err = validate_map_op(map, key_sz, value_sz, true);
10426 	if (err)
10427 		return libbpf_err(err);
10428 
10429 	return bpf_map_update_elem(map->fd, key, value, flags);
10430 }
10431 
10432 int bpf_map__delete_elem(const struct bpf_map *map,
10433 			 const void *key, size_t key_sz, __u64 flags)
10434 {
10435 	int err;
10436 
10437 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
10438 	if (err)
10439 		return libbpf_err(err);
10440 
10441 	return bpf_map_delete_elem_flags(map->fd, key, flags);
10442 }
10443 
10444 int bpf_map__lookup_and_delete_elem(const struct bpf_map *map,
10445 				    const void *key, size_t key_sz,
10446 				    void *value, size_t value_sz, __u64 flags)
10447 {
10448 	int err;
10449 
10450 	err = validate_map_op(map, key_sz, value_sz, true);
10451 	if (err)
10452 		return libbpf_err(err);
10453 
10454 	return bpf_map_lookup_and_delete_elem_flags(map->fd, key, value, flags);
10455 }
10456 
10457 int bpf_map__get_next_key(const struct bpf_map *map,
10458 			  const void *cur_key, void *next_key, size_t key_sz)
10459 {
10460 	int err;
10461 
10462 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
10463 	if (err)
10464 		return libbpf_err(err);
10465 
10466 	return bpf_map_get_next_key(map->fd, cur_key, next_key);
10467 }
10468 
10469 long libbpf_get_error(const void *ptr)
10470 {
10471 	if (!IS_ERR_OR_NULL(ptr))
10472 		return 0;
10473 
10474 	if (IS_ERR(ptr))
10475 		errno = -PTR_ERR(ptr);
10476 
10477 	/* If ptr == NULL, then errno should be already set by the failing
10478 	 * API, because libbpf never returns NULL on success and it now always
10479 	 * sets errno on error. So no extra errno handling for ptr == NULL
10480 	 * case.
10481 	 */
10482 	return -errno;
10483 }
10484 
10485 /* Replace link's underlying BPF program with the new one */
10486 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
10487 {
10488 	int ret;
10489 
10490 	ret = bpf_link_update(bpf_link__fd(link), bpf_program__fd(prog), NULL);
10491 	return libbpf_err_errno(ret);
10492 }
10493 
10494 /* Release "ownership" of underlying BPF resource (typically, BPF program
10495  * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
10496  * link, when destructed through bpf_link__destroy() call won't attempt to
10497  * detach/unregisted that BPF resource. This is useful in situations where,
10498  * say, attached BPF program has to outlive userspace program that attached it
10499  * in the system. Depending on type of BPF program, though, there might be
10500  * additional steps (like pinning BPF program in BPF FS) necessary to ensure
10501  * exit of userspace program doesn't trigger automatic detachment and clean up
10502  * inside the kernel.
10503  */
10504 void bpf_link__disconnect(struct bpf_link *link)
10505 {
10506 	link->disconnected = true;
10507 }
10508 
10509 int bpf_link__destroy(struct bpf_link *link)
10510 {
10511 	int err = 0;
10512 
10513 	if (IS_ERR_OR_NULL(link))
10514 		return 0;
10515 
10516 	if (!link->disconnected && link->detach)
10517 		err = link->detach(link);
10518 	if (link->pin_path)
10519 		free(link->pin_path);
10520 	if (link->dealloc)
10521 		link->dealloc(link);
10522 	else
10523 		free(link);
10524 
10525 	return libbpf_err(err);
10526 }
10527 
10528 int bpf_link__fd(const struct bpf_link *link)
10529 {
10530 	return link->fd;
10531 }
10532 
10533 const char *bpf_link__pin_path(const struct bpf_link *link)
10534 {
10535 	return link->pin_path;
10536 }
10537 
10538 static int bpf_link__detach_fd(struct bpf_link *link)
10539 {
10540 	return libbpf_err_errno(close(link->fd));
10541 }
10542 
10543 struct bpf_link *bpf_link__open(const char *path)
10544 {
10545 	struct bpf_link *link;
10546 	int fd;
10547 
10548 	fd = bpf_obj_get(path);
10549 	if (fd < 0) {
10550 		fd = -errno;
10551 		pr_warn("failed to open link at %s: %d\n", path, fd);
10552 		return libbpf_err_ptr(fd);
10553 	}
10554 
10555 	link = calloc(1, sizeof(*link));
10556 	if (!link) {
10557 		close(fd);
10558 		return libbpf_err_ptr(-ENOMEM);
10559 	}
10560 	link->detach = &bpf_link__detach_fd;
10561 	link->fd = fd;
10562 
10563 	link->pin_path = strdup(path);
10564 	if (!link->pin_path) {
10565 		bpf_link__destroy(link);
10566 		return libbpf_err_ptr(-ENOMEM);
10567 	}
10568 
10569 	return link;
10570 }
10571 
10572 int bpf_link__detach(struct bpf_link *link)
10573 {
10574 	return bpf_link_detach(link->fd) ? -errno : 0;
10575 }
10576 
10577 int bpf_link__pin(struct bpf_link *link, const char *path)
10578 {
10579 	int err;
10580 
10581 	if (link->pin_path)
10582 		return libbpf_err(-EBUSY);
10583 	err = make_parent_dir(path);
10584 	if (err)
10585 		return libbpf_err(err);
10586 	err = check_path(path);
10587 	if (err)
10588 		return libbpf_err(err);
10589 
10590 	link->pin_path = strdup(path);
10591 	if (!link->pin_path)
10592 		return libbpf_err(-ENOMEM);
10593 
10594 	if (bpf_obj_pin(link->fd, link->pin_path)) {
10595 		err = -errno;
10596 		zfree(&link->pin_path);
10597 		return libbpf_err(err);
10598 	}
10599 
10600 	pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
10601 	return 0;
10602 }
10603 
10604 int bpf_link__unpin(struct bpf_link *link)
10605 {
10606 	int err;
10607 
10608 	if (!link->pin_path)
10609 		return libbpf_err(-EINVAL);
10610 
10611 	err = unlink(link->pin_path);
10612 	if (err != 0)
10613 		return -errno;
10614 
10615 	pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
10616 	zfree(&link->pin_path);
10617 	return 0;
10618 }
10619 
10620 struct bpf_link_perf {
10621 	struct bpf_link link;
10622 	int perf_event_fd;
10623 	/* legacy kprobe support: keep track of probe identifier and type */
10624 	char *legacy_probe_name;
10625 	bool legacy_is_kprobe;
10626 	bool legacy_is_retprobe;
10627 };
10628 
10629 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
10630 static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
10631 
10632 static int bpf_link_perf_detach(struct bpf_link *link)
10633 {
10634 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10635 	int err = 0;
10636 
10637 	if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
10638 		err = -errno;
10639 
10640 	if (perf_link->perf_event_fd != link->fd)
10641 		close(perf_link->perf_event_fd);
10642 	close(link->fd);
10643 
10644 	/* legacy uprobe/kprobe needs to be removed after perf event fd closure */
10645 	if (perf_link->legacy_probe_name) {
10646 		if (perf_link->legacy_is_kprobe) {
10647 			err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
10648 							 perf_link->legacy_is_retprobe);
10649 		} else {
10650 			err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
10651 							 perf_link->legacy_is_retprobe);
10652 		}
10653 	}
10654 
10655 	return err;
10656 }
10657 
10658 static void bpf_link_perf_dealloc(struct bpf_link *link)
10659 {
10660 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10661 
10662 	free(perf_link->legacy_probe_name);
10663 	free(perf_link);
10664 }
10665 
10666 struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
10667 						     const struct bpf_perf_event_opts *opts)
10668 {
10669 	char errmsg[STRERR_BUFSIZE];
10670 	struct bpf_link_perf *link;
10671 	int prog_fd, link_fd = -1, err;
10672 	bool force_ioctl_attach;
10673 
10674 	if (!OPTS_VALID(opts, bpf_perf_event_opts))
10675 		return libbpf_err_ptr(-EINVAL);
10676 
10677 	if (pfd < 0) {
10678 		pr_warn("prog '%s': invalid perf event FD %d\n",
10679 			prog->name, pfd);
10680 		return libbpf_err_ptr(-EINVAL);
10681 	}
10682 	prog_fd = bpf_program__fd(prog);
10683 	if (prog_fd < 0) {
10684 		pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
10685 			prog->name);
10686 		return libbpf_err_ptr(-EINVAL);
10687 	}
10688 
10689 	link = calloc(1, sizeof(*link));
10690 	if (!link)
10691 		return libbpf_err_ptr(-ENOMEM);
10692 	link->link.detach = &bpf_link_perf_detach;
10693 	link->link.dealloc = &bpf_link_perf_dealloc;
10694 	link->perf_event_fd = pfd;
10695 
10696 	force_ioctl_attach = OPTS_GET(opts, force_ioctl_attach, false);
10697 	if (kernel_supports(prog->obj, FEAT_PERF_LINK) && !force_ioctl_attach) {
10698 		DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
10699 			.perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
10700 
10701 		link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
10702 		if (link_fd < 0) {
10703 			err = -errno;
10704 			pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %d (%s)\n",
10705 				prog->name, pfd,
10706 				err, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10707 			goto err_out;
10708 		}
10709 		link->link.fd = link_fd;
10710 	} else {
10711 		if (OPTS_GET(opts, bpf_cookie, 0)) {
10712 			pr_warn("prog '%s': user context value is not supported\n", prog->name);
10713 			err = -EOPNOTSUPP;
10714 			goto err_out;
10715 		}
10716 
10717 		if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
10718 			err = -errno;
10719 			pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
10720 				prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10721 			if (err == -EPROTO)
10722 				pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
10723 					prog->name, pfd);
10724 			goto err_out;
10725 		}
10726 		link->link.fd = pfd;
10727 	}
10728 	if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
10729 		err = -errno;
10730 		pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
10731 			prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10732 		goto err_out;
10733 	}
10734 
10735 	return &link->link;
10736 err_out:
10737 	if (link_fd >= 0)
10738 		close(link_fd);
10739 	free(link);
10740 	return libbpf_err_ptr(err);
10741 }
10742 
10743 struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
10744 {
10745 	return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
10746 }
10747 
10748 /*
10749  * this function is expected to parse integer in the range of [0, 2^31-1] from
10750  * given file using scanf format string fmt. If actual parsed value is
10751  * negative, the result might be indistinguishable from error
10752  */
10753 static int parse_uint_from_file(const char *file, const char *fmt)
10754 {
10755 	char buf[STRERR_BUFSIZE];
10756 	int err, ret;
10757 	FILE *f;
10758 
10759 	f = fopen(file, "re");
10760 	if (!f) {
10761 		err = -errno;
10762 		pr_debug("failed to open '%s': %s\n", file,
10763 			 libbpf_strerror_r(err, buf, sizeof(buf)));
10764 		return err;
10765 	}
10766 	err = fscanf(f, fmt, &ret);
10767 	if (err != 1) {
10768 		err = err == EOF ? -EIO : -errno;
10769 		pr_debug("failed to parse '%s': %s\n", file,
10770 			libbpf_strerror_r(err, buf, sizeof(buf)));
10771 		fclose(f);
10772 		return err;
10773 	}
10774 	fclose(f);
10775 	return ret;
10776 }
10777 
10778 static int determine_kprobe_perf_type(void)
10779 {
10780 	const char *file = "/sys/bus/event_source/devices/kprobe/type";
10781 
10782 	return parse_uint_from_file(file, "%d\n");
10783 }
10784 
10785 static int determine_uprobe_perf_type(void)
10786 {
10787 	const char *file = "/sys/bus/event_source/devices/uprobe/type";
10788 
10789 	return parse_uint_from_file(file, "%d\n");
10790 }
10791 
10792 static int determine_kprobe_retprobe_bit(void)
10793 {
10794 	const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
10795 
10796 	return parse_uint_from_file(file, "config:%d\n");
10797 }
10798 
10799 static int determine_uprobe_retprobe_bit(void)
10800 {
10801 	const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
10802 
10803 	return parse_uint_from_file(file, "config:%d\n");
10804 }
10805 
10806 #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
10807 #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
10808 
10809 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
10810 				 uint64_t offset, int pid, size_t ref_ctr_off)
10811 {
10812 	const size_t attr_sz = sizeof(struct perf_event_attr);
10813 	struct perf_event_attr attr;
10814 	char errmsg[STRERR_BUFSIZE];
10815 	int type, pfd;
10816 
10817 	if ((__u64)ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
10818 		return -EINVAL;
10819 
10820 	memset(&attr, 0, attr_sz);
10821 
10822 	type = uprobe ? determine_uprobe_perf_type()
10823 		      : determine_kprobe_perf_type();
10824 	if (type < 0) {
10825 		pr_warn("failed to determine %s perf type: %s\n",
10826 			uprobe ? "uprobe" : "kprobe",
10827 			libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
10828 		return type;
10829 	}
10830 	if (retprobe) {
10831 		int bit = uprobe ? determine_uprobe_retprobe_bit()
10832 				 : determine_kprobe_retprobe_bit();
10833 
10834 		if (bit < 0) {
10835 			pr_warn("failed to determine %s retprobe bit: %s\n",
10836 				uprobe ? "uprobe" : "kprobe",
10837 				libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
10838 			return bit;
10839 		}
10840 		attr.config |= 1 << bit;
10841 	}
10842 	attr.size = attr_sz;
10843 	attr.type = type;
10844 	attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
10845 	attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
10846 	attr.config2 = offset;		 /* kprobe_addr or probe_offset */
10847 
10848 	/* pid filter is meaningful only for uprobes */
10849 	pfd = syscall(__NR_perf_event_open, &attr,
10850 		      pid < 0 ? -1 : pid /* pid */,
10851 		      pid == -1 ? 0 : -1 /* cpu */,
10852 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
10853 	return pfd >= 0 ? pfd : -errno;
10854 }
10855 
10856 static int append_to_file(const char *file, const char *fmt, ...)
10857 {
10858 	int fd, n, err = 0;
10859 	va_list ap;
10860 	char buf[1024];
10861 
10862 	va_start(ap, fmt);
10863 	n = vsnprintf(buf, sizeof(buf), fmt, ap);
10864 	va_end(ap);
10865 
10866 	if (n < 0 || n >= sizeof(buf))
10867 		return -EINVAL;
10868 
10869 	fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
10870 	if (fd < 0)
10871 		return -errno;
10872 
10873 	if (write(fd, buf, n) < 0)
10874 		err = -errno;
10875 
10876 	close(fd);
10877 	return err;
10878 }
10879 
10880 #define DEBUGFS "/sys/kernel/debug/tracing"
10881 #define TRACEFS "/sys/kernel/tracing"
10882 
10883 static bool use_debugfs(void)
10884 {
10885 	static int has_debugfs = -1;
10886 
10887 	if (has_debugfs < 0)
10888 		has_debugfs = faccessat(AT_FDCWD, DEBUGFS, F_OK, AT_EACCESS) == 0;
10889 
10890 	return has_debugfs == 1;
10891 }
10892 
10893 static const char *tracefs_path(void)
10894 {
10895 	return use_debugfs() ? DEBUGFS : TRACEFS;
10896 }
10897 
10898 static const char *tracefs_kprobe_events(void)
10899 {
10900 	return use_debugfs() ? DEBUGFS"/kprobe_events" : TRACEFS"/kprobe_events";
10901 }
10902 
10903 static const char *tracefs_uprobe_events(void)
10904 {
10905 	return use_debugfs() ? DEBUGFS"/uprobe_events" : TRACEFS"/uprobe_events";
10906 }
10907 
10908 static const char *tracefs_available_filter_functions(void)
10909 {
10910 	return use_debugfs() ? DEBUGFS"/available_filter_functions"
10911 			     : TRACEFS"/available_filter_functions";
10912 }
10913 
10914 static const char *tracefs_available_filter_functions_addrs(void)
10915 {
10916 	return use_debugfs() ? DEBUGFS"/available_filter_functions_addrs"
10917 			     : TRACEFS"/available_filter_functions_addrs";
10918 }
10919 
10920 static void gen_kprobe_legacy_event_name(char *buf, size_t buf_sz,
10921 					 const char *kfunc_name, size_t offset)
10922 {
10923 	static int index = 0;
10924 	int i;
10925 
10926 	snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx_%d", getpid(), kfunc_name, offset,
10927 		 __sync_fetch_and_add(&index, 1));
10928 
10929 	/* sanitize binary_path in the probe name */
10930 	for (i = 0; buf[i]; i++) {
10931 		if (!isalnum(buf[i]))
10932 			buf[i] = '_';
10933 	}
10934 }
10935 
10936 static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
10937 				   const char *kfunc_name, size_t offset)
10938 {
10939 	return append_to_file(tracefs_kprobe_events(), "%c:%s/%s %s+0x%zx",
10940 			      retprobe ? 'r' : 'p',
10941 			      retprobe ? "kretprobes" : "kprobes",
10942 			      probe_name, kfunc_name, offset);
10943 }
10944 
10945 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
10946 {
10947 	return append_to_file(tracefs_kprobe_events(), "-:%s/%s",
10948 			      retprobe ? "kretprobes" : "kprobes", probe_name);
10949 }
10950 
10951 static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
10952 {
10953 	char file[256];
10954 
10955 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
10956 		 tracefs_path(), retprobe ? "kretprobes" : "kprobes", probe_name);
10957 
10958 	return parse_uint_from_file(file, "%d\n");
10959 }
10960 
10961 static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
10962 					 const char *kfunc_name, size_t offset, int pid)
10963 {
10964 	const size_t attr_sz = sizeof(struct perf_event_attr);
10965 	struct perf_event_attr attr;
10966 	char errmsg[STRERR_BUFSIZE];
10967 	int type, pfd, err;
10968 
10969 	err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
10970 	if (err < 0) {
10971 		pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
10972 			kfunc_name, offset,
10973 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10974 		return err;
10975 	}
10976 	type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
10977 	if (type < 0) {
10978 		err = type;
10979 		pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
10980 			kfunc_name, offset,
10981 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10982 		goto err_clean_legacy;
10983 	}
10984 
10985 	memset(&attr, 0, attr_sz);
10986 	attr.size = attr_sz;
10987 	attr.config = type;
10988 	attr.type = PERF_TYPE_TRACEPOINT;
10989 
10990 	pfd = syscall(__NR_perf_event_open, &attr,
10991 		      pid < 0 ? -1 : pid, /* pid */
10992 		      pid == -1 ? 0 : -1, /* cpu */
10993 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
10994 	if (pfd < 0) {
10995 		err = -errno;
10996 		pr_warn("legacy kprobe perf_event_open() failed: %s\n",
10997 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10998 		goto err_clean_legacy;
10999 	}
11000 	return pfd;
11001 
11002 err_clean_legacy:
11003 	/* Clear the newly added legacy kprobe_event */
11004 	remove_kprobe_event_legacy(probe_name, retprobe);
11005 	return err;
11006 }
11007 
11008 static const char *arch_specific_syscall_pfx(void)
11009 {
11010 #if defined(__x86_64__)
11011 	return "x64";
11012 #elif defined(__i386__)
11013 	return "ia32";
11014 #elif defined(__s390x__)
11015 	return "s390x";
11016 #elif defined(__s390__)
11017 	return "s390";
11018 #elif defined(__arm__)
11019 	return "arm";
11020 #elif defined(__aarch64__)
11021 	return "arm64";
11022 #elif defined(__mips__)
11023 	return "mips";
11024 #elif defined(__riscv)
11025 	return "riscv";
11026 #elif defined(__powerpc__)
11027 	return "powerpc";
11028 #elif defined(__powerpc64__)
11029 	return "powerpc64";
11030 #else
11031 	return NULL;
11032 #endif
11033 }
11034 
11035 static int probe_kern_syscall_wrapper(void)
11036 {
11037 	char syscall_name[64];
11038 	const char *ksys_pfx;
11039 
11040 	ksys_pfx = arch_specific_syscall_pfx();
11041 	if (!ksys_pfx)
11042 		return 0;
11043 
11044 	snprintf(syscall_name, sizeof(syscall_name), "__%s_sys_bpf", ksys_pfx);
11045 
11046 	if (determine_kprobe_perf_type() >= 0) {
11047 		int pfd;
11048 
11049 		pfd = perf_event_open_probe(false, false, syscall_name, 0, getpid(), 0);
11050 		if (pfd >= 0)
11051 			close(pfd);
11052 
11053 		return pfd >= 0 ? 1 : 0;
11054 	} else { /* legacy mode */
11055 		char probe_name[128];
11056 
11057 		gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name), syscall_name, 0);
11058 		if (add_kprobe_event_legacy(probe_name, false, syscall_name, 0) < 0)
11059 			return 0;
11060 
11061 		(void)remove_kprobe_event_legacy(probe_name, false);
11062 		return 1;
11063 	}
11064 }
11065 
11066 struct bpf_link *
11067 bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
11068 				const char *func_name,
11069 				const struct bpf_kprobe_opts *opts)
11070 {
11071 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11072 	enum probe_attach_mode attach_mode;
11073 	char errmsg[STRERR_BUFSIZE];
11074 	char *legacy_probe = NULL;
11075 	struct bpf_link *link;
11076 	size_t offset;
11077 	bool retprobe, legacy;
11078 	int pfd, err;
11079 
11080 	if (!OPTS_VALID(opts, bpf_kprobe_opts))
11081 		return libbpf_err_ptr(-EINVAL);
11082 
11083 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
11084 	retprobe = OPTS_GET(opts, retprobe, false);
11085 	offset = OPTS_GET(opts, offset, 0);
11086 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11087 
11088 	legacy = determine_kprobe_perf_type() < 0;
11089 	switch (attach_mode) {
11090 	case PROBE_ATTACH_MODE_LEGACY:
11091 		legacy = true;
11092 		pe_opts.force_ioctl_attach = true;
11093 		break;
11094 	case PROBE_ATTACH_MODE_PERF:
11095 		if (legacy)
11096 			return libbpf_err_ptr(-ENOTSUP);
11097 		pe_opts.force_ioctl_attach = true;
11098 		break;
11099 	case PROBE_ATTACH_MODE_LINK:
11100 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
11101 			return libbpf_err_ptr(-ENOTSUP);
11102 		break;
11103 	case PROBE_ATTACH_MODE_DEFAULT:
11104 		break;
11105 	default:
11106 		return libbpf_err_ptr(-EINVAL);
11107 	}
11108 
11109 	if (!legacy) {
11110 		pfd = perf_event_open_probe(false /* uprobe */, retprobe,
11111 					    func_name, offset,
11112 					    -1 /* pid */, 0 /* ref_ctr_off */);
11113 	} else {
11114 		char probe_name[256];
11115 
11116 		gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name),
11117 					     func_name, offset);
11118 
11119 		legacy_probe = strdup(probe_name);
11120 		if (!legacy_probe)
11121 			return libbpf_err_ptr(-ENOMEM);
11122 
11123 		pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
11124 						    offset, -1 /* pid */);
11125 	}
11126 	if (pfd < 0) {
11127 		err = -errno;
11128 		pr_warn("prog '%s': failed to create %s '%s+0x%zx' perf event: %s\n",
11129 			prog->name, retprobe ? "kretprobe" : "kprobe",
11130 			func_name, offset,
11131 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11132 		goto err_out;
11133 	}
11134 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11135 	err = libbpf_get_error(link);
11136 	if (err) {
11137 		close(pfd);
11138 		pr_warn("prog '%s': failed to attach to %s '%s+0x%zx': %s\n",
11139 			prog->name, retprobe ? "kretprobe" : "kprobe",
11140 			func_name, offset,
11141 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11142 		goto err_clean_legacy;
11143 	}
11144 	if (legacy) {
11145 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
11146 
11147 		perf_link->legacy_probe_name = legacy_probe;
11148 		perf_link->legacy_is_kprobe = true;
11149 		perf_link->legacy_is_retprobe = retprobe;
11150 	}
11151 
11152 	return link;
11153 
11154 err_clean_legacy:
11155 	if (legacy)
11156 		remove_kprobe_event_legacy(legacy_probe, retprobe);
11157 err_out:
11158 	free(legacy_probe);
11159 	return libbpf_err_ptr(err);
11160 }
11161 
11162 struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
11163 					    bool retprobe,
11164 					    const char *func_name)
11165 {
11166 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
11167 		.retprobe = retprobe,
11168 	);
11169 
11170 	return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
11171 }
11172 
11173 struct bpf_link *bpf_program__attach_ksyscall(const struct bpf_program *prog,
11174 					      const char *syscall_name,
11175 					      const struct bpf_ksyscall_opts *opts)
11176 {
11177 	LIBBPF_OPTS(bpf_kprobe_opts, kprobe_opts);
11178 	char func_name[128];
11179 
11180 	if (!OPTS_VALID(opts, bpf_ksyscall_opts))
11181 		return libbpf_err_ptr(-EINVAL);
11182 
11183 	if (kernel_supports(prog->obj, FEAT_SYSCALL_WRAPPER)) {
11184 		/* arch_specific_syscall_pfx() should never return NULL here
11185 		 * because it is guarded by kernel_supports(). However, since
11186 		 * compiler does not know that we have an explicit conditional
11187 		 * as well.
11188 		 */
11189 		snprintf(func_name, sizeof(func_name), "__%s_sys_%s",
11190 			 arch_specific_syscall_pfx() ? : "", syscall_name);
11191 	} else {
11192 		snprintf(func_name, sizeof(func_name), "__se_sys_%s", syscall_name);
11193 	}
11194 
11195 	kprobe_opts.retprobe = OPTS_GET(opts, retprobe, false);
11196 	kprobe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11197 
11198 	return bpf_program__attach_kprobe_opts(prog, func_name, &kprobe_opts);
11199 }
11200 
11201 /* Adapted from perf/util/string.c */
11202 bool glob_match(const char *str, const char *pat)
11203 {
11204 	while (*str && *pat && *pat != '*') {
11205 		if (*pat == '?') {      /* Matches any single character */
11206 			str++;
11207 			pat++;
11208 			continue;
11209 		}
11210 		if (*str != *pat)
11211 			return false;
11212 		str++;
11213 		pat++;
11214 	}
11215 	/* Check wild card */
11216 	if (*pat == '*') {
11217 		while (*pat == '*')
11218 			pat++;
11219 		if (!*pat) /* Tail wild card matches all */
11220 			return true;
11221 		while (*str)
11222 			if (glob_match(str++, pat))
11223 				return true;
11224 	}
11225 	return !*str && !*pat;
11226 }
11227 
11228 struct kprobe_multi_resolve {
11229 	const char *pattern;
11230 	unsigned long *addrs;
11231 	size_t cap;
11232 	size_t cnt;
11233 };
11234 
11235 struct avail_kallsyms_data {
11236 	char **syms;
11237 	size_t cnt;
11238 	struct kprobe_multi_resolve *res;
11239 };
11240 
11241 static int avail_func_cmp(const void *a, const void *b)
11242 {
11243 	return strcmp(*(const char **)a, *(const char **)b);
11244 }
11245 
11246 static int avail_kallsyms_cb(unsigned long long sym_addr, char sym_type,
11247 			     const char *sym_name, void *ctx)
11248 {
11249 	struct avail_kallsyms_data *data = ctx;
11250 	struct kprobe_multi_resolve *res = data->res;
11251 	int err;
11252 
11253 	if (!bsearch(&sym_name, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp))
11254 		return 0;
11255 
11256 	err = libbpf_ensure_mem((void **)&res->addrs, &res->cap, sizeof(*res->addrs), res->cnt + 1);
11257 	if (err)
11258 		return err;
11259 
11260 	res->addrs[res->cnt++] = (unsigned long)sym_addr;
11261 	return 0;
11262 }
11263 
11264 static int libbpf_available_kallsyms_parse(struct kprobe_multi_resolve *res)
11265 {
11266 	const char *available_functions_file = tracefs_available_filter_functions();
11267 	struct avail_kallsyms_data data;
11268 	char sym_name[500];
11269 	FILE *f;
11270 	int err = 0, ret, i;
11271 	char **syms = NULL;
11272 	size_t cap = 0, cnt = 0;
11273 
11274 	f = fopen(available_functions_file, "re");
11275 	if (!f) {
11276 		err = -errno;
11277 		pr_warn("failed to open %s: %d\n", available_functions_file, err);
11278 		return err;
11279 	}
11280 
11281 	while (true) {
11282 		char *name;
11283 
11284 		ret = fscanf(f, "%499s%*[^\n]\n", sym_name);
11285 		if (ret == EOF && feof(f))
11286 			break;
11287 
11288 		if (ret != 1) {
11289 			pr_warn("failed to parse available_filter_functions entry: %d\n", ret);
11290 			err = -EINVAL;
11291 			goto cleanup;
11292 		}
11293 
11294 		if (!glob_match(sym_name, res->pattern))
11295 			continue;
11296 
11297 		err = libbpf_ensure_mem((void **)&syms, &cap, sizeof(*syms), cnt + 1);
11298 		if (err)
11299 			goto cleanup;
11300 
11301 		name = strdup(sym_name);
11302 		if (!name) {
11303 			err = -errno;
11304 			goto cleanup;
11305 		}
11306 
11307 		syms[cnt++] = name;
11308 	}
11309 
11310 	/* no entries found, bail out */
11311 	if (cnt == 0) {
11312 		err = -ENOENT;
11313 		goto cleanup;
11314 	}
11315 
11316 	/* sort available functions */
11317 	qsort(syms, cnt, sizeof(*syms), avail_func_cmp);
11318 
11319 	data.syms = syms;
11320 	data.res = res;
11321 	data.cnt = cnt;
11322 	libbpf_kallsyms_parse(avail_kallsyms_cb, &data);
11323 
11324 	if (res->cnt == 0)
11325 		err = -ENOENT;
11326 
11327 cleanup:
11328 	for (i = 0; i < cnt; i++)
11329 		free((char *)syms[i]);
11330 	free(syms);
11331 
11332 	fclose(f);
11333 	return err;
11334 }
11335 
11336 static bool has_available_filter_functions_addrs(void)
11337 {
11338 	return access(tracefs_available_filter_functions_addrs(), R_OK) != -1;
11339 }
11340 
11341 static int libbpf_available_kprobes_parse(struct kprobe_multi_resolve *res)
11342 {
11343 	const char *available_path = tracefs_available_filter_functions_addrs();
11344 	char sym_name[500];
11345 	FILE *f;
11346 	int ret, err = 0;
11347 	unsigned long long sym_addr;
11348 
11349 	f = fopen(available_path, "re");
11350 	if (!f) {
11351 		err = -errno;
11352 		pr_warn("failed to open %s: %d\n", available_path, err);
11353 		return err;
11354 	}
11355 
11356 	while (true) {
11357 		ret = fscanf(f, "%llx %499s%*[^\n]\n", &sym_addr, sym_name);
11358 		if (ret == EOF && feof(f))
11359 			break;
11360 
11361 		if (ret != 2) {
11362 			pr_warn("failed to parse available_filter_functions_addrs entry: %d\n",
11363 				ret);
11364 			err = -EINVAL;
11365 			goto cleanup;
11366 		}
11367 
11368 		if (!glob_match(sym_name, res->pattern))
11369 			continue;
11370 
11371 		err = libbpf_ensure_mem((void **)&res->addrs, &res->cap,
11372 					sizeof(*res->addrs), res->cnt + 1);
11373 		if (err)
11374 			goto cleanup;
11375 
11376 		res->addrs[res->cnt++] = (unsigned long)sym_addr;
11377 	}
11378 
11379 	if (res->cnt == 0)
11380 		err = -ENOENT;
11381 
11382 cleanup:
11383 	fclose(f);
11384 	return err;
11385 }
11386 
11387 struct bpf_link *
11388 bpf_program__attach_kprobe_multi_opts(const struct bpf_program *prog,
11389 				      const char *pattern,
11390 				      const struct bpf_kprobe_multi_opts *opts)
11391 {
11392 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
11393 	struct kprobe_multi_resolve res = {
11394 		.pattern = pattern,
11395 	};
11396 	struct bpf_link *link = NULL;
11397 	char errmsg[STRERR_BUFSIZE];
11398 	const unsigned long *addrs;
11399 	int err, link_fd, prog_fd;
11400 	const __u64 *cookies;
11401 	const char **syms;
11402 	bool retprobe;
11403 	size_t cnt;
11404 
11405 	if (!OPTS_VALID(opts, bpf_kprobe_multi_opts))
11406 		return libbpf_err_ptr(-EINVAL);
11407 
11408 	syms    = OPTS_GET(opts, syms, false);
11409 	addrs   = OPTS_GET(opts, addrs, false);
11410 	cnt     = OPTS_GET(opts, cnt, false);
11411 	cookies = OPTS_GET(opts, cookies, false);
11412 
11413 	if (!pattern && !addrs && !syms)
11414 		return libbpf_err_ptr(-EINVAL);
11415 	if (pattern && (addrs || syms || cookies || cnt))
11416 		return libbpf_err_ptr(-EINVAL);
11417 	if (!pattern && !cnt)
11418 		return libbpf_err_ptr(-EINVAL);
11419 	if (addrs && syms)
11420 		return libbpf_err_ptr(-EINVAL);
11421 
11422 	if (pattern) {
11423 		if (has_available_filter_functions_addrs())
11424 			err = libbpf_available_kprobes_parse(&res);
11425 		else
11426 			err = libbpf_available_kallsyms_parse(&res);
11427 		if (err)
11428 			goto error;
11429 		addrs = res.addrs;
11430 		cnt = res.cnt;
11431 	}
11432 
11433 	retprobe = OPTS_GET(opts, retprobe, false);
11434 
11435 	lopts.kprobe_multi.syms = syms;
11436 	lopts.kprobe_multi.addrs = addrs;
11437 	lopts.kprobe_multi.cookies = cookies;
11438 	lopts.kprobe_multi.cnt = cnt;
11439 	lopts.kprobe_multi.flags = retprobe ? BPF_F_KPROBE_MULTI_RETURN : 0;
11440 
11441 	link = calloc(1, sizeof(*link));
11442 	if (!link) {
11443 		err = -ENOMEM;
11444 		goto error;
11445 	}
11446 	link->detach = &bpf_link__detach_fd;
11447 
11448 	prog_fd = bpf_program__fd(prog);
11449 	link_fd = bpf_link_create(prog_fd, 0, BPF_TRACE_KPROBE_MULTI, &lopts);
11450 	if (link_fd < 0) {
11451 		err = -errno;
11452 		pr_warn("prog '%s': failed to attach: %s\n",
11453 			prog->name, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11454 		goto error;
11455 	}
11456 	link->fd = link_fd;
11457 	free(res.addrs);
11458 	return link;
11459 
11460 error:
11461 	free(link);
11462 	free(res.addrs);
11463 	return libbpf_err_ptr(err);
11464 }
11465 
11466 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11467 {
11468 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
11469 	unsigned long offset = 0;
11470 	const char *func_name;
11471 	char *func;
11472 	int n;
11473 
11474 	*link = NULL;
11475 
11476 	/* no auto-attach for SEC("kprobe") and SEC("kretprobe") */
11477 	if (strcmp(prog->sec_name, "kprobe") == 0 || strcmp(prog->sec_name, "kretprobe") == 0)
11478 		return 0;
11479 
11480 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
11481 	if (opts.retprobe)
11482 		func_name = prog->sec_name + sizeof("kretprobe/") - 1;
11483 	else
11484 		func_name = prog->sec_name + sizeof("kprobe/") - 1;
11485 
11486 	n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
11487 	if (n < 1) {
11488 		pr_warn("kprobe name is invalid: %s\n", func_name);
11489 		return -EINVAL;
11490 	}
11491 	if (opts.retprobe && offset != 0) {
11492 		free(func);
11493 		pr_warn("kretprobes do not support offset specification\n");
11494 		return -EINVAL;
11495 	}
11496 
11497 	opts.offset = offset;
11498 	*link = bpf_program__attach_kprobe_opts(prog, func, &opts);
11499 	free(func);
11500 	return libbpf_get_error(*link);
11501 }
11502 
11503 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11504 {
11505 	LIBBPF_OPTS(bpf_ksyscall_opts, opts);
11506 	const char *syscall_name;
11507 
11508 	*link = NULL;
11509 
11510 	/* no auto-attach for SEC("ksyscall") and SEC("kretsyscall") */
11511 	if (strcmp(prog->sec_name, "ksyscall") == 0 || strcmp(prog->sec_name, "kretsyscall") == 0)
11512 		return 0;
11513 
11514 	opts.retprobe = str_has_pfx(prog->sec_name, "kretsyscall/");
11515 	if (opts.retprobe)
11516 		syscall_name = prog->sec_name + sizeof("kretsyscall/") - 1;
11517 	else
11518 		syscall_name = prog->sec_name + sizeof("ksyscall/") - 1;
11519 
11520 	*link = bpf_program__attach_ksyscall(prog, syscall_name, &opts);
11521 	return *link ? 0 : -errno;
11522 }
11523 
11524 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11525 {
11526 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts);
11527 	const char *spec;
11528 	char *pattern;
11529 	int n;
11530 
11531 	*link = NULL;
11532 
11533 	/* no auto-attach for SEC("kprobe.multi") and SEC("kretprobe.multi") */
11534 	if (strcmp(prog->sec_name, "kprobe.multi") == 0 ||
11535 	    strcmp(prog->sec_name, "kretprobe.multi") == 0)
11536 		return 0;
11537 
11538 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe.multi/");
11539 	if (opts.retprobe)
11540 		spec = prog->sec_name + sizeof("kretprobe.multi/") - 1;
11541 	else
11542 		spec = prog->sec_name + sizeof("kprobe.multi/") - 1;
11543 
11544 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
11545 	if (n < 1) {
11546 		pr_warn("kprobe multi pattern is invalid: %s\n", pattern);
11547 		return -EINVAL;
11548 	}
11549 
11550 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
11551 	free(pattern);
11552 	return libbpf_get_error(*link);
11553 }
11554 
11555 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11556 {
11557 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
11558 	LIBBPF_OPTS(bpf_uprobe_multi_opts, opts);
11559 	int n, ret = -EINVAL;
11560 
11561 	*link = NULL;
11562 
11563 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
11564 		   &probe_type, &binary_path, &func_name);
11565 	switch (n) {
11566 	case 1:
11567 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
11568 		ret = 0;
11569 		break;
11570 	case 3:
11571 		opts.retprobe = strcmp(probe_type, "uretprobe.multi") == 0;
11572 		*link = bpf_program__attach_uprobe_multi(prog, -1, binary_path, func_name, &opts);
11573 		ret = libbpf_get_error(*link);
11574 		break;
11575 	default:
11576 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
11577 			prog->sec_name);
11578 		break;
11579 	}
11580 	free(probe_type);
11581 	free(binary_path);
11582 	free(func_name);
11583 	return ret;
11584 }
11585 
11586 static void gen_uprobe_legacy_event_name(char *buf, size_t buf_sz,
11587 					 const char *binary_path, uint64_t offset)
11588 {
11589 	int i;
11590 
11591 	snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx", getpid(), binary_path, (size_t)offset);
11592 
11593 	/* sanitize binary_path in the probe name */
11594 	for (i = 0; buf[i]; i++) {
11595 		if (!isalnum(buf[i]))
11596 			buf[i] = '_';
11597 	}
11598 }
11599 
11600 static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
11601 					  const char *binary_path, size_t offset)
11602 {
11603 	return append_to_file(tracefs_uprobe_events(), "%c:%s/%s %s:0x%zx",
11604 			      retprobe ? 'r' : 'p',
11605 			      retprobe ? "uretprobes" : "uprobes",
11606 			      probe_name, binary_path, offset);
11607 }
11608 
11609 static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
11610 {
11611 	return append_to_file(tracefs_uprobe_events(), "-:%s/%s",
11612 			      retprobe ? "uretprobes" : "uprobes", probe_name);
11613 }
11614 
11615 static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
11616 {
11617 	char file[512];
11618 
11619 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11620 		 tracefs_path(), retprobe ? "uretprobes" : "uprobes", probe_name);
11621 
11622 	return parse_uint_from_file(file, "%d\n");
11623 }
11624 
11625 static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
11626 					 const char *binary_path, size_t offset, int pid)
11627 {
11628 	const size_t attr_sz = sizeof(struct perf_event_attr);
11629 	struct perf_event_attr attr;
11630 	int type, pfd, err;
11631 
11632 	err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
11633 	if (err < 0) {
11634 		pr_warn("failed to add legacy uprobe event for %s:0x%zx: %d\n",
11635 			binary_path, (size_t)offset, err);
11636 		return err;
11637 	}
11638 	type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
11639 	if (type < 0) {
11640 		err = type;
11641 		pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %d\n",
11642 			binary_path, offset, err);
11643 		goto err_clean_legacy;
11644 	}
11645 
11646 	memset(&attr, 0, attr_sz);
11647 	attr.size = attr_sz;
11648 	attr.config = type;
11649 	attr.type = PERF_TYPE_TRACEPOINT;
11650 
11651 	pfd = syscall(__NR_perf_event_open, &attr,
11652 		      pid < 0 ? -1 : pid, /* pid */
11653 		      pid == -1 ? 0 : -1, /* cpu */
11654 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
11655 	if (pfd < 0) {
11656 		err = -errno;
11657 		pr_warn("legacy uprobe perf_event_open() failed: %d\n", err);
11658 		goto err_clean_legacy;
11659 	}
11660 	return pfd;
11661 
11662 err_clean_legacy:
11663 	/* Clear the newly added legacy uprobe_event */
11664 	remove_uprobe_event_legacy(probe_name, retprobe);
11665 	return err;
11666 }
11667 
11668 /* Find offset of function name in archive specified by path. Currently
11669  * supported are .zip files that do not compress their contents, as used on
11670  * Android in the form of APKs, for example. "file_name" is the name of the ELF
11671  * file inside the archive. "func_name" matches symbol name or name@@LIB for
11672  * library functions.
11673  *
11674  * An overview of the APK format specifically provided here:
11675  * https://en.wikipedia.org/w/index.php?title=Apk_(file_format)&oldid=1139099120#Package_contents
11676  */
11677 static long elf_find_func_offset_from_archive(const char *archive_path, const char *file_name,
11678 					      const char *func_name)
11679 {
11680 	struct zip_archive *archive;
11681 	struct zip_entry entry;
11682 	long ret;
11683 	Elf *elf;
11684 
11685 	archive = zip_archive_open(archive_path);
11686 	if (IS_ERR(archive)) {
11687 		ret = PTR_ERR(archive);
11688 		pr_warn("zip: failed to open %s: %ld\n", archive_path, ret);
11689 		return ret;
11690 	}
11691 
11692 	ret = zip_archive_find_entry(archive, file_name, &entry);
11693 	if (ret) {
11694 		pr_warn("zip: could not find archive member %s in %s: %ld\n", file_name,
11695 			archive_path, ret);
11696 		goto out;
11697 	}
11698 	pr_debug("zip: found entry for %s in %s at 0x%lx\n", file_name, archive_path,
11699 		 (unsigned long)entry.data_offset);
11700 
11701 	if (entry.compression) {
11702 		pr_warn("zip: entry %s of %s is compressed and cannot be handled\n", file_name,
11703 			archive_path);
11704 		ret = -LIBBPF_ERRNO__FORMAT;
11705 		goto out;
11706 	}
11707 
11708 	elf = elf_memory((void *)entry.data, entry.data_length);
11709 	if (!elf) {
11710 		pr_warn("elf: could not read elf file %s from %s: %s\n", file_name, archive_path,
11711 			elf_errmsg(-1));
11712 		ret = -LIBBPF_ERRNO__LIBELF;
11713 		goto out;
11714 	}
11715 
11716 	ret = elf_find_func_offset(elf, file_name, func_name);
11717 	if (ret > 0) {
11718 		pr_debug("elf: symbol address match for %s of %s in %s: 0x%x + 0x%lx = 0x%lx\n",
11719 			 func_name, file_name, archive_path, entry.data_offset, ret,
11720 			 ret + entry.data_offset);
11721 		ret += entry.data_offset;
11722 	}
11723 	elf_end(elf);
11724 
11725 out:
11726 	zip_archive_close(archive);
11727 	return ret;
11728 }
11729 
11730 static const char *arch_specific_lib_paths(void)
11731 {
11732 	/*
11733 	 * Based on https://packages.debian.org/sid/libc6.
11734 	 *
11735 	 * Assume that the traced program is built for the same architecture
11736 	 * as libbpf, which should cover the vast majority of cases.
11737 	 */
11738 #if defined(__x86_64__)
11739 	return "/lib/x86_64-linux-gnu";
11740 #elif defined(__i386__)
11741 	return "/lib/i386-linux-gnu";
11742 #elif defined(__s390x__)
11743 	return "/lib/s390x-linux-gnu";
11744 #elif defined(__s390__)
11745 	return "/lib/s390-linux-gnu";
11746 #elif defined(__arm__) && defined(__SOFTFP__)
11747 	return "/lib/arm-linux-gnueabi";
11748 #elif defined(__arm__) && !defined(__SOFTFP__)
11749 	return "/lib/arm-linux-gnueabihf";
11750 #elif defined(__aarch64__)
11751 	return "/lib/aarch64-linux-gnu";
11752 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 64
11753 	return "/lib/mips64el-linux-gnuabi64";
11754 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 32
11755 	return "/lib/mipsel-linux-gnu";
11756 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
11757 	return "/lib/powerpc64le-linux-gnu";
11758 #elif defined(__sparc__) && defined(__arch64__)
11759 	return "/lib/sparc64-linux-gnu";
11760 #elif defined(__riscv) && __riscv_xlen == 64
11761 	return "/lib/riscv64-linux-gnu";
11762 #else
11763 	return NULL;
11764 #endif
11765 }
11766 
11767 /* Get full path to program/shared library. */
11768 static int resolve_full_path(const char *file, char *result, size_t result_sz)
11769 {
11770 	const char *search_paths[3] = {};
11771 	int i, perm;
11772 
11773 	if (str_has_sfx(file, ".so") || strstr(file, ".so.")) {
11774 		search_paths[0] = getenv("LD_LIBRARY_PATH");
11775 		search_paths[1] = "/usr/lib64:/usr/lib";
11776 		search_paths[2] = arch_specific_lib_paths();
11777 		perm = R_OK;
11778 	} else {
11779 		search_paths[0] = getenv("PATH");
11780 		search_paths[1] = "/usr/bin:/usr/sbin";
11781 		perm = R_OK | X_OK;
11782 	}
11783 
11784 	for (i = 0; i < ARRAY_SIZE(search_paths); i++) {
11785 		const char *s;
11786 
11787 		if (!search_paths[i])
11788 			continue;
11789 		for (s = search_paths[i]; s != NULL; s = strchr(s, ':')) {
11790 			char *next_path;
11791 			int seg_len;
11792 
11793 			if (s[0] == ':')
11794 				s++;
11795 			next_path = strchr(s, ':');
11796 			seg_len = next_path ? next_path - s : strlen(s);
11797 			if (!seg_len)
11798 				continue;
11799 			snprintf(result, result_sz, "%.*s/%s", seg_len, s, file);
11800 			/* ensure it has required permissions */
11801 			if (faccessat(AT_FDCWD, result, perm, AT_EACCESS) < 0)
11802 				continue;
11803 			pr_debug("resolved '%s' to '%s'\n", file, result);
11804 			return 0;
11805 		}
11806 	}
11807 	return -ENOENT;
11808 }
11809 
11810 struct bpf_link *
11811 bpf_program__attach_uprobe_multi(const struct bpf_program *prog,
11812 				 pid_t pid,
11813 				 const char *path,
11814 				 const char *func_pattern,
11815 				 const struct bpf_uprobe_multi_opts *opts)
11816 {
11817 	const unsigned long *ref_ctr_offsets = NULL, *offsets = NULL;
11818 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
11819 	unsigned long *resolved_offsets = NULL;
11820 	int err = 0, link_fd, prog_fd;
11821 	struct bpf_link *link = NULL;
11822 	char errmsg[STRERR_BUFSIZE];
11823 	char full_path[PATH_MAX];
11824 	const __u64 *cookies;
11825 	const char **syms;
11826 	size_t cnt;
11827 
11828 	if (!OPTS_VALID(opts, bpf_uprobe_multi_opts))
11829 		return libbpf_err_ptr(-EINVAL);
11830 
11831 	syms = OPTS_GET(opts, syms, NULL);
11832 	offsets = OPTS_GET(opts, offsets, NULL);
11833 	ref_ctr_offsets = OPTS_GET(opts, ref_ctr_offsets, NULL);
11834 	cookies = OPTS_GET(opts, cookies, NULL);
11835 	cnt = OPTS_GET(opts, cnt, 0);
11836 
11837 	/*
11838 	 * User can specify 2 mutually exclusive set of inputs:
11839 	 *
11840 	 * 1) use only path/func_pattern/pid arguments
11841 	 *
11842 	 * 2) use path/pid with allowed combinations of:
11843 	 *    syms/offsets/ref_ctr_offsets/cookies/cnt
11844 	 *
11845 	 *    - syms and offsets are mutually exclusive
11846 	 *    - ref_ctr_offsets and cookies are optional
11847 	 *
11848 	 * Any other usage results in error.
11849 	 */
11850 
11851 	if (!path)
11852 		return libbpf_err_ptr(-EINVAL);
11853 	if (!func_pattern && cnt == 0)
11854 		return libbpf_err_ptr(-EINVAL);
11855 
11856 	if (func_pattern) {
11857 		if (syms || offsets || ref_ctr_offsets || cookies || cnt)
11858 			return libbpf_err_ptr(-EINVAL);
11859 	} else {
11860 		if (!!syms == !!offsets)
11861 			return libbpf_err_ptr(-EINVAL);
11862 	}
11863 
11864 	if (func_pattern) {
11865 		if (!strchr(path, '/')) {
11866 			err = resolve_full_path(path, full_path, sizeof(full_path));
11867 			if (err) {
11868 				pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11869 					prog->name, path, err);
11870 				return libbpf_err_ptr(err);
11871 			}
11872 			path = full_path;
11873 		}
11874 
11875 		err = elf_resolve_pattern_offsets(path, func_pattern,
11876 						  &resolved_offsets, &cnt);
11877 		if (err < 0)
11878 			return libbpf_err_ptr(err);
11879 		offsets = resolved_offsets;
11880 	} else if (syms) {
11881 		err = elf_resolve_syms_offsets(path, cnt, syms, &resolved_offsets, STT_FUNC);
11882 		if (err < 0)
11883 			return libbpf_err_ptr(err);
11884 		offsets = resolved_offsets;
11885 	}
11886 
11887 	lopts.uprobe_multi.path = path;
11888 	lopts.uprobe_multi.offsets = offsets;
11889 	lopts.uprobe_multi.ref_ctr_offsets = ref_ctr_offsets;
11890 	lopts.uprobe_multi.cookies = cookies;
11891 	lopts.uprobe_multi.cnt = cnt;
11892 	lopts.uprobe_multi.flags = OPTS_GET(opts, retprobe, false) ? BPF_F_UPROBE_MULTI_RETURN : 0;
11893 
11894 	if (pid == 0)
11895 		pid = getpid();
11896 	if (pid > 0)
11897 		lopts.uprobe_multi.pid = pid;
11898 
11899 	link = calloc(1, sizeof(*link));
11900 	if (!link) {
11901 		err = -ENOMEM;
11902 		goto error;
11903 	}
11904 	link->detach = &bpf_link__detach_fd;
11905 
11906 	prog_fd = bpf_program__fd(prog);
11907 	link_fd = bpf_link_create(prog_fd, 0, BPF_TRACE_UPROBE_MULTI, &lopts);
11908 	if (link_fd < 0) {
11909 		err = -errno;
11910 		pr_warn("prog '%s': failed to attach multi-uprobe: %s\n",
11911 			prog->name, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11912 		goto error;
11913 	}
11914 	link->fd = link_fd;
11915 	free(resolved_offsets);
11916 	return link;
11917 
11918 error:
11919 	free(resolved_offsets);
11920 	free(link);
11921 	return libbpf_err_ptr(err);
11922 }
11923 
11924 LIBBPF_API struct bpf_link *
11925 bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
11926 				const char *binary_path, size_t func_offset,
11927 				const struct bpf_uprobe_opts *opts)
11928 {
11929 	const char *archive_path = NULL, *archive_sep = NULL;
11930 	char errmsg[STRERR_BUFSIZE], *legacy_probe = NULL;
11931 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11932 	enum probe_attach_mode attach_mode;
11933 	char full_path[PATH_MAX];
11934 	struct bpf_link *link;
11935 	size_t ref_ctr_off;
11936 	int pfd, err;
11937 	bool retprobe, legacy;
11938 	const char *func_name;
11939 
11940 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
11941 		return libbpf_err_ptr(-EINVAL);
11942 
11943 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
11944 	retprobe = OPTS_GET(opts, retprobe, false);
11945 	ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
11946 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11947 
11948 	if (!binary_path)
11949 		return libbpf_err_ptr(-EINVAL);
11950 
11951 	/* Check if "binary_path" refers to an archive. */
11952 	archive_sep = strstr(binary_path, "!/");
11953 	if (archive_sep) {
11954 		full_path[0] = '\0';
11955 		libbpf_strlcpy(full_path, binary_path,
11956 			       min(sizeof(full_path), (size_t)(archive_sep - binary_path + 1)));
11957 		archive_path = full_path;
11958 		binary_path = archive_sep + 2;
11959 	} else if (!strchr(binary_path, '/')) {
11960 		err = resolve_full_path(binary_path, full_path, sizeof(full_path));
11961 		if (err) {
11962 			pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11963 				prog->name, binary_path, err);
11964 			return libbpf_err_ptr(err);
11965 		}
11966 		binary_path = full_path;
11967 	}
11968 	func_name = OPTS_GET(opts, func_name, NULL);
11969 	if (func_name) {
11970 		long sym_off;
11971 
11972 		if (archive_path) {
11973 			sym_off = elf_find_func_offset_from_archive(archive_path, binary_path,
11974 								    func_name);
11975 			binary_path = archive_path;
11976 		} else {
11977 			sym_off = elf_find_func_offset_from_file(binary_path, func_name);
11978 		}
11979 		if (sym_off < 0)
11980 			return libbpf_err_ptr(sym_off);
11981 		func_offset += sym_off;
11982 	}
11983 
11984 	legacy = determine_uprobe_perf_type() < 0;
11985 	switch (attach_mode) {
11986 	case PROBE_ATTACH_MODE_LEGACY:
11987 		legacy = true;
11988 		pe_opts.force_ioctl_attach = true;
11989 		break;
11990 	case PROBE_ATTACH_MODE_PERF:
11991 		if (legacy)
11992 			return libbpf_err_ptr(-ENOTSUP);
11993 		pe_opts.force_ioctl_attach = true;
11994 		break;
11995 	case PROBE_ATTACH_MODE_LINK:
11996 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
11997 			return libbpf_err_ptr(-ENOTSUP);
11998 		break;
11999 	case PROBE_ATTACH_MODE_DEFAULT:
12000 		break;
12001 	default:
12002 		return libbpf_err_ptr(-EINVAL);
12003 	}
12004 
12005 	if (!legacy) {
12006 		pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
12007 					    func_offset, pid, ref_ctr_off);
12008 	} else {
12009 		char probe_name[PATH_MAX + 64];
12010 
12011 		if (ref_ctr_off)
12012 			return libbpf_err_ptr(-EINVAL);
12013 
12014 		gen_uprobe_legacy_event_name(probe_name, sizeof(probe_name),
12015 					     binary_path, func_offset);
12016 
12017 		legacy_probe = strdup(probe_name);
12018 		if (!legacy_probe)
12019 			return libbpf_err_ptr(-ENOMEM);
12020 
12021 		pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
12022 						    binary_path, func_offset, pid);
12023 	}
12024 	if (pfd < 0) {
12025 		err = -errno;
12026 		pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
12027 			prog->name, retprobe ? "uretprobe" : "uprobe",
12028 			binary_path, func_offset,
12029 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
12030 		goto err_out;
12031 	}
12032 
12033 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
12034 	err = libbpf_get_error(link);
12035 	if (err) {
12036 		close(pfd);
12037 		pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
12038 			prog->name, retprobe ? "uretprobe" : "uprobe",
12039 			binary_path, func_offset,
12040 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
12041 		goto err_clean_legacy;
12042 	}
12043 	if (legacy) {
12044 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
12045 
12046 		perf_link->legacy_probe_name = legacy_probe;
12047 		perf_link->legacy_is_kprobe = false;
12048 		perf_link->legacy_is_retprobe = retprobe;
12049 	}
12050 	return link;
12051 
12052 err_clean_legacy:
12053 	if (legacy)
12054 		remove_uprobe_event_legacy(legacy_probe, retprobe);
12055 err_out:
12056 	free(legacy_probe);
12057 	return libbpf_err_ptr(err);
12058 }
12059 
12060 /* Format of u[ret]probe section definition supporting auto-attach:
12061  * u[ret]probe/binary:function[+offset]
12062  *
12063  * binary can be an absolute/relative path or a filename; the latter is resolved to a
12064  * full binary path via bpf_program__attach_uprobe_opts.
12065  *
12066  * Specifying uprobe+ ensures we carry out strict matching; either "uprobe" must be
12067  * specified (and auto-attach is not possible) or the above format is specified for
12068  * auto-attach.
12069  */
12070 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12071 {
12072 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts);
12073 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL, *func_off;
12074 	int n, c, ret = -EINVAL;
12075 	long offset = 0;
12076 
12077 	*link = NULL;
12078 
12079 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
12080 		   &probe_type, &binary_path, &func_name);
12081 	switch (n) {
12082 	case 1:
12083 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
12084 		ret = 0;
12085 		break;
12086 	case 2:
12087 		pr_warn("prog '%s': section '%s' missing ':function[+offset]' specification\n",
12088 			prog->name, prog->sec_name);
12089 		break;
12090 	case 3:
12091 		/* check if user specifies `+offset`, if yes, this should be
12092 		 * the last part of the string, make sure sscanf read to EOL
12093 		 */
12094 		func_off = strrchr(func_name, '+');
12095 		if (func_off) {
12096 			n = sscanf(func_off, "+%li%n", &offset, &c);
12097 			if (n == 1 && *(func_off + c) == '\0')
12098 				func_off[0] = '\0';
12099 			else
12100 				offset = 0;
12101 		}
12102 		opts.retprobe = strcmp(probe_type, "uretprobe") == 0 ||
12103 				strcmp(probe_type, "uretprobe.s") == 0;
12104 		if (opts.retprobe && offset != 0) {
12105 			pr_warn("prog '%s': uretprobes do not support offset specification\n",
12106 				prog->name);
12107 			break;
12108 		}
12109 		opts.func_name = func_name;
12110 		*link = bpf_program__attach_uprobe_opts(prog, -1, binary_path, offset, &opts);
12111 		ret = libbpf_get_error(*link);
12112 		break;
12113 	default:
12114 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
12115 			prog->sec_name);
12116 		break;
12117 	}
12118 	free(probe_type);
12119 	free(binary_path);
12120 	free(func_name);
12121 
12122 	return ret;
12123 }
12124 
12125 struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
12126 					    bool retprobe, pid_t pid,
12127 					    const char *binary_path,
12128 					    size_t func_offset)
12129 {
12130 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
12131 
12132 	return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
12133 }
12134 
12135 struct bpf_link *bpf_program__attach_usdt(const struct bpf_program *prog,
12136 					  pid_t pid, const char *binary_path,
12137 					  const char *usdt_provider, const char *usdt_name,
12138 					  const struct bpf_usdt_opts *opts)
12139 {
12140 	char resolved_path[512];
12141 	struct bpf_object *obj = prog->obj;
12142 	struct bpf_link *link;
12143 	__u64 usdt_cookie;
12144 	int err;
12145 
12146 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
12147 		return libbpf_err_ptr(-EINVAL);
12148 
12149 	if (bpf_program__fd(prog) < 0) {
12150 		pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
12151 			prog->name);
12152 		return libbpf_err_ptr(-EINVAL);
12153 	}
12154 
12155 	if (!binary_path)
12156 		return libbpf_err_ptr(-EINVAL);
12157 
12158 	if (!strchr(binary_path, '/')) {
12159 		err = resolve_full_path(binary_path, resolved_path, sizeof(resolved_path));
12160 		if (err) {
12161 			pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
12162 				prog->name, binary_path, err);
12163 			return libbpf_err_ptr(err);
12164 		}
12165 		binary_path = resolved_path;
12166 	}
12167 
12168 	/* USDT manager is instantiated lazily on first USDT attach. It will
12169 	 * be destroyed together with BPF object in bpf_object__close().
12170 	 */
12171 	if (IS_ERR(obj->usdt_man))
12172 		return libbpf_ptr(obj->usdt_man);
12173 	if (!obj->usdt_man) {
12174 		obj->usdt_man = usdt_manager_new(obj);
12175 		if (IS_ERR(obj->usdt_man))
12176 			return libbpf_ptr(obj->usdt_man);
12177 	}
12178 
12179 	usdt_cookie = OPTS_GET(opts, usdt_cookie, 0);
12180 	link = usdt_manager_attach_usdt(obj->usdt_man, prog, pid, binary_path,
12181 					usdt_provider, usdt_name, usdt_cookie);
12182 	err = libbpf_get_error(link);
12183 	if (err)
12184 		return libbpf_err_ptr(err);
12185 	return link;
12186 }
12187 
12188 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12189 {
12190 	char *path = NULL, *provider = NULL, *name = NULL;
12191 	const char *sec_name;
12192 	int n, err;
12193 
12194 	sec_name = bpf_program__section_name(prog);
12195 	if (strcmp(sec_name, "usdt") == 0) {
12196 		/* no auto-attach for just SEC("usdt") */
12197 		*link = NULL;
12198 		return 0;
12199 	}
12200 
12201 	n = sscanf(sec_name, "usdt/%m[^:]:%m[^:]:%m[^:]", &path, &provider, &name);
12202 	if (n != 3) {
12203 		pr_warn("invalid section '%s', expected SEC(\"usdt/<path>:<provider>:<name>\")\n",
12204 			sec_name);
12205 		err = -EINVAL;
12206 	} else {
12207 		*link = bpf_program__attach_usdt(prog, -1 /* any process */, path,
12208 						 provider, name, NULL);
12209 		err = libbpf_get_error(*link);
12210 	}
12211 	free(path);
12212 	free(provider);
12213 	free(name);
12214 	return err;
12215 }
12216 
12217 static int determine_tracepoint_id(const char *tp_category,
12218 				   const char *tp_name)
12219 {
12220 	char file[PATH_MAX];
12221 	int ret;
12222 
12223 	ret = snprintf(file, sizeof(file), "%s/events/%s/%s/id",
12224 		       tracefs_path(), tp_category, tp_name);
12225 	if (ret < 0)
12226 		return -errno;
12227 	if (ret >= sizeof(file)) {
12228 		pr_debug("tracepoint %s/%s path is too long\n",
12229 			 tp_category, tp_name);
12230 		return -E2BIG;
12231 	}
12232 	return parse_uint_from_file(file, "%d\n");
12233 }
12234 
12235 static int perf_event_open_tracepoint(const char *tp_category,
12236 				      const char *tp_name)
12237 {
12238 	const size_t attr_sz = sizeof(struct perf_event_attr);
12239 	struct perf_event_attr attr;
12240 	char errmsg[STRERR_BUFSIZE];
12241 	int tp_id, pfd, err;
12242 
12243 	tp_id = determine_tracepoint_id(tp_category, tp_name);
12244 	if (tp_id < 0) {
12245 		pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
12246 			tp_category, tp_name,
12247 			libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
12248 		return tp_id;
12249 	}
12250 
12251 	memset(&attr, 0, attr_sz);
12252 	attr.type = PERF_TYPE_TRACEPOINT;
12253 	attr.size = attr_sz;
12254 	attr.config = tp_id;
12255 
12256 	pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
12257 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
12258 	if (pfd < 0) {
12259 		err = -errno;
12260 		pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
12261 			tp_category, tp_name,
12262 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
12263 		return err;
12264 	}
12265 	return pfd;
12266 }
12267 
12268 struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
12269 						     const char *tp_category,
12270 						     const char *tp_name,
12271 						     const struct bpf_tracepoint_opts *opts)
12272 {
12273 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
12274 	char errmsg[STRERR_BUFSIZE];
12275 	struct bpf_link *link;
12276 	int pfd, err;
12277 
12278 	if (!OPTS_VALID(opts, bpf_tracepoint_opts))
12279 		return libbpf_err_ptr(-EINVAL);
12280 
12281 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
12282 
12283 	pfd = perf_event_open_tracepoint(tp_category, tp_name);
12284 	if (pfd < 0) {
12285 		pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
12286 			prog->name, tp_category, tp_name,
12287 			libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
12288 		return libbpf_err_ptr(pfd);
12289 	}
12290 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
12291 	err = libbpf_get_error(link);
12292 	if (err) {
12293 		close(pfd);
12294 		pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
12295 			prog->name, tp_category, tp_name,
12296 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
12297 		return libbpf_err_ptr(err);
12298 	}
12299 	return link;
12300 }
12301 
12302 struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
12303 						const char *tp_category,
12304 						const char *tp_name)
12305 {
12306 	return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
12307 }
12308 
12309 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12310 {
12311 	char *sec_name, *tp_cat, *tp_name;
12312 
12313 	*link = NULL;
12314 
12315 	/* no auto-attach for SEC("tp") or SEC("tracepoint") */
12316 	if (strcmp(prog->sec_name, "tp") == 0 || strcmp(prog->sec_name, "tracepoint") == 0)
12317 		return 0;
12318 
12319 	sec_name = strdup(prog->sec_name);
12320 	if (!sec_name)
12321 		return -ENOMEM;
12322 
12323 	/* extract "tp/<category>/<name>" or "tracepoint/<category>/<name>" */
12324 	if (str_has_pfx(prog->sec_name, "tp/"))
12325 		tp_cat = sec_name + sizeof("tp/") - 1;
12326 	else
12327 		tp_cat = sec_name + sizeof("tracepoint/") - 1;
12328 	tp_name = strchr(tp_cat, '/');
12329 	if (!tp_name) {
12330 		free(sec_name);
12331 		return -EINVAL;
12332 	}
12333 	*tp_name = '\0';
12334 	tp_name++;
12335 
12336 	*link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
12337 	free(sec_name);
12338 	return libbpf_get_error(*link);
12339 }
12340 
12341 struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
12342 						    const char *tp_name)
12343 {
12344 	char errmsg[STRERR_BUFSIZE];
12345 	struct bpf_link *link;
12346 	int prog_fd, pfd;
12347 
12348 	prog_fd = bpf_program__fd(prog);
12349 	if (prog_fd < 0) {
12350 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12351 		return libbpf_err_ptr(-EINVAL);
12352 	}
12353 
12354 	link = calloc(1, sizeof(*link));
12355 	if (!link)
12356 		return libbpf_err_ptr(-ENOMEM);
12357 	link->detach = &bpf_link__detach_fd;
12358 
12359 	pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
12360 	if (pfd < 0) {
12361 		pfd = -errno;
12362 		free(link);
12363 		pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
12364 			prog->name, tp_name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
12365 		return libbpf_err_ptr(pfd);
12366 	}
12367 	link->fd = pfd;
12368 	return link;
12369 }
12370 
12371 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12372 {
12373 	static const char *const prefixes[] = {
12374 		"raw_tp",
12375 		"raw_tracepoint",
12376 		"raw_tp.w",
12377 		"raw_tracepoint.w",
12378 	};
12379 	size_t i;
12380 	const char *tp_name = NULL;
12381 
12382 	*link = NULL;
12383 
12384 	for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
12385 		size_t pfx_len;
12386 
12387 		if (!str_has_pfx(prog->sec_name, prefixes[i]))
12388 			continue;
12389 
12390 		pfx_len = strlen(prefixes[i]);
12391 		/* no auto-attach case of, e.g., SEC("raw_tp") */
12392 		if (prog->sec_name[pfx_len] == '\0')
12393 			return 0;
12394 
12395 		if (prog->sec_name[pfx_len] != '/')
12396 			continue;
12397 
12398 		tp_name = prog->sec_name + pfx_len + 1;
12399 		break;
12400 	}
12401 
12402 	if (!tp_name) {
12403 		pr_warn("prog '%s': invalid section name '%s'\n",
12404 			prog->name, prog->sec_name);
12405 		return -EINVAL;
12406 	}
12407 
12408 	*link = bpf_program__attach_raw_tracepoint(prog, tp_name);
12409 	return libbpf_get_error(*link);
12410 }
12411 
12412 /* Common logic for all BPF program types that attach to a btf_id */
12413 static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog,
12414 						   const struct bpf_trace_opts *opts)
12415 {
12416 	LIBBPF_OPTS(bpf_link_create_opts, link_opts);
12417 	char errmsg[STRERR_BUFSIZE];
12418 	struct bpf_link *link;
12419 	int prog_fd, pfd;
12420 
12421 	if (!OPTS_VALID(opts, bpf_trace_opts))
12422 		return libbpf_err_ptr(-EINVAL);
12423 
12424 	prog_fd = bpf_program__fd(prog);
12425 	if (prog_fd < 0) {
12426 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12427 		return libbpf_err_ptr(-EINVAL);
12428 	}
12429 
12430 	link = calloc(1, sizeof(*link));
12431 	if (!link)
12432 		return libbpf_err_ptr(-ENOMEM);
12433 	link->detach = &bpf_link__detach_fd;
12434 
12435 	/* libbpf is smart enough to redirect to BPF_RAW_TRACEPOINT_OPEN on old kernels */
12436 	link_opts.tracing.cookie = OPTS_GET(opts, cookie, 0);
12437 	pfd = bpf_link_create(prog_fd, 0, bpf_program__expected_attach_type(prog), &link_opts);
12438 	if (pfd < 0) {
12439 		pfd = -errno;
12440 		free(link);
12441 		pr_warn("prog '%s': failed to attach: %s\n",
12442 			prog->name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
12443 		return libbpf_err_ptr(pfd);
12444 	}
12445 	link->fd = pfd;
12446 	return link;
12447 }
12448 
12449 struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
12450 {
12451 	return bpf_program__attach_btf_id(prog, NULL);
12452 }
12453 
12454 struct bpf_link *bpf_program__attach_trace_opts(const struct bpf_program *prog,
12455 						const struct bpf_trace_opts *opts)
12456 {
12457 	return bpf_program__attach_btf_id(prog, opts);
12458 }
12459 
12460 struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
12461 {
12462 	return bpf_program__attach_btf_id(prog, NULL);
12463 }
12464 
12465 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12466 {
12467 	*link = bpf_program__attach_trace(prog);
12468 	return libbpf_get_error(*link);
12469 }
12470 
12471 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12472 {
12473 	*link = bpf_program__attach_lsm(prog);
12474 	return libbpf_get_error(*link);
12475 }
12476 
12477 static struct bpf_link *
12478 bpf_program_attach_fd(const struct bpf_program *prog,
12479 		      int target_fd, const char *target_name,
12480 		      const struct bpf_link_create_opts *opts)
12481 {
12482 	enum bpf_attach_type attach_type;
12483 	char errmsg[STRERR_BUFSIZE];
12484 	struct bpf_link *link;
12485 	int prog_fd, link_fd;
12486 
12487 	prog_fd = bpf_program__fd(prog);
12488 	if (prog_fd < 0) {
12489 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12490 		return libbpf_err_ptr(-EINVAL);
12491 	}
12492 
12493 	link = calloc(1, sizeof(*link));
12494 	if (!link)
12495 		return libbpf_err_ptr(-ENOMEM);
12496 	link->detach = &bpf_link__detach_fd;
12497 
12498 	attach_type = bpf_program__expected_attach_type(prog);
12499 	link_fd = bpf_link_create(prog_fd, target_fd, attach_type, opts);
12500 	if (link_fd < 0) {
12501 		link_fd = -errno;
12502 		free(link);
12503 		pr_warn("prog '%s': failed to attach to %s: %s\n",
12504 			prog->name, target_name,
12505 			libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
12506 		return libbpf_err_ptr(link_fd);
12507 	}
12508 	link->fd = link_fd;
12509 	return link;
12510 }
12511 
12512 struct bpf_link *
12513 bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
12514 {
12515 	return bpf_program_attach_fd(prog, cgroup_fd, "cgroup", NULL);
12516 }
12517 
12518 struct bpf_link *
12519 bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
12520 {
12521 	return bpf_program_attach_fd(prog, netns_fd, "netns", NULL);
12522 }
12523 
12524 struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
12525 {
12526 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
12527 	return bpf_program_attach_fd(prog, ifindex, "xdp", NULL);
12528 }
12529 
12530 struct bpf_link *
12531 bpf_program__attach_tcx(const struct bpf_program *prog, int ifindex,
12532 			const struct bpf_tcx_opts *opts)
12533 {
12534 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12535 	__u32 relative_id;
12536 	int relative_fd;
12537 
12538 	if (!OPTS_VALID(opts, bpf_tcx_opts))
12539 		return libbpf_err_ptr(-EINVAL);
12540 
12541 	relative_id = OPTS_GET(opts, relative_id, 0);
12542 	relative_fd = OPTS_GET(opts, relative_fd, 0);
12543 
12544 	/* validate we don't have unexpected combinations of non-zero fields */
12545 	if (!ifindex) {
12546 		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
12547 			prog->name);
12548 		return libbpf_err_ptr(-EINVAL);
12549 	}
12550 	if (relative_fd && relative_id) {
12551 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
12552 			prog->name);
12553 		return libbpf_err_ptr(-EINVAL);
12554 	}
12555 
12556 	link_create_opts.tcx.expected_revision = OPTS_GET(opts, expected_revision, 0);
12557 	link_create_opts.tcx.relative_fd = relative_fd;
12558 	link_create_opts.tcx.relative_id = relative_id;
12559 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
12560 
12561 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
12562 	return bpf_program_attach_fd(prog, ifindex, "tcx", &link_create_opts);
12563 }
12564 
12565 struct bpf_link *
12566 bpf_program__attach_netkit(const struct bpf_program *prog, int ifindex,
12567 			   const struct bpf_netkit_opts *opts)
12568 {
12569 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12570 	__u32 relative_id;
12571 	int relative_fd;
12572 
12573 	if (!OPTS_VALID(opts, bpf_netkit_opts))
12574 		return libbpf_err_ptr(-EINVAL);
12575 
12576 	relative_id = OPTS_GET(opts, relative_id, 0);
12577 	relative_fd = OPTS_GET(opts, relative_fd, 0);
12578 
12579 	/* validate we don't have unexpected combinations of non-zero fields */
12580 	if (!ifindex) {
12581 		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
12582 			prog->name);
12583 		return libbpf_err_ptr(-EINVAL);
12584 	}
12585 	if (relative_fd && relative_id) {
12586 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
12587 			prog->name);
12588 		return libbpf_err_ptr(-EINVAL);
12589 	}
12590 
12591 	link_create_opts.netkit.expected_revision = OPTS_GET(opts, expected_revision, 0);
12592 	link_create_opts.netkit.relative_fd = relative_fd;
12593 	link_create_opts.netkit.relative_id = relative_id;
12594 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
12595 
12596 	return bpf_program_attach_fd(prog, ifindex, "netkit", &link_create_opts);
12597 }
12598 
12599 struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
12600 					      int target_fd,
12601 					      const char *attach_func_name)
12602 {
12603 	int btf_id;
12604 
12605 	if (!!target_fd != !!attach_func_name) {
12606 		pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
12607 			prog->name);
12608 		return libbpf_err_ptr(-EINVAL);
12609 	}
12610 
12611 	if (prog->type != BPF_PROG_TYPE_EXT) {
12612 		pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace",
12613 			prog->name);
12614 		return libbpf_err_ptr(-EINVAL);
12615 	}
12616 
12617 	if (target_fd) {
12618 		LIBBPF_OPTS(bpf_link_create_opts, target_opts);
12619 
12620 		btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd);
12621 		if (btf_id < 0)
12622 			return libbpf_err_ptr(btf_id);
12623 
12624 		target_opts.target_btf_id = btf_id;
12625 
12626 		return bpf_program_attach_fd(prog, target_fd, "freplace",
12627 					     &target_opts);
12628 	} else {
12629 		/* no target, so use raw_tracepoint_open for compatibility
12630 		 * with old kernels
12631 		 */
12632 		return bpf_program__attach_trace(prog);
12633 	}
12634 }
12635 
12636 struct bpf_link *
12637 bpf_program__attach_iter(const struct bpf_program *prog,
12638 			 const struct bpf_iter_attach_opts *opts)
12639 {
12640 	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12641 	char errmsg[STRERR_BUFSIZE];
12642 	struct bpf_link *link;
12643 	int prog_fd, link_fd;
12644 	__u32 target_fd = 0;
12645 
12646 	if (!OPTS_VALID(opts, bpf_iter_attach_opts))
12647 		return libbpf_err_ptr(-EINVAL);
12648 
12649 	link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
12650 	link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
12651 
12652 	prog_fd = bpf_program__fd(prog);
12653 	if (prog_fd < 0) {
12654 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12655 		return libbpf_err_ptr(-EINVAL);
12656 	}
12657 
12658 	link = calloc(1, sizeof(*link));
12659 	if (!link)
12660 		return libbpf_err_ptr(-ENOMEM);
12661 	link->detach = &bpf_link__detach_fd;
12662 
12663 	link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
12664 				  &link_create_opts);
12665 	if (link_fd < 0) {
12666 		link_fd = -errno;
12667 		free(link);
12668 		pr_warn("prog '%s': failed to attach to iterator: %s\n",
12669 			prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
12670 		return libbpf_err_ptr(link_fd);
12671 	}
12672 	link->fd = link_fd;
12673 	return link;
12674 }
12675 
12676 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12677 {
12678 	*link = bpf_program__attach_iter(prog, NULL);
12679 	return libbpf_get_error(*link);
12680 }
12681 
12682 struct bpf_link *bpf_program__attach_netfilter(const struct bpf_program *prog,
12683 					       const struct bpf_netfilter_opts *opts)
12684 {
12685 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
12686 	struct bpf_link *link;
12687 	int prog_fd, link_fd;
12688 
12689 	if (!OPTS_VALID(opts, bpf_netfilter_opts))
12690 		return libbpf_err_ptr(-EINVAL);
12691 
12692 	prog_fd = bpf_program__fd(prog);
12693 	if (prog_fd < 0) {
12694 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12695 		return libbpf_err_ptr(-EINVAL);
12696 	}
12697 
12698 	link = calloc(1, sizeof(*link));
12699 	if (!link)
12700 		return libbpf_err_ptr(-ENOMEM);
12701 
12702 	link->detach = &bpf_link__detach_fd;
12703 
12704 	lopts.netfilter.pf = OPTS_GET(opts, pf, 0);
12705 	lopts.netfilter.hooknum = OPTS_GET(opts, hooknum, 0);
12706 	lopts.netfilter.priority = OPTS_GET(opts, priority, 0);
12707 	lopts.netfilter.flags = OPTS_GET(opts, flags, 0);
12708 
12709 	link_fd = bpf_link_create(prog_fd, 0, BPF_NETFILTER, &lopts);
12710 	if (link_fd < 0) {
12711 		char errmsg[STRERR_BUFSIZE];
12712 
12713 		link_fd = -errno;
12714 		free(link);
12715 		pr_warn("prog '%s': failed to attach to netfilter: %s\n",
12716 			prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
12717 		return libbpf_err_ptr(link_fd);
12718 	}
12719 	link->fd = link_fd;
12720 
12721 	return link;
12722 }
12723 
12724 struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
12725 {
12726 	struct bpf_link *link = NULL;
12727 	int err;
12728 
12729 	if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
12730 		return libbpf_err_ptr(-EOPNOTSUPP);
12731 
12732 	err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, &link);
12733 	if (err)
12734 		return libbpf_err_ptr(err);
12735 
12736 	/* When calling bpf_program__attach() explicitly, auto-attach support
12737 	 * is expected to work, so NULL returned link is considered an error.
12738 	 * This is different for skeleton's attach, see comment in
12739 	 * bpf_object__attach_skeleton().
12740 	 */
12741 	if (!link)
12742 		return libbpf_err_ptr(-EOPNOTSUPP);
12743 
12744 	return link;
12745 }
12746 
12747 struct bpf_link_struct_ops {
12748 	struct bpf_link link;
12749 	int map_fd;
12750 };
12751 
12752 static int bpf_link__detach_struct_ops(struct bpf_link *link)
12753 {
12754 	struct bpf_link_struct_ops *st_link;
12755 	__u32 zero = 0;
12756 
12757 	st_link = container_of(link, struct bpf_link_struct_ops, link);
12758 
12759 	if (st_link->map_fd < 0)
12760 		/* w/o a real link */
12761 		return bpf_map_delete_elem(link->fd, &zero);
12762 
12763 	return close(link->fd);
12764 }
12765 
12766 struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
12767 {
12768 	struct bpf_link_struct_ops *link;
12769 	__u32 zero = 0;
12770 	int err, fd;
12771 
12772 	if (!bpf_map__is_struct_ops(map) || map->fd == -1)
12773 		return libbpf_err_ptr(-EINVAL);
12774 
12775 	link = calloc(1, sizeof(*link));
12776 	if (!link)
12777 		return libbpf_err_ptr(-EINVAL);
12778 
12779 	/* kern_vdata should be prepared during the loading phase. */
12780 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
12781 	/* It can be EBUSY if the map has been used to create or
12782 	 * update a link before.  We don't allow updating the value of
12783 	 * a struct_ops once it is set.  That ensures that the value
12784 	 * never changed.  So, it is safe to skip EBUSY.
12785 	 */
12786 	if (err && (!(map->def.map_flags & BPF_F_LINK) || err != -EBUSY)) {
12787 		free(link);
12788 		return libbpf_err_ptr(err);
12789 	}
12790 
12791 	link->link.detach = bpf_link__detach_struct_ops;
12792 
12793 	if (!(map->def.map_flags & BPF_F_LINK)) {
12794 		/* w/o a real link */
12795 		link->link.fd = map->fd;
12796 		link->map_fd = -1;
12797 		return &link->link;
12798 	}
12799 
12800 	fd = bpf_link_create(map->fd, 0, BPF_STRUCT_OPS, NULL);
12801 	if (fd < 0) {
12802 		free(link);
12803 		return libbpf_err_ptr(fd);
12804 	}
12805 
12806 	link->link.fd = fd;
12807 	link->map_fd = map->fd;
12808 
12809 	return &link->link;
12810 }
12811 
12812 /*
12813  * Swap the back struct_ops of a link with a new struct_ops map.
12814  */
12815 int bpf_link__update_map(struct bpf_link *link, const struct bpf_map *map)
12816 {
12817 	struct bpf_link_struct_ops *st_ops_link;
12818 	__u32 zero = 0;
12819 	int err;
12820 
12821 	if (!bpf_map__is_struct_ops(map) || !map_is_created(map))
12822 		return -EINVAL;
12823 
12824 	st_ops_link = container_of(link, struct bpf_link_struct_ops, link);
12825 	/* Ensure the type of a link is correct */
12826 	if (st_ops_link->map_fd < 0)
12827 		return -EINVAL;
12828 
12829 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
12830 	/* It can be EBUSY if the map has been used to create or
12831 	 * update a link before.  We don't allow updating the value of
12832 	 * a struct_ops once it is set.  That ensures that the value
12833 	 * never changed.  So, it is safe to skip EBUSY.
12834 	 */
12835 	if (err && err != -EBUSY)
12836 		return err;
12837 
12838 	err = bpf_link_update(link->fd, map->fd, NULL);
12839 	if (err < 0)
12840 		return err;
12841 
12842 	st_ops_link->map_fd = map->fd;
12843 
12844 	return 0;
12845 }
12846 
12847 typedef enum bpf_perf_event_ret (*bpf_perf_event_print_t)(struct perf_event_header *hdr,
12848 							  void *private_data);
12849 
12850 static enum bpf_perf_event_ret
12851 perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
12852 		       void **copy_mem, size_t *copy_size,
12853 		       bpf_perf_event_print_t fn, void *private_data)
12854 {
12855 	struct perf_event_mmap_page *header = mmap_mem;
12856 	__u64 data_head = ring_buffer_read_head(header);
12857 	__u64 data_tail = header->data_tail;
12858 	void *base = ((__u8 *)header) + page_size;
12859 	int ret = LIBBPF_PERF_EVENT_CONT;
12860 	struct perf_event_header *ehdr;
12861 	size_t ehdr_size;
12862 
12863 	while (data_head != data_tail) {
12864 		ehdr = base + (data_tail & (mmap_size - 1));
12865 		ehdr_size = ehdr->size;
12866 
12867 		if (((void *)ehdr) + ehdr_size > base + mmap_size) {
12868 			void *copy_start = ehdr;
12869 			size_t len_first = base + mmap_size - copy_start;
12870 			size_t len_secnd = ehdr_size - len_first;
12871 
12872 			if (*copy_size < ehdr_size) {
12873 				free(*copy_mem);
12874 				*copy_mem = malloc(ehdr_size);
12875 				if (!*copy_mem) {
12876 					*copy_size = 0;
12877 					ret = LIBBPF_PERF_EVENT_ERROR;
12878 					break;
12879 				}
12880 				*copy_size = ehdr_size;
12881 			}
12882 
12883 			memcpy(*copy_mem, copy_start, len_first);
12884 			memcpy(*copy_mem + len_first, base, len_secnd);
12885 			ehdr = *copy_mem;
12886 		}
12887 
12888 		ret = fn(ehdr, private_data);
12889 		data_tail += ehdr_size;
12890 		if (ret != LIBBPF_PERF_EVENT_CONT)
12891 			break;
12892 	}
12893 
12894 	ring_buffer_write_tail(header, data_tail);
12895 	return libbpf_err(ret);
12896 }
12897 
12898 struct perf_buffer;
12899 
12900 struct perf_buffer_params {
12901 	struct perf_event_attr *attr;
12902 	/* if event_cb is specified, it takes precendence */
12903 	perf_buffer_event_fn event_cb;
12904 	/* sample_cb and lost_cb are higher-level common-case callbacks */
12905 	perf_buffer_sample_fn sample_cb;
12906 	perf_buffer_lost_fn lost_cb;
12907 	void *ctx;
12908 	int cpu_cnt;
12909 	int *cpus;
12910 	int *map_keys;
12911 };
12912 
12913 struct perf_cpu_buf {
12914 	struct perf_buffer *pb;
12915 	void *base; /* mmap()'ed memory */
12916 	void *buf; /* for reconstructing segmented data */
12917 	size_t buf_size;
12918 	int fd;
12919 	int cpu;
12920 	int map_key;
12921 };
12922 
12923 struct perf_buffer {
12924 	perf_buffer_event_fn event_cb;
12925 	perf_buffer_sample_fn sample_cb;
12926 	perf_buffer_lost_fn lost_cb;
12927 	void *ctx; /* passed into callbacks */
12928 
12929 	size_t page_size;
12930 	size_t mmap_size;
12931 	struct perf_cpu_buf **cpu_bufs;
12932 	struct epoll_event *events;
12933 	int cpu_cnt; /* number of allocated CPU buffers */
12934 	int epoll_fd; /* perf event FD */
12935 	int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
12936 };
12937 
12938 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
12939 				      struct perf_cpu_buf *cpu_buf)
12940 {
12941 	if (!cpu_buf)
12942 		return;
12943 	if (cpu_buf->base &&
12944 	    munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
12945 		pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
12946 	if (cpu_buf->fd >= 0) {
12947 		ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
12948 		close(cpu_buf->fd);
12949 	}
12950 	free(cpu_buf->buf);
12951 	free(cpu_buf);
12952 }
12953 
12954 void perf_buffer__free(struct perf_buffer *pb)
12955 {
12956 	int i;
12957 
12958 	if (IS_ERR_OR_NULL(pb))
12959 		return;
12960 	if (pb->cpu_bufs) {
12961 		for (i = 0; i < pb->cpu_cnt; i++) {
12962 			struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
12963 
12964 			if (!cpu_buf)
12965 				continue;
12966 
12967 			bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
12968 			perf_buffer__free_cpu_buf(pb, cpu_buf);
12969 		}
12970 		free(pb->cpu_bufs);
12971 	}
12972 	if (pb->epoll_fd >= 0)
12973 		close(pb->epoll_fd);
12974 	free(pb->events);
12975 	free(pb);
12976 }
12977 
12978 static struct perf_cpu_buf *
12979 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
12980 			  int cpu, int map_key)
12981 {
12982 	struct perf_cpu_buf *cpu_buf;
12983 	char msg[STRERR_BUFSIZE];
12984 	int err;
12985 
12986 	cpu_buf = calloc(1, sizeof(*cpu_buf));
12987 	if (!cpu_buf)
12988 		return ERR_PTR(-ENOMEM);
12989 
12990 	cpu_buf->pb = pb;
12991 	cpu_buf->cpu = cpu;
12992 	cpu_buf->map_key = map_key;
12993 
12994 	cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
12995 			      -1, PERF_FLAG_FD_CLOEXEC);
12996 	if (cpu_buf->fd < 0) {
12997 		err = -errno;
12998 		pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
12999 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
13000 		goto error;
13001 	}
13002 
13003 	cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
13004 			     PROT_READ | PROT_WRITE, MAP_SHARED,
13005 			     cpu_buf->fd, 0);
13006 	if (cpu_buf->base == MAP_FAILED) {
13007 		cpu_buf->base = NULL;
13008 		err = -errno;
13009 		pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
13010 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
13011 		goto error;
13012 	}
13013 
13014 	if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
13015 		err = -errno;
13016 		pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
13017 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
13018 		goto error;
13019 	}
13020 
13021 	return cpu_buf;
13022 
13023 error:
13024 	perf_buffer__free_cpu_buf(pb, cpu_buf);
13025 	return (struct perf_cpu_buf *)ERR_PTR(err);
13026 }
13027 
13028 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
13029 					      struct perf_buffer_params *p);
13030 
13031 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
13032 				     perf_buffer_sample_fn sample_cb,
13033 				     perf_buffer_lost_fn lost_cb,
13034 				     void *ctx,
13035 				     const struct perf_buffer_opts *opts)
13036 {
13037 	const size_t attr_sz = sizeof(struct perf_event_attr);
13038 	struct perf_buffer_params p = {};
13039 	struct perf_event_attr attr;
13040 	__u32 sample_period;
13041 
13042 	if (!OPTS_VALID(opts, perf_buffer_opts))
13043 		return libbpf_err_ptr(-EINVAL);
13044 
13045 	sample_period = OPTS_GET(opts, sample_period, 1);
13046 	if (!sample_period)
13047 		sample_period = 1;
13048 
13049 	memset(&attr, 0, attr_sz);
13050 	attr.size = attr_sz;
13051 	attr.config = PERF_COUNT_SW_BPF_OUTPUT;
13052 	attr.type = PERF_TYPE_SOFTWARE;
13053 	attr.sample_type = PERF_SAMPLE_RAW;
13054 	attr.sample_period = sample_period;
13055 	attr.wakeup_events = sample_period;
13056 
13057 	p.attr = &attr;
13058 	p.sample_cb = sample_cb;
13059 	p.lost_cb = lost_cb;
13060 	p.ctx = ctx;
13061 
13062 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
13063 }
13064 
13065 struct perf_buffer *perf_buffer__new_raw(int map_fd, size_t page_cnt,
13066 					 struct perf_event_attr *attr,
13067 					 perf_buffer_event_fn event_cb, void *ctx,
13068 					 const struct perf_buffer_raw_opts *opts)
13069 {
13070 	struct perf_buffer_params p = {};
13071 
13072 	if (!attr)
13073 		return libbpf_err_ptr(-EINVAL);
13074 
13075 	if (!OPTS_VALID(opts, perf_buffer_raw_opts))
13076 		return libbpf_err_ptr(-EINVAL);
13077 
13078 	p.attr = attr;
13079 	p.event_cb = event_cb;
13080 	p.ctx = ctx;
13081 	p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
13082 	p.cpus = OPTS_GET(opts, cpus, NULL);
13083 	p.map_keys = OPTS_GET(opts, map_keys, NULL);
13084 
13085 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
13086 }
13087 
13088 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
13089 					      struct perf_buffer_params *p)
13090 {
13091 	const char *online_cpus_file = "/sys/devices/system/cpu/online";
13092 	struct bpf_map_info map;
13093 	char msg[STRERR_BUFSIZE];
13094 	struct perf_buffer *pb;
13095 	bool *online = NULL;
13096 	__u32 map_info_len;
13097 	int err, i, j, n;
13098 
13099 	if (page_cnt == 0 || (page_cnt & (page_cnt - 1))) {
13100 		pr_warn("page count should be power of two, but is %zu\n",
13101 			page_cnt);
13102 		return ERR_PTR(-EINVAL);
13103 	}
13104 
13105 	/* best-effort sanity checks */
13106 	memset(&map, 0, sizeof(map));
13107 	map_info_len = sizeof(map);
13108 	err = bpf_map_get_info_by_fd(map_fd, &map, &map_info_len);
13109 	if (err) {
13110 		err = -errno;
13111 		/* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
13112 		 * -EBADFD, -EFAULT, or -E2BIG on real error
13113 		 */
13114 		if (err != -EINVAL) {
13115 			pr_warn("failed to get map info for map FD %d: %s\n",
13116 				map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
13117 			return ERR_PTR(err);
13118 		}
13119 		pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
13120 			 map_fd);
13121 	} else {
13122 		if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
13123 			pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
13124 				map.name);
13125 			return ERR_PTR(-EINVAL);
13126 		}
13127 	}
13128 
13129 	pb = calloc(1, sizeof(*pb));
13130 	if (!pb)
13131 		return ERR_PTR(-ENOMEM);
13132 
13133 	pb->event_cb = p->event_cb;
13134 	pb->sample_cb = p->sample_cb;
13135 	pb->lost_cb = p->lost_cb;
13136 	pb->ctx = p->ctx;
13137 
13138 	pb->page_size = getpagesize();
13139 	pb->mmap_size = pb->page_size * page_cnt;
13140 	pb->map_fd = map_fd;
13141 
13142 	pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
13143 	if (pb->epoll_fd < 0) {
13144 		err = -errno;
13145 		pr_warn("failed to create epoll instance: %s\n",
13146 			libbpf_strerror_r(err, msg, sizeof(msg)));
13147 		goto error;
13148 	}
13149 
13150 	if (p->cpu_cnt > 0) {
13151 		pb->cpu_cnt = p->cpu_cnt;
13152 	} else {
13153 		pb->cpu_cnt = libbpf_num_possible_cpus();
13154 		if (pb->cpu_cnt < 0) {
13155 			err = pb->cpu_cnt;
13156 			goto error;
13157 		}
13158 		if (map.max_entries && map.max_entries < pb->cpu_cnt)
13159 			pb->cpu_cnt = map.max_entries;
13160 	}
13161 
13162 	pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
13163 	if (!pb->events) {
13164 		err = -ENOMEM;
13165 		pr_warn("failed to allocate events: out of memory\n");
13166 		goto error;
13167 	}
13168 	pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
13169 	if (!pb->cpu_bufs) {
13170 		err = -ENOMEM;
13171 		pr_warn("failed to allocate buffers: out of memory\n");
13172 		goto error;
13173 	}
13174 
13175 	err = parse_cpu_mask_file(online_cpus_file, &online, &n);
13176 	if (err) {
13177 		pr_warn("failed to get online CPU mask: %d\n", err);
13178 		goto error;
13179 	}
13180 
13181 	for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
13182 		struct perf_cpu_buf *cpu_buf;
13183 		int cpu, map_key;
13184 
13185 		cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
13186 		map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
13187 
13188 		/* in case user didn't explicitly requested particular CPUs to
13189 		 * be attached to, skip offline/not present CPUs
13190 		 */
13191 		if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
13192 			continue;
13193 
13194 		cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
13195 		if (IS_ERR(cpu_buf)) {
13196 			err = PTR_ERR(cpu_buf);
13197 			goto error;
13198 		}
13199 
13200 		pb->cpu_bufs[j] = cpu_buf;
13201 
13202 		err = bpf_map_update_elem(pb->map_fd, &map_key,
13203 					  &cpu_buf->fd, 0);
13204 		if (err) {
13205 			err = -errno;
13206 			pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
13207 				cpu, map_key, cpu_buf->fd,
13208 				libbpf_strerror_r(err, msg, sizeof(msg)));
13209 			goto error;
13210 		}
13211 
13212 		pb->events[j].events = EPOLLIN;
13213 		pb->events[j].data.ptr = cpu_buf;
13214 		if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
13215 			      &pb->events[j]) < 0) {
13216 			err = -errno;
13217 			pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
13218 				cpu, cpu_buf->fd,
13219 				libbpf_strerror_r(err, msg, sizeof(msg)));
13220 			goto error;
13221 		}
13222 		j++;
13223 	}
13224 	pb->cpu_cnt = j;
13225 	free(online);
13226 
13227 	return pb;
13228 
13229 error:
13230 	free(online);
13231 	if (pb)
13232 		perf_buffer__free(pb);
13233 	return ERR_PTR(err);
13234 }
13235 
13236 struct perf_sample_raw {
13237 	struct perf_event_header header;
13238 	uint32_t size;
13239 	char data[];
13240 };
13241 
13242 struct perf_sample_lost {
13243 	struct perf_event_header header;
13244 	uint64_t id;
13245 	uint64_t lost;
13246 	uint64_t sample_id;
13247 };
13248 
13249 static enum bpf_perf_event_ret
13250 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
13251 {
13252 	struct perf_cpu_buf *cpu_buf = ctx;
13253 	struct perf_buffer *pb = cpu_buf->pb;
13254 	void *data = e;
13255 
13256 	/* user wants full control over parsing perf event */
13257 	if (pb->event_cb)
13258 		return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
13259 
13260 	switch (e->type) {
13261 	case PERF_RECORD_SAMPLE: {
13262 		struct perf_sample_raw *s = data;
13263 
13264 		if (pb->sample_cb)
13265 			pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
13266 		break;
13267 	}
13268 	case PERF_RECORD_LOST: {
13269 		struct perf_sample_lost *s = data;
13270 
13271 		if (pb->lost_cb)
13272 			pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
13273 		break;
13274 	}
13275 	default:
13276 		pr_warn("unknown perf sample type %d\n", e->type);
13277 		return LIBBPF_PERF_EVENT_ERROR;
13278 	}
13279 	return LIBBPF_PERF_EVENT_CONT;
13280 }
13281 
13282 static int perf_buffer__process_records(struct perf_buffer *pb,
13283 					struct perf_cpu_buf *cpu_buf)
13284 {
13285 	enum bpf_perf_event_ret ret;
13286 
13287 	ret = perf_event_read_simple(cpu_buf->base, pb->mmap_size,
13288 				     pb->page_size, &cpu_buf->buf,
13289 				     &cpu_buf->buf_size,
13290 				     perf_buffer__process_record, cpu_buf);
13291 	if (ret != LIBBPF_PERF_EVENT_CONT)
13292 		return ret;
13293 	return 0;
13294 }
13295 
13296 int perf_buffer__epoll_fd(const struct perf_buffer *pb)
13297 {
13298 	return pb->epoll_fd;
13299 }
13300 
13301 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
13302 {
13303 	int i, cnt, err;
13304 
13305 	cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
13306 	if (cnt < 0)
13307 		return -errno;
13308 
13309 	for (i = 0; i < cnt; i++) {
13310 		struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
13311 
13312 		err = perf_buffer__process_records(pb, cpu_buf);
13313 		if (err) {
13314 			pr_warn("error while processing records: %d\n", err);
13315 			return libbpf_err(err);
13316 		}
13317 	}
13318 	return cnt;
13319 }
13320 
13321 /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
13322  * manager.
13323  */
13324 size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
13325 {
13326 	return pb->cpu_cnt;
13327 }
13328 
13329 /*
13330  * Return perf_event FD of a ring buffer in *buf_idx* slot of
13331  * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
13332  * select()/poll()/epoll() Linux syscalls.
13333  */
13334 int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
13335 {
13336 	struct perf_cpu_buf *cpu_buf;
13337 
13338 	if (buf_idx >= pb->cpu_cnt)
13339 		return libbpf_err(-EINVAL);
13340 
13341 	cpu_buf = pb->cpu_bufs[buf_idx];
13342 	if (!cpu_buf)
13343 		return libbpf_err(-ENOENT);
13344 
13345 	return cpu_buf->fd;
13346 }
13347 
13348 int perf_buffer__buffer(struct perf_buffer *pb, int buf_idx, void **buf, size_t *buf_size)
13349 {
13350 	struct perf_cpu_buf *cpu_buf;
13351 
13352 	if (buf_idx >= pb->cpu_cnt)
13353 		return libbpf_err(-EINVAL);
13354 
13355 	cpu_buf = pb->cpu_bufs[buf_idx];
13356 	if (!cpu_buf)
13357 		return libbpf_err(-ENOENT);
13358 
13359 	*buf = cpu_buf->base;
13360 	*buf_size = pb->mmap_size;
13361 	return 0;
13362 }
13363 
13364 /*
13365  * Consume data from perf ring buffer corresponding to slot *buf_idx* in
13366  * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
13367  * consume, do nothing and return success.
13368  * Returns:
13369  *   - 0 on success;
13370  *   - <0 on failure.
13371  */
13372 int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
13373 {
13374 	struct perf_cpu_buf *cpu_buf;
13375 
13376 	if (buf_idx >= pb->cpu_cnt)
13377 		return libbpf_err(-EINVAL);
13378 
13379 	cpu_buf = pb->cpu_bufs[buf_idx];
13380 	if (!cpu_buf)
13381 		return libbpf_err(-ENOENT);
13382 
13383 	return perf_buffer__process_records(pb, cpu_buf);
13384 }
13385 
13386 int perf_buffer__consume(struct perf_buffer *pb)
13387 {
13388 	int i, err;
13389 
13390 	for (i = 0; i < pb->cpu_cnt; i++) {
13391 		struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
13392 
13393 		if (!cpu_buf)
13394 			continue;
13395 
13396 		err = perf_buffer__process_records(pb, cpu_buf);
13397 		if (err) {
13398 			pr_warn("perf_buffer: failed to process records in buffer #%d: %d\n", i, err);
13399 			return libbpf_err(err);
13400 		}
13401 	}
13402 	return 0;
13403 }
13404 
13405 int bpf_program__set_attach_target(struct bpf_program *prog,
13406 				   int attach_prog_fd,
13407 				   const char *attach_func_name)
13408 {
13409 	int btf_obj_fd = 0, btf_id = 0, err;
13410 
13411 	if (!prog || attach_prog_fd < 0)
13412 		return libbpf_err(-EINVAL);
13413 
13414 	if (prog->obj->loaded)
13415 		return libbpf_err(-EINVAL);
13416 
13417 	if (attach_prog_fd && !attach_func_name) {
13418 		/* remember attach_prog_fd and let bpf_program__load() find
13419 		 * BTF ID during the program load
13420 		 */
13421 		prog->attach_prog_fd = attach_prog_fd;
13422 		return 0;
13423 	}
13424 
13425 	if (attach_prog_fd) {
13426 		btf_id = libbpf_find_prog_btf_id(attach_func_name,
13427 						 attach_prog_fd);
13428 		if (btf_id < 0)
13429 			return libbpf_err(btf_id);
13430 	} else {
13431 		if (!attach_func_name)
13432 			return libbpf_err(-EINVAL);
13433 
13434 		/* load btf_vmlinux, if not yet */
13435 		err = bpf_object__load_vmlinux_btf(prog->obj, true);
13436 		if (err)
13437 			return libbpf_err(err);
13438 		err = find_kernel_btf_id(prog->obj, attach_func_name,
13439 					 prog->expected_attach_type,
13440 					 &btf_obj_fd, &btf_id);
13441 		if (err)
13442 			return libbpf_err(err);
13443 	}
13444 
13445 	prog->attach_btf_id = btf_id;
13446 	prog->attach_btf_obj_fd = btf_obj_fd;
13447 	prog->attach_prog_fd = attach_prog_fd;
13448 	return 0;
13449 }
13450 
13451 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
13452 {
13453 	int err = 0, n, len, start, end = -1;
13454 	bool *tmp;
13455 
13456 	*mask = NULL;
13457 	*mask_sz = 0;
13458 
13459 	/* Each sub string separated by ',' has format \d+-\d+ or \d+ */
13460 	while (*s) {
13461 		if (*s == ',' || *s == '\n') {
13462 			s++;
13463 			continue;
13464 		}
13465 		n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
13466 		if (n <= 0 || n > 2) {
13467 			pr_warn("Failed to get CPU range %s: %d\n", s, n);
13468 			err = -EINVAL;
13469 			goto cleanup;
13470 		} else if (n == 1) {
13471 			end = start;
13472 		}
13473 		if (start < 0 || start > end) {
13474 			pr_warn("Invalid CPU range [%d,%d] in %s\n",
13475 				start, end, s);
13476 			err = -EINVAL;
13477 			goto cleanup;
13478 		}
13479 		tmp = realloc(*mask, end + 1);
13480 		if (!tmp) {
13481 			err = -ENOMEM;
13482 			goto cleanup;
13483 		}
13484 		*mask = tmp;
13485 		memset(tmp + *mask_sz, 0, start - *mask_sz);
13486 		memset(tmp + start, 1, end - start + 1);
13487 		*mask_sz = end + 1;
13488 		s += len;
13489 	}
13490 	if (!*mask_sz) {
13491 		pr_warn("Empty CPU range\n");
13492 		return -EINVAL;
13493 	}
13494 	return 0;
13495 cleanup:
13496 	free(*mask);
13497 	*mask = NULL;
13498 	return err;
13499 }
13500 
13501 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
13502 {
13503 	int fd, err = 0, len;
13504 	char buf[128];
13505 
13506 	fd = open(fcpu, O_RDONLY | O_CLOEXEC);
13507 	if (fd < 0) {
13508 		err = -errno;
13509 		pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
13510 		return err;
13511 	}
13512 	len = read(fd, buf, sizeof(buf));
13513 	close(fd);
13514 	if (len <= 0) {
13515 		err = len ? -errno : -EINVAL;
13516 		pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
13517 		return err;
13518 	}
13519 	if (len >= sizeof(buf)) {
13520 		pr_warn("CPU mask is too big in file %s\n", fcpu);
13521 		return -E2BIG;
13522 	}
13523 	buf[len] = '\0';
13524 
13525 	return parse_cpu_mask_str(buf, mask, mask_sz);
13526 }
13527 
13528 int libbpf_num_possible_cpus(void)
13529 {
13530 	static const char *fcpu = "/sys/devices/system/cpu/possible";
13531 	static int cpus;
13532 	int err, n, i, tmp_cpus;
13533 	bool *mask;
13534 
13535 	tmp_cpus = READ_ONCE(cpus);
13536 	if (tmp_cpus > 0)
13537 		return tmp_cpus;
13538 
13539 	err = parse_cpu_mask_file(fcpu, &mask, &n);
13540 	if (err)
13541 		return libbpf_err(err);
13542 
13543 	tmp_cpus = 0;
13544 	for (i = 0; i < n; i++) {
13545 		if (mask[i])
13546 			tmp_cpus++;
13547 	}
13548 	free(mask);
13549 
13550 	WRITE_ONCE(cpus, tmp_cpus);
13551 	return tmp_cpus;
13552 }
13553 
13554 static int populate_skeleton_maps(const struct bpf_object *obj,
13555 				  struct bpf_map_skeleton *maps,
13556 				  size_t map_cnt)
13557 {
13558 	int i;
13559 
13560 	for (i = 0; i < map_cnt; i++) {
13561 		struct bpf_map **map = maps[i].map;
13562 		const char *name = maps[i].name;
13563 		void **mmaped = maps[i].mmaped;
13564 
13565 		*map = bpf_object__find_map_by_name(obj, name);
13566 		if (!*map) {
13567 			pr_warn("failed to find skeleton map '%s'\n", name);
13568 			return -ESRCH;
13569 		}
13570 
13571 		/* externs shouldn't be pre-setup from user code */
13572 		if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
13573 			*mmaped = (*map)->mmaped;
13574 	}
13575 	return 0;
13576 }
13577 
13578 static int populate_skeleton_progs(const struct bpf_object *obj,
13579 				   struct bpf_prog_skeleton *progs,
13580 				   size_t prog_cnt)
13581 {
13582 	int i;
13583 
13584 	for (i = 0; i < prog_cnt; i++) {
13585 		struct bpf_program **prog = progs[i].prog;
13586 		const char *name = progs[i].name;
13587 
13588 		*prog = bpf_object__find_program_by_name(obj, name);
13589 		if (!*prog) {
13590 			pr_warn("failed to find skeleton program '%s'\n", name);
13591 			return -ESRCH;
13592 		}
13593 	}
13594 	return 0;
13595 }
13596 
13597 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
13598 			      const struct bpf_object_open_opts *opts)
13599 {
13600 	DECLARE_LIBBPF_OPTS(bpf_object_open_opts, skel_opts,
13601 		.object_name = s->name,
13602 	);
13603 	struct bpf_object *obj;
13604 	int err;
13605 
13606 	/* Attempt to preserve opts->object_name, unless overriden by user
13607 	 * explicitly. Overwriting object name for skeletons is discouraged,
13608 	 * as it breaks global data maps, because they contain object name
13609 	 * prefix as their own map name prefix. When skeleton is generated,
13610 	 * bpftool is making an assumption that this name will stay the same.
13611 	 */
13612 	if (opts) {
13613 		memcpy(&skel_opts, opts, sizeof(*opts));
13614 		if (!opts->object_name)
13615 			skel_opts.object_name = s->name;
13616 	}
13617 
13618 	obj = bpf_object__open_mem(s->data, s->data_sz, &skel_opts);
13619 	err = libbpf_get_error(obj);
13620 	if (err) {
13621 		pr_warn("failed to initialize skeleton BPF object '%s': %d\n",
13622 			s->name, err);
13623 		return libbpf_err(err);
13624 	}
13625 
13626 	*s->obj = obj;
13627 	err = populate_skeleton_maps(obj, s->maps, s->map_cnt);
13628 	if (err) {
13629 		pr_warn("failed to populate skeleton maps for '%s': %d\n", s->name, err);
13630 		return libbpf_err(err);
13631 	}
13632 
13633 	err = populate_skeleton_progs(obj, s->progs, s->prog_cnt);
13634 	if (err) {
13635 		pr_warn("failed to populate skeleton progs for '%s': %d\n", s->name, err);
13636 		return libbpf_err(err);
13637 	}
13638 
13639 	return 0;
13640 }
13641 
13642 int bpf_object__open_subskeleton(struct bpf_object_subskeleton *s)
13643 {
13644 	int err, len, var_idx, i;
13645 	const char *var_name;
13646 	const struct bpf_map *map;
13647 	struct btf *btf;
13648 	__u32 map_type_id;
13649 	const struct btf_type *map_type, *var_type;
13650 	const struct bpf_var_skeleton *var_skel;
13651 	struct btf_var_secinfo *var;
13652 
13653 	if (!s->obj)
13654 		return libbpf_err(-EINVAL);
13655 
13656 	btf = bpf_object__btf(s->obj);
13657 	if (!btf) {
13658 		pr_warn("subskeletons require BTF at runtime (object %s)\n",
13659 			bpf_object__name(s->obj));
13660 		return libbpf_err(-errno);
13661 	}
13662 
13663 	err = populate_skeleton_maps(s->obj, s->maps, s->map_cnt);
13664 	if (err) {
13665 		pr_warn("failed to populate subskeleton maps: %d\n", err);
13666 		return libbpf_err(err);
13667 	}
13668 
13669 	err = populate_skeleton_progs(s->obj, s->progs, s->prog_cnt);
13670 	if (err) {
13671 		pr_warn("failed to populate subskeleton maps: %d\n", err);
13672 		return libbpf_err(err);
13673 	}
13674 
13675 	for (var_idx = 0; var_idx < s->var_cnt; var_idx++) {
13676 		var_skel = &s->vars[var_idx];
13677 		map = *var_skel->map;
13678 		map_type_id = bpf_map__btf_value_type_id(map);
13679 		map_type = btf__type_by_id(btf, map_type_id);
13680 
13681 		if (!btf_is_datasec(map_type)) {
13682 			pr_warn("type for map '%1$s' is not a datasec: %2$s",
13683 				bpf_map__name(map),
13684 				__btf_kind_str(btf_kind(map_type)));
13685 			return libbpf_err(-EINVAL);
13686 		}
13687 
13688 		len = btf_vlen(map_type);
13689 		var = btf_var_secinfos(map_type);
13690 		for (i = 0; i < len; i++, var++) {
13691 			var_type = btf__type_by_id(btf, var->type);
13692 			var_name = btf__name_by_offset(btf, var_type->name_off);
13693 			if (strcmp(var_name, var_skel->name) == 0) {
13694 				*var_skel->addr = map->mmaped + var->offset;
13695 				break;
13696 			}
13697 		}
13698 	}
13699 	return 0;
13700 }
13701 
13702 void bpf_object__destroy_subskeleton(struct bpf_object_subskeleton *s)
13703 {
13704 	if (!s)
13705 		return;
13706 	free(s->maps);
13707 	free(s->progs);
13708 	free(s->vars);
13709 	free(s);
13710 }
13711 
13712 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
13713 {
13714 	int i, err;
13715 
13716 	err = bpf_object__load(*s->obj);
13717 	if (err) {
13718 		pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
13719 		return libbpf_err(err);
13720 	}
13721 
13722 	for (i = 0; i < s->map_cnt; i++) {
13723 		struct bpf_map *map = *s->maps[i].map;
13724 		size_t mmap_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
13725 		int prot, map_fd = map->fd;
13726 		void **mmaped = s->maps[i].mmaped;
13727 
13728 		if (!mmaped)
13729 			continue;
13730 
13731 		if (!(map->def.map_flags & BPF_F_MMAPABLE)) {
13732 			*mmaped = NULL;
13733 			continue;
13734 		}
13735 
13736 		if (map->def.map_flags & BPF_F_RDONLY_PROG)
13737 			prot = PROT_READ;
13738 		else
13739 			prot = PROT_READ | PROT_WRITE;
13740 
13741 		/* Remap anonymous mmap()-ed "map initialization image" as
13742 		 * a BPF map-backed mmap()-ed memory, but preserving the same
13743 		 * memory address. This will cause kernel to change process'
13744 		 * page table to point to a different piece of kernel memory,
13745 		 * but from userspace point of view memory address (and its
13746 		 * contents, being identical at this point) will stay the
13747 		 * same. This mapping will be released by bpf_object__close()
13748 		 * as per normal clean up procedure, so we don't need to worry
13749 		 * about it from skeleton's clean up perspective.
13750 		 */
13751 		*mmaped = mmap(map->mmaped, mmap_sz, prot, MAP_SHARED | MAP_FIXED, map_fd, 0);
13752 		if (*mmaped == MAP_FAILED) {
13753 			err = -errno;
13754 			*mmaped = NULL;
13755 			pr_warn("failed to re-mmap() map '%s': %d\n",
13756 				 bpf_map__name(map), err);
13757 			return libbpf_err(err);
13758 		}
13759 	}
13760 
13761 	return 0;
13762 }
13763 
13764 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
13765 {
13766 	int i, err;
13767 
13768 	for (i = 0; i < s->prog_cnt; i++) {
13769 		struct bpf_program *prog = *s->progs[i].prog;
13770 		struct bpf_link **link = s->progs[i].link;
13771 
13772 		if (!prog->autoload || !prog->autoattach)
13773 			continue;
13774 
13775 		/* auto-attaching not supported for this program */
13776 		if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
13777 			continue;
13778 
13779 		/* if user already set the link manually, don't attempt auto-attach */
13780 		if (*link)
13781 			continue;
13782 
13783 		err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, link);
13784 		if (err) {
13785 			pr_warn("prog '%s': failed to auto-attach: %d\n",
13786 				bpf_program__name(prog), err);
13787 			return libbpf_err(err);
13788 		}
13789 
13790 		/* It's possible that for some SEC() definitions auto-attach
13791 		 * is supported in some cases (e.g., if definition completely
13792 		 * specifies target information), but is not in other cases.
13793 		 * SEC("uprobe") is one such case. If user specified target
13794 		 * binary and function name, such BPF program can be
13795 		 * auto-attached. But if not, it shouldn't trigger skeleton's
13796 		 * attach to fail. It should just be skipped.
13797 		 * attach_fn signals such case with returning 0 (no error) and
13798 		 * setting link to NULL.
13799 		 */
13800 	}
13801 
13802 	return 0;
13803 }
13804 
13805 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
13806 {
13807 	int i;
13808 
13809 	for (i = 0; i < s->prog_cnt; i++) {
13810 		struct bpf_link **link = s->progs[i].link;
13811 
13812 		bpf_link__destroy(*link);
13813 		*link = NULL;
13814 	}
13815 }
13816 
13817 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
13818 {
13819 	if (!s)
13820 		return;
13821 
13822 	if (s->progs)
13823 		bpf_object__detach_skeleton(s);
13824 	if (s->obj)
13825 		bpf_object__close(*s->obj);
13826 	free(s->maps);
13827 	free(s->progs);
13828 	free(s);
13829 }
13830