xref: /openbmc/linux/tools/lib/bpf/libbpf.c (revision 6aeadf78)
1 // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
2 
3 /*
4  * Common eBPF ELF object loading operations.
5  *
6  * Copyright (C) 2013-2015 Alexei Starovoitov <ast@kernel.org>
7  * Copyright (C) 2015 Wang Nan <wangnan0@huawei.com>
8  * Copyright (C) 2015 Huawei Inc.
9  * Copyright (C) 2017 Nicira, Inc.
10  * Copyright (C) 2019 Isovalent, Inc.
11  */
12 
13 #ifndef _GNU_SOURCE
14 #define _GNU_SOURCE
15 #endif
16 #include <stdlib.h>
17 #include <stdio.h>
18 #include <stdarg.h>
19 #include <libgen.h>
20 #include <inttypes.h>
21 #include <limits.h>
22 #include <string.h>
23 #include <unistd.h>
24 #include <endian.h>
25 #include <fcntl.h>
26 #include <errno.h>
27 #include <ctype.h>
28 #include <asm/unistd.h>
29 #include <linux/err.h>
30 #include <linux/kernel.h>
31 #include <linux/bpf.h>
32 #include <linux/btf.h>
33 #include <linux/filter.h>
34 #include <linux/limits.h>
35 #include <linux/perf_event.h>
36 #include <linux/ring_buffer.h>
37 #include <sys/epoll.h>
38 #include <sys/ioctl.h>
39 #include <sys/mman.h>
40 #include <sys/stat.h>
41 #include <sys/types.h>
42 #include <sys/vfs.h>
43 #include <sys/utsname.h>
44 #include <sys/resource.h>
45 #include <libelf.h>
46 #include <gelf.h>
47 #include <zlib.h>
48 
49 #include "libbpf.h"
50 #include "bpf.h"
51 #include "btf.h"
52 #include "str_error.h"
53 #include "libbpf_internal.h"
54 #include "hashmap.h"
55 #include "bpf_gen_internal.h"
56 #include "zip.h"
57 
58 #ifndef BPF_FS_MAGIC
59 #define BPF_FS_MAGIC		0xcafe4a11
60 #endif
61 
62 #define BPF_INSN_SZ (sizeof(struct bpf_insn))
63 
64 /* vsprintf() in __base_pr() uses nonliteral format string. It may break
65  * compilation if user enables corresponding warning. Disable it explicitly.
66  */
67 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
68 
69 #define __printf(a, b)	__attribute__((format(printf, a, b)))
70 
71 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj);
72 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog);
73 
74 static const char * const attach_type_name[] = {
75 	[BPF_CGROUP_INET_INGRESS]	= "cgroup_inet_ingress",
76 	[BPF_CGROUP_INET_EGRESS]	= "cgroup_inet_egress",
77 	[BPF_CGROUP_INET_SOCK_CREATE]	= "cgroup_inet_sock_create",
78 	[BPF_CGROUP_INET_SOCK_RELEASE]	= "cgroup_inet_sock_release",
79 	[BPF_CGROUP_SOCK_OPS]		= "cgroup_sock_ops",
80 	[BPF_CGROUP_DEVICE]		= "cgroup_device",
81 	[BPF_CGROUP_INET4_BIND]		= "cgroup_inet4_bind",
82 	[BPF_CGROUP_INET6_BIND]		= "cgroup_inet6_bind",
83 	[BPF_CGROUP_INET4_CONNECT]	= "cgroup_inet4_connect",
84 	[BPF_CGROUP_INET6_CONNECT]	= "cgroup_inet6_connect",
85 	[BPF_CGROUP_INET4_POST_BIND]	= "cgroup_inet4_post_bind",
86 	[BPF_CGROUP_INET6_POST_BIND]	= "cgroup_inet6_post_bind",
87 	[BPF_CGROUP_INET4_GETPEERNAME]	= "cgroup_inet4_getpeername",
88 	[BPF_CGROUP_INET6_GETPEERNAME]	= "cgroup_inet6_getpeername",
89 	[BPF_CGROUP_INET4_GETSOCKNAME]	= "cgroup_inet4_getsockname",
90 	[BPF_CGROUP_INET6_GETSOCKNAME]	= "cgroup_inet6_getsockname",
91 	[BPF_CGROUP_UDP4_SENDMSG]	= "cgroup_udp4_sendmsg",
92 	[BPF_CGROUP_UDP6_SENDMSG]	= "cgroup_udp6_sendmsg",
93 	[BPF_CGROUP_SYSCTL]		= "cgroup_sysctl",
94 	[BPF_CGROUP_UDP4_RECVMSG]	= "cgroup_udp4_recvmsg",
95 	[BPF_CGROUP_UDP6_RECVMSG]	= "cgroup_udp6_recvmsg",
96 	[BPF_CGROUP_GETSOCKOPT]		= "cgroup_getsockopt",
97 	[BPF_CGROUP_SETSOCKOPT]		= "cgroup_setsockopt",
98 	[BPF_SK_SKB_STREAM_PARSER]	= "sk_skb_stream_parser",
99 	[BPF_SK_SKB_STREAM_VERDICT]	= "sk_skb_stream_verdict",
100 	[BPF_SK_SKB_VERDICT]		= "sk_skb_verdict",
101 	[BPF_SK_MSG_VERDICT]		= "sk_msg_verdict",
102 	[BPF_LIRC_MODE2]		= "lirc_mode2",
103 	[BPF_FLOW_DISSECTOR]		= "flow_dissector",
104 	[BPF_TRACE_RAW_TP]		= "trace_raw_tp",
105 	[BPF_TRACE_FENTRY]		= "trace_fentry",
106 	[BPF_TRACE_FEXIT]		= "trace_fexit",
107 	[BPF_MODIFY_RETURN]		= "modify_return",
108 	[BPF_LSM_MAC]			= "lsm_mac",
109 	[BPF_LSM_CGROUP]		= "lsm_cgroup",
110 	[BPF_SK_LOOKUP]			= "sk_lookup",
111 	[BPF_TRACE_ITER]		= "trace_iter",
112 	[BPF_XDP_DEVMAP]		= "xdp_devmap",
113 	[BPF_XDP_CPUMAP]		= "xdp_cpumap",
114 	[BPF_XDP]			= "xdp",
115 	[BPF_SK_REUSEPORT_SELECT]	= "sk_reuseport_select",
116 	[BPF_SK_REUSEPORT_SELECT_OR_MIGRATE]	= "sk_reuseport_select_or_migrate",
117 	[BPF_PERF_EVENT]		= "perf_event",
118 	[BPF_TRACE_KPROBE_MULTI]	= "trace_kprobe_multi",
119 	[BPF_STRUCT_OPS]		= "struct_ops",
120 	[BPF_NETFILTER]			= "netfilter",
121 };
122 
123 static const char * const link_type_name[] = {
124 	[BPF_LINK_TYPE_UNSPEC]			= "unspec",
125 	[BPF_LINK_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
126 	[BPF_LINK_TYPE_TRACING]			= "tracing",
127 	[BPF_LINK_TYPE_CGROUP]			= "cgroup",
128 	[BPF_LINK_TYPE_ITER]			= "iter",
129 	[BPF_LINK_TYPE_NETNS]			= "netns",
130 	[BPF_LINK_TYPE_XDP]			= "xdp",
131 	[BPF_LINK_TYPE_PERF_EVENT]		= "perf_event",
132 	[BPF_LINK_TYPE_KPROBE_MULTI]		= "kprobe_multi",
133 	[BPF_LINK_TYPE_STRUCT_OPS]		= "struct_ops",
134 	[BPF_LINK_TYPE_NETFILTER]		= "netfilter",
135 };
136 
137 static const char * const map_type_name[] = {
138 	[BPF_MAP_TYPE_UNSPEC]			= "unspec",
139 	[BPF_MAP_TYPE_HASH]			= "hash",
140 	[BPF_MAP_TYPE_ARRAY]			= "array",
141 	[BPF_MAP_TYPE_PROG_ARRAY]		= "prog_array",
142 	[BPF_MAP_TYPE_PERF_EVENT_ARRAY]		= "perf_event_array",
143 	[BPF_MAP_TYPE_PERCPU_HASH]		= "percpu_hash",
144 	[BPF_MAP_TYPE_PERCPU_ARRAY]		= "percpu_array",
145 	[BPF_MAP_TYPE_STACK_TRACE]		= "stack_trace",
146 	[BPF_MAP_TYPE_CGROUP_ARRAY]		= "cgroup_array",
147 	[BPF_MAP_TYPE_LRU_HASH]			= "lru_hash",
148 	[BPF_MAP_TYPE_LRU_PERCPU_HASH]		= "lru_percpu_hash",
149 	[BPF_MAP_TYPE_LPM_TRIE]			= "lpm_trie",
150 	[BPF_MAP_TYPE_ARRAY_OF_MAPS]		= "array_of_maps",
151 	[BPF_MAP_TYPE_HASH_OF_MAPS]		= "hash_of_maps",
152 	[BPF_MAP_TYPE_DEVMAP]			= "devmap",
153 	[BPF_MAP_TYPE_DEVMAP_HASH]		= "devmap_hash",
154 	[BPF_MAP_TYPE_SOCKMAP]			= "sockmap",
155 	[BPF_MAP_TYPE_CPUMAP]			= "cpumap",
156 	[BPF_MAP_TYPE_XSKMAP]			= "xskmap",
157 	[BPF_MAP_TYPE_SOCKHASH]			= "sockhash",
158 	[BPF_MAP_TYPE_CGROUP_STORAGE]		= "cgroup_storage",
159 	[BPF_MAP_TYPE_REUSEPORT_SOCKARRAY]	= "reuseport_sockarray",
160 	[BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE]	= "percpu_cgroup_storage",
161 	[BPF_MAP_TYPE_QUEUE]			= "queue",
162 	[BPF_MAP_TYPE_STACK]			= "stack",
163 	[BPF_MAP_TYPE_SK_STORAGE]		= "sk_storage",
164 	[BPF_MAP_TYPE_STRUCT_OPS]		= "struct_ops",
165 	[BPF_MAP_TYPE_RINGBUF]			= "ringbuf",
166 	[BPF_MAP_TYPE_INODE_STORAGE]		= "inode_storage",
167 	[BPF_MAP_TYPE_TASK_STORAGE]		= "task_storage",
168 	[BPF_MAP_TYPE_BLOOM_FILTER]		= "bloom_filter",
169 	[BPF_MAP_TYPE_USER_RINGBUF]             = "user_ringbuf",
170 	[BPF_MAP_TYPE_CGRP_STORAGE]		= "cgrp_storage",
171 };
172 
173 static const char * const prog_type_name[] = {
174 	[BPF_PROG_TYPE_UNSPEC]			= "unspec",
175 	[BPF_PROG_TYPE_SOCKET_FILTER]		= "socket_filter",
176 	[BPF_PROG_TYPE_KPROBE]			= "kprobe",
177 	[BPF_PROG_TYPE_SCHED_CLS]		= "sched_cls",
178 	[BPF_PROG_TYPE_SCHED_ACT]		= "sched_act",
179 	[BPF_PROG_TYPE_TRACEPOINT]		= "tracepoint",
180 	[BPF_PROG_TYPE_XDP]			= "xdp",
181 	[BPF_PROG_TYPE_PERF_EVENT]		= "perf_event",
182 	[BPF_PROG_TYPE_CGROUP_SKB]		= "cgroup_skb",
183 	[BPF_PROG_TYPE_CGROUP_SOCK]		= "cgroup_sock",
184 	[BPF_PROG_TYPE_LWT_IN]			= "lwt_in",
185 	[BPF_PROG_TYPE_LWT_OUT]			= "lwt_out",
186 	[BPF_PROG_TYPE_LWT_XMIT]		= "lwt_xmit",
187 	[BPF_PROG_TYPE_SOCK_OPS]		= "sock_ops",
188 	[BPF_PROG_TYPE_SK_SKB]			= "sk_skb",
189 	[BPF_PROG_TYPE_CGROUP_DEVICE]		= "cgroup_device",
190 	[BPF_PROG_TYPE_SK_MSG]			= "sk_msg",
191 	[BPF_PROG_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
192 	[BPF_PROG_TYPE_CGROUP_SOCK_ADDR]	= "cgroup_sock_addr",
193 	[BPF_PROG_TYPE_LWT_SEG6LOCAL]		= "lwt_seg6local",
194 	[BPF_PROG_TYPE_LIRC_MODE2]		= "lirc_mode2",
195 	[BPF_PROG_TYPE_SK_REUSEPORT]		= "sk_reuseport",
196 	[BPF_PROG_TYPE_FLOW_DISSECTOR]		= "flow_dissector",
197 	[BPF_PROG_TYPE_CGROUP_SYSCTL]		= "cgroup_sysctl",
198 	[BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE]	= "raw_tracepoint_writable",
199 	[BPF_PROG_TYPE_CGROUP_SOCKOPT]		= "cgroup_sockopt",
200 	[BPF_PROG_TYPE_TRACING]			= "tracing",
201 	[BPF_PROG_TYPE_STRUCT_OPS]		= "struct_ops",
202 	[BPF_PROG_TYPE_EXT]			= "ext",
203 	[BPF_PROG_TYPE_LSM]			= "lsm",
204 	[BPF_PROG_TYPE_SK_LOOKUP]		= "sk_lookup",
205 	[BPF_PROG_TYPE_SYSCALL]			= "syscall",
206 	[BPF_PROG_TYPE_NETFILTER]		= "netfilter",
207 };
208 
209 static int __base_pr(enum libbpf_print_level level, const char *format,
210 		     va_list args)
211 {
212 	if (level == LIBBPF_DEBUG)
213 		return 0;
214 
215 	return vfprintf(stderr, format, args);
216 }
217 
218 static libbpf_print_fn_t __libbpf_pr = __base_pr;
219 
220 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
221 {
222 	libbpf_print_fn_t old_print_fn;
223 
224 	old_print_fn = __atomic_exchange_n(&__libbpf_pr, fn, __ATOMIC_RELAXED);
225 
226 	return old_print_fn;
227 }
228 
229 __printf(2, 3)
230 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
231 {
232 	va_list args;
233 	int old_errno;
234 	libbpf_print_fn_t print_fn;
235 
236 	print_fn = __atomic_load_n(&__libbpf_pr, __ATOMIC_RELAXED);
237 	if (!print_fn)
238 		return;
239 
240 	old_errno = errno;
241 
242 	va_start(args, format);
243 	__libbpf_pr(level, format, args);
244 	va_end(args);
245 
246 	errno = old_errno;
247 }
248 
249 static void pr_perm_msg(int err)
250 {
251 	struct rlimit limit;
252 	char buf[100];
253 
254 	if (err != -EPERM || geteuid() != 0)
255 		return;
256 
257 	err = getrlimit(RLIMIT_MEMLOCK, &limit);
258 	if (err)
259 		return;
260 
261 	if (limit.rlim_cur == RLIM_INFINITY)
262 		return;
263 
264 	if (limit.rlim_cur < 1024)
265 		snprintf(buf, sizeof(buf), "%zu bytes", (size_t)limit.rlim_cur);
266 	else if (limit.rlim_cur < 1024*1024)
267 		snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
268 	else
269 		snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
270 
271 	pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
272 		buf);
273 }
274 
275 #define STRERR_BUFSIZE  128
276 
277 /* Copied from tools/perf/util/util.h */
278 #ifndef zfree
279 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
280 #endif
281 
282 #ifndef zclose
283 # define zclose(fd) ({			\
284 	int ___err = 0;			\
285 	if ((fd) >= 0)			\
286 		___err = close((fd));	\
287 	fd = -1;			\
288 	___err; })
289 #endif
290 
291 static inline __u64 ptr_to_u64(const void *ptr)
292 {
293 	return (__u64) (unsigned long) ptr;
294 }
295 
296 int libbpf_set_strict_mode(enum libbpf_strict_mode mode)
297 {
298 	/* as of v1.0 libbpf_set_strict_mode() is a no-op */
299 	return 0;
300 }
301 
302 __u32 libbpf_major_version(void)
303 {
304 	return LIBBPF_MAJOR_VERSION;
305 }
306 
307 __u32 libbpf_minor_version(void)
308 {
309 	return LIBBPF_MINOR_VERSION;
310 }
311 
312 const char *libbpf_version_string(void)
313 {
314 #define __S(X) #X
315 #define _S(X) __S(X)
316 	return  "v" _S(LIBBPF_MAJOR_VERSION) "." _S(LIBBPF_MINOR_VERSION);
317 #undef _S
318 #undef __S
319 }
320 
321 enum reloc_type {
322 	RELO_LD64,
323 	RELO_CALL,
324 	RELO_DATA,
325 	RELO_EXTERN_LD64,
326 	RELO_EXTERN_CALL,
327 	RELO_SUBPROG_ADDR,
328 	RELO_CORE,
329 };
330 
331 struct reloc_desc {
332 	enum reloc_type type;
333 	int insn_idx;
334 	union {
335 		const struct bpf_core_relo *core_relo; /* used when type == RELO_CORE */
336 		struct {
337 			int map_idx;
338 			int sym_off;
339 			int ext_idx;
340 		};
341 	};
342 };
343 
344 /* stored as sec_def->cookie for all libbpf-supported SEC()s */
345 enum sec_def_flags {
346 	SEC_NONE = 0,
347 	/* expected_attach_type is optional, if kernel doesn't support that */
348 	SEC_EXP_ATTACH_OPT = 1,
349 	/* legacy, only used by libbpf_get_type_names() and
350 	 * libbpf_attach_type_by_name(), not used by libbpf itself at all.
351 	 * This used to be associated with cgroup (and few other) BPF programs
352 	 * that were attachable through BPF_PROG_ATTACH command. Pretty
353 	 * meaningless nowadays, though.
354 	 */
355 	SEC_ATTACHABLE = 2,
356 	SEC_ATTACHABLE_OPT = SEC_ATTACHABLE | SEC_EXP_ATTACH_OPT,
357 	/* attachment target is specified through BTF ID in either kernel or
358 	 * other BPF program's BTF object
359 	 */
360 	SEC_ATTACH_BTF = 4,
361 	/* BPF program type allows sleeping/blocking in kernel */
362 	SEC_SLEEPABLE = 8,
363 	/* BPF program support non-linear XDP buffer */
364 	SEC_XDP_FRAGS = 16,
365 };
366 
367 struct bpf_sec_def {
368 	char *sec;
369 	enum bpf_prog_type prog_type;
370 	enum bpf_attach_type expected_attach_type;
371 	long cookie;
372 	int handler_id;
373 
374 	libbpf_prog_setup_fn_t prog_setup_fn;
375 	libbpf_prog_prepare_load_fn_t prog_prepare_load_fn;
376 	libbpf_prog_attach_fn_t prog_attach_fn;
377 };
378 
379 /*
380  * bpf_prog should be a better name but it has been used in
381  * linux/filter.h.
382  */
383 struct bpf_program {
384 	char *name;
385 	char *sec_name;
386 	size_t sec_idx;
387 	const struct bpf_sec_def *sec_def;
388 	/* this program's instruction offset (in number of instructions)
389 	 * within its containing ELF section
390 	 */
391 	size_t sec_insn_off;
392 	/* number of original instructions in ELF section belonging to this
393 	 * program, not taking into account subprogram instructions possible
394 	 * appended later during relocation
395 	 */
396 	size_t sec_insn_cnt;
397 	/* Offset (in number of instructions) of the start of instruction
398 	 * belonging to this BPF program  within its containing main BPF
399 	 * program. For the entry-point (main) BPF program, this is always
400 	 * zero. For a sub-program, this gets reset before each of main BPF
401 	 * programs are processed and relocated and is used to determined
402 	 * whether sub-program was already appended to the main program, and
403 	 * if yes, at which instruction offset.
404 	 */
405 	size_t sub_insn_off;
406 
407 	/* instructions that belong to BPF program; insns[0] is located at
408 	 * sec_insn_off instruction within its ELF section in ELF file, so
409 	 * when mapping ELF file instruction index to the local instruction,
410 	 * one needs to subtract sec_insn_off; and vice versa.
411 	 */
412 	struct bpf_insn *insns;
413 	/* actual number of instruction in this BPF program's image; for
414 	 * entry-point BPF programs this includes the size of main program
415 	 * itself plus all the used sub-programs, appended at the end
416 	 */
417 	size_t insns_cnt;
418 
419 	struct reloc_desc *reloc_desc;
420 	int nr_reloc;
421 
422 	/* BPF verifier log settings */
423 	char *log_buf;
424 	size_t log_size;
425 	__u32 log_level;
426 
427 	struct bpf_object *obj;
428 
429 	int fd;
430 	bool autoload;
431 	bool autoattach;
432 	bool mark_btf_static;
433 	enum bpf_prog_type type;
434 	enum bpf_attach_type expected_attach_type;
435 
436 	int prog_ifindex;
437 	__u32 attach_btf_obj_fd;
438 	__u32 attach_btf_id;
439 	__u32 attach_prog_fd;
440 
441 	void *func_info;
442 	__u32 func_info_rec_size;
443 	__u32 func_info_cnt;
444 
445 	void *line_info;
446 	__u32 line_info_rec_size;
447 	__u32 line_info_cnt;
448 	__u32 prog_flags;
449 };
450 
451 struct bpf_struct_ops {
452 	const char *tname;
453 	const struct btf_type *type;
454 	struct bpf_program **progs;
455 	__u32 *kern_func_off;
456 	/* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
457 	void *data;
458 	/* e.g. struct bpf_struct_ops_tcp_congestion_ops in
459 	 *      btf_vmlinux's format.
460 	 * struct bpf_struct_ops_tcp_congestion_ops {
461 	 *	[... some other kernel fields ...]
462 	 *	struct tcp_congestion_ops data;
463 	 * }
464 	 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
465 	 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
466 	 * from "data".
467 	 */
468 	void *kern_vdata;
469 	__u32 type_id;
470 };
471 
472 #define DATA_SEC ".data"
473 #define BSS_SEC ".bss"
474 #define RODATA_SEC ".rodata"
475 #define KCONFIG_SEC ".kconfig"
476 #define KSYMS_SEC ".ksyms"
477 #define STRUCT_OPS_SEC ".struct_ops"
478 #define STRUCT_OPS_LINK_SEC ".struct_ops.link"
479 
480 enum libbpf_map_type {
481 	LIBBPF_MAP_UNSPEC,
482 	LIBBPF_MAP_DATA,
483 	LIBBPF_MAP_BSS,
484 	LIBBPF_MAP_RODATA,
485 	LIBBPF_MAP_KCONFIG,
486 };
487 
488 struct bpf_map_def {
489 	unsigned int type;
490 	unsigned int key_size;
491 	unsigned int value_size;
492 	unsigned int max_entries;
493 	unsigned int map_flags;
494 };
495 
496 struct bpf_map {
497 	struct bpf_object *obj;
498 	char *name;
499 	/* real_name is defined for special internal maps (.rodata*,
500 	 * .data*, .bss, .kconfig) and preserves their original ELF section
501 	 * name. This is important to be able to find corresponding BTF
502 	 * DATASEC information.
503 	 */
504 	char *real_name;
505 	int fd;
506 	int sec_idx;
507 	size_t sec_offset;
508 	int map_ifindex;
509 	int inner_map_fd;
510 	struct bpf_map_def def;
511 	__u32 numa_node;
512 	__u32 btf_var_idx;
513 	__u32 btf_key_type_id;
514 	__u32 btf_value_type_id;
515 	__u32 btf_vmlinux_value_type_id;
516 	enum libbpf_map_type libbpf_type;
517 	void *mmaped;
518 	struct bpf_struct_ops *st_ops;
519 	struct bpf_map *inner_map;
520 	void **init_slots;
521 	int init_slots_sz;
522 	char *pin_path;
523 	bool pinned;
524 	bool reused;
525 	bool autocreate;
526 	__u64 map_extra;
527 };
528 
529 enum extern_type {
530 	EXT_UNKNOWN,
531 	EXT_KCFG,
532 	EXT_KSYM,
533 };
534 
535 enum kcfg_type {
536 	KCFG_UNKNOWN,
537 	KCFG_CHAR,
538 	KCFG_BOOL,
539 	KCFG_INT,
540 	KCFG_TRISTATE,
541 	KCFG_CHAR_ARR,
542 };
543 
544 struct extern_desc {
545 	enum extern_type type;
546 	int sym_idx;
547 	int btf_id;
548 	int sec_btf_id;
549 	const char *name;
550 	bool is_set;
551 	bool is_weak;
552 	union {
553 		struct {
554 			enum kcfg_type type;
555 			int sz;
556 			int align;
557 			int data_off;
558 			bool is_signed;
559 		} kcfg;
560 		struct {
561 			unsigned long long addr;
562 
563 			/* target btf_id of the corresponding kernel var. */
564 			int kernel_btf_obj_fd;
565 			int kernel_btf_id;
566 
567 			/* local btf_id of the ksym extern's type. */
568 			__u32 type_id;
569 			/* BTF fd index to be patched in for insn->off, this is
570 			 * 0 for vmlinux BTF, index in obj->fd_array for module
571 			 * BTF
572 			 */
573 			__s16 btf_fd_idx;
574 		} ksym;
575 	};
576 };
577 
578 struct module_btf {
579 	struct btf *btf;
580 	char *name;
581 	__u32 id;
582 	int fd;
583 	int fd_array_idx;
584 };
585 
586 enum sec_type {
587 	SEC_UNUSED = 0,
588 	SEC_RELO,
589 	SEC_BSS,
590 	SEC_DATA,
591 	SEC_RODATA,
592 };
593 
594 struct elf_sec_desc {
595 	enum sec_type sec_type;
596 	Elf64_Shdr *shdr;
597 	Elf_Data *data;
598 };
599 
600 struct elf_state {
601 	int fd;
602 	const void *obj_buf;
603 	size_t obj_buf_sz;
604 	Elf *elf;
605 	Elf64_Ehdr *ehdr;
606 	Elf_Data *symbols;
607 	Elf_Data *st_ops_data;
608 	Elf_Data *st_ops_link_data;
609 	size_t shstrndx; /* section index for section name strings */
610 	size_t strtabidx;
611 	struct elf_sec_desc *secs;
612 	size_t sec_cnt;
613 	int btf_maps_shndx;
614 	__u32 btf_maps_sec_btf_id;
615 	int text_shndx;
616 	int symbols_shndx;
617 	int st_ops_shndx;
618 	int st_ops_link_shndx;
619 };
620 
621 struct usdt_manager;
622 
623 struct bpf_object {
624 	char name[BPF_OBJ_NAME_LEN];
625 	char license[64];
626 	__u32 kern_version;
627 
628 	struct bpf_program *programs;
629 	size_t nr_programs;
630 	struct bpf_map *maps;
631 	size_t nr_maps;
632 	size_t maps_cap;
633 
634 	char *kconfig;
635 	struct extern_desc *externs;
636 	int nr_extern;
637 	int kconfig_map_idx;
638 
639 	bool loaded;
640 	bool has_subcalls;
641 	bool has_rodata;
642 
643 	struct bpf_gen *gen_loader;
644 
645 	/* Information when doing ELF related work. Only valid if efile.elf is not NULL */
646 	struct elf_state efile;
647 
648 	struct btf *btf;
649 	struct btf_ext *btf_ext;
650 
651 	/* Parse and load BTF vmlinux if any of the programs in the object need
652 	 * it at load time.
653 	 */
654 	struct btf *btf_vmlinux;
655 	/* Path to the custom BTF to be used for BPF CO-RE relocations as an
656 	 * override for vmlinux BTF.
657 	 */
658 	char *btf_custom_path;
659 	/* vmlinux BTF override for CO-RE relocations */
660 	struct btf *btf_vmlinux_override;
661 	/* Lazily initialized kernel module BTFs */
662 	struct module_btf *btf_modules;
663 	bool btf_modules_loaded;
664 	size_t btf_module_cnt;
665 	size_t btf_module_cap;
666 
667 	/* optional log settings passed to BPF_BTF_LOAD and BPF_PROG_LOAD commands */
668 	char *log_buf;
669 	size_t log_size;
670 	__u32 log_level;
671 
672 	int *fd_array;
673 	size_t fd_array_cap;
674 	size_t fd_array_cnt;
675 
676 	struct usdt_manager *usdt_man;
677 
678 	char path[];
679 };
680 
681 static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
682 static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
683 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
684 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
685 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn);
686 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
687 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
688 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx);
689 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx);
690 
691 void bpf_program__unload(struct bpf_program *prog)
692 {
693 	if (!prog)
694 		return;
695 
696 	zclose(prog->fd);
697 
698 	zfree(&prog->func_info);
699 	zfree(&prog->line_info);
700 }
701 
702 static void bpf_program__exit(struct bpf_program *prog)
703 {
704 	if (!prog)
705 		return;
706 
707 	bpf_program__unload(prog);
708 	zfree(&prog->name);
709 	zfree(&prog->sec_name);
710 	zfree(&prog->insns);
711 	zfree(&prog->reloc_desc);
712 
713 	prog->nr_reloc = 0;
714 	prog->insns_cnt = 0;
715 	prog->sec_idx = -1;
716 }
717 
718 static bool insn_is_subprog_call(const struct bpf_insn *insn)
719 {
720 	return BPF_CLASS(insn->code) == BPF_JMP &&
721 	       BPF_OP(insn->code) == BPF_CALL &&
722 	       BPF_SRC(insn->code) == BPF_K &&
723 	       insn->src_reg == BPF_PSEUDO_CALL &&
724 	       insn->dst_reg == 0 &&
725 	       insn->off == 0;
726 }
727 
728 static bool is_call_insn(const struct bpf_insn *insn)
729 {
730 	return insn->code == (BPF_JMP | BPF_CALL);
731 }
732 
733 static bool insn_is_pseudo_func(struct bpf_insn *insn)
734 {
735 	return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
736 }
737 
738 static int
739 bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
740 		      const char *name, size_t sec_idx, const char *sec_name,
741 		      size_t sec_off, void *insn_data, size_t insn_data_sz)
742 {
743 	if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
744 		pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
745 			sec_name, name, sec_off, insn_data_sz);
746 		return -EINVAL;
747 	}
748 
749 	memset(prog, 0, sizeof(*prog));
750 	prog->obj = obj;
751 
752 	prog->sec_idx = sec_idx;
753 	prog->sec_insn_off = sec_off / BPF_INSN_SZ;
754 	prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
755 	/* insns_cnt can later be increased by appending used subprograms */
756 	prog->insns_cnt = prog->sec_insn_cnt;
757 
758 	prog->type = BPF_PROG_TYPE_UNSPEC;
759 	prog->fd = -1;
760 
761 	/* libbpf's convention for SEC("?abc...") is that it's just like
762 	 * SEC("abc...") but the corresponding bpf_program starts out with
763 	 * autoload set to false.
764 	 */
765 	if (sec_name[0] == '?') {
766 		prog->autoload = false;
767 		/* from now on forget there was ? in section name */
768 		sec_name++;
769 	} else {
770 		prog->autoload = true;
771 	}
772 
773 	prog->autoattach = true;
774 
775 	/* inherit object's log_level */
776 	prog->log_level = obj->log_level;
777 
778 	prog->sec_name = strdup(sec_name);
779 	if (!prog->sec_name)
780 		goto errout;
781 
782 	prog->name = strdup(name);
783 	if (!prog->name)
784 		goto errout;
785 
786 	prog->insns = malloc(insn_data_sz);
787 	if (!prog->insns)
788 		goto errout;
789 	memcpy(prog->insns, insn_data, insn_data_sz);
790 
791 	return 0;
792 errout:
793 	pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
794 	bpf_program__exit(prog);
795 	return -ENOMEM;
796 }
797 
798 static int
799 bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
800 			 const char *sec_name, int sec_idx)
801 {
802 	Elf_Data *symbols = obj->efile.symbols;
803 	struct bpf_program *prog, *progs;
804 	void *data = sec_data->d_buf;
805 	size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
806 	int nr_progs, err, i;
807 	const char *name;
808 	Elf64_Sym *sym;
809 
810 	progs = obj->programs;
811 	nr_progs = obj->nr_programs;
812 	nr_syms = symbols->d_size / sizeof(Elf64_Sym);
813 
814 	for (i = 0; i < nr_syms; i++) {
815 		sym = elf_sym_by_idx(obj, i);
816 
817 		if (sym->st_shndx != sec_idx)
818 			continue;
819 		if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC)
820 			continue;
821 
822 		prog_sz = sym->st_size;
823 		sec_off = sym->st_value;
824 
825 		name = elf_sym_str(obj, sym->st_name);
826 		if (!name) {
827 			pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
828 				sec_name, sec_off);
829 			return -LIBBPF_ERRNO__FORMAT;
830 		}
831 
832 		if (sec_off + prog_sz > sec_sz) {
833 			pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
834 				sec_name, sec_off);
835 			return -LIBBPF_ERRNO__FORMAT;
836 		}
837 
838 		if (sec_idx != obj->efile.text_shndx && ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
839 			pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
840 			return -ENOTSUP;
841 		}
842 
843 		pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
844 			 sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
845 
846 		progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
847 		if (!progs) {
848 			/*
849 			 * In this case the original obj->programs
850 			 * is still valid, so don't need special treat for
851 			 * bpf_close_object().
852 			 */
853 			pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
854 				sec_name, name);
855 			return -ENOMEM;
856 		}
857 		obj->programs = progs;
858 
859 		prog = &progs[nr_progs];
860 
861 		err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
862 					    sec_off, data + sec_off, prog_sz);
863 		if (err)
864 			return err;
865 
866 		/* if function is a global/weak symbol, but has restricted
867 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
868 		 * as static to enable more permissive BPF verification mode
869 		 * with more outside context available to BPF verifier
870 		 */
871 		if (ELF64_ST_BIND(sym->st_info) != STB_LOCAL
872 		    && (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
873 			|| ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL))
874 			prog->mark_btf_static = true;
875 
876 		nr_progs++;
877 		obj->nr_programs = nr_progs;
878 	}
879 
880 	return 0;
881 }
882 
883 static const struct btf_member *
884 find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
885 {
886 	struct btf_member *m;
887 	int i;
888 
889 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
890 		if (btf_member_bit_offset(t, i) == bit_offset)
891 			return m;
892 	}
893 
894 	return NULL;
895 }
896 
897 static const struct btf_member *
898 find_member_by_name(const struct btf *btf, const struct btf_type *t,
899 		    const char *name)
900 {
901 	struct btf_member *m;
902 	int i;
903 
904 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
905 		if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
906 			return m;
907 	}
908 
909 	return NULL;
910 }
911 
912 #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
913 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
914 				   const char *name, __u32 kind);
915 
916 static int
917 find_struct_ops_kern_types(const struct btf *btf, const char *tname,
918 			   const struct btf_type **type, __u32 *type_id,
919 			   const struct btf_type **vtype, __u32 *vtype_id,
920 			   const struct btf_member **data_member)
921 {
922 	const struct btf_type *kern_type, *kern_vtype;
923 	const struct btf_member *kern_data_member;
924 	__s32 kern_vtype_id, kern_type_id;
925 	__u32 i;
926 
927 	kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
928 	if (kern_type_id < 0) {
929 		pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n",
930 			tname);
931 		return kern_type_id;
932 	}
933 	kern_type = btf__type_by_id(btf, kern_type_id);
934 
935 	/* Find the corresponding "map_value" type that will be used
936 	 * in map_update(BPF_MAP_TYPE_STRUCT_OPS).  For example,
937 	 * find "struct bpf_struct_ops_tcp_congestion_ops" from the
938 	 * btf_vmlinux.
939 	 */
940 	kern_vtype_id = find_btf_by_prefix_kind(btf, STRUCT_OPS_VALUE_PREFIX,
941 						tname, BTF_KIND_STRUCT);
942 	if (kern_vtype_id < 0) {
943 		pr_warn("struct_ops init_kern: struct %s%s is not found in kernel BTF\n",
944 			STRUCT_OPS_VALUE_PREFIX, tname);
945 		return kern_vtype_id;
946 	}
947 	kern_vtype = btf__type_by_id(btf, kern_vtype_id);
948 
949 	/* Find "struct tcp_congestion_ops" from
950 	 * struct bpf_struct_ops_tcp_congestion_ops {
951 	 *	[ ... ]
952 	 *	struct tcp_congestion_ops data;
953 	 * }
954 	 */
955 	kern_data_member = btf_members(kern_vtype);
956 	for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
957 		if (kern_data_member->type == kern_type_id)
958 			break;
959 	}
960 	if (i == btf_vlen(kern_vtype)) {
961 		pr_warn("struct_ops init_kern: struct %s data is not found in struct %s%s\n",
962 			tname, STRUCT_OPS_VALUE_PREFIX, tname);
963 		return -EINVAL;
964 	}
965 
966 	*type = kern_type;
967 	*type_id = kern_type_id;
968 	*vtype = kern_vtype;
969 	*vtype_id = kern_vtype_id;
970 	*data_member = kern_data_member;
971 
972 	return 0;
973 }
974 
975 static bool bpf_map__is_struct_ops(const struct bpf_map *map)
976 {
977 	return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
978 }
979 
980 /* Init the map's fields that depend on kern_btf */
981 static int bpf_map__init_kern_struct_ops(struct bpf_map *map,
982 					 const struct btf *btf,
983 					 const struct btf *kern_btf)
984 {
985 	const struct btf_member *member, *kern_member, *kern_data_member;
986 	const struct btf_type *type, *kern_type, *kern_vtype;
987 	__u32 i, kern_type_id, kern_vtype_id, kern_data_off;
988 	struct bpf_struct_ops *st_ops;
989 	void *data, *kern_data;
990 	const char *tname;
991 	int err;
992 
993 	st_ops = map->st_ops;
994 	type = st_ops->type;
995 	tname = st_ops->tname;
996 	err = find_struct_ops_kern_types(kern_btf, tname,
997 					 &kern_type, &kern_type_id,
998 					 &kern_vtype, &kern_vtype_id,
999 					 &kern_data_member);
1000 	if (err)
1001 		return err;
1002 
1003 	pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
1004 		 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
1005 
1006 	map->def.value_size = kern_vtype->size;
1007 	map->btf_vmlinux_value_type_id = kern_vtype_id;
1008 
1009 	st_ops->kern_vdata = calloc(1, kern_vtype->size);
1010 	if (!st_ops->kern_vdata)
1011 		return -ENOMEM;
1012 
1013 	data = st_ops->data;
1014 	kern_data_off = kern_data_member->offset / 8;
1015 	kern_data = st_ops->kern_vdata + kern_data_off;
1016 
1017 	member = btf_members(type);
1018 	for (i = 0; i < btf_vlen(type); i++, member++) {
1019 		const struct btf_type *mtype, *kern_mtype;
1020 		__u32 mtype_id, kern_mtype_id;
1021 		void *mdata, *kern_mdata;
1022 		__s64 msize, kern_msize;
1023 		__u32 moff, kern_moff;
1024 		__u32 kern_member_idx;
1025 		const char *mname;
1026 
1027 		mname = btf__name_by_offset(btf, member->name_off);
1028 		kern_member = find_member_by_name(kern_btf, kern_type, mname);
1029 		if (!kern_member) {
1030 			pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
1031 				map->name, mname);
1032 			return -ENOTSUP;
1033 		}
1034 
1035 		kern_member_idx = kern_member - btf_members(kern_type);
1036 		if (btf_member_bitfield_size(type, i) ||
1037 		    btf_member_bitfield_size(kern_type, kern_member_idx)) {
1038 			pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
1039 				map->name, mname);
1040 			return -ENOTSUP;
1041 		}
1042 
1043 		moff = member->offset / 8;
1044 		kern_moff = kern_member->offset / 8;
1045 
1046 		mdata = data + moff;
1047 		kern_mdata = kern_data + kern_moff;
1048 
1049 		mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
1050 		kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
1051 						    &kern_mtype_id);
1052 		if (BTF_INFO_KIND(mtype->info) !=
1053 		    BTF_INFO_KIND(kern_mtype->info)) {
1054 			pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
1055 				map->name, mname, BTF_INFO_KIND(mtype->info),
1056 				BTF_INFO_KIND(kern_mtype->info));
1057 			return -ENOTSUP;
1058 		}
1059 
1060 		if (btf_is_ptr(mtype)) {
1061 			struct bpf_program *prog;
1062 
1063 			prog = st_ops->progs[i];
1064 			if (!prog)
1065 				continue;
1066 
1067 			kern_mtype = skip_mods_and_typedefs(kern_btf,
1068 							    kern_mtype->type,
1069 							    &kern_mtype_id);
1070 
1071 			/* mtype->type must be a func_proto which was
1072 			 * guaranteed in bpf_object__collect_st_ops_relos(),
1073 			 * so only check kern_mtype for func_proto here.
1074 			 */
1075 			if (!btf_is_func_proto(kern_mtype)) {
1076 				pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
1077 					map->name, mname);
1078 				return -ENOTSUP;
1079 			}
1080 
1081 			prog->attach_btf_id = kern_type_id;
1082 			prog->expected_attach_type = kern_member_idx;
1083 
1084 			st_ops->kern_func_off[i] = kern_data_off + kern_moff;
1085 
1086 			pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
1087 				 map->name, mname, prog->name, moff,
1088 				 kern_moff);
1089 
1090 			continue;
1091 		}
1092 
1093 		msize = btf__resolve_size(btf, mtype_id);
1094 		kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
1095 		if (msize < 0 || kern_msize < 0 || msize != kern_msize) {
1096 			pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
1097 				map->name, mname, (ssize_t)msize,
1098 				(ssize_t)kern_msize);
1099 			return -ENOTSUP;
1100 		}
1101 
1102 		pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
1103 			 map->name, mname, (unsigned int)msize,
1104 			 moff, kern_moff);
1105 		memcpy(kern_mdata, mdata, msize);
1106 	}
1107 
1108 	return 0;
1109 }
1110 
1111 static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
1112 {
1113 	struct bpf_map *map;
1114 	size_t i;
1115 	int err;
1116 
1117 	for (i = 0; i < obj->nr_maps; i++) {
1118 		map = &obj->maps[i];
1119 
1120 		if (!bpf_map__is_struct_ops(map))
1121 			continue;
1122 
1123 		err = bpf_map__init_kern_struct_ops(map, obj->btf,
1124 						    obj->btf_vmlinux);
1125 		if (err)
1126 			return err;
1127 	}
1128 
1129 	return 0;
1130 }
1131 
1132 static int init_struct_ops_maps(struct bpf_object *obj, const char *sec_name,
1133 				int shndx, Elf_Data *data, __u32 map_flags)
1134 {
1135 	const struct btf_type *type, *datasec;
1136 	const struct btf_var_secinfo *vsi;
1137 	struct bpf_struct_ops *st_ops;
1138 	const char *tname, *var_name;
1139 	__s32 type_id, datasec_id;
1140 	const struct btf *btf;
1141 	struct bpf_map *map;
1142 	__u32 i;
1143 
1144 	if (shndx == -1)
1145 		return 0;
1146 
1147 	btf = obj->btf;
1148 	datasec_id = btf__find_by_name_kind(btf, sec_name,
1149 					    BTF_KIND_DATASEC);
1150 	if (datasec_id < 0) {
1151 		pr_warn("struct_ops init: DATASEC %s not found\n",
1152 			sec_name);
1153 		return -EINVAL;
1154 	}
1155 
1156 	datasec = btf__type_by_id(btf, datasec_id);
1157 	vsi = btf_var_secinfos(datasec);
1158 	for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
1159 		type = btf__type_by_id(obj->btf, vsi->type);
1160 		var_name = btf__name_by_offset(obj->btf, type->name_off);
1161 
1162 		type_id = btf__resolve_type(obj->btf, vsi->type);
1163 		if (type_id < 0) {
1164 			pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
1165 				vsi->type, sec_name);
1166 			return -EINVAL;
1167 		}
1168 
1169 		type = btf__type_by_id(obj->btf, type_id);
1170 		tname = btf__name_by_offset(obj->btf, type->name_off);
1171 		if (!tname[0]) {
1172 			pr_warn("struct_ops init: anonymous type is not supported\n");
1173 			return -ENOTSUP;
1174 		}
1175 		if (!btf_is_struct(type)) {
1176 			pr_warn("struct_ops init: %s is not a struct\n", tname);
1177 			return -EINVAL;
1178 		}
1179 
1180 		map = bpf_object__add_map(obj);
1181 		if (IS_ERR(map))
1182 			return PTR_ERR(map);
1183 
1184 		map->sec_idx = shndx;
1185 		map->sec_offset = vsi->offset;
1186 		map->name = strdup(var_name);
1187 		if (!map->name)
1188 			return -ENOMEM;
1189 
1190 		map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
1191 		map->def.key_size = sizeof(int);
1192 		map->def.value_size = type->size;
1193 		map->def.max_entries = 1;
1194 		map->def.map_flags = map_flags;
1195 
1196 		map->st_ops = calloc(1, sizeof(*map->st_ops));
1197 		if (!map->st_ops)
1198 			return -ENOMEM;
1199 		st_ops = map->st_ops;
1200 		st_ops->data = malloc(type->size);
1201 		st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1202 		st_ops->kern_func_off = malloc(btf_vlen(type) *
1203 					       sizeof(*st_ops->kern_func_off));
1204 		if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1205 			return -ENOMEM;
1206 
1207 		if (vsi->offset + type->size > data->d_size) {
1208 			pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1209 				var_name, sec_name);
1210 			return -EINVAL;
1211 		}
1212 
1213 		memcpy(st_ops->data,
1214 		       data->d_buf + vsi->offset,
1215 		       type->size);
1216 		st_ops->tname = tname;
1217 		st_ops->type = type;
1218 		st_ops->type_id = type_id;
1219 
1220 		pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
1221 			 tname, type_id, var_name, vsi->offset);
1222 	}
1223 
1224 	return 0;
1225 }
1226 
1227 static int bpf_object_init_struct_ops(struct bpf_object *obj)
1228 {
1229 	int err;
1230 
1231 	err = init_struct_ops_maps(obj, STRUCT_OPS_SEC, obj->efile.st_ops_shndx,
1232 				   obj->efile.st_ops_data, 0);
1233 	err = err ?: init_struct_ops_maps(obj, STRUCT_OPS_LINK_SEC,
1234 					  obj->efile.st_ops_link_shndx,
1235 					  obj->efile.st_ops_link_data,
1236 					  BPF_F_LINK);
1237 	return err;
1238 }
1239 
1240 static struct bpf_object *bpf_object__new(const char *path,
1241 					  const void *obj_buf,
1242 					  size_t obj_buf_sz,
1243 					  const char *obj_name)
1244 {
1245 	struct bpf_object *obj;
1246 	char *end;
1247 
1248 	obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1249 	if (!obj) {
1250 		pr_warn("alloc memory failed for %s\n", path);
1251 		return ERR_PTR(-ENOMEM);
1252 	}
1253 
1254 	strcpy(obj->path, path);
1255 	if (obj_name) {
1256 		libbpf_strlcpy(obj->name, obj_name, sizeof(obj->name));
1257 	} else {
1258 		/* Using basename() GNU version which doesn't modify arg. */
1259 		libbpf_strlcpy(obj->name, basename((void *)path), sizeof(obj->name));
1260 		end = strchr(obj->name, '.');
1261 		if (end)
1262 			*end = 0;
1263 	}
1264 
1265 	obj->efile.fd = -1;
1266 	/*
1267 	 * Caller of this function should also call
1268 	 * bpf_object__elf_finish() after data collection to return
1269 	 * obj_buf to user. If not, we should duplicate the buffer to
1270 	 * avoid user freeing them before elf finish.
1271 	 */
1272 	obj->efile.obj_buf = obj_buf;
1273 	obj->efile.obj_buf_sz = obj_buf_sz;
1274 	obj->efile.btf_maps_shndx = -1;
1275 	obj->efile.st_ops_shndx = -1;
1276 	obj->efile.st_ops_link_shndx = -1;
1277 	obj->kconfig_map_idx = -1;
1278 
1279 	obj->kern_version = get_kernel_version();
1280 	obj->loaded = false;
1281 
1282 	return obj;
1283 }
1284 
1285 static void bpf_object__elf_finish(struct bpf_object *obj)
1286 {
1287 	if (!obj->efile.elf)
1288 		return;
1289 
1290 	elf_end(obj->efile.elf);
1291 	obj->efile.elf = NULL;
1292 	obj->efile.symbols = NULL;
1293 	obj->efile.st_ops_data = NULL;
1294 	obj->efile.st_ops_link_data = NULL;
1295 
1296 	zfree(&obj->efile.secs);
1297 	obj->efile.sec_cnt = 0;
1298 	zclose(obj->efile.fd);
1299 	obj->efile.obj_buf = NULL;
1300 	obj->efile.obj_buf_sz = 0;
1301 }
1302 
1303 static int bpf_object__elf_init(struct bpf_object *obj)
1304 {
1305 	Elf64_Ehdr *ehdr;
1306 	int err = 0;
1307 	Elf *elf;
1308 
1309 	if (obj->efile.elf) {
1310 		pr_warn("elf: init internal error\n");
1311 		return -LIBBPF_ERRNO__LIBELF;
1312 	}
1313 
1314 	if (obj->efile.obj_buf_sz > 0) {
1315 		/* obj_buf should have been validated by bpf_object__open_mem(). */
1316 		elf = elf_memory((char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
1317 	} else {
1318 		obj->efile.fd = open(obj->path, O_RDONLY | O_CLOEXEC);
1319 		if (obj->efile.fd < 0) {
1320 			char errmsg[STRERR_BUFSIZE], *cp;
1321 
1322 			err = -errno;
1323 			cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
1324 			pr_warn("elf: failed to open %s: %s\n", obj->path, cp);
1325 			return err;
1326 		}
1327 
1328 		elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1329 	}
1330 
1331 	if (!elf) {
1332 		pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
1333 		err = -LIBBPF_ERRNO__LIBELF;
1334 		goto errout;
1335 	}
1336 
1337 	obj->efile.elf = elf;
1338 
1339 	if (elf_kind(elf) != ELF_K_ELF) {
1340 		err = -LIBBPF_ERRNO__FORMAT;
1341 		pr_warn("elf: '%s' is not a proper ELF object\n", obj->path);
1342 		goto errout;
1343 	}
1344 
1345 	if (gelf_getclass(elf) != ELFCLASS64) {
1346 		err = -LIBBPF_ERRNO__FORMAT;
1347 		pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path);
1348 		goto errout;
1349 	}
1350 
1351 	obj->efile.ehdr = ehdr = elf64_getehdr(elf);
1352 	if (!obj->efile.ehdr) {
1353 		pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
1354 		err = -LIBBPF_ERRNO__FORMAT;
1355 		goto errout;
1356 	}
1357 
1358 	if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
1359 		pr_warn("elf: failed to get section names section index for %s: %s\n",
1360 			obj->path, elf_errmsg(-1));
1361 		err = -LIBBPF_ERRNO__FORMAT;
1362 		goto errout;
1363 	}
1364 
1365 	/* ELF is corrupted/truncated, avoid calling elf_strptr. */
1366 	if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
1367 		pr_warn("elf: failed to get section names strings from %s: %s\n",
1368 			obj->path, elf_errmsg(-1));
1369 		err = -LIBBPF_ERRNO__FORMAT;
1370 		goto errout;
1371 	}
1372 
1373 	/* Old LLVM set e_machine to EM_NONE */
1374 	if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
1375 		pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
1376 		err = -LIBBPF_ERRNO__FORMAT;
1377 		goto errout;
1378 	}
1379 
1380 	return 0;
1381 errout:
1382 	bpf_object__elf_finish(obj);
1383 	return err;
1384 }
1385 
1386 static int bpf_object__check_endianness(struct bpf_object *obj)
1387 {
1388 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1389 	if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2LSB)
1390 		return 0;
1391 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1392 	if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2MSB)
1393 		return 0;
1394 #else
1395 # error "Unrecognized __BYTE_ORDER__"
1396 #endif
1397 	pr_warn("elf: endianness mismatch in %s.\n", obj->path);
1398 	return -LIBBPF_ERRNO__ENDIAN;
1399 }
1400 
1401 static int
1402 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1403 {
1404 	if (!data) {
1405 		pr_warn("invalid license section in %s\n", obj->path);
1406 		return -LIBBPF_ERRNO__FORMAT;
1407 	}
1408 	/* libbpf_strlcpy() only copies first N - 1 bytes, so size + 1 won't
1409 	 * go over allowed ELF data section buffer
1410 	 */
1411 	libbpf_strlcpy(obj->license, data, min(size + 1, sizeof(obj->license)));
1412 	pr_debug("license of %s is %s\n", obj->path, obj->license);
1413 	return 0;
1414 }
1415 
1416 static int
1417 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1418 {
1419 	__u32 kver;
1420 
1421 	if (!data || size != sizeof(kver)) {
1422 		pr_warn("invalid kver section in %s\n", obj->path);
1423 		return -LIBBPF_ERRNO__FORMAT;
1424 	}
1425 	memcpy(&kver, data, sizeof(kver));
1426 	obj->kern_version = kver;
1427 	pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1428 	return 0;
1429 }
1430 
1431 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1432 {
1433 	if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1434 	    type == BPF_MAP_TYPE_HASH_OF_MAPS)
1435 		return true;
1436 	return false;
1437 }
1438 
1439 static int find_elf_sec_sz(const struct bpf_object *obj, const char *name, __u32 *size)
1440 {
1441 	Elf_Data *data;
1442 	Elf_Scn *scn;
1443 
1444 	if (!name)
1445 		return -EINVAL;
1446 
1447 	scn = elf_sec_by_name(obj, name);
1448 	data = elf_sec_data(obj, scn);
1449 	if (data) {
1450 		*size = data->d_size;
1451 		return 0; /* found it */
1452 	}
1453 
1454 	return -ENOENT;
1455 }
1456 
1457 static Elf64_Sym *find_elf_var_sym(const struct bpf_object *obj, const char *name)
1458 {
1459 	Elf_Data *symbols = obj->efile.symbols;
1460 	const char *sname;
1461 	size_t si;
1462 
1463 	for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
1464 		Elf64_Sym *sym = elf_sym_by_idx(obj, si);
1465 
1466 		if (ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)
1467 			continue;
1468 
1469 		if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL &&
1470 		    ELF64_ST_BIND(sym->st_info) != STB_WEAK)
1471 			continue;
1472 
1473 		sname = elf_sym_str(obj, sym->st_name);
1474 		if (!sname) {
1475 			pr_warn("failed to get sym name string for var %s\n", name);
1476 			return ERR_PTR(-EIO);
1477 		}
1478 		if (strcmp(name, sname) == 0)
1479 			return sym;
1480 	}
1481 
1482 	return ERR_PTR(-ENOENT);
1483 }
1484 
1485 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1486 {
1487 	struct bpf_map *map;
1488 	int err;
1489 
1490 	err = libbpf_ensure_mem((void **)&obj->maps, &obj->maps_cap,
1491 				sizeof(*obj->maps), obj->nr_maps + 1);
1492 	if (err)
1493 		return ERR_PTR(err);
1494 
1495 	map = &obj->maps[obj->nr_maps++];
1496 	map->obj = obj;
1497 	map->fd = -1;
1498 	map->inner_map_fd = -1;
1499 	map->autocreate = true;
1500 
1501 	return map;
1502 }
1503 
1504 static size_t bpf_map_mmap_sz(const struct bpf_map *map)
1505 {
1506 	long page_sz = sysconf(_SC_PAGE_SIZE);
1507 	size_t map_sz;
1508 
1509 	map_sz = (size_t)roundup(map->def.value_size, 8) * map->def.max_entries;
1510 	map_sz = roundup(map_sz, page_sz);
1511 	return map_sz;
1512 }
1513 
1514 static char *internal_map_name(struct bpf_object *obj, const char *real_name)
1515 {
1516 	char map_name[BPF_OBJ_NAME_LEN], *p;
1517 	int pfx_len, sfx_len = max((size_t)7, strlen(real_name));
1518 
1519 	/* This is one of the more confusing parts of libbpf for various
1520 	 * reasons, some of which are historical. The original idea for naming
1521 	 * internal names was to include as much of BPF object name prefix as
1522 	 * possible, so that it can be distinguished from similar internal
1523 	 * maps of a different BPF object.
1524 	 * As an example, let's say we have bpf_object named 'my_object_name'
1525 	 * and internal map corresponding to '.rodata' ELF section. The final
1526 	 * map name advertised to user and to the kernel will be
1527 	 * 'my_objec.rodata', taking first 8 characters of object name and
1528 	 * entire 7 characters of '.rodata'.
1529 	 * Somewhat confusingly, if internal map ELF section name is shorter
1530 	 * than 7 characters, e.g., '.bss', we still reserve 7 characters
1531 	 * for the suffix, even though we only have 4 actual characters, and
1532 	 * resulting map will be called 'my_objec.bss', not even using all 15
1533 	 * characters allowed by the kernel. Oh well, at least the truncated
1534 	 * object name is somewhat consistent in this case. But if the map
1535 	 * name is '.kconfig', we'll still have entirety of '.kconfig' added
1536 	 * (8 chars) and thus will be left with only first 7 characters of the
1537 	 * object name ('my_obje'). Happy guessing, user, that the final map
1538 	 * name will be "my_obje.kconfig".
1539 	 * Now, with libbpf starting to support arbitrarily named .rodata.*
1540 	 * and .data.* data sections, it's possible that ELF section name is
1541 	 * longer than allowed 15 chars, so we now need to be careful to take
1542 	 * only up to 15 first characters of ELF name, taking no BPF object
1543 	 * name characters at all. So '.rodata.abracadabra' will result in
1544 	 * '.rodata.abracad' kernel and user-visible name.
1545 	 * We need to keep this convoluted logic intact for .data, .bss and
1546 	 * .rodata maps, but for new custom .data.custom and .rodata.custom
1547 	 * maps we use their ELF names as is, not prepending bpf_object name
1548 	 * in front. We still need to truncate them to 15 characters for the
1549 	 * kernel. Full name can be recovered for such maps by using DATASEC
1550 	 * BTF type associated with such map's value type, though.
1551 	 */
1552 	if (sfx_len >= BPF_OBJ_NAME_LEN)
1553 		sfx_len = BPF_OBJ_NAME_LEN - 1;
1554 
1555 	/* if there are two or more dots in map name, it's a custom dot map */
1556 	if (strchr(real_name + 1, '.') != NULL)
1557 		pfx_len = 0;
1558 	else
1559 		pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
1560 
1561 	snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1562 		 sfx_len, real_name);
1563 
1564 	/* sanitise map name to characters allowed by kernel */
1565 	for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1566 		if (!isalnum(*p) && *p != '_' && *p != '.')
1567 			*p = '_';
1568 
1569 	return strdup(map_name);
1570 }
1571 
1572 static int
1573 map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map);
1574 
1575 /* Internal BPF map is mmap()'able only if at least one of corresponding
1576  * DATASEC's VARs are to be exposed through BPF skeleton. I.e., it's a GLOBAL
1577  * variable and it's not marked as __hidden (which turns it into, effectively,
1578  * a STATIC variable).
1579  */
1580 static bool map_is_mmapable(struct bpf_object *obj, struct bpf_map *map)
1581 {
1582 	const struct btf_type *t, *vt;
1583 	struct btf_var_secinfo *vsi;
1584 	int i, n;
1585 
1586 	if (!map->btf_value_type_id)
1587 		return false;
1588 
1589 	t = btf__type_by_id(obj->btf, map->btf_value_type_id);
1590 	if (!btf_is_datasec(t))
1591 		return false;
1592 
1593 	vsi = btf_var_secinfos(t);
1594 	for (i = 0, n = btf_vlen(t); i < n; i++, vsi++) {
1595 		vt = btf__type_by_id(obj->btf, vsi->type);
1596 		if (!btf_is_var(vt))
1597 			continue;
1598 
1599 		if (btf_var(vt)->linkage != BTF_VAR_STATIC)
1600 			return true;
1601 	}
1602 
1603 	return false;
1604 }
1605 
1606 static int
1607 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
1608 			      const char *real_name, int sec_idx, void *data, size_t data_sz)
1609 {
1610 	struct bpf_map_def *def;
1611 	struct bpf_map *map;
1612 	int err;
1613 
1614 	map = bpf_object__add_map(obj);
1615 	if (IS_ERR(map))
1616 		return PTR_ERR(map);
1617 
1618 	map->libbpf_type = type;
1619 	map->sec_idx = sec_idx;
1620 	map->sec_offset = 0;
1621 	map->real_name = strdup(real_name);
1622 	map->name = internal_map_name(obj, real_name);
1623 	if (!map->real_name || !map->name) {
1624 		zfree(&map->real_name);
1625 		zfree(&map->name);
1626 		return -ENOMEM;
1627 	}
1628 
1629 	def = &map->def;
1630 	def->type = BPF_MAP_TYPE_ARRAY;
1631 	def->key_size = sizeof(int);
1632 	def->value_size = data_sz;
1633 	def->max_entries = 1;
1634 	def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
1635 			 ? BPF_F_RDONLY_PROG : 0;
1636 
1637 	/* failures are fine because of maps like .rodata.str1.1 */
1638 	(void) map_fill_btf_type_info(obj, map);
1639 
1640 	if (map_is_mmapable(obj, map))
1641 		def->map_flags |= BPF_F_MMAPABLE;
1642 
1643 	pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
1644 		 map->name, map->sec_idx, map->sec_offset, def->map_flags);
1645 
1646 	map->mmaped = mmap(NULL, bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
1647 			   MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1648 	if (map->mmaped == MAP_FAILED) {
1649 		err = -errno;
1650 		map->mmaped = NULL;
1651 		pr_warn("failed to alloc map '%s' content buffer: %d\n",
1652 			map->name, err);
1653 		zfree(&map->real_name);
1654 		zfree(&map->name);
1655 		return err;
1656 	}
1657 
1658 	if (data)
1659 		memcpy(map->mmaped, data, data_sz);
1660 
1661 	pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
1662 	return 0;
1663 }
1664 
1665 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
1666 {
1667 	struct elf_sec_desc *sec_desc;
1668 	const char *sec_name;
1669 	int err = 0, sec_idx;
1670 
1671 	/*
1672 	 * Populate obj->maps with libbpf internal maps.
1673 	 */
1674 	for (sec_idx = 1; sec_idx < obj->efile.sec_cnt; sec_idx++) {
1675 		sec_desc = &obj->efile.secs[sec_idx];
1676 
1677 		/* Skip recognized sections with size 0. */
1678 		if (!sec_desc->data || sec_desc->data->d_size == 0)
1679 			continue;
1680 
1681 		switch (sec_desc->sec_type) {
1682 		case SEC_DATA:
1683 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1684 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
1685 							    sec_name, sec_idx,
1686 							    sec_desc->data->d_buf,
1687 							    sec_desc->data->d_size);
1688 			break;
1689 		case SEC_RODATA:
1690 			obj->has_rodata = true;
1691 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1692 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
1693 							    sec_name, sec_idx,
1694 							    sec_desc->data->d_buf,
1695 							    sec_desc->data->d_size);
1696 			break;
1697 		case SEC_BSS:
1698 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1699 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
1700 							    sec_name, sec_idx,
1701 							    NULL,
1702 							    sec_desc->data->d_size);
1703 			break;
1704 		default:
1705 			/* skip */
1706 			break;
1707 		}
1708 		if (err)
1709 			return err;
1710 	}
1711 	return 0;
1712 }
1713 
1714 
1715 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
1716 					       const void *name)
1717 {
1718 	int i;
1719 
1720 	for (i = 0; i < obj->nr_extern; i++) {
1721 		if (strcmp(obj->externs[i].name, name) == 0)
1722 			return &obj->externs[i];
1723 	}
1724 	return NULL;
1725 }
1726 
1727 static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
1728 			      char value)
1729 {
1730 	switch (ext->kcfg.type) {
1731 	case KCFG_BOOL:
1732 		if (value == 'm') {
1733 			pr_warn("extern (kcfg) '%s': value '%c' implies tristate or char type\n",
1734 				ext->name, value);
1735 			return -EINVAL;
1736 		}
1737 		*(bool *)ext_val = value == 'y' ? true : false;
1738 		break;
1739 	case KCFG_TRISTATE:
1740 		if (value == 'y')
1741 			*(enum libbpf_tristate *)ext_val = TRI_YES;
1742 		else if (value == 'm')
1743 			*(enum libbpf_tristate *)ext_val = TRI_MODULE;
1744 		else /* value == 'n' */
1745 			*(enum libbpf_tristate *)ext_val = TRI_NO;
1746 		break;
1747 	case KCFG_CHAR:
1748 		*(char *)ext_val = value;
1749 		break;
1750 	case KCFG_UNKNOWN:
1751 	case KCFG_INT:
1752 	case KCFG_CHAR_ARR:
1753 	default:
1754 		pr_warn("extern (kcfg) '%s': value '%c' implies bool, tristate, or char type\n",
1755 			ext->name, value);
1756 		return -EINVAL;
1757 	}
1758 	ext->is_set = true;
1759 	return 0;
1760 }
1761 
1762 static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
1763 			      const char *value)
1764 {
1765 	size_t len;
1766 
1767 	if (ext->kcfg.type != KCFG_CHAR_ARR) {
1768 		pr_warn("extern (kcfg) '%s': value '%s' implies char array type\n",
1769 			ext->name, value);
1770 		return -EINVAL;
1771 	}
1772 
1773 	len = strlen(value);
1774 	if (value[len - 1] != '"') {
1775 		pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
1776 			ext->name, value);
1777 		return -EINVAL;
1778 	}
1779 
1780 	/* strip quotes */
1781 	len -= 2;
1782 	if (len >= ext->kcfg.sz) {
1783 		pr_warn("extern (kcfg) '%s': long string '%s' of (%zu bytes) truncated to %d bytes\n",
1784 			ext->name, value, len, ext->kcfg.sz - 1);
1785 		len = ext->kcfg.sz - 1;
1786 	}
1787 	memcpy(ext_val, value + 1, len);
1788 	ext_val[len] = '\0';
1789 	ext->is_set = true;
1790 	return 0;
1791 }
1792 
1793 static int parse_u64(const char *value, __u64 *res)
1794 {
1795 	char *value_end;
1796 	int err;
1797 
1798 	errno = 0;
1799 	*res = strtoull(value, &value_end, 0);
1800 	if (errno) {
1801 		err = -errno;
1802 		pr_warn("failed to parse '%s' as integer: %d\n", value, err);
1803 		return err;
1804 	}
1805 	if (*value_end) {
1806 		pr_warn("failed to parse '%s' as integer completely\n", value);
1807 		return -EINVAL;
1808 	}
1809 	return 0;
1810 }
1811 
1812 static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
1813 {
1814 	int bit_sz = ext->kcfg.sz * 8;
1815 
1816 	if (ext->kcfg.sz == 8)
1817 		return true;
1818 
1819 	/* Validate that value stored in u64 fits in integer of `ext->sz`
1820 	 * bytes size without any loss of information. If the target integer
1821 	 * is signed, we rely on the following limits of integer type of
1822 	 * Y bits and subsequent transformation:
1823 	 *
1824 	 *     -2^(Y-1) <= X           <= 2^(Y-1) - 1
1825 	 *            0 <= X + 2^(Y-1) <= 2^Y - 1
1826 	 *            0 <= X + 2^(Y-1) <  2^Y
1827 	 *
1828 	 *  For unsigned target integer, check that all the (64 - Y) bits are
1829 	 *  zero.
1830 	 */
1831 	if (ext->kcfg.is_signed)
1832 		return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
1833 	else
1834 		return (v >> bit_sz) == 0;
1835 }
1836 
1837 static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
1838 			      __u64 value)
1839 {
1840 	if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR &&
1841 	    ext->kcfg.type != KCFG_BOOL) {
1842 		pr_warn("extern (kcfg) '%s': value '%llu' implies integer, char, or boolean type\n",
1843 			ext->name, (unsigned long long)value);
1844 		return -EINVAL;
1845 	}
1846 	if (ext->kcfg.type == KCFG_BOOL && value > 1) {
1847 		pr_warn("extern (kcfg) '%s': value '%llu' isn't boolean compatible\n",
1848 			ext->name, (unsigned long long)value);
1849 		return -EINVAL;
1850 
1851 	}
1852 	if (!is_kcfg_value_in_range(ext, value)) {
1853 		pr_warn("extern (kcfg) '%s': value '%llu' doesn't fit in %d bytes\n",
1854 			ext->name, (unsigned long long)value, ext->kcfg.sz);
1855 		return -ERANGE;
1856 	}
1857 	switch (ext->kcfg.sz) {
1858 	case 1:
1859 		*(__u8 *)ext_val = value;
1860 		break;
1861 	case 2:
1862 		*(__u16 *)ext_val = value;
1863 		break;
1864 	case 4:
1865 		*(__u32 *)ext_val = value;
1866 		break;
1867 	case 8:
1868 		*(__u64 *)ext_val = value;
1869 		break;
1870 	default:
1871 		return -EINVAL;
1872 	}
1873 	ext->is_set = true;
1874 	return 0;
1875 }
1876 
1877 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
1878 					    char *buf, void *data)
1879 {
1880 	struct extern_desc *ext;
1881 	char *sep, *value;
1882 	int len, err = 0;
1883 	void *ext_val;
1884 	__u64 num;
1885 
1886 	if (!str_has_pfx(buf, "CONFIG_"))
1887 		return 0;
1888 
1889 	sep = strchr(buf, '=');
1890 	if (!sep) {
1891 		pr_warn("failed to parse '%s': no separator\n", buf);
1892 		return -EINVAL;
1893 	}
1894 
1895 	/* Trim ending '\n' */
1896 	len = strlen(buf);
1897 	if (buf[len - 1] == '\n')
1898 		buf[len - 1] = '\0';
1899 	/* Split on '=' and ensure that a value is present. */
1900 	*sep = '\0';
1901 	if (!sep[1]) {
1902 		*sep = '=';
1903 		pr_warn("failed to parse '%s': no value\n", buf);
1904 		return -EINVAL;
1905 	}
1906 
1907 	ext = find_extern_by_name(obj, buf);
1908 	if (!ext || ext->is_set)
1909 		return 0;
1910 
1911 	ext_val = data + ext->kcfg.data_off;
1912 	value = sep + 1;
1913 
1914 	switch (*value) {
1915 	case 'y': case 'n': case 'm':
1916 		err = set_kcfg_value_tri(ext, ext_val, *value);
1917 		break;
1918 	case '"':
1919 		err = set_kcfg_value_str(ext, ext_val, value);
1920 		break;
1921 	default:
1922 		/* assume integer */
1923 		err = parse_u64(value, &num);
1924 		if (err) {
1925 			pr_warn("extern (kcfg) '%s': value '%s' isn't a valid integer\n", ext->name, value);
1926 			return err;
1927 		}
1928 		if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
1929 			pr_warn("extern (kcfg) '%s': value '%s' implies integer type\n", ext->name, value);
1930 			return -EINVAL;
1931 		}
1932 		err = set_kcfg_value_num(ext, ext_val, num);
1933 		break;
1934 	}
1935 	if (err)
1936 		return err;
1937 	pr_debug("extern (kcfg) '%s': set to %s\n", ext->name, value);
1938 	return 0;
1939 }
1940 
1941 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
1942 {
1943 	char buf[PATH_MAX];
1944 	struct utsname uts;
1945 	int len, err = 0;
1946 	gzFile file;
1947 
1948 	uname(&uts);
1949 	len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
1950 	if (len < 0)
1951 		return -EINVAL;
1952 	else if (len >= PATH_MAX)
1953 		return -ENAMETOOLONG;
1954 
1955 	/* gzopen also accepts uncompressed files. */
1956 	file = gzopen(buf, "r");
1957 	if (!file)
1958 		file = gzopen("/proc/config.gz", "r");
1959 
1960 	if (!file) {
1961 		pr_warn("failed to open system Kconfig\n");
1962 		return -ENOENT;
1963 	}
1964 
1965 	while (gzgets(file, buf, sizeof(buf))) {
1966 		err = bpf_object__process_kconfig_line(obj, buf, data);
1967 		if (err) {
1968 			pr_warn("error parsing system Kconfig line '%s': %d\n",
1969 				buf, err);
1970 			goto out;
1971 		}
1972 	}
1973 
1974 out:
1975 	gzclose(file);
1976 	return err;
1977 }
1978 
1979 static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
1980 					const char *config, void *data)
1981 {
1982 	char buf[PATH_MAX];
1983 	int err = 0;
1984 	FILE *file;
1985 
1986 	file = fmemopen((void *)config, strlen(config), "r");
1987 	if (!file) {
1988 		err = -errno;
1989 		pr_warn("failed to open in-memory Kconfig: %d\n", err);
1990 		return err;
1991 	}
1992 
1993 	while (fgets(buf, sizeof(buf), file)) {
1994 		err = bpf_object__process_kconfig_line(obj, buf, data);
1995 		if (err) {
1996 			pr_warn("error parsing in-memory Kconfig line '%s': %d\n",
1997 				buf, err);
1998 			break;
1999 		}
2000 	}
2001 
2002 	fclose(file);
2003 	return err;
2004 }
2005 
2006 static int bpf_object__init_kconfig_map(struct bpf_object *obj)
2007 {
2008 	struct extern_desc *last_ext = NULL, *ext;
2009 	size_t map_sz;
2010 	int i, err;
2011 
2012 	for (i = 0; i < obj->nr_extern; i++) {
2013 		ext = &obj->externs[i];
2014 		if (ext->type == EXT_KCFG)
2015 			last_ext = ext;
2016 	}
2017 
2018 	if (!last_ext)
2019 		return 0;
2020 
2021 	map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
2022 	err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
2023 					    ".kconfig", obj->efile.symbols_shndx,
2024 					    NULL, map_sz);
2025 	if (err)
2026 		return err;
2027 
2028 	obj->kconfig_map_idx = obj->nr_maps - 1;
2029 
2030 	return 0;
2031 }
2032 
2033 const struct btf_type *
2034 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
2035 {
2036 	const struct btf_type *t = btf__type_by_id(btf, id);
2037 
2038 	if (res_id)
2039 		*res_id = id;
2040 
2041 	while (btf_is_mod(t) || btf_is_typedef(t)) {
2042 		if (res_id)
2043 			*res_id = t->type;
2044 		t = btf__type_by_id(btf, t->type);
2045 	}
2046 
2047 	return t;
2048 }
2049 
2050 static const struct btf_type *
2051 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
2052 {
2053 	const struct btf_type *t;
2054 
2055 	t = skip_mods_and_typedefs(btf, id, NULL);
2056 	if (!btf_is_ptr(t))
2057 		return NULL;
2058 
2059 	t = skip_mods_and_typedefs(btf, t->type, res_id);
2060 
2061 	return btf_is_func_proto(t) ? t : NULL;
2062 }
2063 
2064 static const char *__btf_kind_str(__u16 kind)
2065 {
2066 	switch (kind) {
2067 	case BTF_KIND_UNKN: return "void";
2068 	case BTF_KIND_INT: return "int";
2069 	case BTF_KIND_PTR: return "ptr";
2070 	case BTF_KIND_ARRAY: return "array";
2071 	case BTF_KIND_STRUCT: return "struct";
2072 	case BTF_KIND_UNION: return "union";
2073 	case BTF_KIND_ENUM: return "enum";
2074 	case BTF_KIND_FWD: return "fwd";
2075 	case BTF_KIND_TYPEDEF: return "typedef";
2076 	case BTF_KIND_VOLATILE: return "volatile";
2077 	case BTF_KIND_CONST: return "const";
2078 	case BTF_KIND_RESTRICT: return "restrict";
2079 	case BTF_KIND_FUNC: return "func";
2080 	case BTF_KIND_FUNC_PROTO: return "func_proto";
2081 	case BTF_KIND_VAR: return "var";
2082 	case BTF_KIND_DATASEC: return "datasec";
2083 	case BTF_KIND_FLOAT: return "float";
2084 	case BTF_KIND_DECL_TAG: return "decl_tag";
2085 	case BTF_KIND_TYPE_TAG: return "type_tag";
2086 	case BTF_KIND_ENUM64: return "enum64";
2087 	default: return "unknown";
2088 	}
2089 }
2090 
2091 const char *btf_kind_str(const struct btf_type *t)
2092 {
2093 	return __btf_kind_str(btf_kind(t));
2094 }
2095 
2096 /*
2097  * Fetch integer attribute of BTF map definition. Such attributes are
2098  * represented using a pointer to an array, in which dimensionality of array
2099  * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2100  * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2101  * type definition, while using only sizeof(void *) space in ELF data section.
2102  */
2103 static bool get_map_field_int(const char *map_name, const struct btf *btf,
2104 			      const struct btf_member *m, __u32 *res)
2105 {
2106 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2107 	const char *name = btf__name_by_offset(btf, m->name_off);
2108 	const struct btf_array *arr_info;
2109 	const struct btf_type *arr_t;
2110 
2111 	if (!btf_is_ptr(t)) {
2112 		pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2113 			map_name, name, btf_kind_str(t));
2114 		return false;
2115 	}
2116 
2117 	arr_t = btf__type_by_id(btf, t->type);
2118 	if (!arr_t) {
2119 		pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2120 			map_name, name, t->type);
2121 		return false;
2122 	}
2123 	if (!btf_is_array(arr_t)) {
2124 		pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2125 			map_name, name, btf_kind_str(arr_t));
2126 		return false;
2127 	}
2128 	arr_info = btf_array(arr_t);
2129 	*res = arr_info->nelems;
2130 	return true;
2131 }
2132 
2133 static int pathname_concat(char *buf, size_t buf_sz, const char *path, const char *name)
2134 {
2135 	int len;
2136 
2137 	len = snprintf(buf, buf_sz, "%s/%s", path, name);
2138 	if (len < 0)
2139 		return -EINVAL;
2140 	if (len >= buf_sz)
2141 		return -ENAMETOOLONG;
2142 
2143 	return 0;
2144 }
2145 
2146 static int build_map_pin_path(struct bpf_map *map, const char *path)
2147 {
2148 	char buf[PATH_MAX];
2149 	int err;
2150 
2151 	if (!path)
2152 		path = "/sys/fs/bpf";
2153 
2154 	err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
2155 	if (err)
2156 		return err;
2157 
2158 	return bpf_map__set_pin_path(map, buf);
2159 }
2160 
2161 /* should match definition in bpf_helpers.h */
2162 enum libbpf_pin_type {
2163 	LIBBPF_PIN_NONE,
2164 	/* PIN_BY_NAME: pin maps by name (in /sys/fs/bpf by default) */
2165 	LIBBPF_PIN_BY_NAME,
2166 };
2167 
2168 int parse_btf_map_def(const char *map_name, struct btf *btf,
2169 		      const struct btf_type *def_t, bool strict,
2170 		      struct btf_map_def *map_def, struct btf_map_def *inner_def)
2171 {
2172 	const struct btf_type *t;
2173 	const struct btf_member *m;
2174 	bool is_inner = inner_def == NULL;
2175 	int vlen, i;
2176 
2177 	vlen = btf_vlen(def_t);
2178 	m = btf_members(def_t);
2179 	for (i = 0; i < vlen; i++, m++) {
2180 		const char *name = btf__name_by_offset(btf, m->name_off);
2181 
2182 		if (!name) {
2183 			pr_warn("map '%s': invalid field #%d.\n", map_name, i);
2184 			return -EINVAL;
2185 		}
2186 		if (strcmp(name, "type") == 0) {
2187 			if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
2188 				return -EINVAL;
2189 			map_def->parts |= MAP_DEF_MAP_TYPE;
2190 		} else if (strcmp(name, "max_entries") == 0) {
2191 			if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
2192 				return -EINVAL;
2193 			map_def->parts |= MAP_DEF_MAX_ENTRIES;
2194 		} else if (strcmp(name, "map_flags") == 0) {
2195 			if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
2196 				return -EINVAL;
2197 			map_def->parts |= MAP_DEF_MAP_FLAGS;
2198 		} else if (strcmp(name, "numa_node") == 0) {
2199 			if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
2200 				return -EINVAL;
2201 			map_def->parts |= MAP_DEF_NUMA_NODE;
2202 		} else if (strcmp(name, "key_size") == 0) {
2203 			__u32 sz;
2204 
2205 			if (!get_map_field_int(map_name, btf, m, &sz))
2206 				return -EINVAL;
2207 			if (map_def->key_size && map_def->key_size != sz) {
2208 				pr_warn("map '%s': conflicting key size %u != %u.\n",
2209 					map_name, map_def->key_size, sz);
2210 				return -EINVAL;
2211 			}
2212 			map_def->key_size = sz;
2213 			map_def->parts |= MAP_DEF_KEY_SIZE;
2214 		} else if (strcmp(name, "key") == 0) {
2215 			__s64 sz;
2216 
2217 			t = btf__type_by_id(btf, m->type);
2218 			if (!t) {
2219 				pr_warn("map '%s': key type [%d] not found.\n",
2220 					map_name, m->type);
2221 				return -EINVAL;
2222 			}
2223 			if (!btf_is_ptr(t)) {
2224 				pr_warn("map '%s': key spec is not PTR: %s.\n",
2225 					map_name, btf_kind_str(t));
2226 				return -EINVAL;
2227 			}
2228 			sz = btf__resolve_size(btf, t->type);
2229 			if (sz < 0) {
2230 				pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2231 					map_name, t->type, (ssize_t)sz);
2232 				return sz;
2233 			}
2234 			if (map_def->key_size && map_def->key_size != sz) {
2235 				pr_warn("map '%s': conflicting key size %u != %zd.\n",
2236 					map_name, map_def->key_size, (ssize_t)sz);
2237 				return -EINVAL;
2238 			}
2239 			map_def->key_size = sz;
2240 			map_def->key_type_id = t->type;
2241 			map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
2242 		} else if (strcmp(name, "value_size") == 0) {
2243 			__u32 sz;
2244 
2245 			if (!get_map_field_int(map_name, btf, m, &sz))
2246 				return -EINVAL;
2247 			if (map_def->value_size && map_def->value_size != sz) {
2248 				pr_warn("map '%s': conflicting value size %u != %u.\n",
2249 					map_name, map_def->value_size, sz);
2250 				return -EINVAL;
2251 			}
2252 			map_def->value_size = sz;
2253 			map_def->parts |= MAP_DEF_VALUE_SIZE;
2254 		} else if (strcmp(name, "value") == 0) {
2255 			__s64 sz;
2256 
2257 			t = btf__type_by_id(btf, m->type);
2258 			if (!t) {
2259 				pr_warn("map '%s': value type [%d] not found.\n",
2260 					map_name, m->type);
2261 				return -EINVAL;
2262 			}
2263 			if (!btf_is_ptr(t)) {
2264 				pr_warn("map '%s': value spec is not PTR: %s.\n",
2265 					map_name, btf_kind_str(t));
2266 				return -EINVAL;
2267 			}
2268 			sz = btf__resolve_size(btf, t->type);
2269 			if (sz < 0) {
2270 				pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2271 					map_name, t->type, (ssize_t)sz);
2272 				return sz;
2273 			}
2274 			if (map_def->value_size && map_def->value_size != sz) {
2275 				pr_warn("map '%s': conflicting value size %u != %zd.\n",
2276 					map_name, map_def->value_size, (ssize_t)sz);
2277 				return -EINVAL;
2278 			}
2279 			map_def->value_size = sz;
2280 			map_def->value_type_id = t->type;
2281 			map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
2282 		}
2283 		else if (strcmp(name, "values") == 0) {
2284 			bool is_map_in_map = bpf_map_type__is_map_in_map(map_def->map_type);
2285 			bool is_prog_array = map_def->map_type == BPF_MAP_TYPE_PROG_ARRAY;
2286 			const char *desc = is_map_in_map ? "map-in-map inner" : "prog-array value";
2287 			char inner_map_name[128];
2288 			int err;
2289 
2290 			if (is_inner) {
2291 				pr_warn("map '%s': multi-level inner maps not supported.\n",
2292 					map_name);
2293 				return -ENOTSUP;
2294 			}
2295 			if (i != vlen - 1) {
2296 				pr_warn("map '%s': '%s' member should be last.\n",
2297 					map_name, name);
2298 				return -EINVAL;
2299 			}
2300 			if (!is_map_in_map && !is_prog_array) {
2301 				pr_warn("map '%s': should be map-in-map or prog-array.\n",
2302 					map_name);
2303 				return -ENOTSUP;
2304 			}
2305 			if (map_def->value_size && map_def->value_size != 4) {
2306 				pr_warn("map '%s': conflicting value size %u != 4.\n",
2307 					map_name, map_def->value_size);
2308 				return -EINVAL;
2309 			}
2310 			map_def->value_size = 4;
2311 			t = btf__type_by_id(btf, m->type);
2312 			if (!t) {
2313 				pr_warn("map '%s': %s type [%d] not found.\n",
2314 					map_name, desc, m->type);
2315 				return -EINVAL;
2316 			}
2317 			if (!btf_is_array(t) || btf_array(t)->nelems) {
2318 				pr_warn("map '%s': %s spec is not a zero-sized array.\n",
2319 					map_name, desc);
2320 				return -EINVAL;
2321 			}
2322 			t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
2323 			if (!btf_is_ptr(t)) {
2324 				pr_warn("map '%s': %s def is of unexpected kind %s.\n",
2325 					map_name, desc, btf_kind_str(t));
2326 				return -EINVAL;
2327 			}
2328 			t = skip_mods_and_typedefs(btf, t->type, NULL);
2329 			if (is_prog_array) {
2330 				if (!btf_is_func_proto(t)) {
2331 					pr_warn("map '%s': prog-array value def is of unexpected kind %s.\n",
2332 						map_name, btf_kind_str(t));
2333 					return -EINVAL;
2334 				}
2335 				continue;
2336 			}
2337 			if (!btf_is_struct(t)) {
2338 				pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2339 					map_name, btf_kind_str(t));
2340 				return -EINVAL;
2341 			}
2342 
2343 			snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2344 			err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
2345 			if (err)
2346 				return err;
2347 
2348 			map_def->parts |= MAP_DEF_INNER_MAP;
2349 		} else if (strcmp(name, "pinning") == 0) {
2350 			__u32 val;
2351 
2352 			if (is_inner) {
2353 				pr_warn("map '%s': inner def can't be pinned.\n", map_name);
2354 				return -EINVAL;
2355 			}
2356 			if (!get_map_field_int(map_name, btf, m, &val))
2357 				return -EINVAL;
2358 			if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
2359 				pr_warn("map '%s': invalid pinning value %u.\n",
2360 					map_name, val);
2361 				return -EINVAL;
2362 			}
2363 			map_def->pinning = val;
2364 			map_def->parts |= MAP_DEF_PINNING;
2365 		} else if (strcmp(name, "map_extra") == 0) {
2366 			__u32 map_extra;
2367 
2368 			if (!get_map_field_int(map_name, btf, m, &map_extra))
2369 				return -EINVAL;
2370 			map_def->map_extra = map_extra;
2371 			map_def->parts |= MAP_DEF_MAP_EXTRA;
2372 		} else {
2373 			if (strict) {
2374 				pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
2375 				return -ENOTSUP;
2376 			}
2377 			pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
2378 		}
2379 	}
2380 
2381 	if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2382 		pr_warn("map '%s': map type isn't specified.\n", map_name);
2383 		return -EINVAL;
2384 	}
2385 
2386 	return 0;
2387 }
2388 
2389 static size_t adjust_ringbuf_sz(size_t sz)
2390 {
2391 	__u32 page_sz = sysconf(_SC_PAGE_SIZE);
2392 	__u32 mul;
2393 
2394 	/* if user forgot to set any size, make sure they see error */
2395 	if (sz == 0)
2396 		return 0;
2397 	/* Kernel expects BPF_MAP_TYPE_RINGBUF's max_entries to be
2398 	 * a power-of-2 multiple of kernel's page size. If user diligently
2399 	 * satisified these conditions, pass the size through.
2400 	 */
2401 	if ((sz % page_sz) == 0 && is_pow_of_2(sz / page_sz))
2402 		return sz;
2403 
2404 	/* Otherwise find closest (page_sz * power_of_2) product bigger than
2405 	 * user-set size to satisfy both user size request and kernel
2406 	 * requirements and substitute correct max_entries for map creation.
2407 	 */
2408 	for (mul = 1; mul <= UINT_MAX / page_sz; mul <<= 1) {
2409 		if (mul * page_sz > sz)
2410 			return mul * page_sz;
2411 	}
2412 
2413 	/* if it's impossible to satisfy the conditions (i.e., user size is
2414 	 * very close to UINT_MAX but is not a power-of-2 multiple of
2415 	 * page_size) then just return original size and let kernel reject it
2416 	 */
2417 	return sz;
2418 }
2419 
2420 static bool map_is_ringbuf(const struct bpf_map *map)
2421 {
2422 	return map->def.type == BPF_MAP_TYPE_RINGBUF ||
2423 	       map->def.type == BPF_MAP_TYPE_USER_RINGBUF;
2424 }
2425 
2426 static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2427 {
2428 	map->def.type = def->map_type;
2429 	map->def.key_size = def->key_size;
2430 	map->def.value_size = def->value_size;
2431 	map->def.max_entries = def->max_entries;
2432 	map->def.map_flags = def->map_flags;
2433 	map->map_extra = def->map_extra;
2434 
2435 	map->numa_node = def->numa_node;
2436 	map->btf_key_type_id = def->key_type_id;
2437 	map->btf_value_type_id = def->value_type_id;
2438 
2439 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
2440 	if (map_is_ringbuf(map))
2441 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
2442 
2443 	if (def->parts & MAP_DEF_MAP_TYPE)
2444 		pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2445 
2446 	if (def->parts & MAP_DEF_KEY_TYPE)
2447 		pr_debug("map '%s': found key [%u], sz = %u.\n",
2448 			 map->name, def->key_type_id, def->key_size);
2449 	else if (def->parts & MAP_DEF_KEY_SIZE)
2450 		pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2451 
2452 	if (def->parts & MAP_DEF_VALUE_TYPE)
2453 		pr_debug("map '%s': found value [%u], sz = %u.\n",
2454 			 map->name, def->value_type_id, def->value_size);
2455 	else if (def->parts & MAP_DEF_VALUE_SIZE)
2456 		pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2457 
2458 	if (def->parts & MAP_DEF_MAX_ENTRIES)
2459 		pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2460 	if (def->parts & MAP_DEF_MAP_FLAGS)
2461 		pr_debug("map '%s': found map_flags = 0x%x.\n", map->name, def->map_flags);
2462 	if (def->parts & MAP_DEF_MAP_EXTRA)
2463 		pr_debug("map '%s': found map_extra = 0x%llx.\n", map->name,
2464 			 (unsigned long long)def->map_extra);
2465 	if (def->parts & MAP_DEF_PINNING)
2466 		pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2467 	if (def->parts & MAP_DEF_NUMA_NODE)
2468 		pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2469 
2470 	if (def->parts & MAP_DEF_INNER_MAP)
2471 		pr_debug("map '%s': found inner map definition.\n", map->name);
2472 }
2473 
2474 static const char *btf_var_linkage_str(__u32 linkage)
2475 {
2476 	switch (linkage) {
2477 	case BTF_VAR_STATIC: return "static";
2478 	case BTF_VAR_GLOBAL_ALLOCATED: return "global";
2479 	case BTF_VAR_GLOBAL_EXTERN: return "extern";
2480 	default: return "unknown";
2481 	}
2482 }
2483 
2484 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2485 					 const struct btf_type *sec,
2486 					 int var_idx, int sec_idx,
2487 					 const Elf_Data *data, bool strict,
2488 					 const char *pin_root_path)
2489 {
2490 	struct btf_map_def map_def = {}, inner_def = {};
2491 	const struct btf_type *var, *def;
2492 	const struct btf_var_secinfo *vi;
2493 	const struct btf_var *var_extra;
2494 	const char *map_name;
2495 	struct bpf_map *map;
2496 	int err;
2497 
2498 	vi = btf_var_secinfos(sec) + var_idx;
2499 	var = btf__type_by_id(obj->btf, vi->type);
2500 	var_extra = btf_var(var);
2501 	map_name = btf__name_by_offset(obj->btf, var->name_off);
2502 
2503 	if (map_name == NULL || map_name[0] == '\0') {
2504 		pr_warn("map #%d: empty name.\n", var_idx);
2505 		return -EINVAL;
2506 	}
2507 	if ((__u64)vi->offset + vi->size > data->d_size) {
2508 		pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2509 		return -EINVAL;
2510 	}
2511 	if (!btf_is_var(var)) {
2512 		pr_warn("map '%s': unexpected var kind %s.\n",
2513 			map_name, btf_kind_str(var));
2514 		return -EINVAL;
2515 	}
2516 	if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
2517 		pr_warn("map '%s': unsupported map linkage %s.\n",
2518 			map_name, btf_var_linkage_str(var_extra->linkage));
2519 		return -EOPNOTSUPP;
2520 	}
2521 
2522 	def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2523 	if (!btf_is_struct(def)) {
2524 		pr_warn("map '%s': unexpected def kind %s.\n",
2525 			map_name, btf_kind_str(var));
2526 		return -EINVAL;
2527 	}
2528 	if (def->size > vi->size) {
2529 		pr_warn("map '%s': invalid def size.\n", map_name);
2530 		return -EINVAL;
2531 	}
2532 
2533 	map = bpf_object__add_map(obj);
2534 	if (IS_ERR(map))
2535 		return PTR_ERR(map);
2536 	map->name = strdup(map_name);
2537 	if (!map->name) {
2538 		pr_warn("map '%s': failed to alloc map name.\n", map_name);
2539 		return -ENOMEM;
2540 	}
2541 	map->libbpf_type = LIBBPF_MAP_UNSPEC;
2542 	map->def.type = BPF_MAP_TYPE_UNSPEC;
2543 	map->sec_idx = sec_idx;
2544 	map->sec_offset = vi->offset;
2545 	map->btf_var_idx = var_idx;
2546 	pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2547 		 map_name, map->sec_idx, map->sec_offset);
2548 
2549 	err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
2550 	if (err)
2551 		return err;
2552 
2553 	fill_map_from_def(map, &map_def);
2554 
2555 	if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
2556 		err = build_map_pin_path(map, pin_root_path);
2557 		if (err) {
2558 			pr_warn("map '%s': couldn't build pin path.\n", map->name);
2559 			return err;
2560 		}
2561 	}
2562 
2563 	if (map_def.parts & MAP_DEF_INNER_MAP) {
2564 		map->inner_map = calloc(1, sizeof(*map->inner_map));
2565 		if (!map->inner_map)
2566 			return -ENOMEM;
2567 		map->inner_map->fd = -1;
2568 		map->inner_map->sec_idx = sec_idx;
2569 		map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
2570 		if (!map->inner_map->name)
2571 			return -ENOMEM;
2572 		sprintf(map->inner_map->name, "%s.inner", map_name);
2573 
2574 		fill_map_from_def(map->inner_map, &inner_def);
2575 	}
2576 
2577 	err = map_fill_btf_type_info(obj, map);
2578 	if (err)
2579 		return err;
2580 
2581 	return 0;
2582 }
2583 
2584 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
2585 					  const char *pin_root_path)
2586 {
2587 	const struct btf_type *sec = NULL;
2588 	int nr_types, i, vlen, err;
2589 	const struct btf_type *t;
2590 	const char *name;
2591 	Elf_Data *data;
2592 	Elf_Scn *scn;
2593 
2594 	if (obj->efile.btf_maps_shndx < 0)
2595 		return 0;
2596 
2597 	scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
2598 	data = elf_sec_data(obj, scn);
2599 	if (!scn || !data) {
2600 		pr_warn("elf: failed to get %s map definitions for %s\n",
2601 			MAPS_ELF_SEC, obj->path);
2602 		return -EINVAL;
2603 	}
2604 
2605 	nr_types = btf__type_cnt(obj->btf);
2606 	for (i = 1; i < nr_types; i++) {
2607 		t = btf__type_by_id(obj->btf, i);
2608 		if (!btf_is_datasec(t))
2609 			continue;
2610 		name = btf__name_by_offset(obj->btf, t->name_off);
2611 		if (strcmp(name, MAPS_ELF_SEC) == 0) {
2612 			sec = t;
2613 			obj->efile.btf_maps_sec_btf_id = i;
2614 			break;
2615 		}
2616 	}
2617 
2618 	if (!sec) {
2619 		pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
2620 		return -ENOENT;
2621 	}
2622 
2623 	vlen = btf_vlen(sec);
2624 	for (i = 0; i < vlen; i++) {
2625 		err = bpf_object__init_user_btf_map(obj, sec, i,
2626 						    obj->efile.btf_maps_shndx,
2627 						    data, strict,
2628 						    pin_root_path);
2629 		if (err)
2630 			return err;
2631 	}
2632 
2633 	return 0;
2634 }
2635 
2636 static int bpf_object__init_maps(struct bpf_object *obj,
2637 				 const struct bpf_object_open_opts *opts)
2638 {
2639 	const char *pin_root_path;
2640 	bool strict;
2641 	int err = 0;
2642 
2643 	strict = !OPTS_GET(opts, relaxed_maps, false);
2644 	pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
2645 
2646 	err = bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
2647 	err = err ?: bpf_object__init_global_data_maps(obj);
2648 	err = err ?: bpf_object__init_kconfig_map(obj);
2649 	err = err ?: bpf_object_init_struct_ops(obj);
2650 
2651 	return err;
2652 }
2653 
2654 static bool section_have_execinstr(struct bpf_object *obj, int idx)
2655 {
2656 	Elf64_Shdr *sh;
2657 
2658 	sh = elf_sec_hdr(obj, elf_sec_by_idx(obj, idx));
2659 	if (!sh)
2660 		return false;
2661 
2662 	return sh->sh_flags & SHF_EXECINSTR;
2663 }
2664 
2665 static bool btf_needs_sanitization(struct bpf_object *obj)
2666 {
2667 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2668 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2669 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2670 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2671 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2672 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2673 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
2674 
2675 	return !has_func || !has_datasec || !has_func_global || !has_float ||
2676 	       !has_decl_tag || !has_type_tag || !has_enum64;
2677 }
2678 
2679 static int bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *btf)
2680 {
2681 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2682 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2683 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2684 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2685 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2686 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2687 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
2688 	int enum64_placeholder_id = 0;
2689 	struct btf_type *t;
2690 	int i, j, vlen;
2691 
2692 	for (i = 1; i < btf__type_cnt(btf); i++) {
2693 		t = (struct btf_type *)btf__type_by_id(btf, i);
2694 
2695 		if ((!has_datasec && btf_is_var(t)) || (!has_decl_tag && btf_is_decl_tag(t))) {
2696 			/* replace VAR/DECL_TAG with INT */
2697 			t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
2698 			/*
2699 			 * using size = 1 is the safest choice, 4 will be too
2700 			 * big and cause kernel BTF validation failure if
2701 			 * original variable took less than 4 bytes
2702 			 */
2703 			t->size = 1;
2704 			*(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
2705 		} else if (!has_datasec && btf_is_datasec(t)) {
2706 			/* replace DATASEC with STRUCT */
2707 			const struct btf_var_secinfo *v = btf_var_secinfos(t);
2708 			struct btf_member *m = btf_members(t);
2709 			struct btf_type *vt;
2710 			char *name;
2711 
2712 			name = (char *)btf__name_by_offset(btf, t->name_off);
2713 			while (*name) {
2714 				if (*name == '.')
2715 					*name = '_';
2716 				name++;
2717 			}
2718 
2719 			vlen = btf_vlen(t);
2720 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
2721 			for (j = 0; j < vlen; j++, v++, m++) {
2722 				/* order of field assignments is important */
2723 				m->offset = v->offset * 8;
2724 				m->type = v->type;
2725 				/* preserve variable name as member name */
2726 				vt = (void *)btf__type_by_id(btf, v->type);
2727 				m->name_off = vt->name_off;
2728 			}
2729 		} else if (!has_func && btf_is_func_proto(t)) {
2730 			/* replace FUNC_PROTO with ENUM */
2731 			vlen = btf_vlen(t);
2732 			t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
2733 			t->size = sizeof(__u32); /* kernel enforced */
2734 		} else if (!has_func && btf_is_func(t)) {
2735 			/* replace FUNC with TYPEDEF */
2736 			t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
2737 		} else if (!has_func_global && btf_is_func(t)) {
2738 			/* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
2739 			t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
2740 		} else if (!has_float && btf_is_float(t)) {
2741 			/* replace FLOAT with an equally-sized empty STRUCT;
2742 			 * since C compilers do not accept e.g. "float" as a
2743 			 * valid struct name, make it anonymous
2744 			 */
2745 			t->name_off = 0;
2746 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
2747 		} else if (!has_type_tag && btf_is_type_tag(t)) {
2748 			/* replace TYPE_TAG with a CONST */
2749 			t->name_off = 0;
2750 			t->info = BTF_INFO_ENC(BTF_KIND_CONST, 0, 0);
2751 		} else if (!has_enum64 && btf_is_enum(t)) {
2752 			/* clear the kflag */
2753 			t->info = btf_type_info(btf_kind(t), btf_vlen(t), false);
2754 		} else if (!has_enum64 && btf_is_enum64(t)) {
2755 			/* replace ENUM64 with a union */
2756 			struct btf_member *m;
2757 
2758 			if (enum64_placeholder_id == 0) {
2759 				enum64_placeholder_id = btf__add_int(btf, "enum64_placeholder", 1, 0);
2760 				if (enum64_placeholder_id < 0)
2761 					return enum64_placeholder_id;
2762 
2763 				t = (struct btf_type *)btf__type_by_id(btf, i);
2764 			}
2765 
2766 			m = btf_members(t);
2767 			vlen = btf_vlen(t);
2768 			t->info = BTF_INFO_ENC(BTF_KIND_UNION, 0, vlen);
2769 			for (j = 0; j < vlen; j++, m++) {
2770 				m->type = enum64_placeholder_id;
2771 				m->offset = 0;
2772 			}
2773 		}
2774 	}
2775 
2776 	return 0;
2777 }
2778 
2779 static bool libbpf_needs_btf(const struct bpf_object *obj)
2780 {
2781 	return obj->efile.btf_maps_shndx >= 0 ||
2782 	       obj->efile.st_ops_shndx >= 0 ||
2783 	       obj->efile.st_ops_link_shndx >= 0 ||
2784 	       obj->nr_extern > 0;
2785 }
2786 
2787 static bool kernel_needs_btf(const struct bpf_object *obj)
2788 {
2789 	return obj->efile.st_ops_shndx >= 0 || obj->efile.st_ops_link_shndx >= 0;
2790 }
2791 
2792 static int bpf_object__init_btf(struct bpf_object *obj,
2793 				Elf_Data *btf_data,
2794 				Elf_Data *btf_ext_data)
2795 {
2796 	int err = -ENOENT;
2797 
2798 	if (btf_data) {
2799 		obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
2800 		err = libbpf_get_error(obj->btf);
2801 		if (err) {
2802 			obj->btf = NULL;
2803 			pr_warn("Error loading ELF section %s: %d.\n", BTF_ELF_SEC, err);
2804 			goto out;
2805 		}
2806 		/* enforce 8-byte pointers for BPF-targeted BTFs */
2807 		btf__set_pointer_size(obj->btf, 8);
2808 	}
2809 	if (btf_ext_data) {
2810 		struct btf_ext_info *ext_segs[3];
2811 		int seg_num, sec_num;
2812 
2813 		if (!obj->btf) {
2814 			pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
2815 				 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
2816 			goto out;
2817 		}
2818 		obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
2819 		err = libbpf_get_error(obj->btf_ext);
2820 		if (err) {
2821 			pr_warn("Error loading ELF section %s: %d. Ignored and continue.\n",
2822 				BTF_EXT_ELF_SEC, err);
2823 			obj->btf_ext = NULL;
2824 			goto out;
2825 		}
2826 
2827 		/* setup .BTF.ext to ELF section mapping */
2828 		ext_segs[0] = &obj->btf_ext->func_info;
2829 		ext_segs[1] = &obj->btf_ext->line_info;
2830 		ext_segs[2] = &obj->btf_ext->core_relo_info;
2831 		for (seg_num = 0; seg_num < ARRAY_SIZE(ext_segs); seg_num++) {
2832 			struct btf_ext_info *seg = ext_segs[seg_num];
2833 			const struct btf_ext_info_sec *sec;
2834 			const char *sec_name;
2835 			Elf_Scn *scn;
2836 
2837 			if (seg->sec_cnt == 0)
2838 				continue;
2839 
2840 			seg->sec_idxs = calloc(seg->sec_cnt, sizeof(*seg->sec_idxs));
2841 			if (!seg->sec_idxs) {
2842 				err = -ENOMEM;
2843 				goto out;
2844 			}
2845 
2846 			sec_num = 0;
2847 			for_each_btf_ext_sec(seg, sec) {
2848 				/* preventively increment index to avoid doing
2849 				 * this before every continue below
2850 				 */
2851 				sec_num++;
2852 
2853 				sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
2854 				if (str_is_empty(sec_name))
2855 					continue;
2856 				scn = elf_sec_by_name(obj, sec_name);
2857 				if (!scn)
2858 					continue;
2859 
2860 				seg->sec_idxs[sec_num - 1] = elf_ndxscn(scn);
2861 			}
2862 		}
2863 	}
2864 out:
2865 	if (err && libbpf_needs_btf(obj)) {
2866 		pr_warn("BTF is required, but is missing or corrupted.\n");
2867 		return err;
2868 	}
2869 	return 0;
2870 }
2871 
2872 static int compare_vsi_off(const void *_a, const void *_b)
2873 {
2874 	const struct btf_var_secinfo *a = _a;
2875 	const struct btf_var_secinfo *b = _b;
2876 
2877 	return a->offset - b->offset;
2878 }
2879 
2880 static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
2881 			     struct btf_type *t)
2882 {
2883 	__u32 size = 0, i, vars = btf_vlen(t);
2884 	const char *sec_name = btf__name_by_offset(btf, t->name_off);
2885 	struct btf_var_secinfo *vsi;
2886 	bool fixup_offsets = false;
2887 	int err;
2888 
2889 	if (!sec_name) {
2890 		pr_debug("No name found in string section for DATASEC kind.\n");
2891 		return -ENOENT;
2892 	}
2893 
2894 	/* Extern-backing datasecs (.ksyms, .kconfig) have their size and
2895 	 * variable offsets set at the previous step. Further, not every
2896 	 * extern BTF VAR has corresponding ELF symbol preserved, so we skip
2897 	 * all fixups altogether for such sections and go straight to sorting
2898 	 * VARs within their DATASEC.
2899 	 */
2900 	if (strcmp(sec_name, KCONFIG_SEC) == 0 || strcmp(sec_name, KSYMS_SEC) == 0)
2901 		goto sort_vars;
2902 
2903 	/* Clang leaves DATASEC size and VAR offsets as zeroes, so we need to
2904 	 * fix this up. But BPF static linker already fixes this up and fills
2905 	 * all the sizes and offsets during static linking. So this step has
2906 	 * to be optional. But the STV_HIDDEN handling is non-optional for any
2907 	 * non-extern DATASEC, so the variable fixup loop below handles both
2908 	 * functions at the same time, paying the cost of BTF VAR <-> ELF
2909 	 * symbol matching just once.
2910 	 */
2911 	if (t->size == 0) {
2912 		err = find_elf_sec_sz(obj, sec_name, &size);
2913 		if (err || !size) {
2914 			pr_debug("sec '%s': failed to determine size from ELF: size %u, err %d\n",
2915 				 sec_name, size, err);
2916 			return -ENOENT;
2917 		}
2918 
2919 		t->size = size;
2920 		fixup_offsets = true;
2921 	}
2922 
2923 	for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
2924 		const struct btf_type *t_var;
2925 		struct btf_var *var;
2926 		const char *var_name;
2927 		Elf64_Sym *sym;
2928 
2929 		t_var = btf__type_by_id(btf, vsi->type);
2930 		if (!t_var || !btf_is_var(t_var)) {
2931 			pr_debug("sec '%s': unexpected non-VAR type found\n", sec_name);
2932 			return -EINVAL;
2933 		}
2934 
2935 		var = btf_var(t_var);
2936 		if (var->linkage == BTF_VAR_STATIC || var->linkage == BTF_VAR_GLOBAL_EXTERN)
2937 			continue;
2938 
2939 		var_name = btf__name_by_offset(btf, t_var->name_off);
2940 		if (!var_name) {
2941 			pr_debug("sec '%s': failed to find name of DATASEC's member #%d\n",
2942 				 sec_name, i);
2943 			return -ENOENT;
2944 		}
2945 
2946 		sym = find_elf_var_sym(obj, var_name);
2947 		if (IS_ERR(sym)) {
2948 			pr_debug("sec '%s': failed to find ELF symbol for VAR '%s'\n",
2949 				 sec_name, var_name);
2950 			return -ENOENT;
2951 		}
2952 
2953 		if (fixup_offsets)
2954 			vsi->offset = sym->st_value;
2955 
2956 		/* if variable is a global/weak symbol, but has restricted
2957 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF VAR
2958 		 * as static. This follows similar logic for functions (BPF
2959 		 * subprogs) and influences libbpf's further decisions about
2960 		 * whether to make global data BPF array maps as
2961 		 * BPF_F_MMAPABLE.
2962 		 */
2963 		if (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
2964 		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL)
2965 			var->linkage = BTF_VAR_STATIC;
2966 	}
2967 
2968 sort_vars:
2969 	qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
2970 	return 0;
2971 }
2972 
2973 static int bpf_object_fixup_btf(struct bpf_object *obj)
2974 {
2975 	int i, n, err = 0;
2976 
2977 	if (!obj->btf)
2978 		return 0;
2979 
2980 	n = btf__type_cnt(obj->btf);
2981 	for (i = 1; i < n; i++) {
2982 		struct btf_type *t = btf_type_by_id(obj->btf, i);
2983 
2984 		/* Loader needs to fix up some of the things compiler
2985 		 * couldn't get its hands on while emitting BTF. This
2986 		 * is section size and global variable offset. We use
2987 		 * the info from the ELF itself for this purpose.
2988 		 */
2989 		if (btf_is_datasec(t)) {
2990 			err = btf_fixup_datasec(obj, obj->btf, t);
2991 			if (err)
2992 				return err;
2993 		}
2994 	}
2995 
2996 	return 0;
2997 }
2998 
2999 static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
3000 {
3001 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
3002 	    prog->type == BPF_PROG_TYPE_LSM)
3003 		return true;
3004 
3005 	/* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
3006 	 * also need vmlinux BTF
3007 	 */
3008 	if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
3009 		return true;
3010 
3011 	return false;
3012 }
3013 
3014 static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
3015 {
3016 	struct bpf_program *prog;
3017 	int i;
3018 
3019 	/* CO-RE relocations need kernel BTF, only when btf_custom_path
3020 	 * is not specified
3021 	 */
3022 	if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
3023 		return true;
3024 
3025 	/* Support for typed ksyms needs kernel BTF */
3026 	for (i = 0; i < obj->nr_extern; i++) {
3027 		const struct extern_desc *ext;
3028 
3029 		ext = &obj->externs[i];
3030 		if (ext->type == EXT_KSYM && ext->ksym.type_id)
3031 			return true;
3032 	}
3033 
3034 	bpf_object__for_each_program(prog, obj) {
3035 		if (!prog->autoload)
3036 			continue;
3037 		if (prog_needs_vmlinux_btf(prog))
3038 			return true;
3039 	}
3040 
3041 	return false;
3042 }
3043 
3044 static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
3045 {
3046 	int err;
3047 
3048 	/* btf_vmlinux could be loaded earlier */
3049 	if (obj->btf_vmlinux || obj->gen_loader)
3050 		return 0;
3051 
3052 	if (!force && !obj_needs_vmlinux_btf(obj))
3053 		return 0;
3054 
3055 	obj->btf_vmlinux = btf__load_vmlinux_btf();
3056 	err = libbpf_get_error(obj->btf_vmlinux);
3057 	if (err) {
3058 		pr_warn("Error loading vmlinux BTF: %d\n", err);
3059 		obj->btf_vmlinux = NULL;
3060 		return err;
3061 	}
3062 	return 0;
3063 }
3064 
3065 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
3066 {
3067 	struct btf *kern_btf = obj->btf;
3068 	bool btf_mandatory, sanitize;
3069 	int i, err = 0;
3070 
3071 	if (!obj->btf)
3072 		return 0;
3073 
3074 	if (!kernel_supports(obj, FEAT_BTF)) {
3075 		if (kernel_needs_btf(obj)) {
3076 			err = -EOPNOTSUPP;
3077 			goto report;
3078 		}
3079 		pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
3080 		return 0;
3081 	}
3082 
3083 	/* Even though some subprogs are global/weak, user might prefer more
3084 	 * permissive BPF verification process that BPF verifier performs for
3085 	 * static functions, taking into account more context from the caller
3086 	 * functions. In such case, they need to mark such subprogs with
3087 	 * __attribute__((visibility("hidden"))) and libbpf will adjust
3088 	 * corresponding FUNC BTF type to be marked as static and trigger more
3089 	 * involved BPF verification process.
3090 	 */
3091 	for (i = 0; i < obj->nr_programs; i++) {
3092 		struct bpf_program *prog = &obj->programs[i];
3093 		struct btf_type *t;
3094 		const char *name;
3095 		int j, n;
3096 
3097 		if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
3098 			continue;
3099 
3100 		n = btf__type_cnt(obj->btf);
3101 		for (j = 1; j < n; j++) {
3102 			t = btf_type_by_id(obj->btf, j);
3103 			if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
3104 				continue;
3105 
3106 			name = btf__str_by_offset(obj->btf, t->name_off);
3107 			if (strcmp(name, prog->name) != 0)
3108 				continue;
3109 
3110 			t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
3111 			break;
3112 		}
3113 	}
3114 
3115 	sanitize = btf_needs_sanitization(obj);
3116 	if (sanitize) {
3117 		const void *raw_data;
3118 		__u32 sz;
3119 
3120 		/* clone BTF to sanitize a copy and leave the original intact */
3121 		raw_data = btf__raw_data(obj->btf, &sz);
3122 		kern_btf = btf__new(raw_data, sz);
3123 		err = libbpf_get_error(kern_btf);
3124 		if (err)
3125 			return err;
3126 
3127 		/* enforce 8-byte pointers for BPF-targeted BTFs */
3128 		btf__set_pointer_size(obj->btf, 8);
3129 		err = bpf_object__sanitize_btf(obj, kern_btf);
3130 		if (err)
3131 			return err;
3132 	}
3133 
3134 	if (obj->gen_loader) {
3135 		__u32 raw_size = 0;
3136 		const void *raw_data = btf__raw_data(kern_btf, &raw_size);
3137 
3138 		if (!raw_data)
3139 			return -ENOMEM;
3140 		bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
3141 		/* Pretend to have valid FD to pass various fd >= 0 checks.
3142 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
3143 		 */
3144 		btf__set_fd(kern_btf, 0);
3145 	} else {
3146 		/* currently BPF_BTF_LOAD only supports log_level 1 */
3147 		err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
3148 					   obj->log_level ? 1 : 0);
3149 	}
3150 	if (sanitize) {
3151 		if (!err) {
3152 			/* move fd to libbpf's BTF */
3153 			btf__set_fd(obj->btf, btf__fd(kern_btf));
3154 			btf__set_fd(kern_btf, -1);
3155 		}
3156 		btf__free(kern_btf);
3157 	}
3158 report:
3159 	if (err) {
3160 		btf_mandatory = kernel_needs_btf(obj);
3161 		pr_warn("Error loading .BTF into kernel: %d. %s\n", err,
3162 			btf_mandatory ? "BTF is mandatory, can't proceed."
3163 				      : "BTF is optional, ignoring.");
3164 		if (!btf_mandatory)
3165 			err = 0;
3166 	}
3167 	return err;
3168 }
3169 
3170 static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
3171 {
3172 	const char *name;
3173 
3174 	name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
3175 	if (!name) {
3176 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3177 			off, obj->path, elf_errmsg(-1));
3178 		return NULL;
3179 	}
3180 
3181 	return name;
3182 }
3183 
3184 static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
3185 {
3186 	const char *name;
3187 
3188 	name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
3189 	if (!name) {
3190 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3191 			off, obj->path, elf_errmsg(-1));
3192 		return NULL;
3193 	}
3194 
3195 	return name;
3196 }
3197 
3198 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
3199 {
3200 	Elf_Scn *scn;
3201 
3202 	scn = elf_getscn(obj->efile.elf, idx);
3203 	if (!scn) {
3204 		pr_warn("elf: failed to get section(%zu) from %s: %s\n",
3205 			idx, obj->path, elf_errmsg(-1));
3206 		return NULL;
3207 	}
3208 	return scn;
3209 }
3210 
3211 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
3212 {
3213 	Elf_Scn *scn = NULL;
3214 	Elf *elf = obj->efile.elf;
3215 	const char *sec_name;
3216 
3217 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3218 		sec_name = elf_sec_name(obj, scn);
3219 		if (!sec_name)
3220 			return NULL;
3221 
3222 		if (strcmp(sec_name, name) != 0)
3223 			continue;
3224 
3225 		return scn;
3226 	}
3227 	return NULL;
3228 }
3229 
3230 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn)
3231 {
3232 	Elf64_Shdr *shdr;
3233 
3234 	if (!scn)
3235 		return NULL;
3236 
3237 	shdr = elf64_getshdr(scn);
3238 	if (!shdr) {
3239 		pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
3240 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3241 		return NULL;
3242 	}
3243 
3244 	return shdr;
3245 }
3246 
3247 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
3248 {
3249 	const char *name;
3250 	Elf64_Shdr *sh;
3251 
3252 	if (!scn)
3253 		return NULL;
3254 
3255 	sh = elf_sec_hdr(obj, scn);
3256 	if (!sh)
3257 		return NULL;
3258 
3259 	name = elf_sec_str(obj, sh->sh_name);
3260 	if (!name) {
3261 		pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
3262 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3263 		return NULL;
3264 	}
3265 
3266 	return name;
3267 }
3268 
3269 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
3270 {
3271 	Elf_Data *data;
3272 
3273 	if (!scn)
3274 		return NULL;
3275 
3276 	data = elf_getdata(scn, 0);
3277 	if (!data) {
3278 		pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
3279 			elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
3280 			obj->path, elf_errmsg(-1));
3281 		return NULL;
3282 	}
3283 
3284 	return data;
3285 }
3286 
3287 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx)
3288 {
3289 	if (idx >= obj->efile.symbols->d_size / sizeof(Elf64_Sym))
3290 		return NULL;
3291 
3292 	return (Elf64_Sym *)obj->efile.symbols->d_buf + idx;
3293 }
3294 
3295 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx)
3296 {
3297 	if (idx >= data->d_size / sizeof(Elf64_Rel))
3298 		return NULL;
3299 
3300 	return (Elf64_Rel *)data->d_buf + idx;
3301 }
3302 
3303 static bool is_sec_name_dwarf(const char *name)
3304 {
3305 	/* approximation, but the actual list is too long */
3306 	return str_has_pfx(name, ".debug_");
3307 }
3308 
3309 static bool ignore_elf_section(Elf64_Shdr *hdr, const char *name)
3310 {
3311 	/* no special handling of .strtab */
3312 	if (hdr->sh_type == SHT_STRTAB)
3313 		return true;
3314 
3315 	/* ignore .llvm_addrsig section as well */
3316 	if (hdr->sh_type == SHT_LLVM_ADDRSIG)
3317 		return true;
3318 
3319 	/* no subprograms will lead to an empty .text section, ignore it */
3320 	if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
3321 	    strcmp(name, ".text") == 0)
3322 		return true;
3323 
3324 	/* DWARF sections */
3325 	if (is_sec_name_dwarf(name))
3326 		return true;
3327 
3328 	if (str_has_pfx(name, ".rel")) {
3329 		name += sizeof(".rel") - 1;
3330 		/* DWARF section relocations */
3331 		if (is_sec_name_dwarf(name))
3332 			return true;
3333 
3334 		/* .BTF and .BTF.ext don't need relocations */
3335 		if (strcmp(name, BTF_ELF_SEC) == 0 ||
3336 		    strcmp(name, BTF_EXT_ELF_SEC) == 0)
3337 			return true;
3338 	}
3339 
3340 	return false;
3341 }
3342 
3343 static int cmp_progs(const void *_a, const void *_b)
3344 {
3345 	const struct bpf_program *a = _a;
3346 	const struct bpf_program *b = _b;
3347 
3348 	if (a->sec_idx != b->sec_idx)
3349 		return a->sec_idx < b->sec_idx ? -1 : 1;
3350 
3351 	/* sec_insn_off can't be the same within the section */
3352 	return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
3353 }
3354 
3355 static int bpf_object__elf_collect(struct bpf_object *obj)
3356 {
3357 	struct elf_sec_desc *sec_desc;
3358 	Elf *elf = obj->efile.elf;
3359 	Elf_Data *btf_ext_data = NULL;
3360 	Elf_Data *btf_data = NULL;
3361 	int idx = 0, err = 0;
3362 	const char *name;
3363 	Elf_Data *data;
3364 	Elf_Scn *scn;
3365 	Elf64_Shdr *sh;
3366 
3367 	/* ELF section indices are 0-based, but sec #0 is special "invalid"
3368 	 * section. Since section count retrieved by elf_getshdrnum() does
3369 	 * include sec #0, it is already the necessary size of an array to keep
3370 	 * all the sections.
3371 	 */
3372 	if (elf_getshdrnum(obj->efile.elf, &obj->efile.sec_cnt)) {
3373 		pr_warn("elf: failed to get the number of sections for %s: %s\n",
3374 			obj->path, elf_errmsg(-1));
3375 		return -LIBBPF_ERRNO__FORMAT;
3376 	}
3377 	obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs));
3378 	if (!obj->efile.secs)
3379 		return -ENOMEM;
3380 
3381 	/* a bunch of ELF parsing functionality depends on processing symbols,
3382 	 * so do the first pass and find the symbol table
3383 	 */
3384 	scn = NULL;
3385 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3386 		sh = elf_sec_hdr(obj, scn);
3387 		if (!sh)
3388 			return -LIBBPF_ERRNO__FORMAT;
3389 
3390 		if (sh->sh_type == SHT_SYMTAB) {
3391 			if (obj->efile.symbols) {
3392 				pr_warn("elf: multiple symbol tables in %s\n", obj->path);
3393 				return -LIBBPF_ERRNO__FORMAT;
3394 			}
3395 
3396 			data = elf_sec_data(obj, scn);
3397 			if (!data)
3398 				return -LIBBPF_ERRNO__FORMAT;
3399 
3400 			idx = elf_ndxscn(scn);
3401 
3402 			obj->efile.symbols = data;
3403 			obj->efile.symbols_shndx = idx;
3404 			obj->efile.strtabidx = sh->sh_link;
3405 		}
3406 	}
3407 
3408 	if (!obj->efile.symbols) {
3409 		pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
3410 			obj->path);
3411 		return -ENOENT;
3412 	}
3413 
3414 	scn = NULL;
3415 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3416 		idx = elf_ndxscn(scn);
3417 		sec_desc = &obj->efile.secs[idx];
3418 
3419 		sh = elf_sec_hdr(obj, scn);
3420 		if (!sh)
3421 			return -LIBBPF_ERRNO__FORMAT;
3422 
3423 		name = elf_sec_str(obj, sh->sh_name);
3424 		if (!name)
3425 			return -LIBBPF_ERRNO__FORMAT;
3426 
3427 		if (ignore_elf_section(sh, name))
3428 			continue;
3429 
3430 		data = elf_sec_data(obj, scn);
3431 		if (!data)
3432 			return -LIBBPF_ERRNO__FORMAT;
3433 
3434 		pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
3435 			 idx, name, (unsigned long)data->d_size,
3436 			 (int)sh->sh_link, (unsigned long)sh->sh_flags,
3437 			 (int)sh->sh_type);
3438 
3439 		if (strcmp(name, "license") == 0) {
3440 			err = bpf_object__init_license(obj, data->d_buf, data->d_size);
3441 			if (err)
3442 				return err;
3443 		} else if (strcmp(name, "version") == 0) {
3444 			err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
3445 			if (err)
3446 				return err;
3447 		} else if (strcmp(name, "maps") == 0) {
3448 			pr_warn("elf: legacy map definitions in 'maps' section are not supported by libbpf v1.0+\n");
3449 			return -ENOTSUP;
3450 		} else if (strcmp(name, MAPS_ELF_SEC) == 0) {
3451 			obj->efile.btf_maps_shndx = idx;
3452 		} else if (strcmp(name, BTF_ELF_SEC) == 0) {
3453 			if (sh->sh_type != SHT_PROGBITS)
3454 				return -LIBBPF_ERRNO__FORMAT;
3455 			btf_data = data;
3456 		} else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
3457 			if (sh->sh_type != SHT_PROGBITS)
3458 				return -LIBBPF_ERRNO__FORMAT;
3459 			btf_ext_data = data;
3460 		} else if (sh->sh_type == SHT_SYMTAB) {
3461 			/* already processed during the first pass above */
3462 		} else if (sh->sh_type == SHT_PROGBITS && data->d_size > 0) {
3463 			if (sh->sh_flags & SHF_EXECINSTR) {
3464 				if (strcmp(name, ".text") == 0)
3465 					obj->efile.text_shndx = idx;
3466 				err = bpf_object__add_programs(obj, data, name, idx);
3467 				if (err)
3468 					return err;
3469 			} else if (strcmp(name, DATA_SEC) == 0 ||
3470 				   str_has_pfx(name, DATA_SEC ".")) {
3471 				sec_desc->sec_type = SEC_DATA;
3472 				sec_desc->shdr = sh;
3473 				sec_desc->data = data;
3474 			} else if (strcmp(name, RODATA_SEC) == 0 ||
3475 				   str_has_pfx(name, RODATA_SEC ".")) {
3476 				sec_desc->sec_type = SEC_RODATA;
3477 				sec_desc->shdr = sh;
3478 				sec_desc->data = data;
3479 			} else if (strcmp(name, STRUCT_OPS_SEC) == 0) {
3480 				obj->efile.st_ops_data = data;
3481 				obj->efile.st_ops_shndx = idx;
3482 			} else if (strcmp(name, STRUCT_OPS_LINK_SEC) == 0) {
3483 				obj->efile.st_ops_link_data = data;
3484 				obj->efile.st_ops_link_shndx = idx;
3485 			} else {
3486 				pr_info("elf: skipping unrecognized data section(%d) %s\n",
3487 					idx, name);
3488 			}
3489 		} else if (sh->sh_type == SHT_REL) {
3490 			int targ_sec_idx = sh->sh_info; /* points to other section */
3491 
3492 			if (sh->sh_entsize != sizeof(Elf64_Rel) ||
3493 			    targ_sec_idx >= obj->efile.sec_cnt)
3494 				return -LIBBPF_ERRNO__FORMAT;
3495 
3496 			/* Only do relo for section with exec instructions */
3497 			if (!section_have_execinstr(obj, targ_sec_idx) &&
3498 			    strcmp(name, ".rel" STRUCT_OPS_SEC) &&
3499 			    strcmp(name, ".rel" STRUCT_OPS_LINK_SEC) &&
3500 			    strcmp(name, ".rel" MAPS_ELF_SEC)) {
3501 				pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
3502 					idx, name, targ_sec_idx,
3503 					elf_sec_name(obj, elf_sec_by_idx(obj, targ_sec_idx)) ?: "<?>");
3504 				continue;
3505 			}
3506 
3507 			sec_desc->sec_type = SEC_RELO;
3508 			sec_desc->shdr = sh;
3509 			sec_desc->data = data;
3510 		} else if (sh->sh_type == SHT_NOBITS && (strcmp(name, BSS_SEC) == 0 ||
3511 							 str_has_pfx(name, BSS_SEC "."))) {
3512 			sec_desc->sec_type = SEC_BSS;
3513 			sec_desc->shdr = sh;
3514 			sec_desc->data = data;
3515 		} else {
3516 			pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
3517 				(size_t)sh->sh_size);
3518 		}
3519 	}
3520 
3521 	if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
3522 		pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
3523 		return -LIBBPF_ERRNO__FORMAT;
3524 	}
3525 
3526 	/* sort BPF programs by section name and in-section instruction offset
3527 	 * for faster search
3528 	 */
3529 	if (obj->nr_programs)
3530 		qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
3531 
3532 	return bpf_object__init_btf(obj, btf_data, btf_ext_data);
3533 }
3534 
3535 static bool sym_is_extern(const Elf64_Sym *sym)
3536 {
3537 	int bind = ELF64_ST_BIND(sym->st_info);
3538 	/* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
3539 	return sym->st_shndx == SHN_UNDEF &&
3540 	       (bind == STB_GLOBAL || bind == STB_WEAK) &&
3541 	       ELF64_ST_TYPE(sym->st_info) == STT_NOTYPE;
3542 }
3543 
3544 static bool sym_is_subprog(const Elf64_Sym *sym, int text_shndx)
3545 {
3546 	int bind = ELF64_ST_BIND(sym->st_info);
3547 	int type = ELF64_ST_TYPE(sym->st_info);
3548 
3549 	/* in .text section */
3550 	if (sym->st_shndx != text_shndx)
3551 		return false;
3552 
3553 	/* local function */
3554 	if (bind == STB_LOCAL && type == STT_SECTION)
3555 		return true;
3556 
3557 	/* global function */
3558 	return bind == STB_GLOBAL && type == STT_FUNC;
3559 }
3560 
3561 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
3562 {
3563 	const struct btf_type *t;
3564 	const char *tname;
3565 	int i, n;
3566 
3567 	if (!btf)
3568 		return -ESRCH;
3569 
3570 	n = btf__type_cnt(btf);
3571 	for (i = 1; i < n; i++) {
3572 		t = btf__type_by_id(btf, i);
3573 
3574 		if (!btf_is_var(t) && !btf_is_func(t))
3575 			continue;
3576 
3577 		tname = btf__name_by_offset(btf, t->name_off);
3578 		if (strcmp(tname, ext_name))
3579 			continue;
3580 
3581 		if (btf_is_var(t) &&
3582 		    btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
3583 			return -EINVAL;
3584 
3585 		if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
3586 			return -EINVAL;
3587 
3588 		return i;
3589 	}
3590 
3591 	return -ENOENT;
3592 }
3593 
3594 static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
3595 	const struct btf_var_secinfo *vs;
3596 	const struct btf_type *t;
3597 	int i, j, n;
3598 
3599 	if (!btf)
3600 		return -ESRCH;
3601 
3602 	n = btf__type_cnt(btf);
3603 	for (i = 1; i < n; i++) {
3604 		t = btf__type_by_id(btf, i);
3605 
3606 		if (!btf_is_datasec(t))
3607 			continue;
3608 
3609 		vs = btf_var_secinfos(t);
3610 		for (j = 0; j < btf_vlen(t); j++, vs++) {
3611 			if (vs->type == ext_btf_id)
3612 				return i;
3613 		}
3614 	}
3615 
3616 	return -ENOENT;
3617 }
3618 
3619 static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
3620 				     bool *is_signed)
3621 {
3622 	const struct btf_type *t;
3623 	const char *name;
3624 
3625 	t = skip_mods_and_typedefs(btf, id, NULL);
3626 	name = btf__name_by_offset(btf, t->name_off);
3627 
3628 	if (is_signed)
3629 		*is_signed = false;
3630 	switch (btf_kind(t)) {
3631 	case BTF_KIND_INT: {
3632 		int enc = btf_int_encoding(t);
3633 
3634 		if (enc & BTF_INT_BOOL)
3635 			return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
3636 		if (is_signed)
3637 			*is_signed = enc & BTF_INT_SIGNED;
3638 		if (t->size == 1)
3639 			return KCFG_CHAR;
3640 		if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
3641 			return KCFG_UNKNOWN;
3642 		return KCFG_INT;
3643 	}
3644 	case BTF_KIND_ENUM:
3645 		if (t->size != 4)
3646 			return KCFG_UNKNOWN;
3647 		if (strcmp(name, "libbpf_tristate"))
3648 			return KCFG_UNKNOWN;
3649 		return KCFG_TRISTATE;
3650 	case BTF_KIND_ENUM64:
3651 		if (strcmp(name, "libbpf_tristate"))
3652 			return KCFG_UNKNOWN;
3653 		return KCFG_TRISTATE;
3654 	case BTF_KIND_ARRAY:
3655 		if (btf_array(t)->nelems == 0)
3656 			return KCFG_UNKNOWN;
3657 		if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
3658 			return KCFG_UNKNOWN;
3659 		return KCFG_CHAR_ARR;
3660 	default:
3661 		return KCFG_UNKNOWN;
3662 	}
3663 }
3664 
3665 static int cmp_externs(const void *_a, const void *_b)
3666 {
3667 	const struct extern_desc *a = _a;
3668 	const struct extern_desc *b = _b;
3669 
3670 	if (a->type != b->type)
3671 		return a->type < b->type ? -1 : 1;
3672 
3673 	if (a->type == EXT_KCFG) {
3674 		/* descending order by alignment requirements */
3675 		if (a->kcfg.align != b->kcfg.align)
3676 			return a->kcfg.align > b->kcfg.align ? -1 : 1;
3677 		/* ascending order by size, within same alignment class */
3678 		if (a->kcfg.sz != b->kcfg.sz)
3679 			return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
3680 	}
3681 
3682 	/* resolve ties by name */
3683 	return strcmp(a->name, b->name);
3684 }
3685 
3686 static int find_int_btf_id(const struct btf *btf)
3687 {
3688 	const struct btf_type *t;
3689 	int i, n;
3690 
3691 	n = btf__type_cnt(btf);
3692 	for (i = 1; i < n; i++) {
3693 		t = btf__type_by_id(btf, i);
3694 
3695 		if (btf_is_int(t) && btf_int_bits(t) == 32)
3696 			return i;
3697 	}
3698 
3699 	return 0;
3700 }
3701 
3702 static int add_dummy_ksym_var(struct btf *btf)
3703 {
3704 	int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
3705 	const struct btf_var_secinfo *vs;
3706 	const struct btf_type *sec;
3707 
3708 	if (!btf)
3709 		return 0;
3710 
3711 	sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
3712 					    BTF_KIND_DATASEC);
3713 	if (sec_btf_id < 0)
3714 		return 0;
3715 
3716 	sec = btf__type_by_id(btf, sec_btf_id);
3717 	vs = btf_var_secinfos(sec);
3718 	for (i = 0; i < btf_vlen(sec); i++, vs++) {
3719 		const struct btf_type *vt;
3720 
3721 		vt = btf__type_by_id(btf, vs->type);
3722 		if (btf_is_func(vt))
3723 			break;
3724 	}
3725 
3726 	/* No func in ksyms sec.  No need to add dummy var. */
3727 	if (i == btf_vlen(sec))
3728 		return 0;
3729 
3730 	int_btf_id = find_int_btf_id(btf);
3731 	dummy_var_btf_id = btf__add_var(btf,
3732 					"dummy_ksym",
3733 					BTF_VAR_GLOBAL_ALLOCATED,
3734 					int_btf_id);
3735 	if (dummy_var_btf_id < 0)
3736 		pr_warn("cannot create a dummy_ksym var\n");
3737 
3738 	return dummy_var_btf_id;
3739 }
3740 
3741 static int bpf_object__collect_externs(struct bpf_object *obj)
3742 {
3743 	struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
3744 	const struct btf_type *t;
3745 	struct extern_desc *ext;
3746 	int i, n, off, dummy_var_btf_id;
3747 	const char *ext_name, *sec_name;
3748 	Elf_Scn *scn;
3749 	Elf64_Shdr *sh;
3750 
3751 	if (!obj->efile.symbols)
3752 		return 0;
3753 
3754 	scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
3755 	sh = elf_sec_hdr(obj, scn);
3756 	if (!sh || sh->sh_entsize != sizeof(Elf64_Sym))
3757 		return -LIBBPF_ERRNO__FORMAT;
3758 
3759 	dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
3760 	if (dummy_var_btf_id < 0)
3761 		return dummy_var_btf_id;
3762 
3763 	n = sh->sh_size / sh->sh_entsize;
3764 	pr_debug("looking for externs among %d symbols...\n", n);
3765 
3766 	for (i = 0; i < n; i++) {
3767 		Elf64_Sym *sym = elf_sym_by_idx(obj, i);
3768 
3769 		if (!sym)
3770 			return -LIBBPF_ERRNO__FORMAT;
3771 		if (!sym_is_extern(sym))
3772 			continue;
3773 		ext_name = elf_sym_str(obj, sym->st_name);
3774 		if (!ext_name || !ext_name[0])
3775 			continue;
3776 
3777 		ext = obj->externs;
3778 		ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
3779 		if (!ext)
3780 			return -ENOMEM;
3781 		obj->externs = ext;
3782 		ext = &ext[obj->nr_extern];
3783 		memset(ext, 0, sizeof(*ext));
3784 		obj->nr_extern++;
3785 
3786 		ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
3787 		if (ext->btf_id <= 0) {
3788 			pr_warn("failed to find BTF for extern '%s': %d\n",
3789 				ext_name, ext->btf_id);
3790 			return ext->btf_id;
3791 		}
3792 		t = btf__type_by_id(obj->btf, ext->btf_id);
3793 		ext->name = btf__name_by_offset(obj->btf, t->name_off);
3794 		ext->sym_idx = i;
3795 		ext->is_weak = ELF64_ST_BIND(sym->st_info) == STB_WEAK;
3796 
3797 		ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
3798 		if (ext->sec_btf_id <= 0) {
3799 			pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
3800 				ext_name, ext->btf_id, ext->sec_btf_id);
3801 			return ext->sec_btf_id;
3802 		}
3803 		sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
3804 		sec_name = btf__name_by_offset(obj->btf, sec->name_off);
3805 
3806 		if (strcmp(sec_name, KCONFIG_SEC) == 0) {
3807 			if (btf_is_func(t)) {
3808 				pr_warn("extern function %s is unsupported under %s section\n",
3809 					ext->name, KCONFIG_SEC);
3810 				return -ENOTSUP;
3811 			}
3812 			kcfg_sec = sec;
3813 			ext->type = EXT_KCFG;
3814 			ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
3815 			if (ext->kcfg.sz <= 0) {
3816 				pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
3817 					ext_name, ext->kcfg.sz);
3818 				return ext->kcfg.sz;
3819 			}
3820 			ext->kcfg.align = btf__align_of(obj->btf, t->type);
3821 			if (ext->kcfg.align <= 0) {
3822 				pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
3823 					ext_name, ext->kcfg.align);
3824 				return -EINVAL;
3825 			}
3826 			ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
3827 							&ext->kcfg.is_signed);
3828 			if (ext->kcfg.type == KCFG_UNKNOWN) {
3829 				pr_warn("extern (kcfg) '%s': type is unsupported\n", ext_name);
3830 				return -ENOTSUP;
3831 			}
3832 		} else if (strcmp(sec_name, KSYMS_SEC) == 0) {
3833 			ksym_sec = sec;
3834 			ext->type = EXT_KSYM;
3835 			skip_mods_and_typedefs(obj->btf, t->type,
3836 					       &ext->ksym.type_id);
3837 		} else {
3838 			pr_warn("unrecognized extern section '%s'\n", sec_name);
3839 			return -ENOTSUP;
3840 		}
3841 	}
3842 	pr_debug("collected %d externs total\n", obj->nr_extern);
3843 
3844 	if (!obj->nr_extern)
3845 		return 0;
3846 
3847 	/* sort externs by type, for kcfg ones also by (align, size, name) */
3848 	qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
3849 
3850 	/* for .ksyms section, we need to turn all externs into allocated
3851 	 * variables in BTF to pass kernel verification; we do this by
3852 	 * pretending that each extern is a 8-byte variable
3853 	 */
3854 	if (ksym_sec) {
3855 		/* find existing 4-byte integer type in BTF to use for fake
3856 		 * extern variables in DATASEC
3857 		 */
3858 		int int_btf_id = find_int_btf_id(obj->btf);
3859 		/* For extern function, a dummy_var added earlier
3860 		 * will be used to replace the vs->type and
3861 		 * its name string will be used to refill
3862 		 * the missing param's name.
3863 		 */
3864 		const struct btf_type *dummy_var;
3865 
3866 		dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
3867 		for (i = 0; i < obj->nr_extern; i++) {
3868 			ext = &obj->externs[i];
3869 			if (ext->type != EXT_KSYM)
3870 				continue;
3871 			pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
3872 				 i, ext->sym_idx, ext->name);
3873 		}
3874 
3875 		sec = ksym_sec;
3876 		n = btf_vlen(sec);
3877 		for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
3878 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3879 			struct btf_type *vt;
3880 
3881 			vt = (void *)btf__type_by_id(obj->btf, vs->type);
3882 			ext_name = btf__name_by_offset(obj->btf, vt->name_off);
3883 			ext = find_extern_by_name(obj, ext_name);
3884 			if (!ext) {
3885 				pr_warn("failed to find extern definition for BTF %s '%s'\n",
3886 					btf_kind_str(vt), ext_name);
3887 				return -ESRCH;
3888 			}
3889 			if (btf_is_func(vt)) {
3890 				const struct btf_type *func_proto;
3891 				struct btf_param *param;
3892 				int j;
3893 
3894 				func_proto = btf__type_by_id(obj->btf,
3895 							     vt->type);
3896 				param = btf_params(func_proto);
3897 				/* Reuse the dummy_var string if the
3898 				 * func proto does not have param name.
3899 				 */
3900 				for (j = 0; j < btf_vlen(func_proto); j++)
3901 					if (param[j].type && !param[j].name_off)
3902 						param[j].name_off =
3903 							dummy_var->name_off;
3904 				vs->type = dummy_var_btf_id;
3905 				vt->info &= ~0xffff;
3906 				vt->info |= BTF_FUNC_GLOBAL;
3907 			} else {
3908 				btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3909 				vt->type = int_btf_id;
3910 			}
3911 			vs->offset = off;
3912 			vs->size = sizeof(int);
3913 		}
3914 		sec->size = off;
3915 	}
3916 
3917 	if (kcfg_sec) {
3918 		sec = kcfg_sec;
3919 		/* for kcfg externs calculate their offsets within a .kconfig map */
3920 		off = 0;
3921 		for (i = 0; i < obj->nr_extern; i++) {
3922 			ext = &obj->externs[i];
3923 			if (ext->type != EXT_KCFG)
3924 				continue;
3925 
3926 			ext->kcfg.data_off = roundup(off, ext->kcfg.align);
3927 			off = ext->kcfg.data_off + ext->kcfg.sz;
3928 			pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
3929 				 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
3930 		}
3931 		sec->size = off;
3932 		n = btf_vlen(sec);
3933 		for (i = 0; i < n; i++) {
3934 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3935 
3936 			t = btf__type_by_id(obj->btf, vs->type);
3937 			ext_name = btf__name_by_offset(obj->btf, t->name_off);
3938 			ext = find_extern_by_name(obj, ext_name);
3939 			if (!ext) {
3940 				pr_warn("failed to find extern definition for BTF var '%s'\n",
3941 					ext_name);
3942 				return -ESRCH;
3943 			}
3944 			btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3945 			vs->offset = ext->kcfg.data_off;
3946 		}
3947 	}
3948 	return 0;
3949 }
3950 
3951 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog)
3952 {
3953 	return prog->sec_idx == obj->efile.text_shndx && obj->nr_programs > 1;
3954 }
3955 
3956 struct bpf_program *
3957 bpf_object__find_program_by_name(const struct bpf_object *obj,
3958 				 const char *name)
3959 {
3960 	struct bpf_program *prog;
3961 
3962 	bpf_object__for_each_program(prog, obj) {
3963 		if (prog_is_subprog(obj, prog))
3964 			continue;
3965 		if (!strcmp(prog->name, name))
3966 			return prog;
3967 	}
3968 	return errno = ENOENT, NULL;
3969 }
3970 
3971 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
3972 				      int shndx)
3973 {
3974 	switch (obj->efile.secs[shndx].sec_type) {
3975 	case SEC_BSS:
3976 	case SEC_DATA:
3977 	case SEC_RODATA:
3978 		return true;
3979 	default:
3980 		return false;
3981 	}
3982 }
3983 
3984 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
3985 				      int shndx)
3986 {
3987 	return shndx == obj->efile.btf_maps_shndx;
3988 }
3989 
3990 static enum libbpf_map_type
3991 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
3992 {
3993 	if (shndx == obj->efile.symbols_shndx)
3994 		return LIBBPF_MAP_KCONFIG;
3995 
3996 	switch (obj->efile.secs[shndx].sec_type) {
3997 	case SEC_BSS:
3998 		return LIBBPF_MAP_BSS;
3999 	case SEC_DATA:
4000 		return LIBBPF_MAP_DATA;
4001 	case SEC_RODATA:
4002 		return LIBBPF_MAP_RODATA;
4003 	default:
4004 		return LIBBPF_MAP_UNSPEC;
4005 	}
4006 }
4007 
4008 static int bpf_program__record_reloc(struct bpf_program *prog,
4009 				     struct reloc_desc *reloc_desc,
4010 				     __u32 insn_idx, const char *sym_name,
4011 				     const Elf64_Sym *sym, const Elf64_Rel *rel)
4012 {
4013 	struct bpf_insn *insn = &prog->insns[insn_idx];
4014 	size_t map_idx, nr_maps = prog->obj->nr_maps;
4015 	struct bpf_object *obj = prog->obj;
4016 	__u32 shdr_idx = sym->st_shndx;
4017 	enum libbpf_map_type type;
4018 	const char *sym_sec_name;
4019 	struct bpf_map *map;
4020 
4021 	if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
4022 		pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n",
4023 			prog->name, sym_name, insn_idx, insn->code);
4024 		return -LIBBPF_ERRNO__RELOC;
4025 	}
4026 
4027 	if (sym_is_extern(sym)) {
4028 		int sym_idx = ELF64_R_SYM(rel->r_info);
4029 		int i, n = obj->nr_extern;
4030 		struct extern_desc *ext;
4031 
4032 		for (i = 0; i < n; i++) {
4033 			ext = &obj->externs[i];
4034 			if (ext->sym_idx == sym_idx)
4035 				break;
4036 		}
4037 		if (i >= n) {
4038 			pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
4039 				prog->name, sym_name, sym_idx);
4040 			return -LIBBPF_ERRNO__RELOC;
4041 		}
4042 		pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
4043 			 prog->name, i, ext->name, ext->sym_idx, insn_idx);
4044 		if (insn->code == (BPF_JMP | BPF_CALL))
4045 			reloc_desc->type = RELO_EXTERN_CALL;
4046 		else
4047 			reloc_desc->type = RELO_EXTERN_LD64;
4048 		reloc_desc->insn_idx = insn_idx;
4049 		reloc_desc->ext_idx = i;
4050 		return 0;
4051 	}
4052 
4053 	/* sub-program call relocation */
4054 	if (is_call_insn(insn)) {
4055 		if (insn->src_reg != BPF_PSEUDO_CALL) {
4056 			pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
4057 			return -LIBBPF_ERRNO__RELOC;
4058 		}
4059 		/* text_shndx can be 0, if no default "main" program exists */
4060 		if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
4061 			sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4062 			pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
4063 				prog->name, sym_name, sym_sec_name);
4064 			return -LIBBPF_ERRNO__RELOC;
4065 		}
4066 		if (sym->st_value % BPF_INSN_SZ) {
4067 			pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
4068 				prog->name, sym_name, (size_t)sym->st_value);
4069 			return -LIBBPF_ERRNO__RELOC;
4070 		}
4071 		reloc_desc->type = RELO_CALL;
4072 		reloc_desc->insn_idx = insn_idx;
4073 		reloc_desc->sym_off = sym->st_value;
4074 		return 0;
4075 	}
4076 
4077 	if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
4078 		pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
4079 			prog->name, sym_name, shdr_idx);
4080 		return -LIBBPF_ERRNO__RELOC;
4081 	}
4082 
4083 	/* loading subprog addresses */
4084 	if (sym_is_subprog(sym, obj->efile.text_shndx)) {
4085 		/* global_func: sym->st_value = offset in the section, insn->imm = 0.
4086 		 * local_func: sym->st_value = 0, insn->imm = offset in the section.
4087 		 */
4088 		if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
4089 			pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
4090 				prog->name, sym_name, (size_t)sym->st_value, insn->imm);
4091 			return -LIBBPF_ERRNO__RELOC;
4092 		}
4093 
4094 		reloc_desc->type = RELO_SUBPROG_ADDR;
4095 		reloc_desc->insn_idx = insn_idx;
4096 		reloc_desc->sym_off = sym->st_value;
4097 		return 0;
4098 	}
4099 
4100 	type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
4101 	sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4102 
4103 	/* generic map reference relocation */
4104 	if (type == LIBBPF_MAP_UNSPEC) {
4105 		if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
4106 			pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
4107 				prog->name, sym_name, sym_sec_name);
4108 			return -LIBBPF_ERRNO__RELOC;
4109 		}
4110 		for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4111 			map = &obj->maps[map_idx];
4112 			if (map->libbpf_type != type ||
4113 			    map->sec_idx != sym->st_shndx ||
4114 			    map->sec_offset != sym->st_value)
4115 				continue;
4116 			pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n",
4117 				 prog->name, map_idx, map->name, map->sec_idx,
4118 				 map->sec_offset, insn_idx);
4119 			break;
4120 		}
4121 		if (map_idx >= nr_maps) {
4122 			pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
4123 				prog->name, sym_sec_name, (size_t)sym->st_value);
4124 			return -LIBBPF_ERRNO__RELOC;
4125 		}
4126 		reloc_desc->type = RELO_LD64;
4127 		reloc_desc->insn_idx = insn_idx;
4128 		reloc_desc->map_idx = map_idx;
4129 		reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
4130 		return 0;
4131 	}
4132 
4133 	/* global data map relocation */
4134 	if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
4135 		pr_warn("prog '%s': bad data relo against section '%s'\n",
4136 			prog->name, sym_sec_name);
4137 		return -LIBBPF_ERRNO__RELOC;
4138 	}
4139 	for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4140 		map = &obj->maps[map_idx];
4141 		if (map->libbpf_type != type || map->sec_idx != sym->st_shndx)
4142 			continue;
4143 		pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n",
4144 			 prog->name, map_idx, map->name, map->sec_idx,
4145 			 map->sec_offset, insn_idx);
4146 		break;
4147 	}
4148 	if (map_idx >= nr_maps) {
4149 		pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
4150 			prog->name, sym_sec_name);
4151 		return -LIBBPF_ERRNO__RELOC;
4152 	}
4153 
4154 	reloc_desc->type = RELO_DATA;
4155 	reloc_desc->insn_idx = insn_idx;
4156 	reloc_desc->map_idx = map_idx;
4157 	reloc_desc->sym_off = sym->st_value;
4158 	return 0;
4159 }
4160 
4161 static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
4162 {
4163 	return insn_idx >= prog->sec_insn_off &&
4164 	       insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
4165 }
4166 
4167 static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
4168 						 size_t sec_idx, size_t insn_idx)
4169 {
4170 	int l = 0, r = obj->nr_programs - 1, m;
4171 	struct bpf_program *prog;
4172 
4173 	if (!obj->nr_programs)
4174 		return NULL;
4175 
4176 	while (l < r) {
4177 		m = l + (r - l + 1) / 2;
4178 		prog = &obj->programs[m];
4179 
4180 		if (prog->sec_idx < sec_idx ||
4181 		    (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
4182 			l = m;
4183 		else
4184 			r = m - 1;
4185 	}
4186 	/* matching program could be at index l, but it still might be the
4187 	 * wrong one, so we need to double check conditions for the last time
4188 	 */
4189 	prog = &obj->programs[l];
4190 	if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
4191 		return prog;
4192 	return NULL;
4193 }
4194 
4195 static int
4196 bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
4197 {
4198 	const char *relo_sec_name, *sec_name;
4199 	size_t sec_idx = shdr->sh_info, sym_idx;
4200 	struct bpf_program *prog;
4201 	struct reloc_desc *relos;
4202 	int err, i, nrels;
4203 	const char *sym_name;
4204 	__u32 insn_idx;
4205 	Elf_Scn *scn;
4206 	Elf_Data *scn_data;
4207 	Elf64_Sym *sym;
4208 	Elf64_Rel *rel;
4209 
4210 	if (sec_idx >= obj->efile.sec_cnt)
4211 		return -EINVAL;
4212 
4213 	scn = elf_sec_by_idx(obj, sec_idx);
4214 	scn_data = elf_sec_data(obj, scn);
4215 
4216 	relo_sec_name = elf_sec_str(obj, shdr->sh_name);
4217 	sec_name = elf_sec_name(obj, scn);
4218 	if (!relo_sec_name || !sec_name)
4219 		return -EINVAL;
4220 
4221 	pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
4222 		 relo_sec_name, sec_idx, sec_name);
4223 	nrels = shdr->sh_size / shdr->sh_entsize;
4224 
4225 	for (i = 0; i < nrels; i++) {
4226 		rel = elf_rel_by_idx(data, i);
4227 		if (!rel) {
4228 			pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
4229 			return -LIBBPF_ERRNO__FORMAT;
4230 		}
4231 
4232 		sym_idx = ELF64_R_SYM(rel->r_info);
4233 		sym = elf_sym_by_idx(obj, sym_idx);
4234 		if (!sym) {
4235 			pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
4236 				relo_sec_name, sym_idx, i);
4237 			return -LIBBPF_ERRNO__FORMAT;
4238 		}
4239 
4240 		if (sym->st_shndx >= obj->efile.sec_cnt) {
4241 			pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
4242 				relo_sec_name, sym_idx, (size_t)sym->st_shndx, i);
4243 			return -LIBBPF_ERRNO__FORMAT;
4244 		}
4245 
4246 		if (rel->r_offset % BPF_INSN_SZ || rel->r_offset >= scn_data->d_size) {
4247 			pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
4248 				relo_sec_name, (size_t)rel->r_offset, i);
4249 			return -LIBBPF_ERRNO__FORMAT;
4250 		}
4251 
4252 		insn_idx = rel->r_offset / BPF_INSN_SZ;
4253 		/* relocations against static functions are recorded as
4254 		 * relocations against the section that contains a function;
4255 		 * in such case, symbol will be STT_SECTION and sym.st_name
4256 		 * will point to empty string (0), so fetch section name
4257 		 * instead
4258 		 */
4259 		if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
4260 			sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx));
4261 		else
4262 			sym_name = elf_sym_str(obj, sym->st_name);
4263 		sym_name = sym_name ?: "<?";
4264 
4265 		pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
4266 			 relo_sec_name, i, insn_idx, sym_name);
4267 
4268 		prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
4269 		if (!prog) {
4270 			pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
4271 				relo_sec_name, i, sec_name, insn_idx);
4272 			continue;
4273 		}
4274 
4275 		relos = libbpf_reallocarray(prog->reloc_desc,
4276 					    prog->nr_reloc + 1, sizeof(*relos));
4277 		if (!relos)
4278 			return -ENOMEM;
4279 		prog->reloc_desc = relos;
4280 
4281 		/* adjust insn_idx to local BPF program frame of reference */
4282 		insn_idx -= prog->sec_insn_off;
4283 		err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
4284 						insn_idx, sym_name, sym, rel);
4285 		if (err)
4286 			return err;
4287 
4288 		prog->nr_reloc++;
4289 	}
4290 	return 0;
4291 }
4292 
4293 static int map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map)
4294 {
4295 	int id;
4296 
4297 	if (!obj->btf)
4298 		return -ENOENT;
4299 
4300 	/* if it's BTF-defined map, we don't need to search for type IDs.
4301 	 * For struct_ops map, it does not need btf_key_type_id and
4302 	 * btf_value_type_id.
4303 	 */
4304 	if (map->sec_idx == obj->efile.btf_maps_shndx || bpf_map__is_struct_ops(map))
4305 		return 0;
4306 
4307 	/*
4308 	 * LLVM annotates global data differently in BTF, that is,
4309 	 * only as '.data', '.bss' or '.rodata'.
4310 	 */
4311 	if (!bpf_map__is_internal(map))
4312 		return -ENOENT;
4313 
4314 	id = btf__find_by_name(obj->btf, map->real_name);
4315 	if (id < 0)
4316 		return id;
4317 
4318 	map->btf_key_type_id = 0;
4319 	map->btf_value_type_id = id;
4320 	return 0;
4321 }
4322 
4323 static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
4324 {
4325 	char file[PATH_MAX], buff[4096];
4326 	FILE *fp;
4327 	__u32 val;
4328 	int err;
4329 
4330 	snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
4331 	memset(info, 0, sizeof(*info));
4332 
4333 	fp = fopen(file, "r");
4334 	if (!fp) {
4335 		err = -errno;
4336 		pr_warn("failed to open %s: %d. No procfs support?\n", file,
4337 			err);
4338 		return err;
4339 	}
4340 
4341 	while (fgets(buff, sizeof(buff), fp)) {
4342 		if (sscanf(buff, "map_type:\t%u", &val) == 1)
4343 			info->type = val;
4344 		else if (sscanf(buff, "key_size:\t%u", &val) == 1)
4345 			info->key_size = val;
4346 		else if (sscanf(buff, "value_size:\t%u", &val) == 1)
4347 			info->value_size = val;
4348 		else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
4349 			info->max_entries = val;
4350 		else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
4351 			info->map_flags = val;
4352 	}
4353 
4354 	fclose(fp);
4355 
4356 	return 0;
4357 }
4358 
4359 bool bpf_map__autocreate(const struct bpf_map *map)
4360 {
4361 	return map->autocreate;
4362 }
4363 
4364 int bpf_map__set_autocreate(struct bpf_map *map, bool autocreate)
4365 {
4366 	if (map->obj->loaded)
4367 		return libbpf_err(-EBUSY);
4368 
4369 	map->autocreate = autocreate;
4370 	return 0;
4371 }
4372 
4373 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
4374 {
4375 	struct bpf_map_info info;
4376 	__u32 len = sizeof(info), name_len;
4377 	int new_fd, err;
4378 	char *new_name;
4379 
4380 	memset(&info, 0, len);
4381 	err = bpf_map_get_info_by_fd(fd, &info, &len);
4382 	if (err && errno == EINVAL)
4383 		err = bpf_get_map_info_from_fdinfo(fd, &info);
4384 	if (err)
4385 		return libbpf_err(err);
4386 
4387 	name_len = strlen(info.name);
4388 	if (name_len == BPF_OBJ_NAME_LEN - 1 && strncmp(map->name, info.name, name_len) == 0)
4389 		new_name = strdup(map->name);
4390 	else
4391 		new_name = strdup(info.name);
4392 
4393 	if (!new_name)
4394 		return libbpf_err(-errno);
4395 
4396 	new_fd = open("/", O_RDONLY | O_CLOEXEC);
4397 	if (new_fd < 0) {
4398 		err = -errno;
4399 		goto err_free_new_name;
4400 	}
4401 
4402 	new_fd = dup3(fd, new_fd, O_CLOEXEC);
4403 	if (new_fd < 0) {
4404 		err = -errno;
4405 		goto err_close_new_fd;
4406 	}
4407 
4408 	err = zclose(map->fd);
4409 	if (err) {
4410 		err = -errno;
4411 		goto err_close_new_fd;
4412 	}
4413 	free(map->name);
4414 
4415 	map->fd = new_fd;
4416 	map->name = new_name;
4417 	map->def.type = info.type;
4418 	map->def.key_size = info.key_size;
4419 	map->def.value_size = info.value_size;
4420 	map->def.max_entries = info.max_entries;
4421 	map->def.map_flags = info.map_flags;
4422 	map->btf_key_type_id = info.btf_key_type_id;
4423 	map->btf_value_type_id = info.btf_value_type_id;
4424 	map->reused = true;
4425 	map->map_extra = info.map_extra;
4426 
4427 	return 0;
4428 
4429 err_close_new_fd:
4430 	close(new_fd);
4431 err_free_new_name:
4432 	free(new_name);
4433 	return libbpf_err(err);
4434 }
4435 
4436 __u32 bpf_map__max_entries(const struct bpf_map *map)
4437 {
4438 	return map->def.max_entries;
4439 }
4440 
4441 struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
4442 {
4443 	if (!bpf_map_type__is_map_in_map(map->def.type))
4444 		return errno = EINVAL, NULL;
4445 
4446 	return map->inner_map;
4447 }
4448 
4449 int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
4450 {
4451 	if (map->obj->loaded)
4452 		return libbpf_err(-EBUSY);
4453 
4454 	map->def.max_entries = max_entries;
4455 
4456 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
4457 	if (map_is_ringbuf(map))
4458 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
4459 
4460 	return 0;
4461 }
4462 
4463 static int
4464 bpf_object__probe_loading(struct bpf_object *obj)
4465 {
4466 	char *cp, errmsg[STRERR_BUFSIZE];
4467 	struct bpf_insn insns[] = {
4468 		BPF_MOV64_IMM(BPF_REG_0, 0),
4469 		BPF_EXIT_INSN(),
4470 	};
4471 	int ret, insn_cnt = ARRAY_SIZE(insns);
4472 
4473 	if (obj->gen_loader)
4474 		return 0;
4475 
4476 	ret = bump_rlimit_memlock();
4477 	if (ret)
4478 		pr_warn("Failed to bump RLIMIT_MEMLOCK (err = %d), you might need to do it explicitly!\n", ret);
4479 
4480 	/* make sure basic loading works */
4481 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4482 	if (ret < 0)
4483 		ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
4484 	if (ret < 0) {
4485 		ret = errno;
4486 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4487 		pr_warn("Error in %s():%s(%d). Couldn't load trivial BPF "
4488 			"program. Make sure your kernel supports BPF "
4489 			"(CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is "
4490 			"set to big enough value.\n", __func__, cp, ret);
4491 		return -ret;
4492 	}
4493 	close(ret);
4494 
4495 	return 0;
4496 }
4497 
4498 static int probe_fd(int fd)
4499 {
4500 	if (fd >= 0)
4501 		close(fd);
4502 	return fd >= 0;
4503 }
4504 
4505 static int probe_kern_prog_name(void)
4506 {
4507 	const size_t attr_sz = offsetofend(union bpf_attr, prog_name);
4508 	struct bpf_insn insns[] = {
4509 		BPF_MOV64_IMM(BPF_REG_0, 0),
4510 		BPF_EXIT_INSN(),
4511 	};
4512 	union bpf_attr attr;
4513 	int ret;
4514 
4515 	memset(&attr, 0, attr_sz);
4516 	attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
4517 	attr.license = ptr_to_u64("GPL");
4518 	attr.insns = ptr_to_u64(insns);
4519 	attr.insn_cnt = (__u32)ARRAY_SIZE(insns);
4520 	libbpf_strlcpy(attr.prog_name, "libbpf_nametest", sizeof(attr.prog_name));
4521 
4522 	/* make sure loading with name works */
4523 	ret = sys_bpf_prog_load(&attr, attr_sz, PROG_LOAD_ATTEMPTS);
4524 	return probe_fd(ret);
4525 }
4526 
4527 static int probe_kern_global_data(void)
4528 {
4529 	char *cp, errmsg[STRERR_BUFSIZE];
4530 	struct bpf_insn insns[] = {
4531 		BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
4532 		BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
4533 		BPF_MOV64_IMM(BPF_REG_0, 0),
4534 		BPF_EXIT_INSN(),
4535 	};
4536 	int ret, map, insn_cnt = ARRAY_SIZE(insns);
4537 
4538 	map = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_global", sizeof(int), 32, 1, NULL);
4539 	if (map < 0) {
4540 		ret = -errno;
4541 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4542 		pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4543 			__func__, cp, -ret);
4544 		return ret;
4545 	}
4546 
4547 	insns[0].imm = map;
4548 
4549 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4550 	close(map);
4551 	return probe_fd(ret);
4552 }
4553 
4554 static int probe_kern_btf(void)
4555 {
4556 	static const char strs[] = "\0int";
4557 	__u32 types[] = {
4558 		/* int */
4559 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4560 	};
4561 
4562 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4563 					     strs, sizeof(strs)));
4564 }
4565 
4566 static int probe_kern_btf_func(void)
4567 {
4568 	static const char strs[] = "\0int\0x\0a";
4569 	/* void x(int a) {} */
4570 	__u32 types[] = {
4571 		/* int */
4572 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4573 		/* FUNC_PROTO */                                /* [2] */
4574 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4575 		BTF_PARAM_ENC(7, 1),
4576 		/* FUNC x */                                    /* [3] */
4577 		BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
4578 	};
4579 
4580 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4581 					     strs, sizeof(strs)));
4582 }
4583 
4584 static int probe_kern_btf_func_global(void)
4585 {
4586 	static const char strs[] = "\0int\0x\0a";
4587 	/* static void x(int a) {} */
4588 	__u32 types[] = {
4589 		/* int */
4590 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4591 		/* FUNC_PROTO */                                /* [2] */
4592 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4593 		BTF_PARAM_ENC(7, 1),
4594 		/* FUNC x BTF_FUNC_GLOBAL */                    /* [3] */
4595 		BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, BTF_FUNC_GLOBAL), 2),
4596 	};
4597 
4598 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4599 					     strs, sizeof(strs)));
4600 }
4601 
4602 static int probe_kern_btf_datasec(void)
4603 {
4604 	static const char strs[] = "\0x\0.data";
4605 	/* static int a; */
4606 	__u32 types[] = {
4607 		/* int */
4608 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4609 		/* VAR x */                                     /* [2] */
4610 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4611 		BTF_VAR_STATIC,
4612 		/* DATASEC val */                               /* [3] */
4613 		BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
4614 		BTF_VAR_SECINFO_ENC(2, 0, 4),
4615 	};
4616 
4617 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4618 					     strs, sizeof(strs)));
4619 }
4620 
4621 static int probe_kern_btf_float(void)
4622 {
4623 	static const char strs[] = "\0float";
4624 	__u32 types[] = {
4625 		/* float */
4626 		BTF_TYPE_FLOAT_ENC(1, 4),
4627 	};
4628 
4629 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4630 					     strs, sizeof(strs)));
4631 }
4632 
4633 static int probe_kern_btf_decl_tag(void)
4634 {
4635 	static const char strs[] = "\0tag";
4636 	__u32 types[] = {
4637 		/* int */
4638 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4639 		/* VAR x */                                     /* [2] */
4640 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4641 		BTF_VAR_STATIC,
4642 		/* attr */
4643 		BTF_TYPE_DECL_TAG_ENC(1, 2, -1),
4644 	};
4645 
4646 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4647 					     strs, sizeof(strs)));
4648 }
4649 
4650 static int probe_kern_btf_type_tag(void)
4651 {
4652 	static const char strs[] = "\0tag";
4653 	__u32 types[] = {
4654 		/* int */
4655 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),		/* [1] */
4656 		/* attr */
4657 		BTF_TYPE_TYPE_TAG_ENC(1, 1),				/* [2] */
4658 		/* ptr */
4659 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_PTR, 0, 0), 2),	/* [3] */
4660 	};
4661 
4662 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4663 					     strs, sizeof(strs)));
4664 }
4665 
4666 static int probe_kern_array_mmap(void)
4667 {
4668 	LIBBPF_OPTS(bpf_map_create_opts, opts, .map_flags = BPF_F_MMAPABLE);
4669 	int fd;
4670 
4671 	fd = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_mmap", sizeof(int), sizeof(int), 1, &opts);
4672 	return probe_fd(fd);
4673 }
4674 
4675 static int probe_kern_exp_attach_type(void)
4676 {
4677 	LIBBPF_OPTS(bpf_prog_load_opts, opts, .expected_attach_type = BPF_CGROUP_INET_SOCK_CREATE);
4678 	struct bpf_insn insns[] = {
4679 		BPF_MOV64_IMM(BPF_REG_0, 0),
4680 		BPF_EXIT_INSN(),
4681 	};
4682 	int fd, insn_cnt = ARRAY_SIZE(insns);
4683 
4684 	/* use any valid combination of program type and (optional)
4685 	 * non-zero expected attach type (i.e., not a BPF_CGROUP_INET_INGRESS)
4686 	 * to see if kernel supports expected_attach_type field for
4687 	 * BPF_PROG_LOAD command
4688 	 */
4689 	fd = bpf_prog_load(BPF_PROG_TYPE_CGROUP_SOCK, NULL, "GPL", insns, insn_cnt, &opts);
4690 	return probe_fd(fd);
4691 }
4692 
4693 static int probe_kern_probe_read_kernel(void)
4694 {
4695 	struct bpf_insn insns[] = {
4696 		BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),	/* r1 = r10 (fp) */
4697 		BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -8),	/* r1 += -8 */
4698 		BPF_MOV64_IMM(BPF_REG_2, 8),		/* r2 = 8 */
4699 		BPF_MOV64_IMM(BPF_REG_3, 0),		/* r3 = 0 */
4700 		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_probe_read_kernel),
4701 		BPF_EXIT_INSN(),
4702 	};
4703 	int fd, insn_cnt = ARRAY_SIZE(insns);
4704 
4705 	fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
4706 	return probe_fd(fd);
4707 }
4708 
4709 static int probe_prog_bind_map(void)
4710 {
4711 	char *cp, errmsg[STRERR_BUFSIZE];
4712 	struct bpf_insn insns[] = {
4713 		BPF_MOV64_IMM(BPF_REG_0, 0),
4714 		BPF_EXIT_INSN(),
4715 	};
4716 	int ret, map, prog, insn_cnt = ARRAY_SIZE(insns);
4717 
4718 	map = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_det_bind", sizeof(int), 32, 1, NULL);
4719 	if (map < 0) {
4720 		ret = -errno;
4721 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4722 		pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4723 			__func__, cp, -ret);
4724 		return ret;
4725 	}
4726 
4727 	prog = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4728 	if (prog < 0) {
4729 		close(map);
4730 		return 0;
4731 	}
4732 
4733 	ret = bpf_prog_bind_map(prog, map, NULL);
4734 
4735 	close(map);
4736 	close(prog);
4737 
4738 	return ret >= 0;
4739 }
4740 
4741 static int probe_module_btf(void)
4742 {
4743 	static const char strs[] = "\0int";
4744 	__u32 types[] = {
4745 		/* int */
4746 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4747 	};
4748 	struct bpf_btf_info info;
4749 	__u32 len = sizeof(info);
4750 	char name[16];
4751 	int fd, err;
4752 
4753 	fd = libbpf__load_raw_btf((char *)types, sizeof(types), strs, sizeof(strs));
4754 	if (fd < 0)
4755 		return 0; /* BTF not supported at all */
4756 
4757 	memset(&info, 0, sizeof(info));
4758 	info.name = ptr_to_u64(name);
4759 	info.name_len = sizeof(name);
4760 
4761 	/* check that BPF_OBJ_GET_INFO_BY_FD supports specifying name pointer;
4762 	 * kernel's module BTF support coincides with support for
4763 	 * name/name_len fields in struct bpf_btf_info.
4764 	 */
4765 	err = bpf_btf_get_info_by_fd(fd, &info, &len);
4766 	close(fd);
4767 	return !err;
4768 }
4769 
4770 static int probe_perf_link(void)
4771 {
4772 	struct bpf_insn insns[] = {
4773 		BPF_MOV64_IMM(BPF_REG_0, 0),
4774 		BPF_EXIT_INSN(),
4775 	};
4776 	int prog_fd, link_fd, err;
4777 
4778 	prog_fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL",
4779 				insns, ARRAY_SIZE(insns), NULL);
4780 	if (prog_fd < 0)
4781 		return -errno;
4782 
4783 	/* use invalid perf_event FD to get EBADF, if link is supported;
4784 	 * otherwise EINVAL should be returned
4785 	 */
4786 	link_fd = bpf_link_create(prog_fd, -1, BPF_PERF_EVENT, NULL);
4787 	err = -errno; /* close() can clobber errno */
4788 
4789 	if (link_fd >= 0)
4790 		close(link_fd);
4791 	close(prog_fd);
4792 
4793 	return link_fd < 0 && err == -EBADF;
4794 }
4795 
4796 static int probe_kern_bpf_cookie(void)
4797 {
4798 	struct bpf_insn insns[] = {
4799 		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_get_attach_cookie),
4800 		BPF_EXIT_INSN(),
4801 	};
4802 	int ret, insn_cnt = ARRAY_SIZE(insns);
4803 
4804 	ret = bpf_prog_load(BPF_PROG_TYPE_KPROBE, NULL, "GPL", insns, insn_cnt, NULL);
4805 	return probe_fd(ret);
4806 }
4807 
4808 static int probe_kern_btf_enum64(void)
4809 {
4810 	static const char strs[] = "\0enum64";
4811 	__u32 types[] = {
4812 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_ENUM64, 0, 0), 8),
4813 	};
4814 
4815 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4816 					     strs, sizeof(strs)));
4817 }
4818 
4819 static int probe_kern_syscall_wrapper(void);
4820 
4821 enum kern_feature_result {
4822 	FEAT_UNKNOWN = 0,
4823 	FEAT_SUPPORTED = 1,
4824 	FEAT_MISSING = 2,
4825 };
4826 
4827 typedef int (*feature_probe_fn)(void);
4828 
4829 static struct kern_feature_desc {
4830 	const char *desc;
4831 	feature_probe_fn probe;
4832 	enum kern_feature_result res;
4833 } feature_probes[__FEAT_CNT] = {
4834 	[FEAT_PROG_NAME] = {
4835 		"BPF program name", probe_kern_prog_name,
4836 	},
4837 	[FEAT_GLOBAL_DATA] = {
4838 		"global variables", probe_kern_global_data,
4839 	},
4840 	[FEAT_BTF] = {
4841 		"minimal BTF", probe_kern_btf,
4842 	},
4843 	[FEAT_BTF_FUNC] = {
4844 		"BTF functions", probe_kern_btf_func,
4845 	},
4846 	[FEAT_BTF_GLOBAL_FUNC] = {
4847 		"BTF global function", probe_kern_btf_func_global,
4848 	},
4849 	[FEAT_BTF_DATASEC] = {
4850 		"BTF data section and variable", probe_kern_btf_datasec,
4851 	},
4852 	[FEAT_ARRAY_MMAP] = {
4853 		"ARRAY map mmap()", probe_kern_array_mmap,
4854 	},
4855 	[FEAT_EXP_ATTACH_TYPE] = {
4856 		"BPF_PROG_LOAD expected_attach_type attribute",
4857 		probe_kern_exp_attach_type,
4858 	},
4859 	[FEAT_PROBE_READ_KERN] = {
4860 		"bpf_probe_read_kernel() helper", probe_kern_probe_read_kernel,
4861 	},
4862 	[FEAT_PROG_BIND_MAP] = {
4863 		"BPF_PROG_BIND_MAP support", probe_prog_bind_map,
4864 	},
4865 	[FEAT_MODULE_BTF] = {
4866 		"module BTF support", probe_module_btf,
4867 	},
4868 	[FEAT_BTF_FLOAT] = {
4869 		"BTF_KIND_FLOAT support", probe_kern_btf_float,
4870 	},
4871 	[FEAT_PERF_LINK] = {
4872 		"BPF perf link support", probe_perf_link,
4873 	},
4874 	[FEAT_BTF_DECL_TAG] = {
4875 		"BTF_KIND_DECL_TAG support", probe_kern_btf_decl_tag,
4876 	},
4877 	[FEAT_BTF_TYPE_TAG] = {
4878 		"BTF_KIND_TYPE_TAG support", probe_kern_btf_type_tag,
4879 	},
4880 	[FEAT_MEMCG_ACCOUNT] = {
4881 		"memcg-based memory accounting", probe_memcg_account,
4882 	},
4883 	[FEAT_BPF_COOKIE] = {
4884 		"BPF cookie support", probe_kern_bpf_cookie,
4885 	},
4886 	[FEAT_BTF_ENUM64] = {
4887 		"BTF_KIND_ENUM64 support", probe_kern_btf_enum64,
4888 	},
4889 	[FEAT_SYSCALL_WRAPPER] = {
4890 		"Kernel using syscall wrapper", probe_kern_syscall_wrapper,
4891 	},
4892 };
4893 
4894 bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
4895 {
4896 	struct kern_feature_desc *feat = &feature_probes[feat_id];
4897 	int ret;
4898 
4899 	if (obj && obj->gen_loader)
4900 		/* To generate loader program assume the latest kernel
4901 		 * to avoid doing extra prog_load, map_create syscalls.
4902 		 */
4903 		return true;
4904 
4905 	if (READ_ONCE(feat->res) == FEAT_UNKNOWN) {
4906 		ret = feat->probe();
4907 		if (ret > 0) {
4908 			WRITE_ONCE(feat->res, FEAT_SUPPORTED);
4909 		} else if (ret == 0) {
4910 			WRITE_ONCE(feat->res, FEAT_MISSING);
4911 		} else {
4912 			pr_warn("Detection of kernel %s support failed: %d\n", feat->desc, ret);
4913 			WRITE_ONCE(feat->res, FEAT_MISSING);
4914 		}
4915 	}
4916 
4917 	return READ_ONCE(feat->res) == FEAT_SUPPORTED;
4918 }
4919 
4920 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
4921 {
4922 	struct bpf_map_info map_info;
4923 	char msg[STRERR_BUFSIZE];
4924 	__u32 map_info_len = sizeof(map_info);
4925 	int err;
4926 
4927 	memset(&map_info, 0, map_info_len);
4928 	err = bpf_map_get_info_by_fd(map_fd, &map_info, &map_info_len);
4929 	if (err && errno == EINVAL)
4930 		err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
4931 	if (err) {
4932 		pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
4933 			libbpf_strerror_r(errno, msg, sizeof(msg)));
4934 		return false;
4935 	}
4936 
4937 	return (map_info.type == map->def.type &&
4938 		map_info.key_size == map->def.key_size &&
4939 		map_info.value_size == map->def.value_size &&
4940 		map_info.max_entries == map->def.max_entries &&
4941 		map_info.map_flags == map->def.map_flags &&
4942 		map_info.map_extra == map->map_extra);
4943 }
4944 
4945 static int
4946 bpf_object__reuse_map(struct bpf_map *map)
4947 {
4948 	char *cp, errmsg[STRERR_BUFSIZE];
4949 	int err, pin_fd;
4950 
4951 	pin_fd = bpf_obj_get(map->pin_path);
4952 	if (pin_fd < 0) {
4953 		err = -errno;
4954 		if (err == -ENOENT) {
4955 			pr_debug("found no pinned map to reuse at '%s'\n",
4956 				 map->pin_path);
4957 			return 0;
4958 		}
4959 
4960 		cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
4961 		pr_warn("couldn't retrieve pinned map '%s': %s\n",
4962 			map->pin_path, cp);
4963 		return err;
4964 	}
4965 
4966 	if (!map_is_reuse_compat(map, pin_fd)) {
4967 		pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
4968 			map->pin_path);
4969 		close(pin_fd);
4970 		return -EINVAL;
4971 	}
4972 
4973 	err = bpf_map__reuse_fd(map, pin_fd);
4974 	close(pin_fd);
4975 	if (err)
4976 		return err;
4977 
4978 	map->pinned = true;
4979 	pr_debug("reused pinned map at '%s'\n", map->pin_path);
4980 
4981 	return 0;
4982 }
4983 
4984 static int
4985 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
4986 {
4987 	enum libbpf_map_type map_type = map->libbpf_type;
4988 	char *cp, errmsg[STRERR_BUFSIZE];
4989 	int err, zero = 0;
4990 
4991 	if (obj->gen_loader) {
4992 		bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
4993 					 map->mmaped, map->def.value_size);
4994 		if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
4995 			bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
4996 		return 0;
4997 	}
4998 	err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
4999 	if (err) {
5000 		err = -errno;
5001 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5002 		pr_warn("Error setting initial map(%s) contents: %s\n",
5003 			map->name, cp);
5004 		return err;
5005 	}
5006 
5007 	/* Freeze .rodata and .kconfig map as read-only from syscall side. */
5008 	if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
5009 		err = bpf_map_freeze(map->fd);
5010 		if (err) {
5011 			err = -errno;
5012 			cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5013 			pr_warn("Error freezing map(%s) as read-only: %s\n",
5014 				map->name, cp);
5015 			return err;
5016 		}
5017 	}
5018 	return 0;
5019 }
5020 
5021 static void bpf_map__destroy(struct bpf_map *map);
5022 
5023 static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
5024 {
5025 	LIBBPF_OPTS(bpf_map_create_opts, create_attr);
5026 	struct bpf_map_def *def = &map->def;
5027 	const char *map_name = NULL;
5028 	int err = 0;
5029 
5030 	if (kernel_supports(obj, FEAT_PROG_NAME))
5031 		map_name = map->name;
5032 	create_attr.map_ifindex = map->map_ifindex;
5033 	create_attr.map_flags = def->map_flags;
5034 	create_attr.numa_node = map->numa_node;
5035 	create_attr.map_extra = map->map_extra;
5036 
5037 	if (bpf_map__is_struct_ops(map))
5038 		create_attr.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
5039 
5040 	if (obj->btf && btf__fd(obj->btf) >= 0) {
5041 		create_attr.btf_fd = btf__fd(obj->btf);
5042 		create_attr.btf_key_type_id = map->btf_key_type_id;
5043 		create_attr.btf_value_type_id = map->btf_value_type_id;
5044 	}
5045 
5046 	if (bpf_map_type__is_map_in_map(def->type)) {
5047 		if (map->inner_map) {
5048 			err = bpf_object__create_map(obj, map->inner_map, true);
5049 			if (err) {
5050 				pr_warn("map '%s': failed to create inner map: %d\n",
5051 					map->name, err);
5052 				return err;
5053 			}
5054 			map->inner_map_fd = bpf_map__fd(map->inner_map);
5055 		}
5056 		if (map->inner_map_fd >= 0)
5057 			create_attr.inner_map_fd = map->inner_map_fd;
5058 	}
5059 
5060 	switch (def->type) {
5061 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5062 	case BPF_MAP_TYPE_CGROUP_ARRAY:
5063 	case BPF_MAP_TYPE_STACK_TRACE:
5064 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5065 	case BPF_MAP_TYPE_HASH_OF_MAPS:
5066 	case BPF_MAP_TYPE_DEVMAP:
5067 	case BPF_MAP_TYPE_DEVMAP_HASH:
5068 	case BPF_MAP_TYPE_CPUMAP:
5069 	case BPF_MAP_TYPE_XSKMAP:
5070 	case BPF_MAP_TYPE_SOCKMAP:
5071 	case BPF_MAP_TYPE_SOCKHASH:
5072 	case BPF_MAP_TYPE_QUEUE:
5073 	case BPF_MAP_TYPE_STACK:
5074 		create_attr.btf_fd = 0;
5075 		create_attr.btf_key_type_id = 0;
5076 		create_attr.btf_value_type_id = 0;
5077 		map->btf_key_type_id = 0;
5078 		map->btf_value_type_id = 0;
5079 	default:
5080 		break;
5081 	}
5082 
5083 	if (obj->gen_loader) {
5084 		bpf_gen__map_create(obj->gen_loader, def->type, map_name,
5085 				    def->key_size, def->value_size, def->max_entries,
5086 				    &create_attr, is_inner ? -1 : map - obj->maps);
5087 		/* Pretend to have valid FD to pass various fd >= 0 checks.
5088 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
5089 		 */
5090 		map->fd = 0;
5091 	} else {
5092 		map->fd = bpf_map_create(def->type, map_name,
5093 					 def->key_size, def->value_size,
5094 					 def->max_entries, &create_attr);
5095 	}
5096 	if (map->fd < 0 && (create_attr.btf_key_type_id ||
5097 			    create_attr.btf_value_type_id)) {
5098 		char *cp, errmsg[STRERR_BUFSIZE];
5099 
5100 		err = -errno;
5101 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5102 		pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
5103 			map->name, cp, err);
5104 		create_attr.btf_fd = 0;
5105 		create_attr.btf_key_type_id = 0;
5106 		create_attr.btf_value_type_id = 0;
5107 		map->btf_key_type_id = 0;
5108 		map->btf_value_type_id = 0;
5109 		map->fd = bpf_map_create(def->type, map_name,
5110 					 def->key_size, def->value_size,
5111 					 def->max_entries, &create_attr);
5112 	}
5113 
5114 	err = map->fd < 0 ? -errno : 0;
5115 
5116 	if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
5117 		if (obj->gen_loader)
5118 			map->inner_map->fd = -1;
5119 		bpf_map__destroy(map->inner_map);
5120 		zfree(&map->inner_map);
5121 	}
5122 
5123 	return err;
5124 }
5125 
5126 static int init_map_in_map_slots(struct bpf_object *obj, struct bpf_map *map)
5127 {
5128 	const struct bpf_map *targ_map;
5129 	unsigned int i;
5130 	int fd, err = 0;
5131 
5132 	for (i = 0; i < map->init_slots_sz; i++) {
5133 		if (!map->init_slots[i])
5134 			continue;
5135 
5136 		targ_map = map->init_slots[i];
5137 		fd = bpf_map__fd(targ_map);
5138 
5139 		if (obj->gen_loader) {
5140 			bpf_gen__populate_outer_map(obj->gen_loader,
5141 						    map - obj->maps, i,
5142 						    targ_map - obj->maps);
5143 		} else {
5144 			err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5145 		}
5146 		if (err) {
5147 			err = -errno;
5148 			pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %d\n",
5149 				map->name, i, targ_map->name, fd, err);
5150 			return err;
5151 		}
5152 		pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
5153 			 map->name, i, targ_map->name, fd);
5154 	}
5155 
5156 	zfree(&map->init_slots);
5157 	map->init_slots_sz = 0;
5158 
5159 	return 0;
5160 }
5161 
5162 static int init_prog_array_slots(struct bpf_object *obj, struct bpf_map *map)
5163 {
5164 	const struct bpf_program *targ_prog;
5165 	unsigned int i;
5166 	int fd, err;
5167 
5168 	if (obj->gen_loader)
5169 		return -ENOTSUP;
5170 
5171 	for (i = 0; i < map->init_slots_sz; i++) {
5172 		if (!map->init_slots[i])
5173 			continue;
5174 
5175 		targ_prog = map->init_slots[i];
5176 		fd = bpf_program__fd(targ_prog);
5177 
5178 		err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5179 		if (err) {
5180 			err = -errno;
5181 			pr_warn("map '%s': failed to initialize slot [%d] to prog '%s' fd=%d: %d\n",
5182 				map->name, i, targ_prog->name, fd, err);
5183 			return err;
5184 		}
5185 		pr_debug("map '%s': slot [%d] set to prog '%s' fd=%d\n",
5186 			 map->name, i, targ_prog->name, fd);
5187 	}
5188 
5189 	zfree(&map->init_slots);
5190 	map->init_slots_sz = 0;
5191 
5192 	return 0;
5193 }
5194 
5195 static int bpf_object_init_prog_arrays(struct bpf_object *obj)
5196 {
5197 	struct bpf_map *map;
5198 	int i, err;
5199 
5200 	for (i = 0; i < obj->nr_maps; i++) {
5201 		map = &obj->maps[i];
5202 
5203 		if (!map->init_slots_sz || map->def.type != BPF_MAP_TYPE_PROG_ARRAY)
5204 			continue;
5205 
5206 		err = init_prog_array_slots(obj, map);
5207 		if (err < 0) {
5208 			zclose(map->fd);
5209 			return err;
5210 		}
5211 	}
5212 	return 0;
5213 }
5214 
5215 static int map_set_def_max_entries(struct bpf_map *map)
5216 {
5217 	if (map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !map->def.max_entries) {
5218 		int nr_cpus;
5219 
5220 		nr_cpus = libbpf_num_possible_cpus();
5221 		if (nr_cpus < 0) {
5222 			pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
5223 				map->name, nr_cpus);
5224 			return nr_cpus;
5225 		}
5226 		pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
5227 		map->def.max_entries = nr_cpus;
5228 	}
5229 
5230 	return 0;
5231 }
5232 
5233 static int
5234 bpf_object__create_maps(struct bpf_object *obj)
5235 {
5236 	struct bpf_map *map;
5237 	char *cp, errmsg[STRERR_BUFSIZE];
5238 	unsigned int i, j;
5239 	int err;
5240 	bool retried;
5241 
5242 	for (i = 0; i < obj->nr_maps; i++) {
5243 		map = &obj->maps[i];
5244 
5245 		/* To support old kernels, we skip creating global data maps
5246 		 * (.rodata, .data, .kconfig, etc); later on, during program
5247 		 * loading, if we detect that at least one of the to-be-loaded
5248 		 * programs is referencing any global data map, we'll error
5249 		 * out with program name and relocation index logged.
5250 		 * This approach allows to accommodate Clang emitting
5251 		 * unnecessary .rodata.str1.1 sections for string literals,
5252 		 * but also it allows to have CO-RE applications that use
5253 		 * global variables in some of BPF programs, but not others.
5254 		 * If those global variable-using programs are not loaded at
5255 		 * runtime due to bpf_program__set_autoload(prog, false),
5256 		 * bpf_object loading will succeed just fine even on old
5257 		 * kernels.
5258 		 */
5259 		if (bpf_map__is_internal(map) && !kernel_supports(obj, FEAT_GLOBAL_DATA))
5260 			map->autocreate = false;
5261 
5262 		if (!map->autocreate) {
5263 			pr_debug("map '%s': skipped auto-creating...\n", map->name);
5264 			continue;
5265 		}
5266 
5267 		err = map_set_def_max_entries(map);
5268 		if (err)
5269 			goto err_out;
5270 
5271 		retried = false;
5272 retry:
5273 		if (map->pin_path) {
5274 			err = bpf_object__reuse_map(map);
5275 			if (err) {
5276 				pr_warn("map '%s': error reusing pinned map\n",
5277 					map->name);
5278 				goto err_out;
5279 			}
5280 			if (retried && map->fd < 0) {
5281 				pr_warn("map '%s': cannot find pinned map\n",
5282 					map->name);
5283 				err = -ENOENT;
5284 				goto err_out;
5285 			}
5286 		}
5287 
5288 		if (map->fd >= 0) {
5289 			pr_debug("map '%s': skipping creation (preset fd=%d)\n",
5290 				 map->name, map->fd);
5291 		} else {
5292 			err = bpf_object__create_map(obj, map, false);
5293 			if (err)
5294 				goto err_out;
5295 
5296 			pr_debug("map '%s': created successfully, fd=%d\n",
5297 				 map->name, map->fd);
5298 
5299 			if (bpf_map__is_internal(map)) {
5300 				err = bpf_object__populate_internal_map(obj, map);
5301 				if (err < 0) {
5302 					zclose(map->fd);
5303 					goto err_out;
5304 				}
5305 			}
5306 
5307 			if (map->init_slots_sz && map->def.type != BPF_MAP_TYPE_PROG_ARRAY) {
5308 				err = init_map_in_map_slots(obj, map);
5309 				if (err < 0) {
5310 					zclose(map->fd);
5311 					goto err_out;
5312 				}
5313 			}
5314 		}
5315 
5316 		if (map->pin_path && !map->pinned) {
5317 			err = bpf_map__pin(map, NULL);
5318 			if (err) {
5319 				zclose(map->fd);
5320 				if (!retried && err == -EEXIST) {
5321 					retried = true;
5322 					goto retry;
5323 				}
5324 				pr_warn("map '%s': failed to auto-pin at '%s': %d\n",
5325 					map->name, map->pin_path, err);
5326 				goto err_out;
5327 			}
5328 		}
5329 	}
5330 
5331 	return 0;
5332 
5333 err_out:
5334 	cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5335 	pr_warn("map '%s': failed to create: %s(%d)\n", map->name, cp, err);
5336 	pr_perm_msg(err);
5337 	for (j = 0; j < i; j++)
5338 		zclose(obj->maps[j].fd);
5339 	return err;
5340 }
5341 
5342 static bool bpf_core_is_flavor_sep(const char *s)
5343 {
5344 	/* check X___Y name pattern, where X and Y are not underscores */
5345 	return s[0] != '_' &&				      /* X */
5346 	       s[1] == '_' && s[2] == '_' && s[3] == '_' &&   /* ___ */
5347 	       s[4] != '_';				      /* Y */
5348 }
5349 
5350 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
5351  * before last triple underscore. Struct name part after last triple
5352  * underscore is ignored by BPF CO-RE relocation during relocation matching.
5353  */
5354 size_t bpf_core_essential_name_len(const char *name)
5355 {
5356 	size_t n = strlen(name);
5357 	int i;
5358 
5359 	for (i = n - 5; i >= 0; i--) {
5360 		if (bpf_core_is_flavor_sep(name + i))
5361 			return i + 1;
5362 	}
5363 	return n;
5364 }
5365 
5366 void bpf_core_free_cands(struct bpf_core_cand_list *cands)
5367 {
5368 	if (!cands)
5369 		return;
5370 
5371 	free(cands->cands);
5372 	free(cands);
5373 }
5374 
5375 int bpf_core_add_cands(struct bpf_core_cand *local_cand,
5376 		       size_t local_essent_len,
5377 		       const struct btf *targ_btf,
5378 		       const char *targ_btf_name,
5379 		       int targ_start_id,
5380 		       struct bpf_core_cand_list *cands)
5381 {
5382 	struct bpf_core_cand *new_cands, *cand;
5383 	const struct btf_type *t, *local_t;
5384 	const char *targ_name, *local_name;
5385 	size_t targ_essent_len;
5386 	int n, i;
5387 
5388 	local_t = btf__type_by_id(local_cand->btf, local_cand->id);
5389 	local_name = btf__str_by_offset(local_cand->btf, local_t->name_off);
5390 
5391 	n = btf__type_cnt(targ_btf);
5392 	for (i = targ_start_id; i < n; i++) {
5393 		t = btf__type_by_id(targ_btf, i);
5394 		if (!btf_kind_core_compat(t, local_t))
5395 			continue;
5396 
5397 		targ_name = btf__name_by_offset(targ_btf, t->name_off);
5398 		if (str_is_empty(targ_name))
5399 			continue;
5400 
5401 		targ_essent_len = bpf_core_essential_name_len(targ_name);
5402 		if (targ_essent_len != local_essent_len)
5403 			continue;
5404 
5405 		if (strncmp(local_name, targ_name, local_essent_len) != 0)
5406 			continue;
5407 
5408 		pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s in [%s]\n",
5409 			 local_cand->id, btf_kind_str(local_t),
5410 			 local_name, i, btf_kind_str(t), targ_name,
5411 			 targ_btf_name);
5412 		new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
5413 					      sizeof(*cands->cands));
5414 		if (!new_cands)
5415 			return -ENOMEM;
5416 
5417 		cand = &new_cands[cands->len];
5418 		cand->btf = targ_btf;
5419 		cand->id = i;
5420 
5421 		cands->cands = new_cands;
5422 		cands->len++;
5423 	}
5424 	return 0;
5425 }
5426 
5427 static int load_module_btfs(struct bpf_object *obj)
5428 {
5429 	struct bpf_btf_info info;
5430 	struct module_btf *mod_btf;
5431 	struct btf *btf;
5432 	char name[64];
5433 	__u32 id = 0, len;
5434 	int err, fd;
5435 
5436 	if (obj->btf_modules_loaded)
5437 		return 0;
5438 
5439 	if (obj->gen_loader)
5440 		return 0;
5441 
5442 	/* don't do this again, even if we find no module BTFs */
5443 	obj->btf_modules_loaded = true;
5444 
5445 	/* kernel too old to support module BTFs */
5446 	if (!kernel_supports(obj, FEAT_MODULE_BTF))
5447 		return 0;
5448 
5449 	while (true) {
5450 		err = bpf_btf_get_next_id(id, &id);
5451 		if (err && errno == ENOENT)
5452 			return 0;
5453 		if (err) {
5454 			err = -errno;
5455 			pr_warn("failed to iterate BTF objects: %d\n", err);
5456 			return err;
5457 		}
5458 
5459 		fd = bpf_btf_get_fd_by_id(id);
5460 		if (fd < 0) {
5461 			if (errno == ENOENT)
5462 				continue; /* expected race: BTF was unloaded */
5463 			err = -errno;
5464 			pr_warn("failed to get BTF object #%d FD: %d\n", id, err);
5465 			return err;
5466 		}
5467 
5468 		len = sizeof(info);
5469 		memset(&info, 0, sizeof(info));
5470 		info.name = ptr_to_u64(name);
5471 		info.name_len = sizeof(name);
5472 
5473 		err = bpf_btf_get_info_by_fd(fd, &info, &len);
5474 		if (err) {
5475 			err = -errno;
5476 			pr_warn("failed to get BTF object #%d info: %d\n", id, err);
5477 			goto err_out;
5478 		}
5479 
5480 		/* ignore non-module BTFs */
5481 		if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
5482 			close(fd);
5483 			continue;
5484 		}
5485 
5486 		btf = btf_get_from_fd(fd, obj->btf_vmlinux);
5487 		err = libbpf_get_error(btf);
5488 		if (err) {
5489 			pr_warn("failed to load module [%s]'s BTF object #%d: %d\n",
5490 				name, id, err);
5491 			goto err_out;
5492 		}
5493 
5494 		err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
5495 					sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
5496 		if (err)
5497 			goto err_out;
5498 
5499 		mod_btf = &obj->btf_modules[obj->btf_module_cnt++];
5500 
5501 		mod_btf->btf = btf;
5502 		mod_btf->id = id;
5503 		mod_btf->fd = fd;
5504 		mod_btf->name = strdup(name);
5505 		if (!mod_btf->name) {
5506 			err = -ENOMEM;
5507 			goto err_out;
5508 		}
5509 		continue;
5510 
5511 err_out:
5512 		close(fd);
5513 		return err;
5514 	}
5515 
5516 	return 0;
5517 }
5518 
5519 static struct bpf_core_cand_list *
5520 bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
5521 {
5522 	struct bpf_core_cand local_cand = {};
5523 	struct bpf_core_cand_list *cands;
5524 	const struct btf *main_btf;
5525 	const struct btf_type *local_t;
5526 	const char *local_name;
5527 	size_t local_essent_len;
5528 	int err, i;
5529 
5530 	local_cand.btf = local_btf;
5531 	local_cand.id = local_type_id;
5532 	local_t = btf__type_by_id(local_btf, local_type_id);
5533 	if (!local_t)
5534 		return ERR_PTR(-EINVAL);
5535 
5536 	local_name = btf__name_by_offset(local_btf, local_t->name_off);
5537 	if (str_is_empty(local_name))
5538 		return ERR_PTR(-EINVAL);
5539 	local_essent_len = bpf_core_essential_name_len(local_name);
5540 
5541 	cands = calloc(1, sizeof(*cands));
5542 	if (!cands)
5543 		return ERR_PTR(-ENOMEM);
5544 
5545 	/* Attempt to find target candidates in vmlinux BTF first */
5546 	main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
5547 	err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
5548 	if (err)
5549 		goto err_out;
5550 
5551 	/* if vmlinux BTF has any candidate, don't got for module BTFs */
5552 	if (cands->len)
5553 		return cands;
5554 
5555 	/* if vmlinux BTF was overridden, don't attempt to load module BTFs */
5556 	if (obj->btf_vmlinux_override)
5557 		return cands;
5558 
5559 	/* now look through module BTFs, trying to still find candidates */
5560 	err = load_module_btfs(obj);
5561 	if (err)
5562 		goto err_out;
5563 
5564 	for (i = 0; i < obj->btf_module_cnt; i++) {
5565 		err = bpf_core_add_cands(&local_cand, local_essent_len,
5566 					 obj->btf_modules[i].btf,
5567 					 obj->btf_modules[i].name,
5568 					 btf__type_cnt(obj->btf_vmlinux),
5569 					 cands);
5570 		if (err)
5571 			goto err_out;
5572 	}
5573 
5574 	return cands;
5575 err_out:
5576 	bpf_core_free_cands(cands);
5577 	return ERR_PTR(err);
5578 }
5579 
5580 /* Check local and target types for compatibility. This check is used for
5581  * type-based CO-RE relocations and follow slightly different rules than
5582  * field-based relocations. This function assumes that root types were already
5583  * checked for name match. Beyond that initial root-level name check, names
5584  * are completely ignored. Compatibility rules are as follows:
5585  *   - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
5586  *     kind should match for local and target types (i.e., STRUCT is not
5587  *     compatible with UNION);
5588  *   - for ENUMs, the size is ignored;
5589  *   - for INT, size and signedness are ignored;
5590  *   - for ARRAY, dimensionality is ignored, element types are checked for
5591  *     compatibility recursively;
5592  *   - CONST/VOLATILE/RESTRICT modifiers are ignored;
5593  *   - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
5594  *   - FUNC_PROTOs are compatible if they have compatible signature: same
5595  *     number of input args and compatible return and argument types.
5596  * These rules are not set in stone and probably will be adjusted as we get
5597  * more experience with using BPF CO-RE relocations.
5598  */
5599 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
5600 			      const struct btf *targ_btf, __u32 targ_id)
5601 {
5602 	return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id, 32);
5603 }
5604 
5605 int bpf_core_types_match(const struct btf *local_btf, __u32 local_id,
5606 			 const struct btf *targ_btf, __u32 targ_id)
5607 {
5608 	return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false, 32);
5609 }
5610 
5611 static size_t bpf_core_hash_fn(const long key, void *ctx)
5612 {
5613 	return key;
5614 }
5615 
5616 static bool bpf_core_equal_fn(const long k1, const long k2, void *ctx)
5617 {
5618 	return k1 == k2;
5619 }
5620 
5621 static int record_relo_core(struct bpf_program *prog,
5622 			    const struct bpf_core_relo *core_relo, int insn_idx)
5623 {
5624 	struct reloc_desc *relos, *relo;
5625 
5626 	relos = libbpf_reallocarray(prog->reloc_desc,
5627 				    prog->nr_reloc + 1, sizeof(*relos));
5628 	if (!relos)
5629 		return -ENOMEM;
5630 	relo = &relos[prog->nr_reloc];
5631 	relo->type = RELO_CORE;
5632 	relo->insn_idx = insn_idx;
5633 	relo->core_relo = core_relo;
5634 	prog->reloc_desc = relos;
5635 	prog->nr_reloc++;
5636 	return 0;
5637 }
5638 
5639 static const struct bpf_core_relo *find_relo_core(struct bpf_program *prog, int insn_idx)
5640 {
5641 	struct reloc_desc *relo;
5642 	int i;
5643 
5644 	for (i = 0; i < prog->nr_reloc; i++) {
5645 		relo = &prog->reloc_desc[i];
5646 		if (relo->type != RELO_CORE || relo->insn_idx != insn_idx)
5647 			continue;
5648 
5649 		return relo->core_relo;
5650 	}
5651 
5652 	return NULL;
5653 }
5654 
5655 static int bpf_core_resolve_relo(struct bpf_program *prog,
5656 				 const struct bpf_core_relo *relo,
5657 				 int relo_idx,
5658 				 const struct btf *local_btf,
5659 				 struct hashmap *cand_cache,
5660 				 struct bpf_core_relo_res *targ_res)
5661 {
5662 	struct bpf_core_spec specs_scratch[3] = {};
5663 	struct bpf_core_cand_list *cands = NULL;
5664 	const char *prog_name = prog->name;
5665 	const struct btf_type *local_type;
5666 	const char *local_name;
5667 	__u32 local_id = relo->type_id;
5668 	int err;
5669 
5670 	local_type = btf__type_by_id(local_btf, local_id);
5671 	if (!local_type)
5672 		return -EINVAL;
5673 
5674 	local_name = btf__name_by_offset(local_btf, local_type->name_off);
5675 	if (!local_name)
5676 		return -EINVAL;
5677 
5678 	if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
5679 	    !hashmap__find(cand_cache, local_id, &cands)) {
5680 		cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
5681 		if (IS_ERR(cands)) {
5682 			pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n",
5683 				prog_name, relo_idx, local_id, btf_kind_str(local_type),
5684 				local_name, PTR_ERR(cands));
5685 			return PTR_ERR(cands);
5686 		}
5687 		err = hashmap__set(cand_cache, local_id, cands, NULL, NULL);
5688 		if (err) {
5689 			bpf_core_free_cands(cands);
5690 			return err;
5691 		}
5692 	}
5693 
5694 	return bpf_core_calc_relo_insn(prog_name, relo, relo_idx, local_btf, cands, specs_scratch,
5695 				       targ_res);
5696 }
5697 
5698 static int
5699 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
5700 {
5701 	const struct btf_ext_info_sec *sec;
5702 	struct bpf_core_relo_res targ_res;
5703 	const struct bpf_core_relo *rec;
5704 	const struct btf_ext_info *seg;
5705 	struct hashmap_entry *entry;
5706 	struct hashmap *cand_cache = NULL;
5707 	struct bpf_program *prog;
5708 	struct bpf_insn *insn;
5709 	const char *sec_name;
5710 	int i, err = 0, insn_idx, sec_idx, sec_num;
5711 
5712 	if (obj->btf_ext->core_relo_info.len == 0)
5713 		return 0;
5714 
5715 	if (targ_btf_path) {
5716 		obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
5717 		err = libbpf_get_error(obj->btf_vmlinux_override);
5718 		if (err) {
5719 			pr_warn("failed to parse target BTF: %d\n", err);
5720 			return err;
5721 		}
5722 	}
5723 
5724 	cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
5725 	if (IS_ERR(cand_cache)) {
5726 		err = PTR_ERR(cand_cache);
5727 		goto out;
5728 	}
5729 
5730 	seg = &obj->btf_ext->core_relo_info;
5731 	sec_num = 0;
5732 	for_each_btf_ext_sec(seg, sec) {
5733 		sec_idx = seg->sec_idxs[sec_num];
5734 		sec_num++;
5735 
5736 		sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
5737 		if (str_is_empty(sec_name)) {
5738 			err = -EINVAL;
5739 			goto out;
5740 		}
5741 
5742 		pr_debug("sec '%s': found %d CO-RE relocations\n", sec_name, sec->num_info);
5743 
5744 		for_each_btf_ext_rec(seg, sec, i, rec) {
5745 			if (rec->insn_off % BPF_INSN_SZ)
5746 				return -EINVAL;
5747 			insn_idx = rec->insn_off / BPF_INSN_SZ;
5748 			prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
5749 			if (!prog) {
5750 				/* When __weak subprog is "overridden" by another instance
5751 				 * of the subprog from a different object file, linker still
5752 				 * appends all the .BTF.ext info that used to belong to that
5753 				 * eliminated subprogram.
5754 				 * This is similar to what x86-64 linker does for relocations.
5755 				 * So just ignore such relocations just like we ignore
5756 				 * subprog instructions when discovering subprograms.
5757 				 */
5758 				pr_debug("sec '%s': skipping CO-RE relocation #%d for insn #%d belonging to eliminated weak subprogram\n",
5759 					 sec_name, i, insn_idx);
5760 				continue;
5761 			}
5762 			/* no need to apply CO-RE relocation if the program is
5763 			 * not going to be loaded
5764 			 */
5765 			if (!prog->autoload)
5766 				continue;
5767 
5768 			/* adjust insn_idx from section frame of reference to the local
5769 			 * program's frame of reference; (sub-)program code is not yet
5770 			 * relocated, so it's enough to just subtract in-section offset
5771 			 */
5772 			insn_idx = insn_idx - prog->sec_insn_off;
5773 			if (insn_idx >= prog->insns_cnt)
5774 				return -EINVAL;
5775 			insn = &prog->insns[insn_idx];
5776 
5777 			err = record_relo_core(prog, rec, insn_idx);
5778 			if (err) {
5779 				pr_warn("prog '%s': relo #%d: failed to record relocation: %d\n",
5780 					prog->name, i, err);
5781 				goto out;
5782 			}
5783 
5784 			if (prog->obj->gen_loader)
5785 				continue;
5786 
5787 			err = bpf_core_resolve_relo(prog, rec, i, obj->btf, cand_cache, &targ_res);
5788 			if (err) {
5789 				pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
5790 					prog->name, i, err);
5791 				goto out;
5792 			}
5793 
5794 			err = bpf_core_patch_insn(prog->name, insn, insn_idx, rec, i, &targ_res);
5795 			if (err) {
5796 				pr_warn("prog '%s': relo #%d: failed to patch insn #%u: %d\n",
5797 					prog->name, i, insn_idx, err);
5798 				goto out;
5799 			}
5800 		}
5801 	}
5802 
5803 out:
5804 	/* obj->btf_vmlinux and module BTFs are freed after object load */
5805 	btf__free(obj->btf_vmlinux_override);
5806 	obj->btf_vmlinux_override = NULL;
5807 
5808 	if (!IS_ERR_OR_NULL(cand_cache)) {
5809 		hashmap__for_each_entry(cand_cache, entry, i) {
5810 			bpf_core_free_cands(entry->pvalue);
5811 		}
5812 		hashmap__free(cand_cache);
5813 	}
5814 	return err;
5815 }
5816 
5817 /* base map load ldimm64 special constant, used also for log fixup logic */
5818 #define POISON_LDIMM64_MAP_BASE 2001000000
5819 #define POISON_LDIMM64_MAP_PFX "200100"
5820 
5821 static void poison_map_ldimm64(struct bpf_program *prog, int relo_idx,
5822 			       int insn_idx, struct bpf_insn *insn,
5823 			       int map_idx, const struct bpf_map *map)
5824 {
5825 	int i;
5826 
5827 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that loads map #%d '%s'\n",
5828 		 prog->name, relo_idx, insn_idx, map_idx, map->name);
5829 
5830 	/* we turn single ldimm64 into two identical invalid calls */
5831 	for (i = 0; i < 2; i++) {
5832 		insn->code = BPF_JMP | BPF_CALL;
5833 		insn->dst_reg = 0;
5834 		insn->src_reg = 0;
5835 		insn->off = 0;
5836 		/* if this instruction is reachable (not a dead code),
5837 		 * verifier will complain with something like:
5838 		 * invalid func unknown#2001000123
5839 		 * where lower 123 is map index into obj->maps[] array
5840 		 */
5841 		insn->imm = POISON_LDIMM64_MAP_BASE + map_idx;
5842 
5843 		insn++;
5844 	}
5845 }
5846 
5847 /* unresolved kfunc call special constant, used also for log fixup logic */
5848 #define POISON_CALL_KFUNC_BASE 2002000000
5849 #define POISON_CALL_KFUNC_PFX "2002"
5850 
5851 static void poison_kfunc_call(struct bpf_program *prog, int relo_idx,
5852 			      int insn_idx, struct bpf_insn *insn,
5853 			      int ext_idx, const struct extern_desc *ext)
5854 {
5855 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that calls kfunc '%s'\n",
5856 		 prog->name, relo_idx, insn_idx, ext->name);
5857 
5858 	/* we turn kfunc call into invalid helper call with identifiable constant */
5859 	insn->code = BPF_JMP | BPF_CALL;
5860 	insn->dst_reg = 0;
5861 	insn->src_reg = 0;
5862 	insn->off = 0;
5863 	/* if this instruction is reachable (not a dead code),
5864 	 * verifier will complain with something like:
5865 	 * invalid func unknown#2001000123
5866 	 * where lower 123 is extern index into obj->externs[] array
5867 	 */
5868 	insn->imm = POISON_CALL_KFUNC_BASE + ext_idx;
5869 }
5870 
5871 /* Relocate data references within program code:
5872  *  - map references;
5873  *  - global variable references;
5874  *  - extern references.
5875  */
5876 static int
5877 bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
5878 {
5879 	int i;
5880 
5881 	for (i = 0; i < prog->nr_reloc; i++) {
5882 		struct reloc_desc *relo = &prog->reloc_desc[i];
5883 		struct bpf_insn *insn = &prog->insns[relo->insn_idx];
5884 		const struct bpf_map *map;
5885 		struct extern_desc *ext;
5886 
5887 		switch (relo->type) {
5888 		case RELO_LD64:
5889 			map = &obj->maps[relo->map_idx];
5890 			if (obj->gen_loader) {
5891 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
5892 				insn[0].imm = relo->map_idx;
5893 			} else if (map->autocreate) {
5894 				insn[0].src_reg = BPF_PSEUDO_MAP_FD;
5895 				insn[0].imm = map->fd;
5896 			} else {
5897 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
5898 						   relo->map_idx, map);
5899 			}
5900 			break;
5901 		case RELO_DATA:
5902 			map = &obj->maps[relo->map_idx];
5903 			insn[1].imm = insn[0].imm + relo->sym_off;
5904 			if (obj->gen_loader) {
5905 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
5906 				insn[0].imm = relo->map_idx;
5907 			} else if (map->autocreate) {
5908 				insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
5909 				insn[0].imm = map->fd;
5910 			} else {
5911 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
5912 						   relo->map_idx, map);
5913 			}
5914 			break;
5915 		case RELO_EXTERN_LD64:
5916 			ext = &obj->externs[relo->ext_idx];
5917 			if (ext->type == EXT_KCFG) {
5918 				if (obj->gen_loader) {
5919 					insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
5920 					insn[0].imm = obj->kconfig_map_idx;
5921 				} else {
5922 					insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
5923 					insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
5924 				}
5925 				insn[1].imm = ext->kcfg.data_off;
5926 			} else /* EXT_KSYM */ {
5927 				if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
5928 					insn[0].src_reg = BPF_PSEUDO_BTF_ID;
5929 					insn[0].imm = ext->ksym.kernel_btf_id;
5930 					insn[1].imm = ext->ksym.kernel_btf_obj_fd;
5931 				} else { /* typeless ksyms or unresolved typed ksyms */
5932 					insn[0].imm = (__u32)ext->ksym.addr;
5933 					insn[1].imm = ext->ksym.addr >> 32;
5934 				}
5935 			}
5936 			break;
5937 		case RELO_EXTERN_CALL:
5938 			ext = &obj->externs[relo->ext_idx];
5939 			insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
5940 			if (ext->is_set) {
5941 				insn[0].imm = ext->ksym.kernel_btf_id;
5942 				insn[0].off = ext->ksym.btf_fd_idx;
5943 			} else { /* unresolved weak kfunc call */
5944 				poison_kfunc_call(prog, i, relo->insn_idx, insn,
5945 						  relo->ext_idx, ext);
5946 			}
5947 			break;
5948 		case RELO_SUBPROG_ADDR:
5949 			if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
5950 				pr_warn("prog '%s': relo #%d: bad insn\n",
5951 					prog->name, i);
5952 				return -EINVAL;
5953 			}
5954 			/* handled already */
5955 			break;
5956 		case RELO_CALL:
5957 			/* handled already */
5958 			break;
5959 		case RELO_CORE:
5960 			/* will be handled by bpf_program_record_relos() */
5961 			break;
5962 		default:
5963 			pr_warn("prog '%s': relo #%d: bad relo type %d\n",
5964 				prog->name, i, relo->type);
5965 			return -EINVAL;
5966 		}
5967 	}
5968 
5969 	return 0;
5970 }
5971 
5972 static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
5973 				    const struct bpf_program *prog,
5974 				    const struct btf_ext_info *ext_info,
5975 				    void **prog_info, __u32 *prog_rec_cnt,
5976 				    __u32 *prog_rec_sz)
5977 {
5978 	void *copy_start = NULL, *copy_end = NULL;
5979 	void *rec, *rec_end, *new_prog_info;
5980 	const struct btf_ext_info_sec *sec;
5981 	size_t old_sz, new_sz;
5982 	int i, sec_num, sec_idx, off_adj;
5983 
5984 	sec_num = 0;
5985 	for_each_btf_ext_sec(ext_info, sec) {
5986 		sec_idx = ext_info->sec_idxs[sec_num];
5987 		sec_num++;
5988 		if (prog->sec_idx != sec_idx)
5989 			continue;
5990 
5991 		for_each_btf_ext_rec(ext_info, sec, i, rec) {
5992 			__u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
5993 
5994 			if (insn_off < prog->sec_insn_off)
5995 				continue;
5996 			if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
5997 				break;
5998 
5999 			if (!copy_start)
6000 				copy_start = rec;
6001 			copy_end = rec + ext_info->rec_size;
6002 		}
6003 
6004 		if (!copy_start)
6005 			return -ENOENT;
6006 
6007 		/* append func/line info of a given (sub-)program to the main
6008 		 * program func/line info
6009 		 */
6010 		old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
6011 		new_sz = old_sz + (copy_end - copy_start);
6012 		new_prog_info = realloc(*prog_info, new_sz);
6013 		if (!new_prog_info)
6014 			return -ENOMEM;
6015 		*prog_info = new_prog_info;
6016 		*prog_rec_cnt = new_sz / ext_info->rec_size;
6017 		memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
6018 
6019 		/* Kernel instruction offsets are in units of 8-byte
6020 		 * instructions, while .BTF.ext instruction offsets generated
6021 		 * by Clang are in units of bytes. So convert Clang offsets
6022 		 * into kernel offsets and adjust offset according to program
6023 		 * relocated position.
6024 		 */
6025 		off_adj = prog->sub_insn_off - prog->sec_insn_off;
6026 		rec = new_prog_info + old_sz;
6027 		rec_end = new_prog_info + new_sz;
6028 		for (; rec < rec_end; rec += ext_info->rec_size) {
6029 			__u32 *insn_off = rec;
6030 
6031 			*insn_off = *insn_off / BPF_INSN_SZ + off_adj;
6032 		}
6033 		*prog_rec_sz = ext_info->rec_size;
6034 		return 0;
6035 	}
6036 
6037 	return -ENOENT;
6038 }
6039 
6040 static int
6041 reloc_prog_func_and_line_info(const struct bpf_object *obj,
6042 			      struct bpf_program *main_prog,
6043 			      const struct bpf_program *prog)
6044 {
6045 	int err;
6046 
6047 	/* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
6048 	 * supprot func/line info
6049 	 */
6050 	if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
6051 		return 0;
6052 
6053 	/* only attempt func info relocation if main program's func_info
6054 	 * relocation was successful
6055 	 */
6056 	if (main_prog != prog && !main_prog->func_info)
6057 		goto line_info;
6058 
6059 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
6060 				       &main_prog->func_info,
6061 				       &main_prog->func_info_cnt,
6062 				       &main_prog->func_info_rec_size);
6063 	if (err) {
6064 		if (err != -ENOENT) {
6065 			pr_warn("prog '%s': error relocating .BTF.ext function info: %d\n",
6066 				prog->name, err);
6067 			return err;
6068 		}
6069 		if (main_prog->func_info) {
6070 			/*
6071 			 * Some info has already been found but has problem
6072 			 * in the last btf_ext reloc. Must have to error out.
6073 			 */
6074 			pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
6075 			return err;
6076 		}
6077 		/* Have problem loading the very first info. Ignore the rest. */
6078 		pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
6079 			prog->name);
6080 	}
6081 
6082 line_info:
6083 	/* don't relocate line info if main program's relocation failed */
6084 	if (main_prog != prog && !main_prog->line_info)
6085 		return 0;
6086 
6087 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
6088 				       &main_prog->line_info,
6089 				       &main_prog->line_info_cnt,
6090 				       &main_prog->line_info_rec_size);
6091 	if (err) {
6092 		if (err != -ENOENT) {
6093 			pr_warn("prog '%s': error relocating .BTF.ext line info: %d\n",
6094 				prog->name, err);
6095 			return err;
6096 		}
6097 		if (main_prog->line_info) {
6098 			/*
6099 			 * Some info has already been found but has problem
6100 			 * in the last btf_ext reloc. Must have to error out.
6101 			 */
6102 			pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
6103 			return err;
6104 		}
6105 		/* Have problem loading the very first info. Ignore the rest. */
6106 		pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
6107 			prog->name);
6108 	}
6109 	return 0;
6110 }
6111 
6112 static int cmp_relo_by_insn_idx(const void *key, const void *elem)
6113 {
6114 	size_t insn_idx = *(const size_t *)key;
6115 	const struct reloc_desc *relo = elem;
6116 
6117 	if (insn_idx == relo->insn_idx)
6118 		return 0;
6119 	return insn_idx < relo->insn_idx ? -1 : 1;
6120 }
6121 
6122 static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
6123 {
6124 	if (!prog->nr_reloc)
6125 		return NULL;
6126 	return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
6127 		       sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
6128 }
6129 
6130 static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
6131 {
6132 	int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
6133 	struct reloc_desc *relos;
6134 	int i;
6135 
6136 	if (main_prog == subprog)
6137 		return 0;
6138 	relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
6139 	if (!relos)
6140 		return -ENOMEM;
6141 	if (subprog->nr_reloc)
6142 		memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
6143 		       sizeof(*relos) * subprog->nr_reloc);
6144 
6145 	for (i = main_prog->nr_reloc; i < new_cnt; i++)
6146 		relos[i].insn_idx += subprog->sub_insn_off;
6147 	/* After insn_idx adjustment the 'relos' array is still sorted
6148 	 * by insn_idx and doesn't break bsearch.
6149 	 */
6150 	main_prog->reloc_desc = relos;
6151 	main_prog->nr_reloc = new_cnt;
6152 	return 0;
6153 }
6154 
6155 static int
6156 bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
6157 		       struct bpf_program *prog)
6158 {
6159 	size_t sub_insn_idx, insn_idx, new_cnt;
6160 	struct bpf_program *subprog;
6161 	struct bpf_insn *insns, *insn;
6162 	struct reloc_desc *relo;
6163 	int err;
6164 
6165 	err = reloc_prog_func_and_line_info(obj, main_prog, prog);
6166 	if (err)
6167 		return err;
6168 
6169 	for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
6170 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6171 		if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
6172 			continue;
6173 
6174 		relo = find_prog_insn_relo(prog, insn_idx);
6175 		if (relo && relo->type == RELO_EXTERN_CALL)
6176 			/* kfunc relocations will be handled later
6177 			 * in bpf_object__relocate_data()
6178 			 */
6179 			continue;
6180 		if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
6181 			pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
6182 				prog->name, insn_idx, relo->type);
6183 			return -LIBBPF_ERRNO__RELOC;
6184 		}
6185 		if (relo) {
6186 			/* sub-program instruction index is a combination of
6187 			 * an offset of a symbol pointed to by relocation and
6188 			 * call instruction's imm field; for global functions,
6189 			 * call always has imm = -1, but for static functions
6190 			 * relocation is against STT_SECTION and insn->imm
6191 			 * points to a start of a static function
6192 			 *
6193 			 * for subprog addr relocation, the relo->sym_off + insn->imm is
6194 			 * the byte offset in the corresponding section.
6195 			 */
6196 			if (relo->type == RELO_CALL)
6197 				sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
6198 			else
6199 				sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
6200 		} else if (insn_is_pseudo_func(insn)) {
6201 			/*
6202 			 * RELO_SUBPROG_ADDR relo is always emitted even if both
6203 			 * functions are in the same section, so it shouldn't reach here.
6204 			 */
6205 			pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
6206 				prog->name, insn_idx);
6207 			return -LIBBPF_ERRNO__RELOC;
6208 		} else {
6209 			/* if subprogram call is to a static function within
6210 			 * the same ELF section, there won't be any relocation
6211 			 * emitted, but it also means there is no additional
6212 			 * offset necessary, insns->imm is relative to
6213 			 * instruction's original position within the section
6214 			 */
6215 			sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
6216 		}
6217 
6218 		/* we enforce that sub-programs should be in .text section */
6219 		subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
6220 		if (!subprog) {
6221 			pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
6222 				prog->name);
6223 			return -LIBBPF_ERRNO__RELOC;
6224 		}
6225 
6226 		/* if it's the first call instruction calling into this
6227 		 * subprogram (meaning this subprog hasn't been processed
6228 		 * yet) within the context of current main program:
6229 		 *   - append it at the end of main program's instructions blog;
6230 		 *   - process is recursively, while current program is put on hold;
6231 		 *   - if that subprogram calls some other not yet processes
6232 		 *   subprogram, same thing will happen recursively until
6233 		 *   there are no more unprocesses subprograms left to append
6234 		 *   and relocate.
6235 		 */
6236 		if (subprog->sub_insn_off == 0) {
6237 			subprog->sub_insn_off = main_prog->insns_cnt;
6238 
6239 			new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
6240 			insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
6241 			if (!insns) {
6242 				pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
6243 				return -ENOMEM;
6244 			}
6245 			main_prog->insns = insns;
6246 			main_prog->insns_cnt = new_cnt;
6247 
6248 			memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
6249 			       subprog->insns_cnt * sizeof(*insns));
6250 
6251 			pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
6252 				 main_prog->name, subprog->insns_cnt, subprog->name);
6253 
6254 			/* The subprog insns are now appended. Append its relos too. */
6255 			err = append_subprog_relos(main_prog, subprog);
6256 			if (err)
6257 				return err;
6258 			err = bpf_object__reloc_code(obj, main_prog, subprog);
6259 			if (err)
6260 				return err;
6261 		}
6262 
6263 		/* main_prog->insns memory could have been re-allocated, so
6264 		 * calculate pointer again
6265 		 */
6266 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6267 		/* calculate correct instruction position within current main
6268 		 * prog; each main prog can have a different set of
6269 		 * subprograms appended (potentially in different order as
6270 		 * well), so position of any subprog can be different for
6271 		 * different main programs
6272 		 */
6273 		insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
6274 
6275 		pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
6276 			 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
6277 	}
6278 
6279 	return 0;
6280 }
6281 
6282 /*
6283  * Relocate sub-program calls.
6284  *
6285  * Algorithm operates as follows. Each entry-point BPF program (referred to as
6286  * main prog) is processed separately. For each subprog (non-entry functions,
6287  * that can be called from either entry progs or other subprogs) gets their
6288  * sub_insn_off reset to zero. This serves as indicator that this subprogram
6289  * hasn't been yet appended and relocated within current main prog. Once its
6290  * relocated, sub_insn_off will point at the position within current main prog
6291  * where given subprog was appended. This will further be used to relocate all
6292  * the call instructions jumping into this subprog.
6293  *
6294  * We start with main program and process all call instructions. If the call
6295  * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
6296  * is zero), subprog instructions are appended at the end of main program's
6297  * instruction array. Then main program is "put on hold" while we recursively
6298  * process newly appended subprogram. If that subprogram calls into another
6299  * subprogram that hasn't been appended, new subprogram is appended again to
6300  * the *main* prog's instructions (subprog's instructions are always left
6301  * untouched, as they need to be in unmodified state for subsequent main progs
6302  * and subprog instructions are always sent only as part of a main prog) and
6303  * the process continues recursively. Once all the subprogs called from a main
6304  * prog or any of its subprogs are appended (and relocated), all their
6305  * positions within finalized instructions array are known, so it's easy to
6306  * rewrite call instructions with correct relative offsets, corresponding to
6307  * desired target subprog.
6308  *
6309  * Its important to realize that some subprogs might not be called from some
6310  * main prog and any of its called/used subprogs. Those will keep their
6311  * subprog->sub_insn_off as zero at all times and won't be appended to current
6312  * main prog and won't be relocated within the context of current main prog.
6313  * They might still be used from other main progs later.
6314  *
6315  * Visually this process can be shown as below. Suppose we have two main
6316  * programs mainA and mainB and BPF object contains three subprogs: subA,
6317  * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
6318  * subC both call subB:
6319  *
6320  *        +--------+ +-------+
6321  *        |        v v       |
6322  *     +--+---+ +--+-+-+ +---+--+
6323  *     | subA | | subB | | subC |
6324  *     +--+---+ +------+ +---+--+
6325  *        ^                  ^
6326  *        |                  |
6327  *    +---+-------+   +------+----+
6328  *    |   mainA   |   |   mainB   |
6329  *    +-----------+   +-----------+
6330  *
6331  * We'll start relocating mainA, will find subA, append it and start
6332  * processing sub A recursively:
6333  *
6334  *    +-----------+------+
6335  *    |   mainA   | subA |
6336  *    +-----------+------+
6337  *
6338  * At this point we notice that subB is used from subA, so we append it and
6339  * relocate (there are no further subcalls from subB):
6340  *
6341  *    +-----------+------+------+
6342  *    |   mainA   | subA | subB |
6343  *    +-----------+------+------+
6344  *
6345  * At this point, we relocate subA calls, then go one level up and finish with
6346  * relocatin mainA calls. mainA is done.
6347  *
6348  * For mainB process is similar but results in different order. We start with
6349  * mainB and skip subA and subB, as mainB never calls them (at least
6350  * directly), but we see subC is needed, so we append and start processing it:
6351  *
6352  *    +-----------+------+
6353  *    |   mainB   | subC |
6354  *    +-----------+------+
6355  * Now we see subC needs subB, so we go back to it, append and relocate it:
6356  *
6357  *    +-----------+------+------+
6358  *    |   mainB   | subC | subB |
6359  *    +-----------+------+------+
6360  *
6361  * At this point we unwind recursion, relocate calls in subC, then in mainB.
6362  */
6363 static int
6364 bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
6365 {
6366 	struct bpf_program *subprog;
6367 	int i, err;
6368 
6369 	/* mark all subprogs as not relocated (yet) within the context of
6370 	 * current main program
6371 	 */
6372 	for (i = 0; i < obj->nr_programs; i++) {
6373 		subprog = &obj->programs[i];
6374 		if (!prog_is_subprog(obj, subprog))
6375 			continue;
6376 
6377 		subprog->sub_insn_off = 0;
6378 	}
6379 
6380 	err = bpf_object__reloc_code(obj, prog, prog);
6381 	if (err)
6382 		return err;
6383 
6384 	return 0;
6385 }
6386 
6387 static void
6388 bpf_object__free_relocs(struct bpf_object *obj)
6389 {
6390 	struct bpf_program *prog;
6391 	int i;
6392 
6393 	/* free up relocation descriptors */
6394 	for (i = 0; i < obj->nr_programs; i++) {
6395 		prog = &obj->programs[i];
6396 		zfree(&prog->reloc_desc);
6397 		prog->nr_reloc = 0;
6398 	}
6399 }
6400 
6401 static int cmp_relocs(const void *_a, const void *_b)
6402 {
6403 	const struct reloc_desc *a = _a;
6404 	const struct reloc_desc *b = _b;
6405 
6406 	if (a->insn_idx != b->insn_idx)
6407 		return a->insn_idx < b->insn_idx ? -1 : 1;
6408 
6409 	/* no two relocations should have the same insn_idx, but ... */
6410 	if (a->type != b->type)
6411 		return a->type < b->type ? -1 : 1;
6412 
6413 	return 0;
6414 }
6415 
6416 static void bpf_object__sort_relos(struct bpf_object *obj)
6417 {
6418 	int i;
6419 
6420 	for (i = 0; i < obj->nr_programs; i++) {
6421 		struct bpf_program *p = &obj->programs[i];
6422 
6423 		if (!p->nr_reloc)
6424 			continue;
6425 
6426 		qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
6427 	}
6428 }
6429 
6430 static int
6431 bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
6432 {
6433 	struct bpf_program *prog;
6434 	size_t i, j;
6435 	int err;
6436 
6437 	if (obj->btf_ext) {
6438 		err = bpf_object__relocate_core(obj, targ_btf_path);
6439 		if (err) {
6440 			pr_warn("failed to perform CO-RE relocations: %d\n",
6441 				err);
6442 			return err;
6443 		}
6444 		bpf_object__sort_relos(obj);
6445 	}
6446 
6447 	/* Before relocating calls pre-process relocations and mark
6448 	 * few ld_imm64 instructions that points to subprogs.
6449 	 * Otherwise bpf_object__reloc_code() later would have to consider
6450 	 * all ld_imm64 insns as relocation candidates. That would
6451 	 * reduce relocation speed, since amount of find_prog_insn_relo()
6452 	 * would increase and most of them will fail to find a relo.
6453 	 */
6454 	for (i = 0; i < obj->nr_programs; i++) {
6455 		prog = &obj->programs[i];
6456 		for (j = 0; j < prog->nr_reloc; j++) {
6457 			struct reloc_desc *relo = &prog->reloc_desc[j];
6458 			struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6459 
6460 			/* mark the insn, so it's recognized by insn_is_pseudo_func() */
6461 			if (relo->type == RELO_SUBPROG_ADDR)
6462 				insn[0].src_reg = BPF_PSEUDO_FUNC;
6463 		}
6464 	}
6465 
6466 	/* relocate subprogram calls and append used subprograms to main
6467 	 * programs; each copy of subprogram code needs to be relocated
6468 	 * differently for each main program, because its code location might
6469 	 * have changed.
6470 	 * Append subprog relos to main programs to allow data relos to be
6471 	 * processed after text is completely relocated.
6472 	 */
6473 	for (i = 0; i < obj->nr_programs; i++) {
6474 		prog = &obj->programs[i];
6475 		/* sub-program's sub-calls are relocated within the context of
6476 		 * its main program only
6477 		 */
6478 		if (prog_is_subprog(obj, prog))
6479 			continue;
6480 		if (!prog->autoload)
6481 			continue;
6482 
6483 		err = bpf_object__relocate_calls(obj, prog);
6484 		if (err) {
6485 			pr_warn("prog '%s': failed to relocate calls: %d\n",
6486 				prog->name, err);
6487 			return err;
6488 		}
6489 	}
6490 	/* Process data relos for main programs */
6491 	for (i = 0; i < obj->nr_programs; i++) {
6492 		prog = &obj->programs[i];
6493 		if (prog_is_subprog(obj, prog))
6494 			continue;
6495 		if (!prog->autoload)
6496 			continue;
6497 		err = bpf_object__relocate_data(obj, prog);
6498 		if (err) {
6499 			pr_warn("prog '%s': failed to relocate data references: %d\n",
6500 				prog->name, err);
6501 			return err;
6502 		}
6503 	}
6504 
6505 	return 0;
6506 }
6507 
6508 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
6509 					    Elf64_Shdr *shdr, Elf_Data *data);
6510 
6511 static int bpf_object__collect_map_relos(struct bpf_object *obj,
6512 					 Elf64_Shdr *shdr, Elf_Data *data)
6513 {
6514 	const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
6515 	int i, j, nrels, new_sz;
6516 	const struct btf_var_secinfo *vi = NULL;
6517 	const struct btf_type *sec, *var, *def;
6518 	struct bpf_map *map = NULL, *targ_map = NULL;
6519 	struct bpf_program *targ_prog = NULL;
6520 	bool is_prog_array, is_map_in_map;
6521 	const struct btf_member *member;
6522 	const char *name, *mname, *type;
6523 	unsigned int moff;
6524 	Elf64_Sym *sym;
6525 	Elf64_Rel *rel;
6526 	void *tmp;
6527 
6528 	if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
6529 		return -EINVAL;
6530 	sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
6531 	if (!sec)
6532 		return -EINVAL;
6533 
6534 	nrels = shdr->sh_size / shdr->sh_entsize;
6535 	for (i = 0; i < nrels; i++) {
6536 		rel = elf_rel_by_idx(data, i);
6537 		if (!rel) {
6538 			pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
6539 			return -LIBBPF_ERRNO__FORMAT;
6540 		}
6541 
6542 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
6543 		if (!sym) {
6544 			pr_warn(".maps relo #%d: symbol %zx not found\n",
6545 				i, (size_t)ELF64_R_SYM(rel->r_info));
6546 			return -LIBBPF_ERRNO__FORMAT;
6547 		}
6548 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
6549 
6550 		pr_debug(".maps relo #%d: for %zd value %zd rel->r_offset %zu name %d ('%s')\n",
6551 			 i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
6552 			 (size_t)rel->r_offset, sym->st_name, name);
6553 
6554 		for (j = 0; j < obj->nr_maps; j++) {
6555 			map = &obj->maps[j];
6556 			if (map->sec_idx != obj->efile.btf_maps_shndx)
6557 				continue;
6558 
6559 			vi = btf_var_secinfos(sec) + map->btf_var_idx;
6560 			if (vi->offset <= rel->r_offset &&
6561 			    rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size)
6562 				break;
6563 		}
6564 		if (j == obj->nr_maps) {
6565 			pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
6566 				i, name, (size_t)rel->r_offset);
6567 			return -EINVAL;
6568 		}
6569 
6570 		is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
6571 		is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
6572 		type = is_map_in_map ? "map" : "prog";
6573 		if (is_map_in_map) {
6574 			if (sym->st_shndx != obj->efile.btf_maps_shndx) {
6575 				pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
6576 					i, name);
6577 				return -LIBBPF_ERRNO__RELOC;
6578 			}
6579 			if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
6580 			    map->def.key_size != sizeof(int)) {
6581 				pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
6582 					i, map->name, sizeof(int));
6583 				return -EINVAL;
6584 			}
6585 			targ_map = bpf_object__find_map_by_name(obj, name);
6586 			if (!targ_map) {
6587 				pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
6588 					i, name);
6589 				return -ESRCH;
6590 			}
6591 		} else if (is_prog_array) {
6592 			targ_prog = bpf_object__find_program_by_name(obj, name);
6593 			if (!targ_prog) {
6594 				pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
6595 					i, name);
6596 				return -ESRCH;
6597 			}
6598 			if (targ_prog->sec_idx != sym->st_shndx ||
6599 			    targ_prog->sec_insn_off * 8 != sym->st_value ||
6600 			    prog_is_subprog(obj, targ_prog)) {
6601 				pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
6602 					i, name);
6603 				return -LIBBPF_ERRNO__RELOC;
6604 			}
6605 		} else {
6606 			return -EINVAL;
6607 		}
6608 
6609 		var = btf__type_by_id(obj->btf, vi->type);
6610 		def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
6611 		if (btf_vlen(def) == 0)
6612 			return -EINVAL;
6613 		member = btf_members(def) + btf_vlen(def) - 1;
6614 		mname = btf__name_by_offset(obj->btf, member->name_off);
6615 		if (strcmp(mname, "values"))
6616 			return -EINVAL;
6617 
6618 		moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
6619 		if (rel->r_offset - vi->offset < moff)
6620 			return -EINVAL;
6621 
6622 		moff = rel->r_offset - vi->offset - moff;
6623 		/* here we use BPF pointer size, which is always 64 bit, as we
6624 		 * are parsing ELF that was built for BPF target
6625 		 */
6626 		if (moff % bpf_ptr_sz)
6627 			return -EINVAL;
6628 		moff /= bpf_ptr_sz;
6629 		if (moff >= map->init_slots_sz) {
6630 			new_sz = moff + 1;
6631 			tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
6632 			if (!tmp)
6633 				return -ENOMEM;
6634 			map->init_slots = tmp;
6635 			memset(map->init_slots + map->init_slots_sz, 0,
6636 			       (new_sz - map->init_slots_sz) * host_ptr_sz);
6637 			map->init_slots_sz = new_sz;
6638 		}
6639 		map->init_slots[moff] = is_map_in_map ? (void *)targ_map : (void *)targ_prog;
6640 
6641 		pr_debug(".maps relo #%d: map '%s' slot [%d] points to %s '%s'\n",
6642 			 i, map->name, moff, type, name);
6643 	}
6644 
6645 	return 0;
6646 }
6647 
6648 static int bpf_object__collect_relos(struct bpf_object *obj)
6649 {
6650 	int i, err;
6651 
6652 	for (i = 0; i < obj->efile.sec_cnt; i++) {
6653 		struct elf_sec_desc *sec_desc = &obj->efile.secs[i];
6654 		Elf64_Shdr *shdr;
6655 		Elf_Data *data;
6656 		int idx;
6657 
6658 		if (sec_desc->sec_type != SEC_RELO)
6659 			continue;
6660 
6661 		shdr = sec_desc->shdr;
6662 		data = sec_desc->data;
6663 		idx = shdr->sh_info;
6664 
6665 		if (shdr->sh_type != SHT_REL) {
6666 			pr_warn("internal error at %d\n", __LINE__);
6667 			return -LIBBPF_ERRNO__INTERNAL;
6668 		}
6669 
6670 		if (idx == obj->efile.st_ops_shndx || idx == obj->efile.st_ops_link_shndx)
6671 			err = bpf_object__collect_st_ops_relos(obj, shdr, data);
6672 		else if (idx == obj->efile.btf_maps_shndx)
6673 			err = bpf_object__collect_map_relos(obj, shdr, data);
6674 		else
6675 			err = bpf_object__collect_prog_relos(obj, shdr, data);
6676 		if (err)
6677 			return err;
6678 	}
6679 
6680 	bpf_object__sort_relos(obj);
6681 	return 0;
6682 }
6683 
6684 static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
6685 {
6686 	if (BPF_CLASS(insn->code) == BPF_JMP &&
6687 	    BPF_OP(insn->code) == BPF_CALL &&
6688 	    BPF_SRC(insn->code) == BPF_K &&
6689 	    insn->src_reg == 0 &&
6690 	    insn->dst_reg == 0) {
6691 		    *func_id = insn->imm;
6692 		    return true;
6693 	}
6694 	return false;
6695 }
6696 
6697 static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
6698 {
6699 	struct bpf_insn *insn = prog->insns;
6700 	enum bpf_func_id func_id;
6701 	int i;
6702 
6703 	if (obj->gen_loader)
6704 		return 0;
6705 
6706 	for (i = 0; i < prog->insns_cnt; i++, insn++) {
6707 		if (!insn_is_helper_call(insn, &func_id))
6708 			continue;
6709 
6710 		/* on kernels that don't yet support
6711 		 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
6712 		 * to bpf_probe_read() which works well for old kernels
6713 		 */
6714 		switch (func_id) {
6715 		case BPF_FUNC_probe_read_kernel:
6716 		case BPF_FUNC_probe_read_user:
6717 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6718 				insn->imm = BPF_FUNC_probe_read;
6719 			break;
6720 		case BPF_FUNC_probe_read_kernel_str:
6721 		case BPF_FUNC_probe_read_user_str:
6722 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6723 				insn->imm = BPF_FUNC_probe_read_str;
6724 			break;
6725 		default:
6726 			break;
6727 		}
6728 	}
6729 	return 0;
6730 }
6731 
6732 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
6733 				     int *btf_obj_fd, int *btf_type_id);
6734 
6735 /* this is called as prog->sec_def->prog_prepare_load_fn for libbpf-supported sec_defs */
6736 static int libbpf_prepare_prog_load(struct bpf_program *prog,
6737 				    struct bpf_prog_load_opts *opts, long cookie)
6738 {
6739 	enum sec_def_flags def = cookie;
6740 
6741 	/* old kernels might not support specifying expected_attach_type */
6742 	if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
6743 		opts->expected_attach_type = 0;
6744 
6745 	if (def & SEC_SLEEPABLE)
6746 		opts->prog_flags |= BPF_F_SLEEPABLE;
6747 
6748 	if (prog->type == BPF_PROG_TYPE_XDP && (def & SEC_XDP_FRAGS))
6749 		opts->prog_flags |= BPF_F_XDP_HAS_FRAGS;
6750 
6751 	if ((def & SEC_ATTACH_BTF) && !prog->attach_btf_id) {
6752 		int btf_obj_fd = 0, btf_type_id = 0, err;
6753 		const char *attach_name;
6754 
6755 		attach_name = strchr(prog->sec_name, '/');
6756 		if (!attach_name) {
6757 			/* if BPF program is annotated with just SEC("fentry")
6758 			 * (or similar) without declaratively specifying
6759 			 * target, then it is expected that target will be
6760 			 * specified with bpf_program__set_attach_target() at
6761 			 * runtime before BPF object load step. If not, then
6762 			 * there is nothing to load into the kernel as BPF
6763 			 * verifier won't be able to validate BPF program
6764 			 * correctness anyways.
6765 			 */
6766 			pr_warn("prog '%s': no BTF-based attach target is specified, use bpf_program__set_attach_target()\n",
6767 				prog->name);
6768 			return -EINVAL;
6769 		}
6770 		attach_name++; /* skip over / */
6771 
6772 		err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
6773 		if (err)
6774 			return err;
6775 
6776 		/* cache resolved BTF FD and BTF type ID in the prog */
6777 		prog->attach_btf_obj_fd = btf_obj_fd;
6778 		prog->attach_btf_id = btf_type_id;
6779 
6780 		/* but by now libbpf common logic is not utilizing
6781 		 * prog->atach_btf_obj_fd/prog->attach_btf_id anymore because
6782 		 * this callback is called after opts were populated by
6783 		 * libbpf, so this callback has to update opts explicitly here
6784 		 */
6785 		opts->attach_btf_obj_fd = btf_obj_fd;
6786 		opts->attach_btf_id = btf_type_id;
6787 	}
6788 	return 0;
6789 }
6790 
6791 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz);
6792 
6793 static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
6794 				struct bpf_insn *insns, int insns_cnt,
6795 				const char *license, __u32 kern_version, int *prog_fd)
6796 {
6797 	LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
6798 	const char *prog_name = NULL;
6799 	char *cp, errmsg[STRERR_BUFSIZE];
6800 	size_t log_buf_size = 0;
6801 	char *log_buf = NULL, *tmp;
6802 	int btf_fd, ret, err;
6803 	bool own_log_buf = true;
6804 	__u32 log_level = prog->log_level;
6805 
6806 	if (prog->type == BPF_PROG_TYPE_UNSPEC) {
6807 		/*
6808 		 * The program type must be set.  Most likely we couldn't find a proper
6809 		 * section definition at load time, and thus we didn't infer the type.
6810 		 */
6811 		pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
6812 			prog->name, prog->sec_name);
6813 		return -EINVAL;
6814 	}
6815 
6816 	if (!insns || !insns_cnt)
6817 		return -EINVAL;
6818 
6819 	load_attr.expected_attach_type = prog->expected_attach_type;
6820 	if (kernel_supports(obj, FEAT_PROG_NAME))
6821 		prog_name = prog->name;
6822 	load_attr.attach_prog_fd = prog->attach_prog_fd;
6823 	load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
6824 	load_attr.attach_btf_id = prog->attach_btf_id;
6825 	load_attr.kern_version = kern_version;
6826 	load_attr.prog_ifindex = prog->prog_ifindex;
6827 
6828 	/* specify func_info/line_info only if kernel supports them */
6829 	btf_fd = bpf_object__btf_fd(obj);
6830 	if (btf_fd >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
6831 		load_attr.prog_btf_fd = btf_fd;
6832 		load_attr.func_info = prog->func_info;
6833 		load_attr.func_info_rec_size = prog->func_info_rec_size;
6834 		load_attr.func_info_cnt = prog->func_info_cnt;
6835 		load_attr.line_info = prog->line_info;
6836 		load_attr.line_info_rec_size = prog->line_info_rec_size;
6837 		load_attr.line_info_cnt = prog->line_info_cnt;
6838 	}
6839 	load_attr.log_level = log_level;
6840 	load_attr.prog_flags = prog->prog_flags;
6841 	load_attr.fd_array = obj->fd_array;
6842 
6843 	/* adjust load_attr if sec_def provides custom preload callback */
6844 	if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
6845 		err = prog->sec_def->prog_prepare_load_fn(prog, &load_attr, prog->sec_def->cookie);
6846 		if (err < 0) {
6847 			pr_warn("prog '%s': failed to prepare load attributes: %d\n",
6848 				prog->name, err);
6849 			return err;
6850 		}
6851 		insns = prog->insns;
6852 		insns_cnt = prog->insns_cnt;
6853 	}
6854 
6855 	if (obj->gen_loader) {
6856 		bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
6857 				   license, insns, insns_cnt, &load_attr,
6858 				   prog - obj->programs);
6859 		*prog_fd = -1;
6860 		return 0;
6861 	}
6862 
6863 retry_load:
6864 	/* if log_level is zero, we don't request logs initially even if
6865 	 * custom log_buf is specified; if the program load fails, then we'll
6866 	 * bump log_level to 1 and use either custom log_buf or we'll allocate
6867 	 * our own and retry the load to get details on what failed
6868 	 */
6869 	if (log_level) {
6870 		if (prog->log_buf) {
6871 			log_buf = prog->log_buf;
6872 			log_buf_size = prog->log_size;
6873 			own_log_buf = false;
6874 		} else if (obj->log_buf) {
6875 			log_buf = obj->log_buf;
6876 			log_buf_size = obj->log_size;
6877 			own_log_buf = false;
6878 		} else {
6879 			log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
6880 			tmp = realloc(log_buf, log_buf_size);
6881 			if (!tmp) {
6882 				ret = -ENOMEM;
6883 				goto out;
6884 			}
6885 			log_buf = tmp;
6886 			log_buf[0] = '\0';
6887 			own_log_buf = true;
6888 		}
6889 	}
6890 
6891 	load_attr.log_buf = log_buf;
6892 	load_attr.log_size = log_buf_size;
6893 	load_attr.log_level = log_level;
6894 
6895 	ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
6896 	if (ret >= 0) {
6897 		if (log_level && own_log_buf) {
6898 			pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
6899 				 prog->name, log_buf);
6900 		}
6901 
6902 		if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
6903 			struct bpf_map *map;
6904 			int i;
6905 
6906 			for (i = 0; i < obj->nr_maps; i++) {
6907 				map = &prog->obj->maps[i];
6908 				if (map->libbpf_type != LIBBPF_MAP_RODATA)
6909 					continue;
6910 
6911 				if (bpf_prog_bind_map(ret, bpf_map__fd(map), NULL)) {
6912 					cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
6913 					pr_warn("prog '%s': failed to bind map '%s': %s\n",
6914 						prog->name, map->real_name, cp);
6915 					/* Don't fail hard if can't bind rodata. */
6916 				}
6917 			}
6918 		}
6919 
6920 		*prog_fd = ret;
6921 		ret = 0;
6922 		goto out;
6923 	}
6924 
6925 	if (log_level == 0) {
6926 		log_level = 1;
6927 		goto retry_load;
6928 	}
6929 	/* On ENOSPC, increase log buffer size and retry, unless custom
6930 	 * log_buf is specified.
6931 	 * Be careful to not overflow u32, though. Kernel's log buf size limit
6932 	 * isn't part of UAPI so it can always be bumped to full 4GB. So don't
6933 	 * multiply by 2 unless we are sure we'll fit within 32 bits.
6934 	 * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
6935 	 */
6936 	if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
6937 		goto retry_load;
6938 
6939 	ret = -errno;
6940 
6941 	/* post-process verifier log to improve error descriptions */
6942 	fixup_verifier_log(prog, log_buf, log_buf_size);
6943 
6944 	cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
6945 	pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, cp);
6946 	pr_perm_msg(ret);
6947 
6948 	if (own_log_buf && log_buf && log_buf[0] != '\0') {
6949 		pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
6950 			prog->name, log_buf);
6951 	}
6952 
6953 out:
6954 	if (own_log_buf)
6955 		free(log_buf);
6956 	return ret;
6957 }
6958 
6959 static char *find_prev_line(char *buf, char *cur)
6960 {
6961 	char *p;
6962 
6963 	if (cur == buf) /* end of a log buf */
6964 		return NULL;
6965 
6966 	p = cur - 1;
6967 	while (p - 1 >= buf && *(p - 1) != '\n')
6968 		p--;
6969 
6970 	return p;
6971 }
6972 
6973 static void patch_log(char *buf, size_t buf_sz, size_t log_sz,
6974 		      char *orig, size_t orig_sz, const char *patch)
6975 {
6976 	/* size of the remaining log content to the right from the to-be-replaced part */
6977 	size_t rem_sz = (buf + log_sz) - (orig + orig_sz);
6978 	size_t patch_sz = strlen(patch);
6979 
6980 	if (patch_sz != orig_sz) {
6981 		/* If patch line(s) are longer than original piece of verifier log,
6982 		 * shift log contents by (patch_sz - orig_sz) bytes to the right
6983 		 * starting from after to-be-replaced part of the log.
6984 		 *
6985 		 * If patch line(s) are shorter than original piece of verifier log,
6986 		 * shift log contents by (orig_sz - patch_sz) bytes to the left
6987 		 * starting from after to-be-replaced part of the log
6988 		 *
6989 		 * We need to be careful about not overflowing available
6990 		 * buf_sz capacity. If that's the case, we'll truncate the end
6991 		 * of the original log, as necessary.
6992 		 */
6993 		if (patch_sz > orig_sz) {
6994 			if (orig + patch_sz >= buf + buf_sz) {
6995 				/* patch is big enough to cover remaining space completely */
6996 				patch_sz -= (orig + patch_sz) - (buf + buf_sz) + 1;
6997 				rem_sz = 0;
6998 			} else if (patch_sz - orig_sz > buf_sz - log_sz) {
6999 				/* patch causes part of remaining log to be truncated */
7000 				rem_sz -= (patch_sz - orig_sz) - (buf_sz - log_sz);
7001 			}
7002 		}
7003 		/* shift remaining log to the right by calculated amount */
7004 		memmove(orig + patch_sz, orig + orig_sz, rem_sz);
7005 	}
7006 
7007 	memcpy(orig, patch, patch_sz);
7008 }
7009 
7010 static void fixup_log_failed_core_relo(struct bpf_program *prog,
7011 				       char *buf, size_t buf_sz, size_t log_sz,
7012 				       char *line1, char *line2, char *line3)
7013 {
7014 	/* Expected log for failed and not properly guarded CO-RE relocation:
7015 	 * line1 -> 123: (85) call unknown#195896080
7016 	 * line2 -> invalid func unknown#195896080
7017 	 * line3 -> <anything else or end of buffer>
7018 	 *
7019 	 * "123" is the index of the instruction that was poisoned. We extract
7020 	 * instruction index to find corresponding CO-RE relocation and
7021 	 * replace this part of the log with more relevant information about
7022 	 * failed CO-RE relocation.
7023 	 */
7024 	const struct bpf_core_relo *relo;
7025 	struct bpf_core_spec spec;
7026 	char patch[512], spec_buf[256];
7027 	int insn_idx, err, spec_len;
7028 
7029 	if (sscanf(line1, "%d: (%*d) call unknown#195896080\n", &insn_idx) != 1)
7030 		return;
7031 
7032 	relo = find_relo_core(prog, insn_idx);
7033 	if (!relo)
7034 		return;
7035 
7036 	err = bpf_core_parse_spec(prog->name, prog->obj->btf, relo, &spec);
7037 	if (err)
7038 		return;
7039 
7040 	spec_len = bpf_core_format_spec(spec_buf, sizeof(spec_buf), &spec);
7041 	snprintf(patch, sizeof(patch),
7042 		 "%d: <invalid CO-RE relocation>\n"
7043 		 "failed to resolve CO-RE relocation %s%s\n",
7044 		 insn_idx, spec_buf, spec_len >= sizeof(spec_buf) ? "..." : "");
7045 
7046 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7047 }
7048 
7049 static void fixup_log_missing_map_load(struct bpf_program *prog,
7050 				       char *buf, size_t buf_sz, size_t log_sz,
7051 				       char *line1, char *line2, char *line3)
7052 {
7053 	/* Expected log for failed and not properly guarded map reference:
7054 	 * line1 -> 123: (85) call unknown#2001000345
7055 	 * line2 -> invalid func unknown#2001000345
7056 	 * line3 -> <anything else or end of buffer>
7057 	 *
7058 	 * "123" is the index of the instruction that was poisoned.
7059 	 * "345" in "2001000345" is a map index in obj->maps to fetch map name.
7060 	 */
7061 	struct bpf_object *obj = prog->obj;
7062 	const struct bpf_map *map;
7063 	int insn_idx, map_idx;
7064 	char patch[128];
7065 
7066 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &map_idx) != 2)
7067 		return;
7068 
7069 	map_idx -= POISON_LDIMM64_MAP_BASE;
7070 	if (map_idx < 0 || map_idx >= obj->nr_maps)
7071 		return;
7072 	map = &obj->maps[map_idx];
7073 
7074 	snprintf(patch, sizeof(patch),
7075 		 "%d: <invalid BPF map reference>\n"
7076 		 "BPF map '%s' is referenced but wasn't created\n",
7077 		 insn_idx, map->name);
7078 
7079 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7080 }
7081 
7082 static void fixup_log_missing_kfunc_call(struct bpf_program *prog,
7083 					 char *buf, size_t buf_sz, size_t log_sz,
7084 					 char *line1, char *line2, char *line3)
7085 {
7086 	/* Expected log for failed and not properly guarded kfunc call:
7087 	 * line1 -> 123: (85) call unknown#2002000345
7088 	 * line2 -> invalid func unknown#2002000345
7089 	 * line3 -> <anything else or end of buffer>
7090 	 *
7091 	 * "123" is the index of the instruction that was poisoned.
7092 	 * "345" in "2002000345" is an extern index in obj->externs to fetch kfunc name.
7093 	 */
7094 	struct bpf_object *obj = prog->obj;
7095 	const struct extern_desc *ext;
7096 	int insn_idx, ext_idx;
7097 	char patch[128];
7098 
7099 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &ext_idx) != 2)
7100 		return;
7101 
7102 	ext_idx -= POISON_CALL_KFUNC_BASE;
7103 	if (ext_idx < 0 || ext_idx >= obj->nr_extern)
7104 		return;
7105 	ext = &obj->externs[ext_idx];
7106 
7107 	snprintf(patch, sizeof(patch),
7108 		 "%d: <invalid kfunc call>\n"
7109 		 "kfunc '%s' is referenced but wasn't resolved\n",
7110 		 insn_idx, ext->name);
7111 
7112 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7113 }
7114 
7115 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz)
7116 {
7117 	/* look for familiar error patterns in last N lines of the log */
7118 	const size_t max_last_line_cnt = 10;
7119 	char *prev_line, *cur_line, *next_line;
7120 	size_t log_sz;
7121 	int i;
7122 
7123 	if (!buf)
7124 		return;
7125 
7126 	log_sz = strlen(buf) + 1;
7127 	next_line = buf + log_sz - 1;
7128 
7129 	for (i = 0; i < max_last_line_cnt; i++, next_line = cur_line) {
7130 		cur_line = find_prev_line(buf, next_line);
7131 		if (!cur_line)
7132 			return;
7133 
7134 		if (str_has_pfx(cur_line, "invalid func unknown#195896080\n")) {
7135 			prev_line = find_prev_line(buf, cur_line);
7136 			if (!prev_line)
7137 				continue;
7138 
7139 			/* failed CO-RE relocation case */
7140 			fixup_log_failed_core_relo(prog, buf, buf_sz, log_sz,
7141 						   prev_line, cur_line, next_line);
7142 			return;
7143 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_LDIMM64_MAP_PFX)) {
7144 			prev_line = find_prev_line(buf, cur_line);
7145 			if (!prev_line)
7146 				continue;
7147 
7148 			/* reference to uncreated BPF map */
7149 			fixup_log_missing_map_load(prog, buf, buf_sz, log_sz,
7150 						   prev_line, cur_line, next_line);
7151 			return;
7152 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_CALL_KFUNC_PFX)) {
7153 			prev_line = find_prev_line(buf, cur_line);
7154 			if (!prev_line)
7155 				continue;
7156 
7157 			/* reference to unresolved kfunc */
7158 			fixup_log_missing_kfunc_call(prog, buf, buf_sz, log_sz,
7159 						     prev_line, cur_line, next_line);
7160 			return;
7161 		}
7162 	}
7163 }
7164 
7165 static int bpf_program_record_relos(struct bpf_program *prog)
7166 {
7167 	struct bpf_object *obj = prog->obj;
7168 	int i;
7169 
7170 	for (i = 0; i < prog->nr_reloc; i++) {
7171 		struct reloc_desc *relo = &prog->reloc_desc[i];
7172 		struct extern_desc *ext = &obj->externs[relo->ext_idx];
7173 		int kind;
7174 
7175 		switch (relo->type) {
7176 		case RELO_EXTERN_LD64:
7177 			if (ext->type != EXT_KSYM)
7178 				continue;
7179 			kind = btf_is_var(btf__type_by_id(obj->btf, ext->btf_id)) ?
7180 				BTF_KIND_VAR : BTF_KIND_FUNC;
7181 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7182 					       ext->is_weak, !ext->ksym.type_id,
7183 					       true, kind, relo->insn_idx);
7184 			break;
7185 		case RELO_EXTERN_CALL:
7186 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7187 					       ext->is_weak, false, false, BTF_KIND_FUNC,
7188 					       relo->insn_idx);
7189 			break;
7190 		case RELO_CORE: {
7191 			struct bpf_core_relo cr = {
7192 				.insn_off = relo->insn_idx * 8,
7193 				.type_id = relo->core_relo->type_id,
7194 				.access_str_off = relo->core_relo->access_str_off,
7195 				.kind = relo->core_relo->kind,
7196 			};
7197 
7198 			bpf_gen__record_relo_core(obj->gen_loader, &cr);
7199 			break;
7200 		}
7201 		default:
7202 			continue;
7203 		}
7204 	}
7205 	return 0;
7206 }
7207 
7208 static int
7209 bpf_object__load_progs(struct bpf_object *obj, int log_level)
7210 {
7211 	struct bpf_program *prog;
7212 	size_t i;
7213 	int err;
7214 
7215 	for (i = 0; i < obj->nr_programs; i++) {
7216 		prog = &obj->programs[i];
7217 		err = bpf_object__sanitize_prog(obj, prog);
7218 		if (err)
7219 			return err;
7220 	}
7221 
7222 	for (i = 0; i < obj->nr_programs; i++) {
7223 		prog = &obj->programs[i];
7224 		if (prog_is_subprog(obj, prog))
7225 			continue;
7226 		if (!prog->autoload) {
7227 			pr_debug("prog '%s': skipped loading\n", prog->name);
7228 			continue;
7229 		}
7230 		prog->log_level |= log_level;
7231 
7232 		if (obj->gen_loader)
7233 			bpf_program_record_relos(prog);
7234 
7235 		err = bpf_object_load_prog(obj, prog, prog->insns, prog->insns_cnt,
7236 					   obj->license, obj->kern_version, &prog->fd);
7237 		if (err) {
7238 			pr_warn("prog '%s': failed to load: %d\n", prog->name, err);
7239 			return err;
7240 		}
7241 	}
7242 
7243 	bpf_object__free_relocs(obj);
7244 	return 0;
7245 }
7246 
7247 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
7248 
7249 static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
7250 {
7251 	struct bpf_program *prog;
7252 	int err;
7253 
7254 	bpf_object__for_each_program(prog, obj) {
7255 		prog->sec_def = find_sec_def(prog->sec_name);
7256 		if (!prog->sec_def) {
7257 			/* couldn't guess, but user might manually specify */
7258 			pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
7259 				prog->name, prog->sec_name);
7260 			continue;
7261 		}
7262 
7263 		prog->type = prog->sec_def->prog_type;
7264 		prog->expected_attach_type = prog->sec_def->expected_attach_type;
7265 
7266 		/* sec_def can have custom callback which should be called
7267 		 * after bpf_program is initialized to adjust its properties
7268 		 */
7269 		if (prog->sec_def->prog_setup_fn) {
7270 			err = prog->sec_def->prog_setup_fn(prog, prog->sec_def->cookie);
7271 			if (err < 0) {
7272 				pr_warn("prog '%s': failed to initialize: %d\n",
7273 					prog->name, err);
7274 				return err;
7275 			}
7276 		}
7277 	}
7278 
7279 	return 0;
7280 }
7281 
7282 static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
7283 					  const struct bpf_object_open_opts *opts)
7284 {
7285 	const char *obj_name, *kconfig, *btf_tmp_path;
7286 	struct bpf_object *obj;
7287 	char tmp_name[64];
7288 	int err;
7289 	char *log_buf;
7290 	size_t log_size;
7291 	__u32 log_level;
7292 
7293 	if (elf_version(EV_CURRENT) == EV_NONE) {
7294 		pr_warn("failed to init libelf for %s\n",
7295 			path ? : "(mem buf)");
7296 		return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
7297 	}
7298 
7299 	if (!OPTS_VALID(opts, bpf_object_open_opts))
7300 		return ERR_PTR(-EINVAL);
7301 
7302 	obj_name = OPTS_GET(opts, object_name, NULL);
7303 	if (obj_buf) {
7304 		if (!obj_name) {
7305 			snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
7306 				 (unsigned long)obj_buf,
7307 				 (unsigned long)obj_buf_sz);
7308 			obj_name = tmp_name;
7309 		}
7310 		path = obj_name;
7311 		pr_debug("loading object '%s' from buffer\n", obj_name);
7312 	}
7313 
7314 	log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
7315 	log_size = OPTS_GET(opts, kernel_log_size, 0);
7316 	log_level = OPTS_GET(opts, kernel_log_level, 0);
7317 	if (log_size > UINT_MAX)
7318 		return ERR_PTR(-EINVAL);
7319 	if (log_size && !log_buf)
7320 		return ERR_PTR(-EINVAL);
7321 
7322 	obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
7323 	if (IS_ERR(obj))
7324 		return obj;
7325 
7326 	obj->log_buf = log_buf;
7327 	obj->log_size = log_size;
7328 	obj->log_level = log_level;
7329 
7330 	btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
7331 	if (btf_tmp_path) {
7332 		if (strlen(btf_tmp_path) >= PATH_MAX) {
7333 			err = -ENAMETOOLONG;
7334 			goto out;
7335 		}
7336 		obj->btf_custom_path = strdup(btf_tmp_path);
7337 		if (!obj->btf_custom_path) {
7338 			err = -ENOMEM;
7339 			goto out;
7340 		}
7341 	}
7342 
7343 	kconfig = OPTS_GET(opts, kconfig, NULL);
7344 	if (kconfig) {
7345 		obj->kconfig = strdup(kconfig);
7346 		if (!obj->kconfig) {
7347 			err = -ENOMEM;
7348 			goto out;
7349 		}
7350 	}
7351 
7352 	err = bpf_object__elf_init(obj);
7353 	err = err ? : bpf_object__check_endianness(obj);
7354 	err = err ? : bpf_object__elf_collect(obj);
7355 	err = err ? : bpf_object__collect_externs(obj);
7356 	err = err ? : bpf_object_fixup_btf(obj);
7357 	err = err ? : bpf_object__init_maps(obj, opts);
7358 	err = err ? : bpf_object_init_progs(obj, opts);
7359 	err = err ? : bpf_object__collect_relos(obj);
7360 	if (err)
7361 		goto out;
7362 
7363 	bpf_object__elf_finish(obj);
7364 
7365 	return obj;
7366 out:
7367 	bpf_object__close(obj);
7368 	return ERR_PTR(err);
7369 }
7370 
7371 struct bpf_object *
7372 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
7373 {
7374 	if (!path)
7375 		return libbpf_err_ptr(-EINVAL);
7376 
7377 	pr_debug("loading %s\n", path);
7378 
7379 	return libbpf_ptr(bpf_object_open(path, NULL, 0, opts));
7380 }
7381 
7382 struct bpf_object *bpf_object__open(const char *path)
7383 {
7384 	return bpf_object__open_file(path, NULL);
7385 }
7386 
7387 struct bpf_object *
7388 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
7389 		     const struct bpf_object_open_opts *opts)
7390 {
7391 	if (!obj_buf || obj_buf_sz == 0)
7392 		return libbpf_err_ptr(-EINVAL);
7393 
7394 	return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, opts));
7395 }
7396 
7397 static int bpf_object_unload(struct bpf_object *obj)
7398 {
7399 	size_t i;
7400 
7401 	if (!obj)
7402 		return libbpf_err(-EINVAL);
7403 
7404 	for (i = 0; i < obj->nr_maps; i++) {
7405 		zclose(obj->maps[i].fd);
7406 		if (obj->maps[i].st_ops)
7407 			zfree(&obj->maps[i].st_ops->kern_vdata);
7408 	}
7409 
7410 	for (i = 0; i < obj->nr_programs; i++)
7411 		bpf_program__unload(&obj->programs[i]);
7412 
7413 	return 0;
7414 }
7415 
7416 static int bpf_object__sanitize_maps(struct bpf_object *obj)
7417 {
7418 	struct bpf_map *m;
7419 
7420 	bpf_object__for_each_map(m, obj) {
7421 		if (!bpf_map__is_internal(m))
7422 			continue;
7423 		if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
7424 			m->def.map_flags &= ~BPF_F_MMAPABLE;
7425 	}
7426 
7427 	return 0;
7428 }
7429 
7430 int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
7431 {
7432 	char sym_type, sym_name[500];
7433 	unsigned long long sym_addr;
7434 	int ret, err = 0;
7435 	FILE *f;
7436 
7437 	f = fopen("/proc/kallsyms", "r");
7438 	if (!f) {
7439 		err = -errno;
7440 		pr_warn("failed to open /proc/kallsyms: %d\n", err);
7441 		return err;
7442 	}
7443 
7444 	while (true) {
7445 		ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
7446 			     &sym_addr, &sym_type, sym_name);
7447 		if (ret == EOF && feof(f))
7448 			break;
7449 		if (ret != 3) {
7450 			pr_warn("failed to read kallsyms entry: %d\n", ret);
7451 			err = -EINVAL;
7452 			break;
7453 		}
7454 
7455 		err = cb(sym_addr, sym_type, sym_name, ctx);
7456 		if (err)
7457 			break;
7458 	}
7459 
7460 	fclose(f);
7461 	return err;
7462 }
7463 
7464 static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
7465 		       const char *sym_name, void *ctx)
7466 {
7467 	struct bpf_object *obj = ctx;
7468 	const struct btf_type *t;
7469 	struct extern_desc *ext;
7470 
7471 	ext = find_extern_by_name(obj, sym_name);
7472 	if (!ext || ext->type != EXT_KSYM)
7473 		return 0;
7474 
7475 	t = btf__type_by_id(obj->btf, ext->btf_id);
7476 	if (!btf_is_var(t))
7477 		return 0;
7478 
7479 	if (ext->is_set && ext->ksym.addr != sym_addr) {
7480 		pr_warn("extern (ksym) '%s': resolution is ambiguous: 0x%llx or 0x%llx\n",
7481 			sym_name, ext->ksym.addr, sym_addr);
7482 		return -EINVAL;
7483 	}
7484 	if (!ext->is_set) {
7485 		ext->is_set = true;
7486 		ext->ksym.addr = sym_addr;
7487 		pr_debug("extern (ksym) '%s': set to 0x%llx\n", sym_name, sym_addr);
7488 	}
7489 	return 0;
7490 }
7491 
7492 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
7493 {
7494 	return libbpf_kallsyms_parse(kallsyms_cb, obj);
7495 }
7496 
7497 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
7498 			    __u16 kind, struct btf **res_btf,
7499 			    struct module_btf **res_mod_btf)
7500 {
7501 	struct module_btf *mod_btf;
7502 	struct btf *btf;
7503 	int i, id, err;
7504 
7505 	btf = obj->btf_vmlinux;
7506 	mod_btf = NULL;
7507 	id = btf__find_by_name_kind(btf, ksym_name, kind);
7508 
7509 	if (id == -ENOENT) {
7510 		err = load_module_btfs(obj);
7511 		if (err)
7512 			return err;
7513 
7514 		for (i = 0; i < obj->btf_module_cnt; i++) {
7515 			/* we assume module_btf's BTF FD is always >0 */
7516 			mod_btf = &obj->btf_modules[i];
7517 			btf = mod_btf->btf;
7518 			id = btf__find_by_name_kind_own(btf, ksym_name, kind);
7519 			if (id != -ENOENT)
7520 				break;
7521 		}
7522 	}
7523 	if (id <= 0)
7524 		return -ESRCH;
7525 
7526 	*res_btf = btf;
7527 	*res_mod_btf = mod_btf;
7528 	return id;
7529 }
7530 
7531 static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
7532 					       struct extern_desc *ext)
7533 {
7534 	const struct btf_type *targ_var, *targ_type;
7535 	__u32 targ_type_id, local_type_id;
7536 	struct module_btf *mod_btf = NULL;
7537 	const char *targ_var_name;
7538 	struct btf *btf = NULL;
7539 	int id, err;
7540 
7541 	id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
7542 	if (id < 0) {
7543 		if (id == -ESRCH && ext->is_weak)
7544 			return 0;
7545 		pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
7546 			ext->name);
7547 		return id;
7548 	}
7549 
7550 	/* find local type_id */
7551 	local_type_id = ext->ksym.type_id;
7552 
7553 	/* find target type_id */
7554 	targ_var = btf__type_by_id(btf, id);
7555 	targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
7556 	targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
7557 
7558 	err = bpf_core_types_are_compat(obj->btf, local_type_id,
7559 					btf, targ_type_id);
7560 	if (err <= 0) {
7561 		const struct btf_type *local_type;
7562 		const char *targ_name, *local_name;
7563 
7564 		local_type = btf__type_by_id(obj->btf, local_type_id);
7565 		local_name = btf__name_by_offset(obj->btf, local_type->name_off);
7566 		targ_name = btf__name_by_offset(btf, targ_type->name_off);
7567 
7568 		pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
7569 			ext->name, local_type_id,
7570 			btf_kind_str(local_type), local_name, targ_type_id,
7571 			btf_kind_str(targ_type), targ_name);
7572 		return -EINVAL;
7573 	}
7574 
7575 	ext->is_set = true;
7576 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
7577 	ext->ksym.kernel_btf_id = id;
7578 	pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
7579 		 ext->name, id, btf_kind_str(targ_var), targ_var_name);
7580 
7581 	return 0;
7582 }
7583 
7584 static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
7585 						struct extern_desc *ext)
7586 {
7587 	int local_func_proto_id, kfunc_proto_id, kfunc_id;
7588 	struct module_btf *mod_btf = NULL;
7589 	const struct btf_type *kern_func;
7590 	struct btf *kern_btf = NULL;
7591 	int ret;
7592 
7593 	local_func_proto_id = ext->ksym.type_id;
7594 
7595 	kfunc_id = find_ksym_btf_id(obj, ext->name, BTF_KIND_FUNC, &kern_btf, &mod_btf);
7596 	if (kfunc_id < 0) {
7597 		if (kfunc_id == -ESRCH && ext->is_weak)
7598 			return 0;
7599 		pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
7600 			ext->name);
7601 		return kfunc_id;
7602 	}
7603 
7604 	kern_func = btf__type_by_id(kern_btf, kfunc_id);
7605 	kfunc_proto_id = kern_func->type;
7606 
7607 	ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
7608 					kern_btf, kfunc_proto_id);
7609 	if (ret <= 0) {
7610 		pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with %s [%d]\n",
7611 			ext->name, local_func_proto_id,
7612 			mod_btf ? mod_btf->name : "vmlinux", kfunc_proto_id);
7613 		return -EINVAL;
7614 	}
7615 
7616 	/* set index for module BTF fd in fd_array, if unset */
7617 	if (mod_btf && !mod_btf->fd_array_idx) {
7618 		/* insn->off is s16 */
7619 		if (obj->fd_array_cnt == INT16_MAX) {
7620 			pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
7621 				ext->name, mod_btf->fd_array_idx);
7622 			return -E2BIG;
7623 		}
7624 		/* Cannot use index 0 for module BTF fd */
7625 		if (!obj->fd_array_cnt)
7626 			obj->fd_array_cnt = 1;
7627 
7628 		ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
7629 					obj->fd_array_cnt + 1);
7630 		if (ret)
7631 			return ret;
7632 		mod_btf->fd_array_idx = obj->fd_array_cnt;
7633 		/* we assume module BTF FD is always >0 */
7634 		obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
7635 	}
7636 
7637 	ext->is_set = true;
7638 	ext->ksym.kernel_btf_id = kfunc_id;
7639 	ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
7640 	/* Also set kernel_btf_obj_fd to make sure that bpf_object__relocate_data()
7641 	 * populates FD into ld_imm64 insn when it's used to point to kfunc.
7642 	 * {kernel_btf_id, btf_fd_idx} -> fixup bpf_call.
7643 	 * {kernel_btf_id, kernel_btf_obj_fd} -> fixup ld_imm64.
7644 	 */
7645 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
7646 	pr_debug("extern (func ksym) '%s': resolved to %s [%d]\n",
7647 		 ext->name, mod_btf ? mod_btf->name : "vmlinux", kfunc_id);
7648 
7649 	return 0;
7650 }
7651 
7652 static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
7653 {
7654 	const struct btf_type *t;
7655 	struct extern_desc *ext;
7656 	int i, err;
7657 
7658 	for (i = 0; i < obj->nr_extern; i++) {
7659 		ext = &obj->externs[i];
7660 		if (ext->type != EXT_KSYM || !ext->ksym.type_id)
7661 			continue;
7662 
7663 		if (obj->gen_loader) {
7664 			ext->is_set = true;
7665 			ext->ksym.kernel_btf_obj_fd = 0;
7666 			ext->ksym.kernel_btf_id = 0;
7667 			continue;
7668 		}
7669 		t = btf__type_by_id(obj->btf, ext->btf_id);
7670 		if (btf_is_var(t))
7671 			err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
7672 		else
7673 			err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
7674 		if (err)
7675 			return err;
7676 	}
7677 	return 0;
7678 }
7679 
7680 static int bpf_object__resolve_externs(struct bpf_object *obj,
7681 				       const char *extra_kconfig)
7682 {
7683 	bool need_config = false, need_kallsyms = false;
7684 	bool need_vmlinux_btf = false;
7685 	struct extern_desc *ext;
7686 	void *kcfg_data = NULL;
7687 	int err, i;
7688 
7689 	if (obj->nr_extern == 0)
7690 		return 0;
7691 
7692 	if (obj->kconfig_map_idx >= 0)
7693 		kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
7694 
7695 	for (i = 0; i < obj->nr_extern; i++) {
7696 		ext = &obj->externs[i];
7697 
7698 		if (ext->type == EXT_KSYM) {
7699 			if (ext->ksym.type_id)
7700 				need_vmlinux_btf = true;
7701 			else
7702 				need_kallsyms = true;
7703 			continue;
7704 		} else if (ext->type == EXT_KCFG) {
7705 			void *ext_ptr = kcfg_data + ext->kcfg.data_off;
7706 			__u64 value = 0;
7707 
7708 			/* Kconfig externs need actual /proc/config.gz */
7709 			if (str_has_pfx(ext->name, "CONFIG_")) {
7710 				need_config = true;
7711 				continue;
7712 			}
7713 
7714 			/* Virtual kcfg externs are customly handled by libbpf */
7715 			if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
7716 				value = get_kernel_version();
7717 				if (!value) {
7718 					pr_warn("extern (kcfg) '%s': failed to get kernel version\n", ext->name);
7719 					return -EINVAL;
7720 				}
7721 			} else if (strcmp(ext->name, "LINUX_HAS_BPF_COOKIE") == 0) {
7722 				value = kernel_supports(obj, FEAT_BPF_COOKIE);
7723 			} else if (strcmp(ext->name, "LINUX_HAS_SYSCALL_WRAPPER") == 0) {
7724 				value = kernel_supports(obj, FEAT_SYSCALL_WRAPPER);
7725 			} else if (!str_has_pfx(ext->name, "LINUX_") || !ext->is_weak) {
7726 				/* Currently libbpf supports only CONFIG_ and LINUX_ prefixed
7727 				 * __kconfig externs, where LINUX_ ones are virtual and filled out
7728 				 * customly by libbpf (their values don't come from Kconfig).
7729 				 * If LINUX_xxx variable is not recognized by libbpf, but is marked
7730 				 * __weak, it defaults to zero value, just like for CONFIG_xxx
7731 				 * externs.
7732 				 */
7733 				pr_warn("extern (kcfg) '%s': unrecognized virtual extern\n", ext->name);
7734 				return -EINVAL;
7735 			}
7736 
7737 			err = set_kcfg_value_num(ext, ext_ptr, value);
7738 			if (err)
7739 				return err;
7740 			pr_debug("extern (kcfg) '%s': set to 0x%llx\n",
7741 				 ext->name, (long long)value);
7742 		} else {
7743 			pr_warn("extern '%s': unrecognized extern kind\n", ext->name);
7744 			return -EINVAL;
7745 		}
7746 	}
7747 	if (need_config && extra_kconfig) {
7748 		err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
7749 		if (err)
7750 			return -EINVAL;
7751 		need_config = false;
7752 		for (i = 0; i < obj->nr_extern; i++) {
7753 			ext = &obj->externs[i];
7754 			if (ext->type == EXT_KCFG && !ext->is_set) {
7755 				need_config = true;
7756 				break;
7757 			}
7758 		}
7759 	}
7760 	if (need_config) {
7761 		err = bpf_object__read_kconfig_file(obj, kcfg_data);
7762 		if (err)
7763 			return -EINVAL;
7764 	}
7765 	if (need_kallsyms) {
7766 		err = bpf_object__read_kallsyms_file(obj);
7767 		if (err)
7768 			return -EINVAL;
7769 	}
7770 	if (need_vmlinux_btf) {
7771 		err = bpf_object__resolve_ksyms_btf_id(obj);
7772 		if (err)
7773 			return -EINVAL;
7774 	}
7775 	for (i = 0; i < obj->nr_extern; i++) {
7776 		ext = &obj->externs[i];
7777 
7778 		if (!ext->is_set && !ext->is_weak) {
7779 			pr_warn("extern '%s' (strong): not resolved\n", ext->name);
7780 			return -ESRCH;
7781 		} else if (!ext->is_set) {
7782 			pr_debug("extern '%s' (weak): not resolved, defaulting to zero\n",
7783 				 ext->name);
7784 		}
7785 	}
7786 
7787 	return 0;
7788 }
7789 
7790 static void bpf_map_prepare_vdata(const struct bpf_map *map)
7791 {
7792 	struct bpf_struct_ops *st_ops;
7793 	__u32 i;
7794 
7795 	st_ops = map->st_ops;
7796 	for (i = 0; i < btf_vlen(st_ops->type); i++) {
7797 		struct bpf_program *prog = st_ops->progs[i];
7798 		void *kern_data;
7799 		int prog_fd;
7800 
7801 		if (!prog)
7802 			continue;
7803 
7804 		prog_fd = bpf_program__fd(prog);
7805 		kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
7806 		*(unsigned long *)kern_data = prog_fd;
7807 	}
7808 }
7809 
7810 static int bpf_object_prepare_struct_ops(struct bpf_object *obj)
7811 {
7812 	int i;
7813 
7814 	for (i = 0; i < obj->nr_maps; i++)
7815 		if (bpf_map__is_struct_ops(&obj->maps[i]))
7816 			bpf_map_prepare_vdata(&obj->maps[i]);
7817 
7818 	return 0;
7819 }
7820 
7821 static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
7822 {
7823 	int err, i;
7824 
7825 	if (!obj)
7826 		return libbpf_err(-EINVAL);
7827 
7828 	if (obj->loaded) {
7829 		pr_warn("object '%s': load can't be attempted twice\n", obj->name);
7830 		return libbpf_err(-EINVAL);
7831 	}
7832 
7833 	if (obj->gen_loader)
7834 		bpf_gen__init(obj->gen_loader, extra_log_level, obj->nr_programs, obj->nr_maps);
7835 
7836 	err = bpf_object__probe_loading(obj);
7837 	err = err ? : bpf_object__load_vmlinux_btf(obj, false);
7838 	err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
7839 	err = err ? : bpf_object__sanitize_and_load_btf(obj);
7840 	err = err ? : bpf_object__sanitize_maps(obj);
7841 	err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
7842 	err = err ? : bpf_object__create_maps(obj);
7843 	err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
7844 	err = err ? : bpf_object__load_progs(obj, extra_log_level);
7845 	err = err ? : bpf_object_init_prog_arrays(obj);
7846 	err = err ? : bpf_object_prepare_struct_ops(obj);
7847 
7848 	if (obj->gen_loader) {
7849 		/* reset FDs */
7850 		if (obj->btf)
7851 			btf__set_fd(obj->btf, -1);
7852 		for (i = 0; i < obj->nr_maps; i++)
7853 			obj->maps[i].fd = -1;
7854 		if (!err)
7855 			err = bpf_gen__finish(obj->gen_loader, obj->nr_programs, obj->nr_maps);
7856 	}
7857 
7858 	/* clean up fd_array */
7859 	zfree(&obj->fd_array);
7860 
7861 	/* clean up module BTFs */
7862 	for (i = 0; i < obj->btf_module_cnt; i++) {
7863 		close(obj->btf_modules[i].fd);
7864 		btf__free(obj->btf_modules[i].btf);
7865 		free(obj->btf_modules[i].name);
7866 	}
7867 	free(obj->btf_modules);
7868 
7869 	/* clean up vmlinux BTF */
7870 	btf__free(obj->btf_vmlinux);
7871 	obj->btf_vmlinux = NULL;
7872 
7873 	obj->loaded = true; /* doesn't matter if successfully or not */
7874 
7875 	if (err)
7876 		goto out;
7877 
7878 	return 0;
7879 out:
7880 	/* unpin any maps that were auto-pinned during load */
7881 	for (i = 0; i < obj->nr_maps; i++)
7882 		if (obj->maps[i].pinned && !obj->maps[i].reused)
7883 			bpf_map__unpin(&obj->maps[i], NULL);
7884 
7885 	bpf_object_unload(obj);
7886 	pr_warn("failed to load object '%s'\n", obj->path);
7887 	return libbpf_err(err);
7888 }
7889 
7890 int bpf_object__load(struct bpf_object *obj)
7891 {
7892 	return bpf_object_load(obj, 0, NULL);
7893 }
7894 
7895 static int make_parent_dir(const char *path)
7896 {
7897 	char *cp, errmsg[STRERR_BUFSIZE];
7898 	char *dname, *dir;
7899 	int err = 0;
7900 
7901 	dname = strdup(path);
7902 	if (dname == NULL)
7903 		return -ENOMEM;
7904 
7905 	dir = dirname(dname);
7906 	if (mkdir(dir, 0700) && errno != EEXIST)
7907 		err = -errno;
7908 
7909 	free(dname);
7910 	if (err) {
7911 		cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
7912 		pr_warn("failed to mkdir %s: %s\n", path, cp);
7913 	}
7914 	return err;
7915 }
7916 
7917 static int check_path(const char *path)
7918 {
7919 	char *cp, errmsg[STRERR_BUFSIZE];
7920 	struct statfs st_fs;
7921 	char *dname, *dir;
7922 	int err = 0;
7923 
7924 	if (path == NULL)
7925 		return -EINVAL;
7926 
7927 	dname = strdup(path);
7928 	if (dname == NULL)
7929 		return -ENOMEM;
7930 
7931 	dir = dirname(dname);
7932 	if (statfs(dir, &st_fs)) {
7933 		cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
7934 		pr_warn("failed to statfs %s: %s\n", dir, cp);
7935 		err = -errno;
7936 	}
7937 	free(dname);
7938 
7939 	if (!err && st_fs.f_type != BPF_FS_MAGIC) {
7940 		pr_warn("specified path %s is not on BPF FS\n", path);
7941 		err = -EINVAL;
7942 	}
7943 
7944 	return err;
7945 }
7946 
7947 int bpf_program__pin(struct bpf_program *prog, const char *path)
7948 {
7949 	char *cp, errmsg[STRERR_BUFSIZE];
7950 	int err;
7951 
7952 	if (prog->fd < 0) {
7953 		pr_warn("prog '%s': can't pin program that wasn't loaded\n", prog->name);
7954 		return libbpf_err(-EINVAL);
7955 	}
7956 
7957 	err = make_parent_dir(path);
7958 	if (err)
7959 		return libbpf_err(err);
7960 
7961 	err = check_path(path);
7962 	if (err)
7963 		return libbpf_err(err);
7964 
7965 	if (bpf_obj_pin(prog->fd, path)) {
7966 		err = -errno;
7967 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
7968 		pr_warn("prog '%s': failed to pin at '%s': %s\n", prog->name, path, cp);
7969 		return libbpf_err(err);
7970 	}
7971 
7972 	pr_debug("prog '%s': pinned at '%s'\n", prog->name, path);
7973 	return 0;
7974 }
7975 
7976 int bpf_program__unpin(struct bpf_program *prog, const char *path)
7977 {
7978 	int err;
7979 
7980 	if (prog->fd < 0) {
7981 		pr_warn("prog '%s': can't unpin program that wasn't loaded\n", prog->name);
7982 		return libbpf_err(-EINVAL);
7983 	}
7984 
7985 	err = check_path(path);
7986 	if (err)
7987 		return libbpf_err(err);
7988 
7989 	err = unlink(path);
7990 	if (err)
7991 		return libbpf_err(-errno);
7992 
7993 	pr_debug("prog '%s': unpinned from '%s'\n", prog->name, path);
7994 	return 0;
7995 }
7996 
7997 int bpf_map__pin(struct bpf_map *map, const char *path)
7998 {
7999 	char *cp, errmsg[STRERR_BUFSIZE];
8000 	int err;
8001 
8002 	if (map == NULL) {
8003 		pr_warn("invalid map pointer\n");
8004 		return libbpf_err(-EINVAL);
8005 	}
8006 
8007 	if (map->pin_path) {
8008 		if (path && strcmp(path, map->pin_path)) {
8009 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8010 				bpf_map__name(map), map->pin_path, path);
8011 			return libbpf_err(-EINVAL);
8012 		} else if (map->pinned) {
8013 			pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
8014 				 bpf_map__name(map), map->pin_path);
8015 			return 0;
8016 		}
8017 	} else {
8018 		if (!path) {
8019 			pr_warn("missing a path to pin map '%s' at\n",
8020 				bpf_map__name(map));
8021 			return libbpf_err(-EINVAL);
8022 		} else if (map->pinned) {
8023 			pr_warn("map '%s' already pinned\n", bpf_map__name(map));
8024 			return libbpf_err(-EEXIST);
8025 		}
8026 
8027 		map->pin_path = strdup(path);
8028 		if (!map->pin_path) {
8029 			err = -errno;
8030 			goto out_err;
8031 		}
8032 	}
8033 
8034 	err = make_parent_dir(map->pin_path);
8035 	if (err)
8036 		return libbpf_err(err);
8037 
8038 	err = check_path(map->pin_path);
8039 	if (err)
8040 		return libbpf_err(err);
8041 
8042 	if (bpf_obj_pin(map->fd, map->pin_path)) {
8043 		err = -errno;
8044 		goto out_err;
8045 	}
8046 
8047 	map->pinned = true;
8048 	pr_debug("pinned map '%s'\n", map->pin_path);
8049 
8050 	return 0;
8051 
8052 out_err:
8053 	cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
8054 	pr_warn("failed to pin map: %s\n", cp);
8055 	return libbpf_err(err);
8056 }
8057 
8058 int bpf_map__unpin(struct bpf_map *map, const char *path)
8059 {
8060 	int err;
8061 
8062 	if (map == NULL) {
8063 		pr_warn("invalid map pointer\n");
8064 		return libbpf_err(-EINVAL);
8065 	}
8066 
8067 	if (map->pin_path) {
8068 		if (path && strcmp(path, map->pin_path)) {
8069 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8070 				bpf_map__name(map), map->pin_path, path);
8071 			return libbpf_err(-EINVAL);
8072 		}
8073 		path = map->pin_path;
8074 	} else if (!path) {
8075 		pr_warn("no path to unpin map '%s' from\n",
8076 			bpf_map__name(map));
8077 		return libbpf_err(-EINVAL);
8078 	}
8079 
8080 	err = check_path(path);
8081 	if (err)
8082 		return libbpf_err(err);
8083 
8084 	err = unlink(path);
8085 	if (err != 0)
8086 		return libbpf_err(-errno);
8087 
8088 	map->pinned = false;
8089 	pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
8090 
8091 	return 0;
8092 }
8093 
8094 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
8095 {
8096 	char *new = NULL;
8097 
8098 	if (path) {
8099 		new = strdup(path);
8100 		if (!new)
8101 			return libbpf_err(-errno);
8102 	}
8103 
8104 	free(map->pin_path);
8105 	map->pin_path = new;
8106 	return 0;
8107 }
8108 
8109 __alias(bpf_map__pin_path)
8110 const char *bpf_map__get_pin_path(const struct bpf_map *map);
8111 
8112 const char *bpf_map__pin_path(const struct bpf_map *map)
8113 {
8114 	return map->pin_path;
8115 }
8116 
8117 bool bpf_map__is_pinned(const struct bpf_map *map)
8118 {
8119 	return map->pinned;
8120 }
8121 
8122 static void sanitize_pin_path(char *s)
8123 {
8124 	/* bpffs disallows periods in path names */
8125 	while (*s) {
8126 		if (*s == '.')
8127 			*s = '_';
8128 		s++;
8129 	}
8130 }
8131 
8132 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
8133 {
8134 	struct bpf_map *map;
8135 	int err;
8136 
8137 	if (!obj)
8138 		return libbpf_err(-ENOENT);
8139 
8140 	if (!obj->loaded) {
8141 		pr_warn("object not yet loaded; load it first\n");
8142 		return libbpf_err(-ENOENT);
8143 	}
8144 
8145 	bpf_object__for_each_map(map, obj) {
8146 		char *pin_path = NULL;
8147 		char buf[PATH_MAX];
8148 
8149 		if (!map->autocreate)
8150 			continue;
8151 
8152 		if (path) {
8153 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8154 			if (err)
8155 				goto err_unpin_maps;
8156 			sanitize_pin_path(buf);
8157 			pin_path = buf;
8158 		} else if (!map->pin_path) {
8159 			continue;
8160 		}
8161 
8162 		err = bpf_map__pin(map, pin_path);
8163 		if (err)
8164 			goto err_unpin_maps;
8165 	}
8166 
8167 	return 0;
8168 
8169 err_unpin_maps:
8170 	while ((map = bpf_object__prev_map(obj, map))) {
8171 		if (!map->pin_path)
8172 			continue;
8173 
8174 		bpf_map__unpin(map, NULL);
8175 	}
8176 
8177 	return libbpf_err(err);
8178 }
8179 
8180 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
8181 {
8182 	struct bpf_map *map;
8183 	int err;
8184 
8185 	if (!obj)
8186 		return libbpf_err(-ENOENT);
8187 
8188 	bpf_object__for_each_map(map, obj) {
8189 		char *pin_path = NULL;
8190 		char buf[PATH_MAX];
8191 
8192 		if (path) {
8193 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8194 			if (err)
8195 				return libbpf_err(err);
8196 			sanitize_pin_path(buf);
8197 			pin_path = buf;
8198 		} else if (!map->pin_path) {
8199 			continue;
8200 		}
8201 
8202 		err = bpf_map__unpin(map, pin_path);
8203 		if (err)
8204 			return libbpf_err(err);
8205 	}
8206 
8207 	return 0;
8208 }
8209 
8210 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
8211 {
8212 	struct bpf_program *prog;
8213 	char buf[PATH_MAX];
8214 	int err;
8215 
8216 	if (!obj)
8217 		return libbpf_err(-ENOENT);
8218 
8219 	if (!obj->loaded) {
8220 		pr_warn("object not yet loaded; load it first\n");
8221 		return libbpf_err(-ENOENT);
8222 	}
8223 
8224 	bpf_object__for_each_program(prog, obj) {
8225 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
8226 		if (err)
8227 			goto err_unpin_programs;
8228 
8229 		err = bpf_program__pin(prog, buf);
8230 		if (err)
8231 			goto err_unpin_programs;
8232 	}
8233 
8234 	return 0;
8235 
8236 err_unpin_programs:
8237 	while ((prog = bpf_object__prev_program(obj, prog))) {
8238 		if (pathname_concat(buf, sizeof(buf), path, prog->name))
8239 			continue;
8240 
8241 		bpf_program__unpin(prog, buf);
8242 	}
8243 
8244 	return libbpf_err(err);
8245 }
8246 
8247 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
8248 {
8249 	struct bpf_program *prog;
8250 	int err;
8251 
8252 	if (!obj)
8253 		return libbpf_err(-ENOENT);
8254 
8255 	bpf_object__for_each_program(prog, obj) {
8256 		char buf[PATH_MAX];
8257 
8258 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
8259 		if (err)
8260 			return libbpf_err(err);
8261 
8262 		err = bpf_program__unpin(prog, buf);
8263 		if (err)
8264 			return libbpf_err(err);
8265 	}
8266 
8267 	return 0;
8268 }
8269 
8270 int bpf_object__pin(struct bpf_object *obj, const char *path)
8271 {
8272 	int err;
8273 
8274 	err = bpf_object__pin_maps(obj, path);
8275 	if (err)
8276 		return libbpf_err(err);
8277 
8278 	err = bpf_object__pin_programs(obj, path);
8279 	if (err) {
8280 		bpf_object__unpin_maps(obj, path);
8281 		return libbpf_err(err);
8282 	}
8283 
8284 	return 0;
8285 }
8286 
8287 static void bpf_map__destroy(struct bpf_map *map)
8288 {
8289 	if (map->inner_map) {
8290 		bpf_map__destroy(map->inner_map);
8291 		zfree(&map->inner_map);
8292 	}
8293 
8294 	zfree(&map->init_slots);
8295 	map->init_slots_sz = 0;
8296 
8297 	if (map->mmaped) {
8298 		munmap(map->mmaped, bpf_map_mmap_sz(map));
8299 		map->mmaped = NULL;
8300 	}
8301 
8302 	if (map->st_ops) {
8303 		zfree(&map->st_ops->data);
8304 		zfree(&map->st_ops->progs);
8305 		zfree(&map->st_ops->kern_func_off);
8306 		zfree(&map->st_ops);
8307 	}
8308 
8309 	zfree(&map->name);
8310 	zfree(&map->real_name);
8311 	zfree(&map->pin_path);
8312 
8313 	if (map->fd >= 0)
8314 		zclose(map->fd);
8315 }
8316 
8317 void bpf_object__close(struct bpf_object *obj)
8318 {
8319 	size_t i;
8320 
8321 	if (IS_ERR_OR_NULL(obj))
8322 		return;
8323 
8324 	usdt_manager_free(obj->usdt_man);
8325 	obj->usdt_man = NULL;
8326 
8327 	bpf_gen__free(obj->gen_loader);
8328 	bpf_object__elf_finish(obj);
8329 	bpf_object_unload(obj);
8330 	btf__free(obj->btf);
8331 	btf_ext__free(obj->btf_ext);
8332 
8333 	for (i = 0; i < obj->nr_maps; i++)
8334 		bpf_map__destroy(&obj->maps[i]);
8335 
8336 	zfree(&obj->btf_custom_path);
8337 	zfree(&obj->kconfig);
8338 	zfree(&obj->externs);
8339 	obj->nr_extern = 0;
8340 
8341 	zfree(&obj->maps);
8342 	obj->nr_maps = 0;
8343 
8344 	if (obj->programs && obj->nr_programs) {
8345 		for (i = 0; i < obj->nr_programs; i++)
8346 			bpf_program__exit(&obj->programs[i]);
8347 	}
8348 	zfree(&obj->programs);
8349 
8350 	free(obj);
8351 }
8352 
8353 const char *bpf_object__name(const struct bpf_object *obj)
8354 {
8355 	return obj ? obj->name : libbpf_err_ptr(-EINVAL);
8356 }
8357 
8358 unsigned int bpf_object__kversion(const struct bpf_object *obj)
8359 {
8360 	return obj ? obj->kern_version : 0;
8361 }
8362 
8363 struct btf *bpf_object__btf(const struct bpf_object *obj)
8364 {
8365 	return obj ? obj->btf : NULL;
8366 }
8367 
8368 int bpf_object__btf_fd(const struct bpf_object *obj)
8369 {
8370 	return obj->btf ? btf__fd(obj->btf) : -1;
8371 }
8372 
8373 int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
8374 {
8375 	if (obj->loaded)
8376 		return libbpf_err(-EINVAL);
8377 
8378 	obj->kern_version = kern_version;
8379 
8380 	return 0;
8381 }
8382 
8383 int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
8384 {
8385 	struct bpf_gen *gen;
8386 
8387 	if (!opts)
8388 		return -EFAULT;
8389 	if (!OPTS_VALID(opts, gen_loader_opts))
8390 		return -EINVAL;
8391 	gen = calloc(sizeof(*gen), 1);
8392 	if (!gen)
8393 		return -ENOMEM;
8394 	gen->opts = opts;
8395 	obj->gen_loader = gen;
8396 	return 0;
8397 }
8398 
8399 static struct bpf_program *
8400 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
8401 		    bool forward)
8402 {
8403 	size_t nr_programs = obj->nr_programs;
8404 	ssize_t idx;
8405 
8406 	if (!nr_programs)
8407 		return NULL;
8408 
8409 	if (!p)
8410 		/* Iter from the beginning */
8411 		return forward ? &obj->programs[0] :
8412 			&obj->programs[nr_programs - 1];
8413 
8414 	if (p->obj != obj) {
8415 		pr_warn("error: program handler doesn't match object\n");
8416 		return errno = EINVAL, NULL;
8417 	}
8418 
8419 	idx = (p - obj->programs) + (forward ? 1 : -1);
8420 	if (idx >= obj->nr_programs || idx < 0)
8421 		return NULL;
8422 	return &obj->programs[idx];
8423 }
8424 
8425 struct bpf_program *
8426 bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
8427 {
8428 	struct bpf_program *prog = prev;
8429 
8430 	do {
8431 		prog = __bpf_program__iter(prog, obj, true);
8432 	} while (prog && prog_is_subprog(obj, prog));
8433 
8434 	return prog;
8435 }
8436 
8437 struct bpf_program *
8438 bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
8439 {
8440 	struct bpf_program *prog = next;
8441 
8442 	do {
8443 		prog = __bpf_program__iter(prog, obj, false);
8444 	} while (prog && prog_is_subprog(obj, prog));
8445 
8446 	return prog;
8447 }
8448 
8449 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
8450 {
8451 	prog->prog_ifindex = ifindex;
8452 }
8453 
8454 const char *bpf_program__name(const struct bpf_program *prog)
8455 {
8456 	return prog->name;
8457 }
8458 
8459 const char *bpf_program__section_name(const struct bpf_program *prog)
8460 {
8461 	return prog->sec_name;
8462 }
8463 
8464 bool bpf_program__autoload(const struct bpf_program *prog)
8465 {
8466 	return prog->autoload;
8467 }
8468 
8469 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
8470 {
8471 	if (prog->obj->loaded)
8472 		return libbpf_err(-EINVAL);
8473 
8474 	prog->autoload = autoload;
8475 	return 0;
8476 }
8477 
8478 bool bpf_program__autoattach(const struct bpf_program *prog)
8479 {
8480 	return prog->autoattach;
8481 }
8482 
8483 void bpf_program__set_autoattach(struct bpf_program *prog, bool autoattach)
8484 {
8485 	prog->autoattach = autoattach;
8486 }
8487 
8488 const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
8489 {
8490 	return prog->insns;
8491 }
8492 
8493 size_t bpf_program__insn_cnt(const struct bpf_program *prog)
8494 {
8495 	return prog->insns_cnt;
8496 }
8497 
8498 int bpf_program__set_insns(struct bpf_program *prog,
8499 			   struct bpf_insn *new_insns, size_t new_insn_cnt)
8500 {
8501 	struct bpf_insn *insns;
8502 
8503 	if (prog->obj->loaded)
8504 		return -EBUSY;
8505 
8506 	insns = libbpf_reallocarray(prog->insns, new_insn_cnt, sizeof(*insns));
8507 	if (!insns) {
8508 		pr_warn("prog '%s': failed to realloc prog code\n", prog->name);
8509 		return -ENOMEM;
8510 	}
8511 	memcpy(insns, new_insns, new_insn_cnt * sizeof(*insns));
8512 
8513 	prog->insns = insns;
8514 	prog->insns_cnt = new_insn_cnt;
8515 	return 0;
8516 }
8517 
8518 int bpf_program__fd(const struct bpf_program *prog)
8519 {
8520 	if (!prog)
8521 		return libbpf_err(-EINVAL);
8522 
8523 	if (prog->fd < 0)
8524 		return libbpf_err(-ENOENT);
8525 
8526 	return prog->fd;
8527 }
8528 
8529 __alias(bpf_program__type)
8530 enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog);
8531 
8532 enum bpf_prog_type bpf_program__type(const struct bpf_program *prog)
8533 {
8534 	return prog->type;
8535 }
8536 
8537 int bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
8538 {
8539 	if (prog->obj->loaded)
8540 		return libbpf_err(-EBUSY);
8541 
8542 	prog->type = type;
8543 	prog->sec_def = NULL;
8544 	return 0;
8545 }
8546 
8547 __alias(bpf_program__expected_attach_type)
8548 enum bpf_attach_type bpf_program__get_expected_attach_type(const struct bpf_program *prog);
8549 
8550 enum bpf_attach_type bpf_program__expected_attach_type(const struct bpf_program *prog)
8551 {
8552 	return prog->expected_attach_type;
8553 }
8554 
8555 int bpf_program__set_expected_attach_type(struct bpf_program *prog,
8556 					   enum bpf_attach_type type)
8557 {
8558 	if (prog->obj->loaded)
8559 		return libbpf_err(-EBUSY);
8560 
8561 	prog->expected_attach_type = type;
8562 	return 0;
8563 }
8564 
8565 __u32 bpf_program__flags(const struct bpf_program *prog)
8566 {
8567 	return prog->prog_flags;
8568 }
8569 
8570 int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
8571 {
8572 	if (prog->obj->loaded)
8573 		return libbpf_err(-EBUSY);
8574 
8575 	prog->prog_flags = flags;
8576 	return 0;
8577 }
8578 
8579 __u32 bpf_program__log_level(const struct bpf_program *prog)
8580 {
8581 	return prog->log_level;
8582 }
8583 
8584 int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
8585 {
8586 	if (prog->obj->loaded)
8587 		return libbpf_err(-EBUSY);
8588 
8589 	prog->log_level = log_level;
8590 	return 0;
8591 }
8592 
8593 const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
8594 {
8595 	*log_size = prog->log_size;
8596 	return prog->log_buf;
8597 }
8598 
8599 int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
8600 {
8601 	if (log_size && !log_buf)
8602 		return -EINVAL;
8603 	if (prog->log_size > UINT_MAX)
8604 		return -EINVAL;
8605 	if (prog->obj->loaded)
8606 		return -EBUSY;
8607 
8608 	prog->log_buf = log_buf;
8609 	prog->log_size = log_size;
8610 	return 0;
8611 }
8612 
8613 #define SEC_DEF(sec_pfx, ptype, atype, flags, ...) {			    \
8614 	.sec = (char *)sec_pfx,						    \
8615 	.prog_type = BPF_PROG_TYPE_##ptype,				    \
8616 	.expected_attach_type = atype,					    \
8617 	.cookie = (long)(flags),					    \
8618 	.prog_prepare_load_fn = libbpf_prepare_prog_load,		    \
8619 	__VA_ARGS__							    \
8620 }
8621 
8622 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8623 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8624 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8625 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8626 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8627 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8628 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8629 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8630 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8631 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8632 
8633 static const struct bpf_sec_def section_defs[] = {
8634 	SEC_DEF("socket",		SOCKET_FILTER, 0, SEC_NONE),
8635 	SEC_DEF("sk_reuseport/migrate",	SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE),
8636 	SEC_DEF("sk_reuseport",		SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE),
8637 	SEC_DEF("kprobe+",		KPROBE,	0, SEC_NONE, attach_kprobe),
8638 	SEC_DEF("uprobe+",		KPROBE,	0, SEC_NONE, attach_uprobe),
8639 	SEC_DEF("uprobe.s+",		KPROBE,	0, SEC_SLEEPABLE, attach_uprobe),
8640 	SEC_DEF("kretprobe+",		KPROBE, 0, SEC_NONE, attach_kprobe),
8641 	SEC_DEF("uretprobe+",		KPROBE, 0, SEC_NONE, attach_uprobe),
8642 	SEC_DEF("uretprobe.s+",		KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
8643 	SEC_DEF("kprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
8644 	SEC_DEF("kretprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
8645 	SEC_DEF("ksyscall+",		KPROBE,	0, SEC_NONE, attach_ksyscall),
8646 	SEC_DEF("kretsyscall+",		KPROBE, 0, SEC_NONE, attach_ksyscall),
8647 	SEC_DEF("usdt+",		KPROBE,	0, SEC_NONE, attach_usdt),
8648 	SEC_DEF("tc",			SCHED_CLS, 0, SEC_NONE),
8649 	SEC_DEF("classifier",		SCHED_CLS, 0, SEC_NONE),
8650 	SEC_DEF("action",		SCHED_ACT, 0, SEC_NONE),
8651 	SEC_DEF("tracepoint+",		TRACEPOINT, 0, SEC_NONE, attach_tp),
8652 	SEC_DEF("tp+",			TRACEPOINT, 0, SEC_NONE, attach_tp),
8653 	SEC_DEF("raw_tracepoint+",	RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
8654 	SEC_DEF("raw_tp+",		RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
8655 	SEC_DEF("raw_tracepoint.w+",	RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
8656 	SEC_DEF("raw_tp.w+",		RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
8657 	SEC_DEF("tp_btf+",		TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
8658 	SEC_DEF("fentry+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
8659 	SEC_DEF("fmod_ret+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
8660 	SEC_DEF("fexit+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
8661 	SEC_DEF("fentry.s+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8662 	SEC_DEF("fmod_ret.s+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8663 	SEC_DEF("fexit.s+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8664 	SEC_DEF("freplace+",		EXT, 0, SEC_ATTACH_BTF, attach_trace),
8665 	SEC_DEF("lsm+",			LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
8666 	SEC_DEF("lsm.s+",		LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
8667 	SEC_DEF("lsm_cgroup+",		LSM, BPF_LSM_CGROUP, SEC_ATTACH_BTF),
8668 	SEC_DEF("iter+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
8669 	SEC_DEF("iter.s+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_iter),
8670 	SEC_DEF("syscall",		SYSCALL, 0, SEC_SLEEPABLE),
8671 	SEC_DEF("xdp.frags/devmap",	XDP, BPF_XDP_DEVMAP, SEC_XDP_FRAGS),
8672 	SEC_DEF("xdp/devmap",		XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
8673 	SEC_DEF("xdp.frags/cpumap",	XDP, BPF_XDP_CPUMAP, SEC_XDP_FRAGS),
8674 	SEC_DEF("xdp/cpumap",		XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
8675 	SEC_DEF("xdp.frags",		XDP, BPF_XDP, SEC_XDP_FRAGS),
8676 	SEC_DEF("xdp",			XDP, BPF_XDP, SEC_ATTACHABLE_OPT),
8677 	SEC_DEF("perf_event",		PERF_EVENT, 0, SEC_NONE),
8678 	SEC_DEF("lwt_in",		LWT_IN, 0, SEC_NONE),
8679 	SEC_DEF("lwt_out",		LWT_OUT, 0, SEC_NONE),
8680 	SEC_DEF("lwt_xmit",		LWT_XMIT, 0, SEC_NONE),
8681 	SEC_DEF("lwt_seg6local",	LWT_SEG6LOCAL, 0, SEC_NONE),
8682 	SEC_DEF("sockops",		SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT),
8683 	SEC_DEF("sk_skb/stream_parser",	SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT),
8684 	SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT),
8685 	SEC_DEF("sk_skb",		SK_SKB, 0, SEC_NONE),
8686 	SEC_DEF("sk_msg",		SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT),
8687 	SEC_DEF("lirc_mode2",		LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT),
8688 	SEC_DEF("flow_dissector",	FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT),
8689 	SEC_DEF("cgroup_skb/ingress",	CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT),
8690 	SEC_DEF("cgroup_skb/egress",	CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT),
8691 	SEC_DEF("cgroup/skb",		CGROUP_SKB, 0, SEC_NONE),
8692 	SEC_DEF("cgroup/sock_create",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE),
8693 	SEC_DEF("cgroup/sock_release",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE),
8694 	SEC_DEF("cgroup/sock",		CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT),
8695 	SEC_DEF("cgroup/post_bind4",	CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE),
8696 	SEC_DEF("cgroup/post_bind6",	CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE),
8697 	SEC_DEF("cgroup/bind4",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE),
8698 	SEC_DEF("cgroup/bind6",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE),
8699 	SEC_DEF("cgroup/connect4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE),
8700 	SEC_DEF("cgroup/connect6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE),
8701 	SEC_DEF("cgroup/sendmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE),
8702 	SEC_DEF("cgroup/sendmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE),
8703 	SEC_DEF("cgroup/recvmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE),
8704 	SEC_DEF("cgroup/recvmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE),
8705 	SEC_DEF("cgroup/getpeername4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE),
8706 	SEC_DEF("cgroup/getpeername6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE),
8707 	SEC_DEF("cgroup/getsockname4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE),
8708 	SEC_DEF("cgroup/getsockname6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE),
8709 	SEC_DEF("cgroup/sysctl",	CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE),
8710 	SEC_DEF("cgroup/getsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE),
8711 	SEC_DEF("cgroup/setsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE),
8712 	SEC_DEF("cgroup/dev",		CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT),
8713 	SEC_DEF("struct_ops+",		STRUCT_OPS, 0, SEC_NONE),
8714 	SEC_DEF("struct_ops.s+",	STRUCT_OPS, 0, SEC_SLEEPABLE),
8715 	SEC_DEF("sk_lookup",		SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE),
8716 	SEC_DEF("netfilter",		NETFILTER, BPF_NETFILTER, SEC_NONE),
8717 };
8718 
8719 static size_t custom_sec_def_cnt;
8720 static struct bpf_sec_def *custom_sec_defs;
8721 static struct bpf_sec_def custom_fallback_def;
8722 static bool has_custom_fallback_def;
8723 
8724 static int last_custom_sec_def_handler_id;
8725 
8726 int libbpf_register_prog_handler(const char *sec,
8727 				 enum bpf_prog_type prog_type,
8728 				 enum bpf_attach_type exp_attach_type,
8729 				 const struct libbpf_prog_handler_opts *opts)
8730 {
8731 	struct bpf_sec_def *sec_def;
8732 
8733 	if (!OPTS_VALID(opts, libbpf_prog_handler_opts))
8734 		return libbpf_err(-EINVAL);
8735 
8736 	if (last_custom_sec_def_handler_id == INT_MAX) /* prevent overflow */
8737 		return libbpf_err(-E2BIG);
8738 
8739 	if (sec) {
8740 		sec_def = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt + 1,
8741 					      sizeof(*sec_def));
8742 		if (!sec_def)
8743 			return libbpf_err(-ENOMEM);
8744 
8745 		custom_sec_defs = sec_def;
8746 		sec_def = &custom_sec_defs[custom_sec_def_cnt];
8747 	} else {
8748 		if (has_custom_fallback_def)
8749 			return libbpf_err(-EBUSY);
8750 
8751 		sec_def = &custom_fallback_def;
8752 	}
8753 
8754 	sec_def->sec = sec ? strdup(sec) : NULL;
8755 	if (sec && !sec_def->sec)
8756 		return libbpf_err(-ENOMEM);
8757 
8758 	sec_def->prog_type = prog_type;
8759 	sec_def->expected_attach_type = exp_attach_type;
8760 	sec_def->cookie = OPTS_GET(opts, cookie, 0);
8761 
8762 	sec_def->prog_setup_fn = OPTS_GET(opts, prog_setup_fn, NULL);
8763 	sec_def->prog_prepare_load_fn = OPTS_GET(opts, prog_prepare_load_fn, NULL);
8764 	sec_def->prog_attach_fn = OPTS_GET(opts, prog_attach_fn, NULL);
8765 
8766 	sec_def->handler_id = ++last_custom_sec_def_handler_id;
8767 
8768 	if (sec)
8769 		custom_sec_def_cnt++;
8770 	else
8771 		has_custom_fallback_def = true;
8772 
8773 	return sec_def->handler_id;
8774 }
8775 
8776 int libbpf_unregister_prog_handler(int handler_id)
8777 {
8778 	struct bpf_sec_def *sec_defs;
8779 	int i;
8780 
8781 	if (handler_id <= 0)
8782 		return libbpf_err(-EINVAL);
8783 
8784 	if (has_custom_fallback_def && custom_fallback_def.handler_id == handler_id) {
8785 		memset(&custom_fallback_def, 0, sizeof(custom_fallback_def));
8786 		has_custom_fallback_def = false;
8787 		return 0;
8788 	}
8789 
8790 	for (i = 0; i < custom_sec_def_cnt; i++) {
8791 		if (custom_sec_defs[i].handler_id == handler_id)
8792 			break;
8793 	}
8794 
8795 	if (i == custom_sec_def_cnt)
8796 		return libbpf_err(-ENOENT);
8797 
8798 	free(custom_sec_defs[i].sec);
8799 	for (i = i + 1; i < custom_sec_def_cnt; i++)
8800 		custom_sec_defs[i - 1] = custom_sec_defs[i];
8801 	custom_sec_def_cnt--;
8802 
8803 	/* try to shrink the array, but it's ok if we couldn't */
8804 	sec_defs = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt, sizeof(*sec_defs));
8805 	if (sec_defs)
8806 		custom_sec_defs = sec_defs;
8807 
8808 	return 0;
8809 }
8810 
8811 static bool sec_def_matches(const struct bpf_sec_def *sec_def, const char *sec_name)
8812 {
8813 	size_t len = strlen(sec_def->sec);
8814 
8815 	/* "type/" always has to have proper SEC("type/extras") form */
8816 	if (sec_def->sec[len - 1] == '/') {
8817 		if (str_has_pfx(sec_name, sec_def->sec))
8818 			return true;
8819 		return false;
8820 	}
8821 
8822 	/* "type+" means it can be either exact SEC("type") or
8823 	 * well-formed SEC("type/extras") with proper '/' separator
8824 	 */
8825 	if (sec_def->sec[len - 1] == '+') {
8826 		len--;
8827 		/* not even a prefix */
8828 		if (strncmp(sec_name, sec_def->sec, len) != 0)
8829 			return false;
8830 		/* exact match or has '/' separator */
8831 		if (sec_name[len] == '\0' || sec_name[len] == '/')
8832 			return true;
8833 		return false;
8834 	}
8835 
8836 	return strcmp(sec_name, sec_def->sec) == 0;
8837 }
8838 
8839 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
8840 {
8841 	const struct bpf_sec_def *sec_def;
8842 	int i, n;
8843 
8844 	n = custom_sec_def_cnt;
8845 	for (i = 0; i < n; i++) {
8846 		sec_def = &custom_sec_defs[i];
8847 		if (sec_def_matches(sec_def, sec_name))
8848 			return sec_def;
8849 	}
8850 
8851 	n = ARRAY_SIZE(section_defs);
8852 	for (i = 0; i < n; i++) {
8853 		sec_def = &section_defs[i];
8854 		if (sec_def_matches(sec_def, sec_name))
8855 			return sec_def;
8856 	}
8857 
8858 	if (has_custom_fallback_def)
8859 		return &custom_fallback_def;
8860 
8861 	return NULL;
8862 }
8863 
8864 #define MAX_TYPE_NAME_SIZE 32
8865 
8866 static char *libbpf_get_type_names(bool attach_type)
8867 {
8868 	int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
8869 	char *buf;
8870 
8871 	buf = malloc(len);
8872 	if (!buf)
8873 		return NULL;
8874 
8875 	buf[0] = '\0';
8876 	/* Forge string buf with all available names */
8877 	for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
8878 		const struct bpf_sec_def *sec_def = &section_defs[i];
8879 
8880 		if (attach_type) {
8881 			if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
8882 				continue;
8883 
8884 			if (!(sec_def->cookie & SEC_ATTACHABLE))
8885 				continue;
8886 		}
8887 
8888 		if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
8889 			free(buf);
8890 			return NULL;
8891 		}
8892 		strcat(buf, " ");
8893 		strcat(buf, section_defs[i].sec);
8894 	}
8895 
8896 	return buf;
8897 }
8898 
8899 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
8900 			     enum bpf_attach_type *expected_attach_type)
8901 {
8902 	const struct bpf_sec_def *sec_def;
8903 	char *type_names;
8904 
8905 	if (!name)
8906 		return libbpf_err(-EINVAL);
8907 
8908 	sec_def = find_sec_def(name);
8909 	if (sec_def) {
8910 		*prog_type = sec_def->prog_type;
8911 		*expected_attach_type = sec_def->expected_attach_type;
8912 		return 0;
8913 	}
8914 
8915 	pr_debug("failed to guess program type from ELF section '%s'\n", name);
8916 	type_names = libbpf_get_type_names(false);
8917 	if (type_names != NULL) {
8918 		pr_debug("supported section(type) names are:%s\n", type_names);
8919 		free(type_names);
8920 	}
8921 
8922 	return libbpf_err(-ESRCH);
8923 }
8924 
8925 const char *libbpf_bpf_attach_type_str(enum bpf_attach_type t)
8926 {
8927 	if (t < 0 || t >= ARRAY_SIZE(attach_type_name))
8928 		return NULL;
8929 
8930 	return attach_type_name[t];
8931 }
8932 
8933 const char *libbpf_bpf_link_type_str(enum bpf_link_type t)
8934 {
8935 	if (t < 0 || t >= ARRAY_SIZE(link_type_name))
8936 		return NULL;
8937 
8938 	return link_type_name[t];
8939 }
8940 
8941 const char *libbpf_bpf_map_type_str(enum bpf_map_type t)
8942 {
8943 	if (t < 0 || t >= ARRAY_SIZE(map_type_name))
8944 		return NULL;
8945 
8946 	return map_type_name[t];
8947 }
8948 
8949 const char *libbpf_bpf_prog_type_str(enum bpf_prog_type t)
8950 {
8951 	if (t < 0 || t >= ARRAY_SIZE(prog_type_name))
8952 		return NULL;
8953 
8954 	return prog_type_name[t];
8955 }
8956 
8957 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
8958 						     int sec_idx,
8959 						     size_t offset)
8960 {
8961 	struct bpf_map *map;
8962 	size_t i;
8963 
8964 	for (i = 0; i < obj->nr_maps; i++) {
8965 		map = &obj->maps[i];
8966 		if (!bpf_map__is_struct_ops(map))
8967 			continue;
8968 		if (map->sec_idx == sec_idx &&
8969 		    map->sec_offset <= offset &&
8970 		    offset - map->sec_offset < map->def.value_size)
8971 			return map;
8972 	}
8973 
8974 	return NULL;
8975 }
8976 
8977 /* Collect the reloc from ELF and populate the st_ops->progs[] */
8978 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
8979 					    Elf64_Shdr *shdr, Elf_Data *data)
8980 {
8981 	const struct btf_member *member;
8982 	struct bpf_struct_ops *st_ops;
8983 	struct bpf_program *prog;
8984 	unsigned int shdr_idx;
8985 	const struct btf *btf;
8986 	struct bpf_map *map;
8987 	unsigned int moff, insn_idx;
8988 	const char *name;
8989 	__u32 member_idx;
8990 	Elf64_Sym *sym;
8991 	Elf64_Rel *rel;
8992 	int i, nrels;
8993 
8994 	btf = obj->btf;
8995 	nrels = shdr->sh_size / shdr->sh_entsize;
8996 	for (i = 0; i < nrels; i++) {
8997 		rel = elf_rel_by_idx(data, i);
8998 		if (!rel) {
8999 			pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
9000 			return -LIBBPF_ERRNO__FORMAT;
9001 		}
9002 
9003 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
9004 		if (!sym) {
9005 			pr_warn("struct_ops reloc: symbol %zx not found\n",
9006 				(size_t)ELF64_R_SYM(rel->r_info));
9007 			return -LIBBPF_ERRNO__FORMAT;
9008 		}
9009 
9010 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
9011 		map = find_struct_ops_map_by_offset(obj, shdr->sh_info, rel->r_offset);
9012 		if (!map) {
9013 			pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
9014 				(size_t)rel->r_offset);
9015 			return -EINVAL;
9016 		}
9017 
9018 		moff = rel->r_offset - map->sec_offset;
9019 		shdr_idx = sym->st_shndx;
9020 		st_ops = map->st_ops;
9021 		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",
9022 			 map->name,
9023 			 (long long)(rel->r_info >> 32),
9024 			 (long long)sym->st_value,
9025 			 shdr_idx, (size_t)rel->r_offset,
9026 			 map->sec_offset, sym->st_name, name);
9027 
9028 		if (shdr_idx >= SHN_LORESERVE) {
9029 			pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
9030 				map->name, (size_t)rel->r_offset, shdr_idx);
9031 			return -LIBBPF_ERRNO__RELOC;
9032 		}
9033 		if (sym->st_value % BPF_INSN_SZ) {
9034 			pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
9035 				map->name, (unsigned long long)sym->st_value);
9036 			return -LIBBPF_ERRNO__FORMAT;
9037 		}
9038 		insn_idx = sym->st_value / BPF_INSN_SZ;
9039 
9040 		member = find_member_by_offset(st_ops->type, moff * 8);
9041 		if (!member) {
9042 			pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
9043 				map->name, moff);
9044 			return -EINVAL;
9045 		}
9046 		member_idx = member - btf_members(st_ops->type);
9047 		name = btf__name_by_offset(btf, member->name_off);
9048 
9049 		if (!resolve_func_ptr(btf, member->type, NULL)) {
9050 			pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
9051 				map->name, name);
9052 			return -EINVAL;
9053 		}
9054 
9055 		prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
9056 		if (!prog) {
9057 			pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
9058 				map->name, shdr_idx, name);
9059 			return -EINVAL;
9060 		}
9061 
9062 		/* prevent the use of BPF prog with invalid type */
9063 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
9064 			pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
9065 				map->name, prog->name);
9066 			return -EINVAL;
9067 		}
9068 
9069 		/* if we haven't yet processed this BPF program, record proper
9070 		 * attach_btf_id and member_idx
9071 		 */
9072 		if (!prog->attach_btf_id) {
9073 			prog->attach_btf_id = st_ops->type_id;
9074 			prog->expected_attach_type = member_idx;
9075 		}
9076 
9077 		/* struct_ops BPF prog can be re-used between multiple
9078 		 * .struct_ops & .struct_ops.link as long as it's the
9079 		 * same struct_ops struct definition and the same
9080 		 * function pointer field
9081 		 */
9082 		if (prog->attach_btf_id != st_ops->type_id ||
9083 		    prog->expected_attach_type != member_idx) {
9084 			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",
9085 				map->name, prog->name, prog->sec_name, prog->type,
9086 				prog->attach_btf_id, prog->expected_attach_type, name);
9087 			return -EINVAL;
9088 		}
9089 
9090 		st_ops->progs[member_idx] = prog;
9091 	}
9092 
9093 	return 0;
9094 }
9095 
9096 #define BTF_TRACE_PREFIX "btf_trace_"
9097 #define BTF_LSM_PREFIX "bpf_lsm_"
9098 #define BTF_ITER_PREFIX "bpf_iter_"
9099 #define BTF_MAX_NAME_SIZE 128
9100 
9101 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
9102 				const char **prefix, int *kind)
9103 {
9104 	switch (attach_type) {
9105 	case BPF_TRACE_RAW_TP:
9106 		*prefix = BTF_TRACE_PREFIX;
9107 		*kind = BTF_KIND_TYPEDEF;
9108 		break;
9109 	case BPF_LSM_MAC:
9110 	case BPF_LSM_CGROUP:
9111 		*prefix = BTF_LSM_PREFIX;
9112 		*kind = BTF_KIND_FUNC;
9113 		break;
9114 	case BPF_TRACE_ITER:
9115 		*prefix = BTF_ITER_PREFIX;
9116 		*kind = BTF_KIND_FUNC;
9117 		break;
9118 	default:
9119 		*prefix = "";
9120 		*kind = BTF_KIND_FUNC;
9121 	}
9122 }
9123 
9124 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
9125 				   const char *name, __u32 kind)
9126 {
9127 	char btf_type_name[BTF_MAX_NAME_SIZE];
9128 	int ret;
9129 
9130 	ret = snprintf(btf_type_name, sizeof(btf_type_name),
9131 		       "%s%s", prefix, name);
9132 	/* snprintf returns the number of characters written excluding the
9133 	 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
9134 	 * indicates truncation.
9135 	 */
9136 	if (ret < 0 || ret >= sizeof(btf_type_name))
9137 		return -ENAMETOOLONG;
9138 	return btf__find_by_name_kind(btf, btf_type_name, kind);
9139 }
9140 
9141 static inline int find_attach_btf_id(struct btf *btf, const char *name,
9142 				     enum bpf_attach_type attach_type)
9143 {
9144 	const char *prefix;
9145 	int kind;
9146 
9147 	btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
9148 	return find_btf_by_prefix_kind(btf, prefix, name, kind);
9149 }
9150 
9151 int libbpf_find_vmlinux_btf_id(const char *name,
9152 			       enum bpf_attach_type attach_type)
9153 {
9154 	struct btf *btf;
9155 	int err;
9156 
9157 	btf = btf__load_vmlinux_btf();
9158 	err = libbpf_get_error(btf);
9159 	if (err) {
9160 		pr_warn("vmlinux BTF is not found\n");
9161 		return libbpf_err(err);
9162 	}
9163 
9164 	err = find_attach_btf_id(btf, name, attach_type);
9165 	if (err <= 0)
9166 		pr_warn("%s is not found in vmlinux BTF\n", name);
9167 
9168 	btf__free(btf);
9169 	return libbpf_err(err);
9170 }
9171 
9172 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
9173 {
9174 	struct bpf_prog_info info;
9175 	__u32 info_len = sizeof(info);
9176 	struct btf *btf;
9177 	int err;
9178 
9179 	memset(&info, 0, info_len);
9180 	err = bpf_prog_get_info_by_fd(attach_prog_fd, &info, &info_len);
9181 	if (err) {
9182 		pr_warn("failed bpf_prog_get_info_by_fd for FD %d: %d\n",
9183 			attach_prog_fd, err);
9184 		return err;
9185 	}
9186 
9187 	err = -EINVAL;
9188 	if (!info.btf_id) {
9189 		pr_warn("The target program doesn't have BTF\n");
9190 		goto out;
9191 	}
9192 	btf = btf__load_from_kernel_by_id(info.btf_id);
9193 	err = libbpf_get_error(btf);
9194 	if (err) {
9195 		pr_warn("Failed to get BTF %d of the program: %d\n", info.btf_id, err);
9196 		goto out;
9197 	}
9198 	err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
9199 	btf__free(btf);
9200 	if (err <= 0) {
9201 		pr_warn("%s is not found in prog's BTF\n", name);
9202 		goto out;
9203 	}
9204 out:
9205 	return err;
9206 }
9207 
9208 static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
9209 			      enum bpf_attach_type attach_type,
9210 			      int *btf_obj_fd, int *btf_type_id)
9211 {
9212 	int ret, i;
9213 
9214 	ret = find_attach_btf_id(obj->btf_vmlinux, attach_name, attach_type);
9215 	if (ret > 0) {
9216 		*btf_obj_fd = 0; /* vmlinux BTF */
9217 		*btf_type_id = ret;
9218 		return 0;
9219 	}
9220 	if (ret != -ENOENT)
9221 		return ret;
9222 
9223 	ret = load_module_btfs(obj);
9224 	if (ret)
9225 		return ret;
9226 
9227 	for (i = 0; i < obj->btf_module_cnt; i++) {
9228 		const struct module_btf *mod = &obj->btf_modules[i];
9229 
9230 		ret = find_attach_btf_id(mod->btf, attach_name, attach_type);
9231 		if (ret > 0) {
9232 			*btf_obj_fd = mod->fd;
9233 			*btf_type_id = ret;
9234 			return 0;
9235 		}
9236 		if (ret == -ENOENT)
9237 			continue;
9238 
9239 		return ret;
9240 	}
9241 
9242 	return -ESRCH;
9243 }
9244 
9245 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
9246 				     int *btf_obj_fd, int *btf_type_id)
9247 {
9248 	enum bpf_attach_type attach_type = prog->expected_attach_type;
9249 	__u32 attach_prog_fd = prog->attach_prog_fd;
9250 	int err = 0;
9251 
9252 	/* BPF program's BTF ID */
9253 	if (prog->type == BPF_PROG_TYPE_EXT || attach_prog_fd) {
9254 		if (!attach_prog_fd) {
9255 			pr_warn("prog '%s': attach program FD is not set\n", prog->name);
9256 			return -EINVAL;
9257 		}
9258 		err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd);
9259 		if (err < 0) {
9260 			pr_warn("prog '%s': failed to find BPF program (FD %d) BTF ID for '%s': %d\n",
9261 				 prog->name, attach_prog_fd, attach_name, err);
9262 			return err;
9263 		}
9264 		*btf_obj_fd = 0;
9265 		*btf_type_id = err;
9266 		return 0;
9267 	}
9268 
9269 	/* kernel/module BTF ID */
9270 	if (prog->obj->gen_loader) {
9271 		bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
9272 		*btf_obj_fd = 0;
9273 		*btf_type_id = 1;
9274 	} else {
9275 		err = find_kernel_btf_id(prog->obj, attach_name, attach_type, btf_obj_fd, btf_type_id);
9276 	}
9277 	if (err) {
9278 		pr_warn("prog '%s': failed to find kernel BTF type ID of '%s': %d\n",
9279 			prog->name, attach_name, err);
9280 		return err;
9281 	}
9282 	return 0;
9283 }
9284 
9285 int libbpf_attach_type_by_name(const char *name,
9286 			       enum bpf_attach_type *attach_type)
9287 {
9288 	char *type_names;
9289 	const struct bpf_sec_def *sec_def;
9290 
9291 	if (!name)
9292 		return libbpf_err(-EINVAL);
9293 
9294 	sec_def = find_sec_def(name);
9295 	if (!sec_def) {
9296 		pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
9297 		type_names = libbpf_get_type_names(true);
9298 		if (type_names != NULL) {
9299 			pr_debug("attachable section(type) names are:%s\n", type_names);
9300 			free(type_names);
9301 		}
9302 
9303 		return libbpf_err(-EINVAL);
9304 	}
9305 
9306 	if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
9307 		return libbpf_err(-EINVAL);
9308 	if (!(sec_def->cookie & SEC_ATTACHABLE))
9309 		return libbpf_err(-EINVAL);
9310 
9311 	*attach_type = sec_def->expected_attach_type;
9312 	return 0;
9313 }
9314 
9315 int bpf_map__fd(const struct bpf_map *map)
9316 {
9317 	return map ? map->fd : libbpf_err(-EINVAL);
9318 }
9319 
9320 static bool map_uses_real_name(const struct bpf_map *map)
9321 {
9322 	/* Since libbpf started to support custom .data.* and .rodata.* maps,
9323 	 * their user-visible name differs from kernel-visible name. Users see
9324 	 * such map's corresponding ELF section name as a map name.
9325 	 * This check distinguishes .data/.rodata from .data.* and .rodata.*
9326 	 * maps to know which name has to be returned to the user.
9327 	 */
9328 	if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
9329 		return true;
9330 	if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
9331 		return true;
9332 	return false;
9333 }
9334 
9335 const char *bpf_map__name(const struct bpf_map *map)
9336 {
9337 	if (!map)
9338 		return NULL;
9339 
9340 	if (map_uses_real_name(map))
9341 		return map->real_name;
9342 
9343 	return map->name;
9344 }
9345 
9346 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
9347 {
9348 	return map->def.type;
9349 }
9350 
9351 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
9352 {
9353 	if (map->fd >= 0)
9354 		return libbpf_err(-EBUSY);
9355 	map->def.type = type;
9356 	return 0;
9357 }
9358 
9359 __u32 bpf_map__map_flags(const struct bpf_map *map)
9360 {
9361 	return map->def.map_flags;
9362 }
9363 
9364 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
9365 {
9366 	if (map->fd >= 0)
9367 		return libbpf_err(-EBUSY);
9368 	map->def.map_flags = flags;
9369 	return 0;
9370 }
9371 
9372 __u64 bpf_map__map_extra(const struct bpf_map *map)
9373 {
9374 	return map->map_extra;
9375 }
9376 
9377 int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
9378 {
9379 	if (map->fd >= 0)
9380 		return libbpf_err(-EBUSY);
9381 	map->map_extra = map_extra;
9382 	return 0;
9383 }
9384 
9385 __u32 bpf_map__numa_node(const struct bpf_map *map)
9386 {
9387 	return map->numa_node;
9388 }
9389 
9390 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
9391 {
9392 	if (map->fd >= 0)
9393 		return libbpf_err(-EBUSY);
9394 	map->numa_node = numa_node;
9395 	return 0;
9396 }
9397 
9398 __u32 bpf_map__key_size(const struct bpf_map *map)
9399 {
9400 	return map->def.key_size;
9401 }
9402 
9403 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
9404 {
9405 	if (map->fd >= 0)
9406 		return libbpf_err(-EBUSY);
9407 	map->def.key_size = size;
9408 	return 0;
9409 }
9410 
9411 __u32 bpf_map__value_size(const struct bpf_map *map)
9412 {
9413 	return map->def.value_size;
9414 }
9415 
9416 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
9417 {
9418 	if (map->fd >= 0)
9419 		return libbpf_err(-EBUSY);
9420 	map->def.value_size = size;
9421 	return 0;
9422 }
9423 
9424 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
9425 {
9426 	return map ? map->btf_key_type_id : 0;
9427 }
9428 
9429 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
9430 {
9431 	return map ? map->btf_value_type_id : 0;
9432 }
9433 
9434 int bpf_map__set_initial_value(struct bpf_map *map,
9435 			       const void *data, size_t size)
9436 {
9437 	if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG ||
9438 	    size != map->def.value_size || map->fd >= 0)
9439 		return libbpf_err(-EINVAL);
9440 
9441 	memcpy(map->mmaped, data, size);
9442 	return 0;
9443 }
9444 
9445 const void *bpf_map__initial_value(struct bpf_map *map, size_t *psize)
9446 {
9447 	if (!map->mmaped)
9448 		return NULL;
9449 	*psize = map->def.value_size;
9450 	return map->mmaped;
9451 }
9452 
9453 bool bpf_map__is_internal(const struct bpf_map *map)
9454 {
9455 	return map->libbpf_type != LIBBPF_MAP_UNSPEC;
9456 }
9457 
9458 __u32 bpf_map__ifindex(const struct bpf_map *map)
9459 {
9460 	return map->map_ifindex;
9461 }
9462 
9463 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
9464 {
9465 	if (map->fd >= 0)
9466 		return libbpf_err(-EBUSY);
9467 	map->map_ifindex = ifindex;
9468 	return 0;
9469 }
9470 
9471 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
9472 {
9473 	if (!bpf_map_type__is_map_in_map(map->def.type)) {
9474 		pr_warn("error: unsupported map type\n");
9475 		return libbpf_err(-EINVAL);
9476 	}
9477 	if (map->inner_map_fd != -1) {
9478 		pr_warn("error: inner_map_fd already specified\n");
9479 		return libbpf_err(-EINVAL);
9480 	}
9481 	if (map->inner_map) {
9482 		bpf_map__destroy(map->inner_map);
9483 		zfree(&map->inner_map);
9484 	}
9485 	map->inner_map_fd = fd;
9486 	return 0;
9487 }
9488 
9489 static struct bpf_map *
9490 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
9491 {
9492 	ssize_t idx;
9493 	struct bpf_map *s, *e;
9494 
9495 	if (!obj || !obj->maps)
9496 		return errno = EINVAL, NULL;
9497 
9498 	s = obj->maps;
9499 	e = obj->maps + obj->nr_maps;
9500 
9501 	if ((m < s) || (m >= e)) {
9502 		pr_warn("error in %s: map handler doesn't belong to object\n",
9503 			 __func__);
9504 		return errno = EINVAL, NULL;
9505 	}
9506 
9507 	idx = (m - obj->maps) + i;
9508 	if (idx >= obj->nr_maps || idx < 0)
9509 		return NULL;
9510 	return &obj->maps[idx];
9511 }
9512 
9513 struct bpf_map *
9514 bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
9515 {
9516 	if (prev == NULL)
9517 		return obj->maps;
9518 
9519 	return __bpf_map__iter(prev, obj, 1);
9520 }
9521 
9522 struct bpf_map *
9523 bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
9524 {
9525 	if (next == NULL) {
9526 		if (!obj->nr_maps)
9527 			return NULL;
9528 		return obj->maps + obj->nr_maps - 1;
9529 	}
9530 
9531 	return __bpf_map__iter(next, obj, -1);
9532 }
9533 
9534 struct bpf_map *
9535 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
9536 {
9537 	struct bpf_map *pos;
9538 
9539 	bpf_object__for_each_map(pos, obj) {
9540 		/* if it's a special internal map name (which always starts
9541 		 * with dot) then check if that special name matches the
9542 		 * real map name (ELF section name)
9543 		 */
9544 		if (name[0] == '.') {
9545 			if (pos->real_name && strcmp(pos->real_name, name) == 0)
9546 				return pos;
9547 			continue;
9548 		}
9549 		/* otherwise map name has to be an exact match */
9550 		if (map_uses_real_name(pos)) {
9551 			if (strcmp(pos->real_name, name) == 0)
9552 				return pos;
9553 			continue;
9554 		}
9555 		if (strcmp(pos->name, name) == 0)
9556 			return pos;
9557 	}
9558 	return errno = ENOENT, NULL;
9559 }
9560 
9561 int
9562 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
9563 {
9564 	return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
9565 }
9566 
9567 static int validate_map_op(const struct bpf_map *map, size_t key_sz,
9568 			   size_t value_sz, bool check_value_sz)
9569 {
9570 	if (map->fd <= 0)
9571 		return -ENOENT;
9572 
9573 	if (map->def.key_size != key_sz) {
9574 		pr_warn("map '%s': unexpected key size %zu provided, expected %u\n",
9575 			map->name, key_sz, map->def.key_size);
9576 		return -EINVAL;
9577 	}
9578 
9579 	if (!check_value_sz)
9580 		return 0;
9581 
9582 	switch (map->def.type) {
9583 	case BPF_MAP_TYPE_PERCPU_ARRAY:
9584 	case BPF_MAP_TYPE_PERCPU_HASH:
9585 	case BPF_MAP_TYPE_LRU_PERCPU_HASH:
9586 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: {
9587 		int num_cpu = libbpf_num_possible_cpus();
9588 		size_t elem_sz = roundup(map->def.value_size, 8);
9589 
9590 		if (value_sz != num_cpu * elem_sz) {
9591 			pr_warn("map '%s': unexpected value size %zu provided for per-CPU map, expected %d * %zu = %zd\n",
9592 				map->name, value_sz, num_cpu, elem_sz, num_cpu * elem_sz);
9593 			return -EINVAL;
9594 		}
9595 		break;
9596 	}
9597 	default:
9598 		if (map->def.value_size != value_sz) {
9599 			pr_warn("map '%s': unexpected value size %zu provided, expected %u\n",
9600 				map->name, value_sz, map->def.value_size);
9601 			return -EINVAL;
9602 		}
9603 		break;
9604 	}
9605 	return 0;
9606 }
9607 
9608 int bpf_map__lookup_elem(const struct bpf_map *map,
9609 			 const void *key, size_t key_sz,
9610 			 void *value, size_t value_sz, __u64 flags)
9611 {
9612 	int err;
9613 
9614 	err = validate_map_op(map, key_sz, value_sz, true);
9615 	if (err)
9616 		return libbpf_err(err);
9617 
9618 	return bpf_map_lookup_elem_flags(map->fd, key, value, flags);
9619 }
9620 
9621 int bpf_map__update_elem(const struct bpf_map *map,
9622 			 const void *key, size_t key_sz,
9623 			 const void *value, size_t value_sz, __u64 flags)
9624 {
9625 	int err;
9626 
9627 	err = validate_map_op(map, key_sz, value_sz, true);
9628 	if (err)
9629 		return libbpf_err(err);
9630 
9631 	return bpf_map_update_elem(map->fd, key, value, flags);
9632 }
9633 
9634 int bpf_map__delete_elem(const struct bpf_map *map,
9635 			 const void *key, size_t key_sz, __u64 flags)
9636 {
9637 	int err;
9638 
9639 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
9640 	if (err)
9641 		return libbpf_err(err);
9642 
9643 	return bpf_map_delete_elem_flags(map->fd, key, flags);
9644 }
9645 
9646 int bpf_map__lookup_and_delete_elem(const struct bpf_map *map,
9647 				    const void *key, size_t key_sz,
9648 				    void *value, size_t value_sz, __u64 flags)
9649 {
9650 	int err;
9651 
9652 	err = validate_map_op(map, key_sz, value_sz, true);
9653 	if (err)
9654 		return libbpf_err(err);
9655 
9656 	return bpf_map_lookup_and_delete_elem_flags(map->fd, key, value, flags);
9657 }
9658 
9659 int bpf_map__get_next_key(const struct bpf_map *map,
9660 			  const void *cur_key, void *next_key, size_t key_sz)
9661 {
9662 	int err;
9663 
9664 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
9665 	if (err)
9666 		return libbpf_err(err);
9667 
9668 	return bpf_map_get_next_key(map->fd, cur_key, next_key);
9669 }
9670 
9671 long libbpf_get_error(const void *ptr)
9672 {
9673 	if (!IS_ERR_OR_NULL(ptr))
9674 		return 0;
9675 
9676 	if (IS_ERR(ptr))
9677 		errno = -PTR_ERR(ptr);
9678 
9679 	/* If ptr == NULL, then errno should be already set by the failing
9680 	 * API, because libbpf never returns NULL on success and it now always
9681 	 * sets errno on error. So no extra errno handling for ptr == NULL
9682 	 * case.
9683 	 */
9684 	return -errno;
9685 }
9686 
9687 /* Replace link's underlying BPF program with the new one */
9688 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
9689 {
9690 	int ret;
9691 
9692 	ret = bpf_link_update(bpf_link__fd(link), bpf_program__fd(prog), NULL);
9693 	return libbpf_err_errno(ret);
9694 }
9695 
9696 /* Release "ownership" of underlying BPF resource (typically, BPF program
9697  * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
9698  * link, when destructed through bpf_link__destroy() call won't attempt to
9699  * detach/unregisted that BPF resource. This is useful in situations where,
9700  * say, attached BPF program has to outlive userspace program that attached it
9701  * in the system. Depending on type of BPF program, though, there might be
9702  * additional steps (like pinning BPF program in BPF FS) necessary to ensure
9703  * exit of userspace program doesn't trigger automatic detachment and clean up
9704  * inside the kernel.
9705  */
9706 void bpf_link__disconnect(struct bpf_link *link)
9707 {
9708 	link->disconnected = true;
9709 }
9710 
9711 int bpf_link__destroy(struct bpf_link *link)
9712 {
9713 	int err = 0;
9714 
9715 	if (IS_ERR_OR_NULL(link))
9716 		return 0;
9717 
9718 	if (!link->disconnected && link->detach)
9719 		err = link->detach(link);
9720 	if (link->pin_path)
9721 		free(link->pin_path);
9722 	if (link->dealloc)
9723 		link->dealloc(link);
9724 	else
9725 		free(link);
9726 
9727 	return libbpf_err(err);
9728 }
9729 
9730 int bpf_link__fd(const struct bpf_link *link)
9731 {
9732 	return link->fd;
9733 }
9734 
9735 const char *bpf_link__pin_path(const struct bpf_link *link)
9736 {
9737 	return link->pin_path;
9738 }
9739 
9740 static int bpf_link__detach_fd(struct bpf_link *link)
9741 {
9742 	return libbpf_err_errno(close(link->fd));
9743 }
9744 
9745 struct bpf_link *bpf_link__open(const char *path)
9746 {
9747 	struct bpf_link *link;
9748 	int fd;
9749 
9750 	fd = bpf_obj_get(path);
9751 	if (fd < 0) {
9752 		fd = -errno;
9753 		pr_warn("failed to open link at %s: %d\n", path, fd);
9754 		return libbpf_err_ptr(fd);
9755 	}
9756 
9757 	link = calloc(1, sizeof(*link));
9758 	if (!link) {
9759 		close(fd);
9760 		return libbpf_err_ptr(-ENOMEM);
9761 	}
9762 	link->detach = &bpf_link__detach_fd;
9763 	link->fd = fd;
9764 
9765 	link->pin_path = strdup(path);
9766 	if (!link->pin_path) {
9767 		bpf_link__destroy(link);
9768 		return libbpf_err_ptr(-ENOMEM);
9769 	}
9770 
9771 	return link;
9772 }
9773 
9774 int bpf_link__detach(struct bpf_link *link)
9775 {
9776 	return bpf_link_detach(link->fd) ? -errno : 0;
9777 }
9778 
9779 int bpf_link__pin(struct bpf_link *link, const char *path)
9780 {
9781 	int err;
9782 
9783 	if (link->pin_path)
9784 		return libbpf_err(-EBUSY);
9785 	err = make_parent_dir(path);
9786 	if (err)
9787 		return libbpf_err(err);
9788 	err = check_path(path);
9789 	if (err)
9790 		return libbpf_err(err);
9791 
9792 	link->pin_path = strdup(path);
9793 	if (!link->pin_path)
9794 		return libbpf_err(-ENOMEM);
9795 
9796 	if (bpf_obj_pin(link->fd, link->pin_path)) {
9797 		err = -errno;
9798 		zfree(&link->pin_path);
9799 		return libbpf_err(err);
9800 	}
9801 
9802 	pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
9803 	return 0;
9804 }
9805 
9806 int bpf_link__unpin(struct bpf_link *link)
9807 {
9808 	int err;
9809 
9810 	if (!link->pin_path)
9811 		return libbpf_err(-EINVAL);
9812 
9813 	err = unlink(link->pin_path);
9814 	if (err != 0)
9815 		return -errno;
9816 
9817 	pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
9818 	zfree(&link->pin_path);
9819 	return 0;
9820 }
9821 
9822 struct bpf_link_perf {
9823 	struct bpf_link link;
9824 	int perf_event_fd;
9825 	/* legacy kprobe support: keep track of probe identifier and type */
9826 	char *legacy_probe_name;
9827 	bool legacy_is_kprobe;
9828 	bool legacy_is_retprobe;
9829 };
9830 
9831 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
9832 static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
9833 
9834 static int bpf_link_perf_detach(struct bpf_link *link)
9835 {
9836 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
9837 	int err = 0;
9838 
9839 	if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
9840 		err = -errno;
9841 
9842 	if (perf_link->perf_event_fd != link->fd)
9843 		close(perf_link->perf_event_fd);
9844 	close(link->fd);
9845 
9846 	/* legacy uprobe/kprobe needs to be removed after perf event fd closure */
9847 	if (perf_link->legacy_probe_name) {
9848 		if (perf_link->legacy_is_kprobe) {
9849 			err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
9850 							 perf_link->legacy_is_retprobe);
9851 		} else {
9852 			err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
9853 							 perf_link->legacy_is_retprobe);
9854 		}
9855 	}
9856 
9857 	return err;
9858 }
9859 
9860 static void bpf_link_perf_dealloc(struct bpf_link *link)
9861 {
9862 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
9863 
9864 	free(perf_link->legacy_probe_name);
9865 	free(perf_link);
9866 }
9867 
9868 struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
9869 						     const struct bpf_perf_event_opts *opts)
9870 {
9871 	char errmsg[STRERR_BUFSIZE];
9872 	struct bpf_link_perf *link;
9873 	int prog_fd, link_fd = -1, err;
9874 	bool force_ioctl_attach;
9875 
9876 	if (!OPTS_VALID(opts, bpf_perf_event_opts))
9877 		return libbpf_err_ptr(-EINVAL);
9878 
9879 	if (pfd < 0) {
9880 		pr_warn("prog '%s': invalid perf event FD %d\n",
9881 			prog->name, pfd);
9882 		return libbpf_err_ptr(-EINVAL);
9883 	}
9884 	prog_fd = bpf_program__fd(prog);
9885 	if (prog_fd < 0) {
9886 		pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
9887 			prog->name);
9888 		return libbpf_err_ptr(-EINVAL);
9889 	}
9890 
9891 	link = calloc(1, sizeof(*link));
9892 	if (!link)
9893 		return libbpf_err_ptr(-ENOMEM);
9894 	link->link.detach = &bpf_link_perf_detach;
9895 	link->link.dealloc = &bpf_link_perf_dealloc;
9896 	link->perf_event_fd = pfd;
9897 
9898 	force_ioctl_attach = OPTS_GET(opts, force_ioctl_attach, false);
9899 	if (kernel_supports(prog->obj, FEAT_PERF_LINK) && !force_ioctl_attach) {
9900 		DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
9901 			.perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
9902 
9903 		link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
9904 		if (link_fd < 0) {
9905 			err = -errno;
9906 			pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %d (%s)\n",
9907 				prog->name, pfd,
9908 				err, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9909 			goto err_out;
9910 		}
9911 		link->link.fd = link_fd;
9912 	} else {
9913 		if (OPTS_GET(opts, bpf_cookie, 0)) {
9914 			pr_warn("prog '%s': user context value is not supported\n", prog->name);
9915 			err = -EOPNOTSUPP;
9916 			goto err_out;
9917 		}
9918 
9919 		if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
9920 			err = -errno;
9921 			pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
9922 				prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9923 			if (err == -EPROTO)
9924 				pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
9925 					prog->name, pfd);
9926 			goto err_out;
9927 		}
9928 		link->link.fd = pfd;
9929 	}
9930 	if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
9931 		err = -errno;
9932 		pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
9933 			prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9934 		goto err_out;
9935 	}
9936 
9937 	return &link->link;
9938 err_out:
9939 	if (link_fd >= 0)
9940 		close(link_fd);
9941 	free(link);
9942 	return libbpf_err_ptr(err);
9943 }
9944 
9945 struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
9946 {
9947 	return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
9948 }
9949 
9950 /*
9951  * this function is expected to parse integer in the range of [0, 2^31-1] from
9952  * given file using scanf format string fmt. If actual parsed value is
9953  * negative, the result might be indistinguishable from error
9954  */
9955 static int parse_uint_from_file(const char *file, const char *fmt)
9956 {
9957 	char buf[STRERR_BUFSIZE];
9958 	int err, ret;
9959 	FILE *f;
9960 
9961 	f = fopen(file, "r");
9962 	if (!f) {
9963 		err = -errno;
9964 		pr_debug("failed to open '%s': %s\n", file,
9965 			 libbpf_strerror_r(err, buf, sizeof(buf)));
9966 		return err;
9967 	}
9968 	err = fscanf(f, fmt, &ret);
9969 	if (err != 1) {
9970 		err = err == EOF ? -EIO : -errno;
9971 		pr_debug("failed to parse '%s': %s\n", file,
9972 			libbpf_strerror_r(err, buf, sizeof(buf)));
9973 		fclose(f);
9974 		return err;
9975 	}
9976 	fclose(f);
9977 	return ret;
9978 }
9979 
9980 static int determine_kprobe_perf_type(void)
9981 {
9982 	const char *file = "/sys/bus/event_source/devices/kprobe/type";
9983 
9984 	return parse_uint_from_file(file, "%d\n");
9985 }
9986 
9987 static int determine_uprobe_perf_type(void)
9988 {
9989 	const char *file = "/sys/bus/event_source/devices/uprobe/type";
9990 
9991 	return parse_uint_from_file(file, "%d\n");
9992 }
9993 
9994 static int determine_kprobe_retprobe_bit(void)
9995 {
9996 	const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
9997 
9998 	return parse_uint_from_file(file, "config:%d\n");
9999 }
10000 
10001 static int determine_uprobe_retprobe_bit(void)
10002 {
10003 	const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
10004 
10005 	return parse_uint_from_file(file, "config:%d\n");
10006 }
10007 
10008 #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
10009 #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
10010 
10011 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
10012 				 uint64_t offset, int pid, size_t ref_ctr_off)
10013 {
10014 	const size_t attr_sz = sizeof(struct perf_event_attr);
10015 	struct perf_event_attr attr;
10016 	char errmsg[STRERR_BUFSIZE];
10017 	int type, pfd;
10018 
10019 	if ((__u64)ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
10020 		return -EINVAL;
10021 
10022 	memset(&attr, 0, attr_sz);
10023 
10024 	type = uprobe ? determine_uprobe_perf_type()
10025 		      : determine_kprobe_perf_type();
10026 	if (type < 0) {
10027 		pr_warn("failed to determine %s perf type: %s\n",
10028 			uprobe ? "uprobe" : "kprobe",
10029 			libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
10030 		return type;
10031 	}
10032 	if (retprobe) {
10033 		int bit = uprobe ? determine_uprobe_retprobe_bit()
10034 				 : determine_kprobe_retprobe_bit();
10035 
10036 		if (bit < 0) {
10037 			pr_warn("failed to determine %s retprobe bit: %s\n",
10038 				uprobe ? "uprobe" : "kprobe",
10039 				libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
10040 			return bit;
10041 		}
10042 		attr.config |= 1 << bit;
10043 	}
10044 	attr.size = attr_sz;
10045 	attr.type = type;
10046 	attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
10047 	attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
10048 	attr.config2 = offset;		 /* kprobe_addr or probe_offset */
10049 
10050 	/* pid filter is meaningful only for uprobes */
10051 	pfd = syscall(__NR_perf_event_open, &attr,
10052 		      pid < 0 ? -1 : pid /* pid */,
10053 		      pid == -1 ? 0 : -1 /* cpu */,
10054 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
10055 	return pfd >= 0 ? pfd : -errno;
10056 }
10057 
10058 static int append_to_file(const char *file, const char *fmt, ...)
10059 {
10060 	int fd, n, err = 0;
10061 	va_list ap;
10062 	char buf[1024];
10063 
10064 	va_start(ap, fmt);
10065 	n = vsnprintf(buf, sizeof(buf), fmt, ap);
10066 	va_end(ap);
10067 
10068 	if (n < 0 || n >= sizeof(buf))
10069 		return -EINVAL;
10070 
10071 	fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
10072 	if (fd < 0)
10073 		return -errno;
10074 
10075 	if (write(fd, buf, n) < 0)
10076 		err = -errno;
10077 
10078 	close(fd);
10079 	return err;
10080 }
10081 
10082 #define DEBUGFS "/sys/kernel/debug/tracing"
10083 #define TRACEFS "/sys/kernel/tracing"
10084 
10085 static bool use_debugfs(void)
10086 {
10087 	static int has_debugfs = -1;
10088 
10089 	if (has_debugfs < 0)
10090 		has_debugfs = faccessat(AT_FDCWD, DEBUGFS, F_OK, AT_EACCESS) == 0;
10091 
10092 	return has_debugfs == 1;
10093 }
10094 
10095 static const char *tracefs_path(void)
10096 {
10097 	return use_debugfs() ? DEBUGFS : TRACEFS;
10098 }
10099 
10100 static const char *tracefs_kprobe_events(void)
10101 {
10102 	return use_debugfs() ? DEBUGFS"/kprobe_events" : TRACEFS"/kprobe_events";
10103 }
10104 
10105 static const char *tracefs_uprobe_events(void)
10106 {
10107 	return use_debugfs() ? DEBUGFS"/uprobe_events" : TRACEFS"/uprobe_events";
10108 }
10109 
10110 static void gen_kprobe_legacy_event_name(char *buf, size_t buf_sz,
10111 					 const char *kfunc_name, size_t offset)
10112 {
10113 	static int index = 0;
10114 	int i;
10115 
10116 	snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx_%d", getpid(), kfunc_name, offset,
10117 		 __sync_fetch_and_add(&index, 1));
10118 
10119 	/* sanitize binary_path in the probe name */
10120 	for (i = 0; buf[i]; i++) {
10121 		if (!isalnum(buf[i]))
10122 			buf[i] = '_';
10123 	}
10124 }
10125 
10126 static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
10127 				   const char *kfunc_name, size_t offset)
10128 {
10129 	return append_to_file(tracefs_kprobe_events(), "%c:%s/%s %s+0x%zx",
10130 			      retprobe ? 'r' : 'p',
10131 			      retprobe ? "kretprobes" : "kprobes",
10132 			      probe_name, kfunc_name, offset);
10133 }
10134 
10135 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
10136 {
10137 	return append_to_file(tracefs_kprobe_events(), "-:%s/%s",
10138 			      retprobe ? "kretprobes" : "kprobes", probe_name);
10139 }
10140 
10141 static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
10142 {
10143 	char file[256];
10144 
10145 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
10146 		 tracefs_path(), retprobe ? "kretprobes" : "kprobes", probe_name);
10147 
10148 	return parse_uint_from_file(file, "%d\n");
10149 }
10150 
10151 static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
10152 					 const char *kfunc_name, size_t offset, int pid)
10153 {
10154 	const size_t attr_sz = sizeof(struct perf_event_attr);
10155 	struct perf_event_attr attr;
10156 	char errmsg[STRERR_BUFSIZE];
10157 	int type, pfd, err;
10158 
10159 	err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
10160 	if (err < 0) {
10161 		pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
10162 			kfunc_name, offset,
10163 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10164 		return err;
10165 	}
10166 	type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
10167 	if (type < 0) {
10168 		err = type;
10169 		pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
10170 			kfunc_name, offset,
10171 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10172 		goto err_clean_legacy;
10173 	}
10174 
10175 	memset(&attr, 0, attr_sz);
10176 	attr.size = attr_sz;
10177 	attr.config = type;
10178 	attr.type = PERF_TYPE_TRACEPOINT;
10179 
10180 	pfd = syscall(__NR_perf_event_open, &attr,
10181 		      pid < 0 ? -1 : pid, /* pid */
10182 		      pid == -1 ? 0 : -1, /* cpu */
10183 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
10184 	if (pfd < 0) {
10185 		err = -errno;
10186 		pr_warn("legacy kprobe perf_event_open() failed: %s\n",
10187 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10188 		goto err_clean_legacy;
10189 	}
10190 	return pfd;
10191 
10192 err_clean_legacy:
10193 	/* Clear the newly added legacy kprobe_event */
10194 	remove_kprobe_event_legacy(probe_name, retprobe);
10195 	return err;
10196 }
10197 
10198 static const char *arch_specific_syscall_pfx(void)
10199 {
10200 #if defined(__x86_64__)
10201 	return "x64";
10202 #elif defined(__i386__)
10203 	return "ia32";
10204 #elif defined(__s390x__)
10205 	return "s390x";
10206 #elif defined(__s390__)
10207 	return "s390";
10208 #elif defined(__arm__)
10209 	return "arm";
10210 #elif defined(__aarch64__)
10211 	return "arm64";
10212 #elif defined(__mips__)
10213 	return "mips";
10214 #elif defined(__riscv)
10215 	return "riscv";
10216 #elif defined(__powerpc__)
10217 	return "powerpc";
10218 #elif defined(__powerpc64__)
10219 	return "powerpc64";
10220 #else
10221 	return NULL;
10222 #endif
10223 }
10224 
10225 static int probe_kern_syscall_wrapper(void)
10226 {
10227 	char syscall_name[64];
10228 	const char *ksys_pfx;
10229 
10230 	ksys_pfx = arch_specific_syscall_pfx();
10231 	if (!ksys_pfx)
10232 		return 0;
10233 
10234 	snprintf(syscall_name, sizeof(syscall_name), "__%s_sys_bpf", ksys_pfx);
10235 
10236 	if (determine_kprobe_perf_type() >= 0) {
10237 		int pfd;
10238 
10239 		pfd = perf_event_open_probe(false, false, syscall_name, 0, getpid(), 0);
10240 		if (pfd >= 0)
10241 			close(pfd);
10242 
10243 		return pfd >= 0 ? 1 : 0;
10244 	} else { /* legacy mode */
10245 		char probe_name[128];
10246 
10247 		gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name), syscall_name, 0);
10248 		if (add_kprobe_event_legacy(probe_name, false, syscall_name, 0) < 0)
10249 			return 0;
10250 
10251 		(void)remove_kprobe_event_legacy(probe_name, false);
10252 		return 1;
10253 	}
10254 }
10255 
10256 struct bpf_link *
10257 bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
10258 				const char *func_name,
10259 				const struct bpf_kprobe_opts *opts)
10260 {
10261 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
10262 	enum probe_attach_mode attach_mode;
10263 	char errmsg[STRERR_BUFSIZE];
10264 	char *legacy_probe = NULL;
10265 	struct bpf_link *link;
10266 	size_t offset;
10267 	bool retprobe, legacy;
10268 	int pfd, err;
10269 
10270 	if (!OPTS_VALID(opts, bpf_kprobe_opts))
10271 		return libbpf_err_ptr(-EINVAL);
10272 
10273 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
10274 	retprobe = OPTS_GET(opts, retprobe, false);
10275 	offset = OPTS_GET(opts, offset, 0);
10276 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10277 
10278 	legacy = determine_kprobe_perf_type() < 0;
10279 	switch (attach_mode) {
10280 	case PROBE_ATTACH_MODE_LEGACY:
10281 		legacy = true;
10282 		pe_opts.force_ioctl_attach = true;
10283 		break;
10284 	case PROBE_ATTACH_MODE_PERF:
10285 		if (legacy)
10286 			return libbpf_err_ptr(-ENOTSUP);
10287 		pe_opts.force_ioctl_attach = true;
10288 		break;
10289 	case PROBE_ATTACH_MODE_LINK:
10290 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
10291 			return libbpf_err_ptr(-ENOTSUP);
10292 		break;
10293 	case PROBE_ATTACH_MODE_DEFAULT:
10294 		break;
10295 	default:
10296 		return libbpf_err_ptr(-EINVAL);
10297 	}
10298 
10299 	if (!legacy) {
10300 		pfd = perf_event_open_probe(false /* uprobe */, retprobe,
10301 					    func_name, offset,
10302 					    -1 /* pid */, 0 /* ref_ctr_off */);
10303 	} else {
10304 		char probe_name[256];
10305 
10306 		gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name),
10307 					     func_name, offset);
10308 
10309 		legacy_probe = strdup(probe_name);
10310 		if (!legacy_probe)
10311 			return libbpf_err_ptr(-ENOMEM);
10312 
10313 		pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
10314 						    offset, -1 /* pid */);
10315 	}
10316 	if (pfd < 0) {
10317 		err = -errno;
10318 		pr_warn("prog '%s': failed to create %s '%s+0x%zx' perf event: %s\n",
10319 			prog->name, retprobe ? "kretprobe" : "kprobe",
10320 			func_name, offset,
10321 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10322 		goto err_out;
10323 	}
10324 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
10325 	err = libbpf_get_error(link);
10326 	if (err) {
10327 		close(pfd);
10328 		pr_warn("prog '%s': failed to attach to %s '%s+0x%zx': %s\n",
10329 			prog->name, retprobe ? "kretprobe" : "kprobe",
10330 			func_name, offset,
10331 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10332 		goto err_clean_legacy;
10333 	}
10334 	if (legacy) {
10335 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10336 
10337 		perf_link->legacy_probe_name = legacy_probe;
10338 		perf_link->legacy_is_kprobe = true;
10339 		perf_link->legacy_is_retprobe = retprobe;
10340 	}
10341 
10342 	return link;
10343 
10344 err_clean_legacy:
10345 	if (legacy)
10346 		remove_kprobe_event_legacy(legacy_probe, retprobe);
10347 err_out:
10348 	free(legacy_probe);
10349 	return libbpf_err_ptr(err);
10350 }
10351 
10352 struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
10353 					    bool retprobe,
10354 					    const char *func_name)
10355 {
10356 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
10357 		.retprobe = retprobe,
10358 	);
10359 
10360 	return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
10361 }
10362 
10363 struct bpf_link *bpf_program__attach_ksyscall(const struct bpf_program *prog,
10364 					      const char *syscall_name,
10365 					      const struct bpf_ksyscall_opts *opts)
10366 {
10367 	LIBBPF_OPTS(bpf_kprobe_opts, kprobe_opts);
10368 	char func_name[128];
10369 
10370 	if (!OPTS_VALID(opts, bpf_ksyscall_opts))
10371 		return libbpf_err_ptr(-EINVAL);
10372 
10373 	if (kernel_supports(prog->obj, FEAT_SYSCALL_WRAPPER)) {
10374 		/* arch_specific_syscall_pfx() should never return NULL here
10375 		 * because it is guarded by kernel_supports(). However, since
10376 		 * compiler does not know that we have an explicit conditional
10377 		 * as well.
10378 		 */
10379 		snprintf(func_name, sizeof(func_name), "__%s_sys_%s",
10380 			 arch_specific_syscall_pfx() ? : "", syscall_name);
10381 	} else {
10382 		snprintf(func_name, sizeof(func_name), "__se_sys_%s", syscall_name);
10383 	}
10384 
10385 	kprobe_opts.retprobe = OPTS_GET(opts, retprobe, false);
10386 	kprobe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10387 
10388 	return bpf_program__attach_kprobe_opts(prog, func_name, &kprobe_opts);
10389 }
10390 
10391 /* Adapted from perf/util/string.c */
10392 static bool glob_match(const char *str, const char *pat)
10393 {
10394 	while (*str && *pat && *pat != '*') {
10395 		if (*pat == '?') {      /* Matches any single character */
10396 			str++;
10397 			pat++;
10398 			continue;
10399 		}
10400 		if (*str != *pat)
10401 			return false;
10402 		str++;
10403 		pat++;
10404 	}
10405 	/* Check wild card */
10406 	if (*pat == '*') {
10407 		while (*pat == '*')
10408 			pat++;
10409 		if (!*pat) /* Tail wild card matches all */
10410 			return true;
10411 		while (*str)
10412 			if (glob_match(str++, pat))
10413 				return true;
10414 	}
10415 	return !*str && !*pat;
10416 }
10417 
10418 struct kprobe_multi_resolve {
10419 	const char *pattern;
10420 	unsigned long *addrs;
10421 	size_t cap;
10422 	size_t cnt;
10423 };
10424 
10425 static int
10426 resolve_kprobe_multi_cb(unsigned long long sym_addr, char sym_type,
10427 			const char *sym_name, void *ctx)
10428 {
10429 	struct kprobe_multi_resolve *res = ctx;
10430 	int err;
10431 
10432 	if (!glob_match(sym_name, res->pattern))
10433 		return 0;
10434 
10435 	err = libbpf_ensure_mem((void **) &res->addrs, &res->cap, sizeof(unsigned long),
10436 				res->cnt + 1);
10437 	if (err)
10438 		return err;
10439 
10440 	res->addrs[res->cnt++] = (unsigned long) sym_addr;
10441 	return 0;
10442 }
10443 
10444 struct bpf_link *
10445 bpf_program__attach_kprobe_multi_opts(const struct bpf_program *prog,
10446 				      const char *pattern,
10447 				      const struct bpf_kprobe_multi_opts *opts)
10448 {
10449 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
10450 	struct kprobe_multi_resolve res = {
10451 		.pattern = pattern,
10452 	};
10453 	struct bpf_link *link = NULL;
10454 	char errmsg[STRERR_BUFSIZE];
10455 	const unsigned long *addrs;
10456 	int err, link_fd, prog_fd;
10457 	const __u64 *cookies;
10458 	const char **syms;
10459 	bool retprobe;
10460 	size_t cnt;
10461 
10462 	if (!OPTS_VALID(opts, bpf_kprobe_multi_opts))
10463 		return libbpf_err_ptr(-EINVAL);
10464 
10465 	syms    = OPTS_GET(opts, syms, false);
10466 	addrs   = OPTS_GET(opts, addrs, false);
10467 	cnt     = OPTS_GET(opts, cnt, false);
10468 	cookies = OPTS_GET(opts, cookies, false);
10469 
10470 	if (!pattern && !addrs && !syms)
10471 		return libbpf_err_ptr(-EINVAL);
10472 	if (pattern && (addrs || syms || cookies || cnt))
10473 		return libbpf_err_ptr(-EINVAL);
10474 	if (!pattern && !cnt)
10475 		return libbpf_err_ptr(-EINVAL);
10476 	if (addrs && syms)
10477 		return libbpf_err_ptr(-EINVAL);
10478 
10479 	if (pattern) {
10480 		err = libbpf_kallsyms_parse(resolve_kprobe_multi_cb, &res);
10481 		if (err)
10482 			goto error;
10483 		if (!res.cnt) {
10484 			err = -ENOENT;
10485 			goto error;
10486 		}
10487 		addrs = res.addrs;
10488 		cnt = res.cnt;
10489 	}
10490 
10491 	retprobe = OPTS_GET(opts, retprobe, false);
10492 
10493 	lopts.kprobe_multi.syms = syms;
10494 	lopts.kprobe_multi.addrs = addrs;
10495 	lopts.kprobe_multi.cookies = cookies;
10496 	lopts.kprobe_multi.cnt = cnt;
10497 	lopts.kprobe_multi.flags = retprobe ? BPF_F_KPROBE_MULTI_RETURN : 0;
10498 
10499 	link = calloc(1, sizeof(*link));
10500 	if (!link) {
10501 		err = -ENOMEM;
10502 		goto error;
10503 	}
10504 	link->detach = &bpf_link__detach_fd;
10505 
10506 	prog_fd = bpf_program__fd(prog);
10507 	link_fd = bpf_link_create(prog_fd, 0, BPF_TRACE_KPROBE_MULTI, &lopts);
10508 	if (link_fd < 0) {
10509 		err = -errno;
10510 		pr_warn("prog '%s': failed to attach: %s\n",
10511 			prog->name, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10512 		goto error;
10513 	}
10514 	link->fd = link_fd;
10515 	free(res.addrs);
10516 	return link;
10517 
10518 error:
10519 	free(link);
10520 	free(res.addrs);
10521 	return libbpf_err_ptr(err);
10522 }
10523 
10524 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10525 {
10526 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
10527 	unsigned long offset = 0;
10528 	const char *func_name;
10529 	char *func;
10530 	int n;
10531 
10532 	*link = NULL;
10533 
10534 	/* no auto-attach for SEC("kprobe") and SEC("kretprobe") */
10535 	if (strcmp(prog->sec_name, "kprobe") == 0 || strcmp(prog->sec_name, "kretprobe") == 0)
10536 		return 0;
10537 
10538 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
10539 	if (opts.retprobe)
10540 		func_name = prog->sec_name + sizeof("kretprobe/") - 1;
10541 	else
10542 		func_name = prog->sec_name + sizeof("kprobe/") - 1;
10543 
10544 	n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
10545 	if (n < 1) {
10546 		pr_warn("kprobe name is invalid: %s\n", func_name);
10547 		return -EINVAL;
10548 	}
10549 	if (opts.retprobe && offset != 0) {
10550 		free(func);
10551 		pr_warn("kretprobes do not support offset specification\n");
10552 		return -EINVAL;
10553 	}
10554 
10555 	opts.offset = offset;
10556 	*link = bpf_program__attach_kprobe_opts(prog, func, &opts);
10557 	free(func);
10558 	return libbpf_get_error(*link);
10559 }
10560 
10561 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10562 {
10563 	LIBBPF_OPTS(bpf_ksyscall_opts, opts);
10564 	const char *syscall_name;
10565 
10566 	*link = NULL;
10567 
10568 	/* no auto-attach for SEC("ksyscall") and SEC("kretsyscall") */
10569 	if (strcmp(prog->sec_name, "ksyscall") == 0 || strcmp(prog->sec_name, "kretsyscall") == 0)
10570 		return 0;
10571 
10572 	opts.retprobe = str_has_pfx(prog->sec_name, "kretsyscall/");
10573 	if (opts.retprobe)
10574 		syscall_name = prog->sec_name + sizeof("kretsyscall/") - 1;
10575 	else
10576 		syscall_name = prog->sec_name + sizeof("ksyscall/") - 1;
10577 
10578 	*link = bpf_program__attach_ksyscall(prog, syscall_name, &opts);
10579 	return *link ? 0 : -errno;
10580 }
10581 
10582 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10583 {
10584 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts);
10585 	const char *spec;
10586 	char *pattern;
10587 	int n;
10588 
10589 	*link = NULL;
10590 
10591 	/* no auto-attach for SEC("kprobe.multi") and SEC("kretprobe.multi") */
10592 	if (strcmp(prog->sec_name, "kprobe.multi") == 0 ||
10593 	    strcmp(prog->sec_name, "kretprobe.multi") == 0)
10594 		return 0;
10595 
10596 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe.multi/");
10597 	if (opts.retprobe)
10598 		spec = prog->sec_name + sizeof("kretprobe.multi/") - 1;
10599 	else
10600 		spec = prog->sec_name + sizeof("kprobe.multi/") - 1;
10601 
10602 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
10603 	if (n < 1) {
10604 		pr_warn("kprobe multi pattern is invalid: %s\n", pattern);
10605 		return -EINVAL;
10606 	}
10607 
10608 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
10609 	free(pattern);
10610 	return libbpf_get_error(*link);
10611 }
10612 
10613 static void gen_uprobe_legacy_event_name(char *buf, size_t buf_sz,
10614 					 const char *binary_path, uint64_t offset)
10615 {
10616 	int i;
10617 
10618 	snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx", getpid(), binary_path, (size_t)offset);
10619 
10620 	/* sanitize binary_path in the probe name */
10621 	for (i = 0; buf[i]; i++) {
10622 		if (!isalnum(buf[i]))
10623 			buf[i] = '_';
10624 	}
10625 }
10626 
10627 static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
10628 					  const char *binary_path, size_t offset)
10629 {
10630 	return append_to_file(tracefs_uprobe_events(), "%c:%s/%s %s:0x%zx",
10631 			      retprobe ? 'r' : 'p',
10632 			      retprobe ? "uretprobes" : "uprobes",
10633 			      probe_name, binary_path, offset);
10634 }
10635 
10636 static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
10637 {
10638 	return append_to_file(tracefs_uprobe_events(), "-:%s/%s",
10639 			      retprobe ? "uretprobes" : "uprobes", probe_name);
10640 }
10641 
10642 static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
10643 {
10644 	char file[512];
10645 
10646 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
10647 		 tracefs_path(), retprobe ? "uretprobes" : "uprobes", probe_name);
10648 
10649 	return parse_uint_from_file(file, "%d\n");
10650 }
10651 
10652 static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
10653 					 const char *binary_path, size_t offset, int pid)
10654 {
10655 	const size_t attr_sz = sizeof(struct perf_event_attr);
10656 	struct perf_event_attr attr;
10657 	int type, pfd, err;
10658 
10659 	err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
10660 	if (err < 0) {
10661 		pr_warn("failed to add legacy uprobe event for %s:0x%zx: %d\n",
10662 			binary_path, (size_t)offset, err);
10663 		return err;
10664 	}
10665 	type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
10666 	if (type < 0) {
10667 		err = type;
10668 		pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %d\n",
10669 			binary_path, offset, err);
10670 		goto err_clean_legacy;
10671 	}
10672 
10673 	memset(&attr, 0, attr_sz);
10674 	attr.size = attr_sz;
10675 	attr.config = type;
10676 	attr.type = PERF_TYPE_TRACEPOINT;
10677 
10678 	pfd = syscall(__NR_perf_event_open, &attr,
10679 		      pid < 0 ? -1 : pid, /* pid */
10680 		      pid == -1 ? 0 : -1, /* cpu */
10681 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
10682 	if (pfd < 0) {
10683 		err = -errno;
10684 		pr_warn("legacy uprobe perf_event_open() failed: %d\n", err);
10685 		goto err_clean_legacy;
10686 	}
10687 	return pfd;
10688 
10689 err_clean_legacy:
10690 	/* Clear the newly added legacy uprobe_event */
10691 	remove_uprobe_event_legacy(probe_name, retprobe);
10692 	return err;
10693 }
10694 
10695 /* Return next ELF section of sh_type after scn, or first of that type if scn is NULL. */
10696 static Elf_Scn *elf_find_next_scn_by_type(Elf *elf, int sh_type, Elf_Scn *scn)
10697 {
10698 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
10699 		GElf_Shdr sh;
10700 
10701 		if (!gelf_getshdr(scn, &sh))
10702 			continue;
10703 		if (sh.sh_type == sh_type)
10704 			return scn;
10705 	}
10706 	return NULL;
10707 }
10708 
10709 /* Find offset of function name in the provided ELF object. "binary_path" is
10710  * the path to the ELF binary represented by "elf", and only used for error
10711  * reporting matters. "name" matches symbol name or name@@LIB for library
10712  * functions.
10713  */
10714 static long elf_find_func_offset(Elf *elf, const char *binary_path, const char *name)
10715 {
10716 	int i, sh_types[2] = { SHT_DYNSYM, SHT_SYMTAB };
10717 	bool is_shared_lib, is_name_qualified;
10718 	long ret = -ENOENT;
10719 	size_t name_len;
10720 	GElf_Ehdr ehdr;
10721 
10722 	if (!gelf_getehdr(elf, &ehdr)) {
10723 		pr_warn("elf: failed to get ehdr from %s: %s\n", binary_path, elf_errmsg(-1));
10724 		ret = -LIBBPF_ERRNO__FORMAT;
10725 		goto out;
10726 	}
10727 	/* for shared lib case, we do not need to calculate relative offset */
10728 	is_shared_lib = ehdr.e_type == ET_DYN;
10729 
10730 	name_len = strlen(name);
10731 	/* Does name specify "@@LIB"? */
10732 	is_name_qualified = strstr(name, "@@") != NULL;
10733 
10734 	/* Search SHT_DYNSYM, SHT_SYMTAB for symbol. This search order is used because if
10735 	 * a binary is stripped, it may only have SHT_DYNSYM, and a fully-statically
10736 	 * linked binary may not have SHT_DYMSYM, so absence of a section should not be
10737 	 * reported as a warning/error.
10738 	 */
10739 	for (i = 0; i < ARRAY_SIZE(sh_types); i++) {
10740 		size_t nr_syms, strtabidx, idx;
10741 		Elf_Data *symbols = NULL;
10742 		Elf_Scn *scn = NULL;
10743 		int last_bind = -1;
10744 		const char *sname;
10745 		GElf_Shdr sh;
10746 
10747 		scn = elf_find_next_scn_by_type(elf, sh_types[i], NULL);
10748 		if (!scn) {
10749 			pr_debug("elf: failed to find symbol table ELF sections in '%s'\n",
10750 				 binary_path);
10751 			continue;
10752 		}
10753 		if (!gelf_getshdr(scn, &sh))
10754 			continue;
10755 		strtabidx = sh.sh_link;
10756 		symbols = elf_getdata(scn, 0);
10757 		if (!symbols) {
10758 			pr_warn("elf: failed to get symbols for symtab section in '%s': %s\n",
10759 				binary_path, elf_errmsg(-1));
10760 			ret = -LIBBPF_ERRNO__FORMAT;
10761 			goto out;
10762 		}
10763 		nr_syms = symbols->d_size / sh.sh_entsize;
10764 
10765 		for (idx = 0; idx < nr_syms; idx++) {
10766 			int curr_bind;
10767 			GElf_Sym sym;
10768 			Elf_Scn *sym_scn;
10769 			GElf_Shdr sym_sh;
10770 
10771 			if (!gelf_getsym(symbols, idx, &sym))
10772 				continue;
10773 
10774 			if (GELF_ST_TYPE(sym.st_info) != STT_FUNC)
10775 				continue;
10776 
10777 			sname = elf_strptr(elf, strtabidx, sym.st_name);
10778 			if (!sname)
10779 				continue;
10780 
10781 			curr_bind = GELF_ST_BIND(sym.st_info);
10782 
10783 			/* User can specify func, func@@LIB or func@@LIB_VERSION. */
10784 			if (strncmp(sname, name, name_len) != 0)
10785 				continue;
10786 			/* ...but we don't want a search for "foo" to match 'foo2" also, so any
10787 			 * additional characters in sname should be of the form "@@LIB".
10788 			 */
10789 			if (!is_name_qualified && sname[name_len] != '\0' && sname[name_len] != '@')
10790 				continue;
10791 
10792 			if (ret >= 0) {
10793 				/* handle multiple matches */
10794 				if (last_bind != STB_WEAK && curr_bind != STB_WEAK) {
10795 					/* Only accept one non-weak bind. */
10796 					pr_warn("elf: ambiguous match for '%s', '%s' in '%s'\n",
10797 						sname, name, binary_path);
10798 					ret = -LIBBPF_ERRNO__FORMAT;
10799 					goto out;
10800 				} else if (curr_bind == STB_WEAK) {
10801 					/* already have a non-weak bind, and
10802 					 * this is a weak bind, so ignore.
10803 					 */
10804 					continue;
10805 				}
10806 			}
10807 
10808 			/* Transform symbol's virtual address (absolute for
10809 			 * binaries and relative for shared libs) into file
10810 			 * offset, which is what kernel is expecting for
10811 			 * uprobe/uretprobe attachment.
10812 			 * See Documentation/trace/uprobetracer.rst for more
10813 			 * details.
10814 			 * This is done by looking up symbol's containing
10815 			 * section's header and using it's virtual address
10816 			 * (sh_addr) and corresponding file offset (sh_offset)
10817 			 * to transform sym.st_value (virtual address) into
10818 			 * desired final file offset.
10819 			 */
10820 			sym_scn = elf_getscn(elf, sym.st_shndx);
10821 			if (!sym_scn)
10822 				continue;
10823 			if (!gelf_getshdr(sym_scn, &sym_sh))
10824 				continue;
10825 
10826 			ret = sym.st_value - sym_sh.sh_addr + sym_sh.sh_offset;
10827 			last_bind = curr_bind;
10828 		}
10829 		if (ret > 0)
10830 			break;
10831 	}
10832 
10833 	if (ret > 0) {
10834 		pr_debug("elf: symbol address match for '%s' in '%s': 0x%lx\n", name, binary_path,
10835 			 ret);
10836 	} else {
10837 		if (ret == 0) {
10838 			pr_warn("elf: '%s' is 0 in symtab for '%s': %s\n", name, binary_path,
10839 				is_shared_lib ? "should not be 0 in a shared library" :
10840 						"try using shared library path instead");
10841 			ret = -ENOENT;
10842 		} else {
10843 			pr_warn("elf: failed to find symbol '%s' in '%s'\n", name, binary_path);
10844 		}
10845 	}
10846 out:
10847 	return ret;
10848 }
10849 
10850 /* Find offset of function name in ELF object specified by path. "name" matches
10851  * symbol name or name@@LIB for library functions.
10852  */
10853 static long elf_find_func_offset_from_file(const char *binary_path, const char *name)
10854 {
10855 	char errmsg[STRERR_BUFSIZE];
10856 	long ret = -ENOENT;
10857 	Elf *elf;
10858 	int fd;
10859 
10860 	fd = open(binary_path, O_RDONLY | O_CLOEXEC);
10861 	if (fd < 0) {
10862 		ret = -errno;
10863 		pr_warn("failed to open %s: %s\n", binary_path,
10864 			libbpf_strerror_r(ret, errmsg, sizeof(errmsg)));
10865 		return ret;
10866 	}
10867 	elf = elf_begin(fd, ELF_C_READ_MMAP, NULL);
10868 	if (!elf) {
10869 		pr_warn("elf: could not read elf from %s: %s\n", binary_path, elf_errmsg(-1));
10870 		close(fd);
10871 		return -LIBBPF_ERRNO__FORMAT;
10872 	}
10873 
10874 	ret = elf_find_func_offset(elf, binary_path, name);
10875 	elf_end(elf);
10876 	close(fd);
10877 	return ret;
10878 }
10879 
10880 /* Find offset of function name in archive specified by path. Currently
10881  * supported are .zip files that do not compress their contents, as used on
10882  * Android in the form of APKs, for example. "file_name" is the name of the ELF
10883  * file inside the archive. "func_name" matches symbol name or name@@LIB for
10884  * library functions.
10885  *
10886  * An overview of the APK format specifically provided here:
10887  * https://en.wikipedia.org/w/index.php?title=Apk_(file_format)&oldid=1139099120#Package_contents
10888  */
10889 static long elf_find_func_offset_from_archive(const char *archive_path, const char *file_name,
10890 					      const char *func_name)
10891 {
10892 	struct zip_archive *archive;
10893 	struct zip_entry entry;
10894 	long ret;
10895 	Elf *elf;
10896 
10897 	archive = zip_archive_open(archive_path);
10898 	if (IS_ERR(archive)) {
10899 		ret = PTR_ERR(archive);
10900 		pr_warn("zip: failed to open %s: %ld\n", archive_path, ret);
10901 		return ret;
10902 	}
10903 
10904 	ret = zip_archive_find_entry(archive, file_name, &entry);
10905 	if (ret) {
10906 		pr_warn("zip: could not find archive member %s in %s: %ld\n", file_name,
10907 			archive_path, ret);
10908 		goto out;
10909 	}
10910 	pr_debug("zip: found entry for %s in %s at 0x%lx\n", file_name, archive_path,
10911 		 (unsigned long)entry.data_offset);
10912 
10913 	if (entry.compression) {
10914 		pr_warn("zip: entry %s of %s is compressed and cannot be handled\n", file_name,
10915 			archive_path);
10916 		ret = -LIBBPF_ERRNO__FORMAT;
10917 		goto out;
10918 	}
10919 
10920 	elf = elf_memory((void *)entry.data, entry.data_length);
10921 	if (!elf) {
10922 		pr_warn("elf: could not read elf file %s from %s: %s\n", file_name, archive_path,
10923 			elf_errmsg(-1));
10924 		ret = -LIBBPF_ERRNO__LIBELF;
10925 		goto out;
10926 	}
10927 
10928 	ret = elf_find_func_offset(elf, file_name, func_name);
10929 	if (ret > 0) {
10930 		pr_debug("elf: symbol address match for %s of %s in %s: 0x%x + 0x%lx = 0x%lx\n",
10931 			 func_name, file_name, archive_path, entry.data_offset, ret,
10932 			 ret + entry.data_offset);
10933 		ret += entry.data_offset;
10934 	}
10935 	elf_end(elf);
10936 
10937 out:
10938 	zip_archive_close(archive);
10939 	return ret;
10940 }
10941 
10942 static const char *arch_specific_lib_paths(void)
10943 {
10944 	/*
10945 	 * Based on https://packages.debian.org/sid/libc6.
10946 	 *
10947 	 * Assume that the traced program is built for the same architecture
10948 	 * as libbpf, which should cover the vast majority of cases.
10949 	 */
10950 #if defined(__x86_64__)
10951 	return "/lib/x86_64-linux-gnu";
10952 #elif defined(__i386__)
10953 	return "/lib/i386-linux-gnu";
10954 #elif defined(__s390x__)
10955 	return "/lib/s390x-linux-gnu";
10956 #elif defined(__s390__)
10957 	return "/lib/s390-linux-gnu";
10958 #elif defined(__arm__) && defined(__SOFTFP__)
10959 	return "/lib/arm-linux-gnueabi";
10960 #elif defined(__arm__) && !defined(__SOFTFP__)
10961 	return "/lib/arm-linux-gnueabihf";
10962 #elif defined(__aarch64__)
10963 	return "/lib/aarch64-linux-gnu";
10964 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 64
10965 	return "/lib/mips64el-linux-gnuabi64";
10966 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 32
10967 	return "/lib/mipsel-linux-gnu";
10968 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
10969 	return "/lib/powerpc64le-linux-gnu";
10970 #elif defined(__sparc__) && defined(__arch64__)
10971 	return "/lib/sparc64-linux-gnu";
10972 #elif defined(__riscv) && __riscv_xlen == 64
10973 	return "/lib/riscv64-linux-gnu";
10974 #else
10975 	return NULL;
10976 #endif
10977 }
10978 
10979 /* Get full path to program/shared library. */
10980 static int resolve_full_path(const char *file, char *result, size_t result_sz)
10981 {
10982 	const char *search_paths[3] = {};
10983 	int i, perm;
10984 
10985 	if (str_has_sfx(file, ".so") || strstr(file, ".so.")) {
10986 		search_paths[0] = getenv("LD_LIBRARY_PATH");
10987 		search_paths[1] = "/usr/lib64:/usr/lib";
10988 		search_paths[2] = arch_specific_lib_paths();
10989 		perm = R_OK;
10990 	} else {
10991 		search_paths[0] = getenv("PATH");
10992 		search_paths[1] = "/usr/bin:/usr/sbin";
10993 		perm = R_OK | X_OK;
10994 	}
10995 
10996 	for (i = 0; i < ARRAY_SIZE(search_paths); i++) {
10997 		const char *s;
10998 
10999 		if (!search_paths[i])
11000 			continue;
11001 		for (s = search_paths[i]; s != NULL; s = strchr(s, ':')) {
11002 			char *next_path;
11003 			int seg_len;
11004 
11005 			if (s[0] == ':')
11006 				s++;
11007 			next_path = strchr(s, ':');
11008 			seg_len = next_path ? next_path - s : strlen(s);
11009 			if (!seg_len)
11010 				continue;
11011 			snprintf(result, result_sz, "%.*s/%s", seg_len, s, file);
11012 			/* ensure it has required permissions */
11013 			if (faccessat(AT_FDCWD, result, perm, AT_EACCESS) < 0)
11014 				continue;
11015 			pr_debug("resolved '%s' to '%s'\n", file, result);
11016 			return 0;
11017 		}
11018 	}
11019 	return -ENOENT;
11020 }
11021 
11022 LIBBPF_API struct bpf_link *
11023 bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
11024 				const char *binary_path, size_t func_offset,
11025 				const struct bpf_uprobe_opts *opts)
11026 {
11027 	const char *archive_path = NULL, *archive_sep = NULL;
11028 	char errmsg[STRERR_BUFSIZE], *legacy_probe = NULL;
11029 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11030 	enum probe_attach_mode attach_mode;
11031 	char full_path[PATH_MAX];
11032 	struct bpf_link *link;
11033 	size_t ref_ctr_off;
11034 	int pfd, err;
11035 	bool retprobe, legacy;
11036 	const char *func_name;
11037 
11038 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
11039 		return libbpf_err_ptr(-EINVAL);
11040 
11041 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
11042 	retprobe = OPTS_GET(opts, retprobe, false);
11043 	ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
11044 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11045 
11046 	if (!binary_path)
11047 		return libbpf_err_ptr(-EINVAL);
11048 
11049 	/* Check if "binary_path" refers to an archive. */
11050 	archive_sep = strstr(binary_path, "!/");
11051 	if (archive_sep) {
11052 		full_path[0] = '\0';
11053 		libbpf_strlcpy(full_path, binary_path,
11054 			       min(sizeof(full_path), (size_t)(archive_sep - binary_path + 1)));
11055 		archive_path = full_path;
11056 		binary_path = archive_sep + 2;
11057 	} else if (!strchr(binary_path, '/')) {
11058 		err = resolve_full_path(binary_path, full_path, sizeof(full_path));
11059 		if (err) {
11060 			pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11061 				prog->name, binary_path, err);
11062 			return libbpf_err_ptr(err);
11063 		}
11064 		binary_path = full_path;
11065 	}
11066 	func_name = OPTS_GET(opts, func_name, NULL);
11067 	if (func_name) {
11068 		long sym_off;
11069 
11070 		if (archive_path) {
11071 			sym_off = elf_find_func_offset_from_archive(archive_path, binary_path,
11072 								    func_name);
11073 			binary_path = archive_path;
11074 		} else {
11075 			sym_off = elf_find_func_offset_from_file(binary_path, func_name);
11076 		}
11077 		if (sym_off < 0)
11078 			return libbpf_err_ptr(sym_off);
11079 		func_offset += sym_off;
11080 	}
11081 
11082 	legacy = determine_uprobe_perf_type() < 0;
11083 	switch (attach_mode) {
11084 	case PROBE_ATTACH_MODE_LEGACY:
11085 		legacy = true;
11086 		pe_opts.force_ioctl_attach = true;
11087 		break;
11088 	case PROBE_ATTACH_MODE_PERF:
11089 		if (legacy)
11090 			return libbpf_err_ptr(-ENOTSUP);
11091 		pe_opts.force_ioctl_attach = true;
11092 		break;
11093 	case PROBE_ATTACH_MODE_LINK:
11094 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
11095 			return libbpf_err_ptr(-ENOTSUP);
11096 		break;
11097 	case PROBE_ATTACH_MODE_DEFAULT:
11098 		break;
11099 	default:
11100 		return libbpf_err_ptr(-EINVAL);
11101 	}
11102 
11103 	if (!legacy) {
11104 		pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
11105 					    func_offset, pid, ref_ctr_off);
11106 	} else {
11107 		char probe_name[PATH_MAX + 64];
11108 
11109 		if (ref_ctr_off)
11110 			return libbpf_err_ptr(-EINVAL);
11111 
11112 		gen_uprobe_legacy_event_name(probe_name, sizeof(probe_name),
11113 					     binary_path, func_offset);
11114 
11115 		legacy_probe = strdup(probe_name);
11116 		if (!legacy_probe)
11117 			return libbpf_err_ptr(-ENOMEM);
11118 
11119 		pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
11120 						    binary_path, func_offset, pid);
11121 	}
11122 	if (pfd < 0) {
11123 		err = -errno;
11124 		pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
11125 			prog->name, retprobe ? "uretprobe" : "uprobe",
11126 			binary_path, func_offset,
11127 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11128 		goto err_out;
11129 	}
11130 
11131 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11132 	err = libbpf_get_error(link);
11133 	if (err) {
11134 		close(pfd);
11135 		pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
11136 			prog->name, retprobe ? "uretprobe" : "uprobe",
11137 			binary_path, func_offset,
11138 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11139 		goto err_clean_legacy;
11140 	}
11141 	if (legacy) {
11142 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
11143 
11144 		perf_link->legacy_probe_name = legacy_probe;
11145 		perf_link->legacy_is_kprobe = false;
11146 		perf_link->legacy_is_retprobe = retprobe;
11147 	}
11148 	return link;
11149 
11150 err_clean_legacy:
11151 	if (legacy)
11152 		remove_uprobe_event_legacy(legacy_probe, retprobe);
11153 err_out:
11154 	free(legacy_probe);
11155 	return libbpf_err_ptr(err);
11156 }
11157 
11158 /* Format of u[ret]probe section definition supporting auto-attach:
11159  * u[ret]probe/binary:function[+offset]
11160  *
11161  * binary can be an absolute/relative path or a filename; the latter is resolved to a
11162  * full binary path via bpf_program__attach_uprobe_opts.
11163  *
11164  * Specifying uprobe+ ensures we carry out strict matching; either "uprobe" must be
11165  * specified (and auto-attach is not possible) or the above format is specified for
11166  * auto-attach.
11167  */
11168 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11169 {
11170 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts);
11171 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
11172 	int n, ret = -EINVAL;
11173 	long offset = 0;
11174 
11175 	*link = NULL;
11176 
11177 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[a-zA-Z0-9_.]+%li",
11178 		   &probe_type, &binary_path, &func_name, &offset);
11179 	switch (n) {
11180 	case 1:
11181 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
11182 		ret = 0;
11183 		break;
11184 	case 2:
11185 		pr_warn("prog '%s': section '%s' missing ':function[+offset]' specification\n",
11186 			prog->name, prog->sec_name);
11187 		break;
11188 	case 3:
11189 	case 4:
11190 		opts.retprobe = strcmp(probe_type, "uretprobe") == 0 ||
11191 				strcmp(probe_type, "uretprobe.s") == 0;
11192 		if (opts.retprobe && offset != 0) {
11193 			pr_warn("prog '%s': uretprobes do not support offset specification\n",
11194 				prog->name);
11195 			break;
11196 		}
11197 		opts.func_name = func_name;
11198 		*link = bpf_program__attach_uprobe_opts(prog, -1, binary_path, offset, &opts);
11199 		ret = libbpf_get_error(*link);
11200 		break;
11201 	default:
11202 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
11203 			prog->sec_name);
11204 		break;
11205 	}
11206 	free(probe_type);
11207 	free(binary_path);
11208 	free(func_name);
11209 
11210 	return ret;
11211 }
11212 
11213 struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
11214 					    bool retprobe, pid_t pid,
11215 					    const char *binary_path,
11216 					    size_t func_offset)
11217 {
11218 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
11219 
11220 	return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
11221 }
11222 
11223 struct bpf_link *bpf_program__attach_usdt(const struct bpf_program *prog,
11224 					  pid_t pid, const char *binary_path,
11225 					  const char *usdt_provider, const char *usdt_name,
11226 					  const struct bpf_usdt_opts *opts)
11227 {
11228 	char resolved_path[512];
11229 	struct bpf_object *obj = prog->obj;
11230 	struct bpf_link *link;
11231 	__u64 usdt_cookie;
11232 	int err;
11233 
11234 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
11235 		return libbpf_err_ptr(-EINVAL);
11236 
11237 	if (bpf_program__fd(prog) < 0) {
11238 		pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
11239 			prog->name);
11240 		return libbpf_err_ptr(-EINVAL);
11241 	}
11242 
11243 	if (!binary_path)
11244 		return libbpf_err_ptr(-EINVAL);
11245 
11246 	if (!strchr(binary_path, '/')) {
11247 		err = resolve_full_path(binary_path, resolved_path, sizeof(resolved_path));
11248 		if (err) {
11249 			pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11250 				prog->name, binary_path, err);
11251 			return libbpf_err_ptr(err);
11252 		}
11253 		binary_path = resolved_path;
11254 	}
11255 
11256 	/* USDT manager is instantiated lazily on first USDT attach. It will
11257 	 * be destroyed together with BPF object in bpf_object__close().
11258 	 */
11259 	if (IS_ERR(obj->usdt_man))
11260 		return libbpf_ptr(obj->usdt_man);
11261 	if (!obj->usdt_man) {
11262 		obj->usdt_man = usdt_manager_new(obj);
11263 		if (IS_ERR(obj->usdt_man))
11264 			return libbpf_ptr(obj->usdt_man);
11265 	}
11266 
11267 	usdt_cookie = OPTS_GET(opts, usdt_cookie, 0);
11268 	link = usdt_manager_attach_usdt(obj->usdt_man, prog, pid, binary_path,
11269 					usdt_provider, usdt_name, usdt_cookie);
11270 	err = libbpf_get_error(link);
11271 	if (err)
11272 		return libbpf_err_ptr(err);
11273 	return link;
11274 }
11275 
11276 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11277 {
11278 	char *path = NULL, *provider = NULL, *name = NULL;
11279 	const char *sec_name;
11280 	int n, err;
11281 
11282 	sec_name = bpf_program__section_name(prog);
11283 	if (strcmp(sec_name, "usdt") == 0) {
11284 		/* no auto-attach for just SEC("usdt") */
11285 		*link = NULL;
11286 		return 0;
11287 	}
11288 
11289 	n = sscanf(sec_name, "usdt/%m[^:]:%m[^:]:%m[^:]", &path, &provider, &name);
11290 	if (n != 3) {
11291 		pr_warn("invalid section '%s', expected SEC(\"usdt/<path>:<provider>:<name>\")\n",
11292 			sec_name);
11293 		err = -EINVAL;
11294 	} else {
11295 		*link = bpf_program__attach_usdt(prog, -1 /* any process */, path,
11296 						 provider, name, NULL);
11297 		err = libbpf_get_error(*link);
11298 	}
11299 	free(path);
11300 	free(provider);
11301 	free(name);
11302 	return err;
11303 }
11304 
11305 static int determine_tracepoint_id(const char *tp_category,
11306 				   const char *tp_name)
11307 {
11308 	char file[PATH_MAX];
11309 	int ret;
11310 
11311 	ret = snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11312 		       tracefs_path(), tp_category, tp_name);
11313 	if (ret < 0)
11314 		return -errno;
11315 	if (ret >= sizeof(file)) {
11316 		pr_debug("tracepoint %s/%s path is too long\n",
11317 			 tp_category, tp_name);
11318 		return -E2BIG;
11319 	}
11320 	return parse_uint_from_file(file, "%d\n");
11321 }
11322 
11323 static int perf_event_open_tracepoint(const char *tp_category,
11324 				      const char *tp_name)
11325 {
11326 	const size_t attr_sz = sizeof(struct perf_event_attr);
11327 	struct perf_event_attr attr;
11328 	char errmsg[STRERR_BUFSIZE];
11329 	int tp_id, pfd, err;
11330 
11331 	tp_id = determine_tracepoint_id(tp_category, tp_name);
11332 	if (tp_id < 0) {
11333 		pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
11334 			tp_category, tp_name,
11335 			libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
11336 		return tp_id;
11337 	}
11338 
11339 	memset(&attr, 0, attr_sz);
11340 	attr.type = PERF_TYPE_TRACEPOINT;
11341 	attr.size = attr_sz;
11342 	attr.config = tp_id;
11343 
11344 	pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
11345 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
11346 	if (pfd < 0) {
11347 		err = -errno;
11348 		pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
11349 			tp_category, tp_name,
11350 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11351 		return err;
11352 	}
11353 	return pfd;
11354 }
11355 
11356 struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
11357 						     const char *tp_category,
11358 						     const char *tp_name,
11359 						     const struct bpf_tracepoint_opts *opts)
11360 {
11361 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11362 	char errmsg[STRERR_BUFSIZE];
11363 	struct bpf_link *link;
11364 	int pfd, err;
11365 
11366 	if (!OPTS_VALID(opts, bpf_tracepoint_opts))
11367 		return libbpf_err_ptr(-EINVAL);
11368 
11369 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11370 
11371 	pfd = perf_event_open_tracepoint(tp_category, tp_name);
11372 	if (pfd < 0) {
11373 		pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
11374 			prog->name, tp_category, tp_name,
11375 			libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11376 		return libbpf_err_ptr(pfd);
11377 	}
11378 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11379 	err = libbpf_get_error(link);
11380 	if (err) {
11381 		close(pfd);
11382 		pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
11383 			prog->name, tp_category, tp_name,
11384 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11385 		return libbpf_err_ptr(err);
11386 	}
11387 	return link;
11388 }
11389 
11390 struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
11391 						const char *tp_category,
11392 						const char *tp_name)
11393 {
11394 	return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
11395 }
11396 
11397 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11398 {
11399 	char *sec_name, *tp_cat, *tp_name;
11400 
11401 	*link = NULL;
11402 
11403 	/* no auto-attach for SEC("tp") or SEC("tracepoint") */
11404 	if (strcmp(prog->sec_name, "tp") == 0 || strcmp(prog->sec_name, "tracepoint") == 0)
11405 		return 0;
11406 
11407 	sec_name = strdup(prog->sec_name);
11408 	if (!sec_name)
11409 		return -ENOMEM;
11410 
11411 	/* extract "tp/<category>/<name>" or "tracepoint/<category>/<name>" */
11412 	if (str_has_pfx(prog->sec_name, "tp/"))
11413 		tp_cat = sec_name + sizeof("tp/") - 1;
11414 	else
11415 		tp_cat = sec_name + sizeof("tracepoint/") - 1;
11416 	tp_name = strchr(tp_cat, '/');
11417 	if (!tp_name) {
11418 		free(sec_name);
11419 		return -EINVAL;
11420 	}
11421 	*tp_name = '\0';
11422 	tp_name++;
11423 
11424 	*link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
11425 	free(sec_name);
11426 	return libbpf_get_error(*link);
11427 }
11428 
11429 struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
11430 						    const char *tp_name)
11431 {
11432 	char errmsg[STRERR_BUFSIZE];
11433 	struct bpf_link *link;
11434 	int prog_fd, pfd;
11435 
11436 	prog_fd = bpf_program__fd(prog);
11437 	if (prog_fd < 0) {
11438 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11439 		return libbpf_err_ptr(-EINVAL);
11440 	}
11441 
11442 	link = calloc(1, sizeof(*link));
11443 	if (!link)
11444 		return libbpf_err_ptr(-ENOMEM);
11445 	link->detach = &bpf_link__detach_fd;
11446 
11447 	pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
11448 	if (pfd < 0) {
11449 		pfd = -errno;
11450 		free(link);
11451 		pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
11452 			prog->name, tp_name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11453 		return libbpf_err_ptr(pfd);
11454 	}
11455 	link->fd = pfd;
11456 	return link;
11457 }
11458 
11459 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11460 {
11461 	static const char *const prefixes[] = {
11462 		"raw_tp",
11463 		"raw_tracepoint",
11464 		"raw_tp.w",
11465 		"raw_tracepoint.w",
11466 	};
11467 	size_t i;
11468 	const char *tp_name = NULL;
11469 
11470 	*link = NULL;
11471 
11472 	for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
11473 		size_t pfx_len;
11474 
11475 		if (!str_has_pfx(prog->sec_name, prefixes[i]))
11476 			continue;
11477 
11478 		pfx_len = strlen(prefixes[i]);
11479 		/* no auto-attach case of, e.g., SEC("raw_tp") */
11480 		if (prog->sec_name[pfx_len] == '\0')
11481 			return 0;
11482 
11483 		if (prog->sec_name[pfx_len] != '/')
11484 			continue;
11485 
11486 		tp_name = prog->sec_name + pfx_len + 1;
11487 		break;
11488 	}
11489 
11490 	if (!tp_name) {
11491 		pr_warn("prog '%s': invalid section name '%s'\n",
11492 			prog->name, prog->sec_name);
11493 		return -EINVAL;
11494 	}
11495 
11496 	*link = bpf_program__attach_raw_tracepoint(prog, tp_name);
11497 	return libbpf_get_error(*link);
11498 }
11499 
11500 /* Common logic for all BPF program types that attach to a btf_id */
11501 static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog,
11502 						   const struct bpf_trace_opts *opts)
11503 {
11504 	LIBBPF_OPTS(bpf_link_create_opts, link_opts);
11505 	char errmsg[STRERR_BUFSIZE];
11506 	struct bpf_link *link;
11507 	int prog_fd, pfd;
11508 
11509 	if (!OPTS_VALID(opts, bpf_trace_opts))
11510 		return libbpf_err_ptr(-EINVAL);
11511 
11512 	prog_fd = bpf_program__fd(prog);
11513 	if (prog_fd < 0) {
11514 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11515 		return libbpf_err_ptr(-EINVAL);
11516 	}
11517 
11518 	link = calloc(1, sizeof(*link));
11519 	if (!link)
11520 		return libbpf_err_ptr(-ENOMEM);
11521 	link->detach = &bpf_link__detach_fd;
11522 
11523 	/* libbpf is smart enough to redirect to BPF_RAW_TRACEPOINT_OPEN on old kernels */
11524 	link_opts.tracing.cookie = OPTS_GET(opts, cookie, 0);
11525 	pfd = bpf_link_create(prog_fd, 0, bpf_program__expected_attach_type(prog), &link_opts);
11526 	if (pfd < 0) {
11527 		pfd = -errno;
11528 		free(link);
11529 		pr_warn("prog '%s': failed to attach: %s\n",
11530 			prog->name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11531 		return libbpf_err_ptr(pfd);
11532 	}
11533 	link->fd = pfd;
11534 	return link;
11535 }
11536 
11537 struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
11538 {
11539 	return bpf_program__attach_btf_id(prog, NULL);
11540 }
11541 
11542 struct bpf_link *bpf_program__attach_trace_opts(const struct bpf_program *prog,
11543 						const struct bpf_trace_opts *opts)
11544 {
11545 	return bpf_program__attach_btf_id(prog, opts);
11546 }
11547 
11548 struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
11549 {
11550 	return bpf_program__attach_btf_id(prog, NULL);
11551 }
11552 
11553 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11554 {
11555 	*link = bpf_program__attach_trace(prog);
11556 	return libbpf_get_error(*link);
11557 }
11558 
11559 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11560 {
11561 	*link = bpf_program__attach_lsm(prog);
11562 	return libbpf_get_error(*link);
11563 }
11564 
11565 static struct bpf_link *
11566 bpf_program__attach_fd(const struct bpf_program *prog, int target_fd, int btf_id,
11567 		       const char *target_name)
11568 {
11569 	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, opts,
11570 			    .target_btf_id = btf_id);
11571 	enum bpf_attach_type attach_type;
11572 	char errmsg[STRERR_BUFSIZE];
11573 	struct bpf_link *link;
11574 	int prog_fd, link_fd;
11575 
11576 	prog_fd = bpf_program__fd(prog);
11577 	if (prog_fd < 0) {
11578 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11579 		return libbpf_err_ptr(-EINVAL);
11580 	}
11581 
11582 	link = calloc(1, sizeof(*link));
11583 	if (!link)
11584 		return libbpf_err_ptr(-ENOMEM);
11585 	link->detach = &bpf_link__detach_fd;
11586 
11587 	attach_type = bpf_program__expected_attach_type(prog);
11588 	link_fd = bpf_link_create(prog_fd, target_fd, attach_type, &opts);
11589 	if (link_fd < 0) {
11590 		link_fd = -errno;
11591 		free(link);
11592 		pr_warn("prog '%s': failed to attach to %s: %s\n",
11593 			prog->name, target_name,
11594 			libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
11595 		return libbpf_err_ptr(link_fd);
11596 	}
11597 	link->fd = link_fd;
11598 	return link;
11599 }
11600 
11601 struct bpf_link *
11602 bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
11603 {
11604 	return bpf_program__attach_fd(prog, cgroup_fd, 0, "cgroup");
11605 }
11606 
11607 struct bpf_link *
11608 bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
11609 {
11610 	return bpf_program__attach_fd(prog, netns_fd, 0, "netns");
11611 }
11612 
11613 struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
11614 {
11615 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
11616 	return bpf_program__attach_fd(prog, ifindex, 0, "xdp");
11617 }
11618 
11619 struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
11620 					      int target_fd,
11621 					      const char *attach_func_name)
11622 {
11623 	int btf_id;
11624 
11625 	if (!!target_fd != !!attach_func_name) {
11626 		pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
11627 			prog->name);
11628 		return libbpf_err_ptr(-EINVAL);
11629 	}
11630 
11631 	if (prog->type != BPF_PROG_TYPE_EXT) {
11632 		pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace",
11633 			prog->name);
11634 		return libbpf_err_ptr(-EINVAL);
11635 	}
11636 
11637 	if (target_fd) {
11638 		btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd);
11639 		if (btf_id < 0)
11640 			return libbpf_err_ptr(btf_id);
11641 
11642 		return bpf_program__attach_fd(prog, target_fd, btf_id, "freplace");
11643 	} else {
11644 		/* no target, so use raw_tracepoint_open for compatibility
11645 		 * with old kernels
11646 		 */
11647 		return bpf_program__attach_trace(prog);
11648 	}
11649 }
11650 
11651 struct bpf_link *
11652 bpf_program__attach_iter(const struct bpf_program *prog,
11653 			 const struct bpf_iter_attach_opts *opts)
11654 {
11655 	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
11656 	char errmsg[STRERR_BUFSIZE];
11657 	struct bpf_link *link;
11658 	int prog_fd, link_fd;
11659 	__u32 target_fd = 0;
11660 
11661 	if (!OPTS_VALID(opts, bpf_iter_attach_opts))
11662 		return libbpf_err_ptr(-EINVAL);
11663 
11664 	link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
11665 	link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
11666 
11667 	prog_fd = bpf_program__fd(prog);
11668 	if (prog_fd < 0) {
11669 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11670 		return libbpf_err_ptr(-EINVAL);
11671 	}
11672 
11673 	link = calloc(1, sizeof(*link));
11674 	if (!link)
11675 		return libbpf_err_ptr(-ENOMEM);
11676 	link->detach = &bpf_link__detach_fd;
11677 
11678 	link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
11679 				  &link_create_opts);
11680 	if (link_fd < 0) {
11681 		link_fd = -errno;
11682 		free(link);
11683 		pr_warn("prog '%s': failed to attach to iterator: %s\n",
11684 			prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
11685 		return libbpf_err_ptr(link_fd);
11686 	}
11687 	link->fd = link_fd;
11688 	return link;
11689 }
11690 
11691 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11692 {
11693 	*link = bpf_program__attach_iter(prog, NULL);
11694 	return libbpf_get_error(*link);
11695 }
11696 
11697 struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
11698 {
11699 	struct bpf_link *link = NULL;
11700 	int err;
11701 
11702 	if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
11703 		return libbpf_err_ptr(-EOPNOTSUPP);
11704 
11705 	err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, &link);
11706 	if (err)
11707 		return libbpf_err_ptr(err);
11708 
11709 	/* When calling bpf_program__attach() explicitly, auto-attach support
11710 	 * is expected to work, so NULL returned link is considered an error.
11711 	 * This is different for skeleton's attach, see comment in
11712 	 * bpf_object__attach_skeleton().
11713 	 */
11714 	if (!link)
11715 		return libbpf_err_ptr(-EOPNOTSUPP);
11716 
11717 	return link;
11718 }
11719 
11720 struct bpf_link_struct_ops {
11721 	struct bpf_link link;
11722 	int map_fd;
11723 };
11724 
11725 static int bpf_link__detach_struct_ops(struct bpf_link *link)
11726 {
11727 	struct bpf_link_struct_ops *st_link;
11728 	__u32 zero = 0;
11729 
11730 	st_link = container_of(link, struct bpf_link_struct_ops, link);
11731 
11732 	if (st_link->map_fd < 0)
11733 		/* w/o a real link */
11734 		return bpf_map_delete_elem(link->fd, &zero);
11735 
11736 	return close(link->fd);
11737 }
11738 
11739 struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
11740 {
11741 	struct bpf_link_struct_ops *link;
11742 	__u32 zero = 0;
11743 	int err, fd;
11744 
11745 	if (!bpf_map__is_struct_ops(map) || map->fd == -1)
11746 		return libbpf_err_ptr(-EINVAL);
11747 
11748 	link = calloc(1, sizeof(*link));
11749 	if (!link)
11750 		return libbpf_err_ptr(-EINVAL);
11751 
11752 	/* kern_vdata should be prepared during the loading phase. */
11753 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
11754 	/* It can be EBUSY if the map has been used to create or
11755 	 * update a link before.  We don't allow updating the value of
11756 	 * a struct_ops once it is set.  That ensures that the value
11757 	 * never changed.  So, it is safe to skip EBUSY.
11758 	 */
11759 	if (err && (!(map->def.map_flags & BPF_F_LINK) || err != -EBUSY)) {
11760 		free(link);
11761 		return libbpf_err_ptr(err);
11762 	}
11763 
11764 	link->link.detach = bpf_link__detach_struct_ops;
11765 
11766 	if (!(map->def.map_flags & BPF_F_LINK)) {
11767 		/* w/o a real link */
11768 		link->link.fd = map->fd;
11769 		link->map_fd = -1;
11770 		return &link->link;
11771 	}
11772 
11773 	fd = bpf_link_create(map->fd, 0, BPF_STRUCT_OPS, NULL);
11774 	if (fd < 0) {
11775 		free(link);
11776 		return libbpf_err_ptr(fd);
11777 	}
11778 
11779 	link->link.fd = fd;
11780 	link->map_fd = map->fd;
11781 
11782 	return &link->link;
11783 }
11784 
11785 /*
11786  * Swap the back struct_ops of a link with a new struct_ops map.
11787  */
11788 int bpf_link__update_map(struct bpf_link *link, const struct bpf_map *map)
11789 {
11790 	struct bpf_link_struct_ops *st_ops_link;
11791 	__u32 zero = 0;
11792 	int err;
11793 
11794 	if (!bpf_map__is_struct_ops(map) || map->fd < 0)
11795 		return -EINVAL;
11796 
11797 	st_ops_link = container_of(link, struct bpf_link_struct_ops, link);
11798 	/* Ensure the type of a link is correct */
11799 	if (st_ops_link->map_fd < 0)
11800 		return -EINVAL;
11801 
11802 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
11803 	/* It can be EBUSY if the map has been used to create or
11804 	 * update a link before.  We don't allow updating the value of
11805 	 * a struct_ops once it is set.  That ensures that the value
11806 	 * never changed.  So, it is safe to skip EBUSY.
11807 	 */
11808 	if (err && err != -EBUSY)
11809 		return err;
11810 
11811 	err = bpf_link_update(link->fd, map->fd, NULL);
11812 	if (err < 0)
11813 		return err;
11814 
11815 	st_ops_link->map_fd = map->fd;
11816 
11817 	return 0;
11818 }
11819 
11820 typedef enum bpf_perf_event_ret (*bpf_perf_event_print_t)(struct perf_event_header *hdr,
11821 							  void *private_data);
11822 
11823 static enum bpf_perf_event_ret
11824 perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
11825 		       void **copy_mem, size_t *copy_size,
11826 		       bpf_perf_event_print_t fn, void *private_data)
11827 {
11828 	struct perf_event_mmap_page *header = mmap_mem;
11829 	__u64 data_head = ring_buffer_read_head(header);
11830 	__u64 data_tail = header->data_tail;
11831 	void *base = ((__u8 *)header) + page_size;
11832 	int ret = LIBBPF_PERF_EVENT_CONT;
11833 	struct perf_event_header *ehdr;
11834 	size_t ehdr_size;
11835 
11836 	while (data_head != data_tail) {
11837 		ehdr = base + (data_tail & (mmap_size - 1));
11838 		ehdr_size = ehdr->size;
11839 
11840 		if (((void *)ehdr) + ehdr_size > base + mmap_size) {
11841 			void *copy_start = ehdr;
11842 			size_t len_first = base + mmap_size - copy_start;
11843 			size_t len_secnd = ehdr_size - len_first;
11844 
11845 			if (*copy_size < ehdr_size) {
11846 				free(*copy_mem);
11847 				*copy_mem = malloc(ehdr_size);
11848 				if (!*copy_mem) {
11849 					*copy_size = 0;
11850 					ret = LIBBPF_PERF_EVENT_ERROR;
11851 					break;
11852 				}
11853 				*copy_size = ehdr_size;
11854 			}
11855 
11856 			memcpy(*copy_mem, copy_start, len_first);
11857 			memcpy(*copy_mem + len_first, base, len_secnd);
11858 			ehdr = *copy_mem;
11859 		}
11860 
11861 		ret = fn(ehdr, private_data);
11862 		data_tail += ehdr_size;
11863 		if (ret != LIBBPF_PERF_EVENT_CONT)
11864 			break;
11865 	}
11866 
11867 	ring_buffer_write_tail(header, data_tail);
11868 	return libbpf_err(ret);
11869 }
11870 
11871 struct perf_buffer;
11872 
11873 struct perf_buffer_params {
11874 	struct perf_event_attr *attr;
11875 	/* if event_cb is specified, it takes precendence */
11876 	perf_buffer_event_fn event_cb;
11877 	/* sample_cb and lost_cb are higher-level common-case callbacks */
11878 	perf_buffer_sample_fn sample_cb;
11879 	perf_buffer_lost_fn lost_cb;
11880 	void *ctx;
11881 	int cpu_cnt;
11882 	int *cpus;
11883 	int *map_keys;
11884 };
11885 
11886 struct perf_cpu_buf {
11887 	struct perf_buffer *pb;
11888 	void *base; /* mmap()'ed memory */
11889 	void *buf; /* for reconstructing segmented data */
11890 	size_t buf_size;
11891 	int fd;
11892 	int cpu;
11893 	int map_key;
11894 };
11895 
11896 struct perf_buffer {
11897 	perf_buffer_event_fn event_cb;
11898 	perf_buffer_sample_fn sample_cb;
11899 	perf_buffer_lost_fn lost_cb;
11900 	void *ctx; /* passed into callbacks */
11901 
11902 	size_t page_size;
11903 	size_t mmap_size;
11904 	struct perf_cpu_buf **cpu_bufs;
11905 	struct epoll_event *events;
11906 	int cpu_cnt; /* number of allocated CPU buffers */
11907 	int epoll_fd; /* perf event FD */
11908 	int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
11909 };
11910 
11911 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
11912 				      struct perf_cpu_buf *cpu_buf)
11913 {
11914 	if (!cpu_buf)
11915 		return;
11916 	if (cpu_buf->base &&
11917 	    munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
11918 		pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
11919 	if (cpu_buf->fd >= 0) {
11920 		ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
11921 		close(cpu_buf->fd);
11922 	}
11923 	free(cpu_buf->buf);
11924 	free(cpu_buf);
11925 }
11926 
11927 void perf_buffer__free(struct perf_buffer *pb)
11928 {
11929 	int i;
11930 
11931 	if (IS_ERR_OR_NULL(pb))
11932 		return;
11933 	if (pb->cpu_bufs) {
11934 		for (i = 0; i < pb->cpu_cnt; i++) {
11935 			struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
11936 
11937 			if (!cpu_buf)
11938 				continue;
11939 
11940 			bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
11941 			perf_buffer__free_cpu_buf(pb, cpu_buf);
11942 		}
11943 		free(pb->cpu_bufs);
11944 	}
11945 	if (pb->epoll_fd >= 0)
11946 		close(pb->epoll_fd);
11947 	free(pb->events);
11948 	free(pb);
11949 }
11950 
11951 static struct perf_cpu_buf *
11952 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
11953 			  int cpu, int map_key)
11954 {
11955 	struct perf_cpu_buf *cpu_buf;
11956 	char msg[STRERR_BUFSIZE];
11957 	int err;
11958 
11959 	cpu_buf = calloc(1, sizeof(*cpu_buf));
11960 	if (!cpu_buf)
11961 		return ERR_PTR(-ENOMEM);
11962 
11963 	cpu_buf->pb = pb;
11964 	cpu_buf->cpu = cpu;
11965 	cpu_buf->map_key = map_key;
11966 
11967 	cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
11968 			      -1, PERF_FLAG_FD_CLOEXEC);
11969 	if (cpu_buf->fd < 0) {
11970 		err = -errno;
11971 		pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
11972 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
11973 		goto error;
11974 	}
11975 
11976 	cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
11977 			     PROT_READ | PROT_WRITE, MAP_SHARED,
11978 			     cpu_buf->fd, 0);
11979 	if (cpu_buf->base == MAP_FAILED) {
11980 		cpu_buf->base = NULL;
11981 		err = -errno;
11982 		pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
11983 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
11984 		goto error;
11985 	}
11986 
11987 	if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
11988 		err = -errno;
11989 		pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
11990 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
11991 		goto error;
11992 	}
11993 
11994 	return cpu_buf;
11995 
11996 error:
11997 	perf_buffer__free_cpu_buf(pb, cpu_buf);
11998 	return (struct perf_cpu_buf *)ERR_PTR(err);
11999 }
12000 
12001 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
12002 					      struct perf_buffer_params *p);
12003 
12004 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
12005 				     perf_buffer_sample_fn sample_cb,
12006 				     perf_buffer_lost_fn lost_cb,
12007 				     void *ctx,
12008 				     const struct perf_buffer_opts *opts)
12009 {
12010 	const size_t attr_sz = sizeof(struct perf_event_attr);
12011 	struct perf_buffer_params p = {};
12012 	struct perf_event_attr attr;
12013 	__u32 sample_period;
12014 
12015 	if (!OPTS_VALID(opts, perf_buffer_opts))
12016 		return libbpf_err_ptr(-EINVAL);
12017 
12018 	sample_period = OPTS_GET(opts, sample_period, 1);
12019 	if (!sample_period)
12020 		sample_period = 1;
12021 
12022 	memset(&attr, 0, attr_sz);
12023 	attr.size = attr_sz;
12024 	attr.config = PERF_COUNT_SW_BPF_OUTPUT;
12025 	attr.type = PERF_TYPE_SOFTWARE;
12026 	attr.sample_type = PERF_SAMPLE_RAW;
12027 	attr.sample_period = sample_period;
12028 	attr.wakeup_events = sample_period;
12029 
12030 	p.attr = &attr;
12031 	p.sample_cb = sample_cb;
12032 	p.lost_cb = lost_cb;
12033 	p.ctx = ctx;
12034 
12035 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
12036 }
12037 
12038 struct perf_buffer *perf_buffer__new_raw(int map_fd, size_t page_cnt,
12039 					 struct perf_event_attr *attr,
12040 					 perf_buffer_event_fn event_cb, void *ctx,
12041 					 const struct perf_buffer_raw_opts *opts)
12042 {
12043 	struct perf_buffer_params p = {};
12044 
12045 	if (!attr)
12046 		return libbpf_err_ptr(-EINVAL);
12047 
12048 	if (!OPTS_VALID(opts, perf_buffer_raw_opts))
12049 		return libbpf_err_ptr(-EINVAL);
12050 
12051 	p.attr = attr;
12052 	p.event_cb = event_cb;
12053 	p.ctx = ctx;
12054 	p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
12055 	p.cpus = OPTS_GET(opts, cpus, NULL);
12056 	p.map_keys = OPTS_GET(opts, map_keys, NULL);
12057 
12058 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
12059 }
12060 
12061 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
12062 					      struct perf_buffer_params *p)
12063 {
12064 	const char *online_cpus_file = "/sys/devices/system/cpu/online";
12065 	struct bpf_map_info map;
12066 	char msg[STRERR_BUFSIZE];
12067 	struct perf_buffer *pb;
12068 	bool *online = NULL;
12069 	__u32 map_info_len;
12070 	int err, i, j, n;
12071 
12072 	if (page_cnt == 0 || (page_cnt & (page_cnt - 1))) {
12073 		pr_warn("page count should be power of two, but is %zu\n",
12074 			page_cnt);
12075 		return ERR_PTR(-EINVAL);
12076 	}
12077 
12078 	/* best-effort sanity checks */
12079 	memset(&map, 0, sizeof(map));
12080 	map_info_len = sizeof(map);
12081 	err = bpf_map_get_info_by_fd(map_fd, &map, &map_info_len);
12082 	if (err) {
12083 		err = -errno;
12084 		/* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
12085 		 * -EBADFD, -EFAULT, or -E2BIG on real error
12086 		 */
12087 		if (err != -EINVAL) {
12088 			pr_warn("failed to get map info for map FD %d: %s\n",
12089 				map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
12090 			return ERR_PTR(err);
12091 		}
12092 		pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
12093 			 map_fd);
12094 	} else {
12095 		if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
12096 			pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
12097 				map.name);
12098 			return ERR_PTR(-EINVAL);
12099 		}
12100 	}
12101 
12102 	pb = calloc(1, sizeof(*pb));
12103 	if (!pb)
12104 		return ERR_PTR(-ENOMEM);
12105 
12106 	pb->event_cb = p->event_cb;
12107 	pb->sample_cb = p->sample_cb;
12108 	pb->lost_cb = p->lost_cb;
12109 	pb->ctx = p->ctx;
12110 
12111 	pb->page_size = getpagesize();
12112 	pb->mmap_size = pb->page_size * page_cnt;
12113 	pb->map_fd = map_fd;
12114 
12115 	pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
12116 	if (pb->epoll_fd < 0) {
12117 		err = -errno;
12118 		pr_warn("failed to create epoll instance: %s\n",
12119 			libbpf_strerror_r(err, msg, sizeof(msg)));
12120 		goto error;
12121 	}
12122 
12123 	if (p->cpu_cnt > 0) {
12124 		pb->cpu_cnt = p->cpu_cnt;
12125 	} else {
12126 		pb->cpu_cnt = libbpf_num_possible_cpus();
12127 		if (pb->cpu_cnt < 0) {
12128 			err = pb->cpu_cnt;
12129 			goto error;
12130 		}
12131 		if (map.max_entries && map.max_entries < pb->cpu_cnt)
12132 			pb->cpu_cnt = map.max_entries;
12133 	}
12134 
12135 	pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
12136 	if (!pb->events) {
12137 		err = -ENOMEM;
12138 		pr_warn("failed to allocate events: out of memory\n");
12139 		goto error;
12140 	}
12141 	pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
12142 	if (!pb->cpu_bufs) {
12143 		err = -ENOMEM;
12144 		pr_warn("failed to allocate buffers: out of memory\n");
12145 		goto error;
12146 	}
12147 
12148 	err = parse_cpu_mask_file(online_cpus_file, &online, &n);
12149 	if (err) {
12150 		pr_warn("failed to get online CPU mask: %d\n", err);
12151 		goto error;
12152 	}
12153 
12154 	for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
12155 		struct perf_cpu_buf *cpu_buf;
12156 		int cpu, map_key;
12157 
12158 		cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
12159 		map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
12160 
12161 		/* in case user didn't explicitly requested particular CPUs to
12162 		 * be attached to, skip offline/not present CPUs
12163 		 */
12164 		if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
12165 			continue;
12166 
12167 		cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
12168 		if (IS_ERR(cpu_buf)) {
12169 			err = PTR_ERR(cpu_buf);
12170 			goto error;
12171 		}
12172 
12173 		pb->cpu_bufs[j] = cpu_buf;
12174 
12175 		err = bpf_map_update_elem(pb->map_fd, &map_key,
12176 					  &cpu_buf->fd, 0);
12177 		if (err) {
12178 			err = -errno;
12179 			pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
12180 				cpu, map_key, cpu_buf->fd,
12181 				libbpf_strerror_r(err, msg, sizeof(msg)));
12182 			goto error;
12183 		}
12184 
12185 		pb->events[j].events = EPOLLIN;
12186 		pb->events[j].data.ptr = cpu_buf;
12187 		if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
12188 			      &pb->events[j]) < 0) {
12189 			err = -errno;
12190 			pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
12191 				cpu, cpu_buf->fd,
12192 				libbpf_strerror_r(err, msg, sizeof(msg)));
12193 			goto error;
12194 		}
12195 		j++;
12196 	}
12197 	pb->cpu_cnt = j;
12198 	free(online);
12199 
12200 	return pb;
12201 
12202 error:
12203 	free(online);
12204 	if (pb)
12205 		perf_buffer__free(pb);
12206 	return ERR_PTR(err);
12207 }
12208 
12209 struct perf_sample_raw {
12210 	struct perf_event_header header;
12211 	uint32_t size;
12212 	char data[];
12213 };
12214 
12215 struct perf_sample_lost {
12216 	struct perf_event_header header;
12217 	uint64_t id;
12218 	uint64_t lost;
12219 	uint64_t sample_id;
12220 };
12221 
12222 static enum bpf_perf_event_ret
12223 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
12224 {
12225 	struct perf_cpu_buf *cpu_buf = ctx;
12226 	struct perf_buffer *pb = cpu_buf->pb;
12227 	void *data = e;
12228 
12229 	/* user wants full control over parsing perf event */
12230 	if (pb->event_cb)
12231 		return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
12232 
12233 	switch (e->type) {
12234 	case PERF_RECORD_SAMPLE: {
12235 		struct perf_sample_raw *s = data;
12236 
12237 		if (pb->sample_cb)
12238 			pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
12239 		break;
12240 	}
12241 	case PERF_RECORD_LOST: {
12242 		struct perf_sample_lost *s = data;
12243 
12244 		if (pb->lost_cb)
12245 			pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
12246 		break;
12247 	}
12248 	default:
12249 		pr_warn("unknown perf sample type %d\n", e->type);
12250 		return LIBBPF_PERF_EVENT_ERROR;
12251 	}
12252 	return LIBBPF_PERF_EVENT_CONT;
12253 }
12254 
12255 static int perf_buffer__process_records(struct perf_buffer *pb,
12256 					struct perf_cpu_buf *cpu_buf)
12257 {
12258 	enum bpf_perf_event_ret ret;
12259 
12260 	ret = perf_event_read_simple(cpu_buf->base, pb->mmap_size,
12261 				     pb->page_size, &cpu_buf->buf,
12262 				     &cpu_buf->buf_size,
12263 				     perf_buffer__process_record, cpu_buf);
12264 	if (ret != LIBBPF_PERF_EVENT_CONT)
12265 		return ret;
12266 	return 0;
12267 }
12268 
12269 int perf_buffer__epoll_fd(const struct perf_buffer *pb)
12270 {
12271 	return pb->epoll_fd;
12272 }
12273 
12274 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
12275 {
12276 	int i, cnt, err;
12277 
12278 	cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
12279 	if (cnt < 0)
12280 		return -errno;
12281 
12282 	for (i = 0; i < cnt; i++) {
12283 		struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
12284 
12285 		err = perf_buffer__process_records(pb, cpu_buf);
12286 		if (err) {
12287 			pr_warn("error while processing records: %d\n", err);
12288 			return libbpf_err(err);
12289 		}
12290 	}
12291 	return cnt;
12292 }
12293 
12294 /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
12295  * manager.
12296  */
12297 size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
12298 {
12299 	return pb->cpu_cnt;
12300 }
12301 
12302 /*
12303  * Return perf_event FD of a ring buffer in *buf_idx* slot of
12304  * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
12305  * select()/poll()/epoll() Linux syscalls.
12306  */
12307 int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
12308 {
12309 	struct perf_cpu_buf *cpu_buf;
12310 
12311 	if (buf_idx >= pb->cpu_cnt)
12312 		return libbpf_err(-EINVAL);
12313 
12314 	cpu_buf = pb->cpu_bufs[buf_idx];
12315 	if (!cpu_buf)
12316 		return libbpf_err(-ENOENT);
12317 
12318 	return cpu_buf->fd;
12319 }
12320 
12321 int perf_buffer__buffer(struct perf_buffer *pb, int buf_idx, void **buf, size_t *buf_size)
12322 {
12323 	struct perf_cpu_buf *cpu_buf;
12324 
12325 	if (buf_idx >= pb->cpu_cnt)
12326 		return libbpf_err(-EINVAL);
12327 
12328 	cpu_buf = pb->cpu_bufs[buf_idx];
12329 	if (!cpu_buf)
12330 		return libbpf_err(-ENOENT);
12331 
12332 	*buf = cpu_buf->base;
12333 	*buf_size = pb->mmap_size;
12334 	return 0;
12335 }
12336 
12337 /*
12338  * Consume data from perf ring buffer corresponding to slot *buf_idx* in
12339  * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
12340  * consume, do nothing and return success.
12341  * Returns:
12342  *   - 0 on success;
12343  *   - <0 on failure.
12344  */
12345 int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
12346 {
12347 	struct perf_cpu_buf *cpu_buf;
12348 
12349 	if (buf_idx >= pb->cpu_cnt)
12350 		return libbpf_err(-EINVAL);
12351 
12352 	cpu_buf = pb->cpu_bufs[buf_idx];
12353 	if (!cpu_buf)
12354 		return libbpf_err(-ENOENT);
12355 
12356 	return perf_buffer__process_records(pb, cpu_buf);
12357 }
12358 
12359 int perf_buffer__consume(struct perf_buffer *pb)
12360 {
12361 	int i, err;
12362 
12363 	for (i = 0; i < pb->cpu_cnt; i++) {
12364 		struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
12365 
12366 		if (!cpu_buf)
12367 			continue;
12368 
12369 		err = perf_buffer__process_records(pb, cpu_buf);
12370 		if (err) {
12371 			pr_warn("perf_buffer: failed to process records in buffer #%d: %d\n", i, err);
12372 			return libbpf_err(err);
12373 		}
12374 	}
12375 	return 0;
12376 }
12377 
12378 int bpf_program__set_attach_target(struct bpf_program *prog,
12379 				   int attach_prog_fd,
12380 				   const char *attach_func_name)
12381 {
12382 	int btf_obj_fd = 0, btf_id = 0, err;
12383 
12384 	if (!prog || attach_prog_fd < 0)
12385 		return libbpf_err(-EINVAL);
12386 
12387 	if (prog->obj->loaded)
12388 		return libbpf_err(-EINVAL);
12389 
12390 	if (attach_prog_fd && !attach_func_name) {
12391 		/* remember attach_prog_fd and let bpf_program__load() find
12392 		 * BTF ID during the program load
12393 		 */
12394 		prog->attach_prog_fd = attach_prog_fd;
12395 		return 0;
12396 	}
12397 
12398 	if (attach_prog_fd) {
12399 		btf_id = libbpf_find_prog_btf_id(attach_func_name,
12400 						 attach_prog_fd);
12401 		if (btf_id < 0)
12402 			return libbpf_err(btf_id);
12403 	} else {
12404 		if (!attach_func_name)
12405 			return libbpf_err(-EINVAL);
12406 
12407 		/* load btf_vmlinux, if not yet */
12408 		err = bpf_object__load_vmlinux_btf(prog->obj, true);
12409 		if (err)
12410 			return libbpf_err(err);
12411 		err = find_kernel_btf_id(prog->obj, attach_func_name,
12412 					 prog->expected_attach_type,
12413 					 &btf_obj_fd, &btf_id);
12414 		if (err)
12415 			return libbpf_err(err);
12416 	}
12417 
12418 	prog->attach_btf_id = btf_id;
12419 	prog->attach_btf_obj_fd = btf_obj_fd;
12420 	prog->attach_prog_fd = attach_prog_fd;
12421 	return 0;
12422 }
12423 
12424 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
12425 {
12426 	int err = 0, n, len, start, end = -1;
12427 	bool *tmp;
12428 
12429 	*mask = NULL;
12430 	*mask_sz = 0;
12431 
12432 	/* Each sub string separated by ',' has format \d+-\d+ or \d+ */
12433 	while (*s) {
12434 		if (*s == ',' || *s == '\n') {
12435 			s++;
12436 			continue;
12437 		}
12438 		n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
12439 		if (n <= 0 || n > 2) {
12440 			pr_warn("Failed to get CPU range %s: %d\n", s, n);
12441 			err = -EINVAL;
12442 			goto cleanup;
12443 		} else if (n == 1) {
12444 			end = start;
12445 		}
12446 		if (start < 0 || start > end) {
12447 			pr_warn("Invalid CPU range [%d,%d] in %s\n",
12448 				start, end, s);
12449 			err = -EINVAL;
12450 			goto cleanup;
12451 		}
12452 		tmp = realloc(*mask, end + 1);
12453 		if (!tmp) {
12454 			err = -ENOMEM;
12455 			goto cleanup;
12456 		}
12457 		*mask = tmp;
12458 		memset(tmp + *mask_sz, 0, start - *mask_sz);
12459 		memset(tmp + start, 1, end - start + 1);
12460 		*mask_sz = end + 1;
12461 		s += len;
12462 	}
12463 	if (!*mask_sz) {
12464 		pr_warn("Empty CPU range\n");
12465 		return -EINVAL;
12466 	}
12467 	return 0;
12468 cleanup:
12469 	free(*mask);
12470 	*mask = NULL;
12471 	return err;
12472 }
12473 
12474 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
12475 {
12476 	int fd, err = 0, len;
12477 	char buf[128];
12478 
12479 	fd = open(fcpu, O_RDONLY | O_CLOEXEC);
12480 	if (fd < 0) {
12481 		err = -errno;
12482 		pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
12483 		return err;
12484 	}
12485 	len = read(fd, buf, sizeof(buf));
12486 	close(fd);
12487 	if (len <= 0) {
12488 		err = len ? -errno : -EINVAL;
12489 		pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
12490 		return err;
12491 	}
12492 	if (len >= sizeof(buf)) {
12493 		pr_warn("CPU mask is too big in file %s\n", fcpu);
12494 		return -E2BIG;
12495 	}
12496 	buf[len] = '\0';
12497 
12498 	return parse_cpu_mask_str(buf, mask, mask_sz);
12499 }
12500 
12501 int libbpf_num_possible_cpus(void)
12502 {
12503 	static const char *fcpu = "/sys/devices/system/cpu/possible";
12504 	static int cpus;
12505 	int err, n, i, tmp_cpus;
12506 	bool *mask;
12507 
12508 	tmp_cpus = READ_ONCE(cpus);
12509 	if (tmp_cpus > 0)
12510 		return tmp_cpus;
12511 
12512 	err = parse_cpu_mask_file(fcpu, &mask, &n);
12513 	if (err)
12514 		return libbpf_err(err);
12515 
12516 	tmp_cpus = 0;
12517 	for (i = 0; i < n; i++) {
12518 		if (mask[i])
12519 			tmp_cpus++;
12520 	}
12521 	free(mask);
12522 
12523 	WRITE_ONCE(cpus, tmp_cpus);
12524 	return tmp_cpus;
12525 }
12526 
12527 static int populate_skeleton_maps(const struct bpf_object *obj,
12528 				  struct bpf_map_skeleton *maps,
12529 				  size_t map_cnt)
12530 {
12531 	int i;
12532 
12533 	for (i = 0; i < map_cnt; i++) {
12534 		struct bpf_map **map = maps[i].map;
12535 		const char *name = maps[i].name;
12536 		void **mmaped = maps[i].mmaped;
12537 
12538 		*map = bpf_object__find_map_by_name(obj, name);
12539 		if (!*map) {
12540 			pr_warn("failed to find skeleton map '%s'\n", name);
12541 			return -ESRCH;
12542 		}
12543 
12544 		/* externs shouldn't be pre-setup from user code */
12545 		if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
12546 			*mmaped = (*map)->mmaped;
12547 	}
12548 	return 0;
12549 }
12550 
12551 static int populate_skeleton_progs(const struct bpf_object *obj,
12552 				   struct bpf_prog_skeleton *progs,
12553 				   size_t prog_cnt)
12554 {
12555 	int i;
12556 
12557 	for (i = 0; i < prog_cnt; i++) {
12558 		struct bpf_program **prog = progs[i].prog;
12559 		const char *name = progs[i].name;
12560 
12561 		*prog = bpf_object__find_program_by_name(obj, name);
12562 		if (!*prog) {
12563 			pr_warn("failed to find skeleton program '%s'\n", name);
12564 			return -ESRCH;
12565 		}
12566 	}
12567 	return 0;
12568 }
12569 
12570 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
12571 			      const struct bpf_object_open_opts *opts)
12572 {
12573 	DECLARE_LIBBPF_OPTS(bpf_object_open_opts, skel_opts,
12574 		.object_name = s->name,
12575 	);
12576 	struct bpf_object *obj;
12577 	int err;
12578 
12579 	/* Attempt to preserve opts->object_name, unless overriden by user
12580 	 * explicitly. Overwriting object name for skeletons is discouraged,
12581 	 * as it breaks global data maps, because they contain object name
12582 	 * prefix as their own map name prefix. When skeleton is generated,
12583 	 * bpftool is making an assumption that this name will stay the same.
12584 	 */
12585 	if (opts) {
12586 		memcpy(&skel_opts, opts, sizeof(*opts));
12587 		if (!opts->object_name)
12588 			skel_opts.object_name = s->name;
12589 	}
12590 
12591 	obj = bpf_object__open_mem(s->data, s->data_sz, &skel_opts);
12592 	err = libbpf_get_error(obj);
12593 	if (err) {
12594 		pr_warn("failed to initialize skeleton BPF object '%s': %d\n",
12595 			s->name, err);
12596 		return libbpf_err(err);
12597 	}
12598 
12599 	*s->obj = obj;
12600 	err = populate_skeleton_maps(obj, s->maps, s->map_cnt);
12601 	if (err) {
12602 		pr_warn("failed to populate skeleton maps for '%s': %d\n", s->name, err);
12603 		return libbpf_err(err);
12604 	}
12605 
12606 	err = populate_skeleton_progs(obj, s->progs, s->prog_cnt);
12607 	if (err) {
12608 		pr_warn("failed to populate skeleton progs for '%s': %d\n", s->name, err);
12609 		return libbpf_err(err);
12610 	}
12611 
12612 	return 0;
12613 }
12614 
12615 int bpf_object__open_subskeleton(struct bpf_object_subskeleton *s)
12616 {
12617 	int err, len, var_idx, i;
12618 	const char *var_name;
12619 	const struct bpf_map *map;
12620 	struct btf *btf;
12621 	__u32 map_type_id;
12622 	const struct btf_type *map_type, *var_type;
12623 	const struct bpf_var_skeleton *var_skel;
12624 	struct btf_var_secinfo *var;
12625 
12626 	if (!s->obj)
12627 		return libbpf_err(-EINVAL);
12628 
12629 	btf = bpf_object__btf(s->obj);
12630 	if (!btf) {
12631 		pr_warn("subskeletons require BTF at runtime (object %s)\n",
12632 			bpf_object__name(s->obj));
12633 		return libbpf_err(-errno);
12634 	}
12635 
12636 	err = populate_skeleton_maps(s->obj, s->maps, s->map_cnt);
12637 	if (err) {
12638 		pr_warn("failed to populate subskeleton maps: %d\n", err);
12639 		return libbpf_err(err);
12640 	}
12641 
12642 	err = populate_skeleton_progs(s->obj, s->progs, s->prog_cnt);
12643 	if (err) {
12644 		pr_warn("failed to populate subskeleton maps: %d\n", err);
12645 		return libbpf_err(err);
12646 	}
12647 
12648 	for (var_idx = 0; var_idx < s->var_cnt; var_idx++) {
12649 		var_skel = &s->vars[var_idx];
12650 		map = *var_skel->map;
12651 		map_type_id = bpf_map__btf_value_type_id(map);
12652 		map_type = btf__type_by_id(btf, map_type_id);
12653 
12654 		if (!btf_is_datasec(map_type)) {
12655 			pr_warn("type for map '%1$s' is not a datasec: %2$s",
12656 				bpf_map__name(map),
12657 				__btf_kind_str(btf_kind(map_type)));
12658 			return libbpf_err(-EINVAL);
12659 		}
12660 
12661 		len = btf_vlen(map_type);
12662 		var = btf_var_secinfos(map_type);
12663 		for (i = 0; i < len; i++, var++) {
12664 			var_type = btf__type_by_id(btf, var->type);
12665 			var_name = btf__name_by_offset(btf, var_type->name_off);
12666 			if (strcmp(var_name, var_skel->name) == 0) {
12667 				*var_skel->addr = map->mmaped + var->offset;
12668 				break;
12669 			}
12670 		}
12671 	}
12672 	return 0;
12673 }
12674 
12675 void bpf_object__destroy_subskeleton(struct bpf_object_subskeleton *s)
12676 {
12677 	if (!s)
12678 		return;
12679 	free(s->maps);
12680 	free(s->progs);
12681 	free(s->vars);
12682 	free(s);
12683 }
12684 
12685 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
12686 {
12687 	int i, err;
12688 
12689 	err = bpf_object__load(*s->obj);
12690 	if (err) {
12691 		pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
12692 		return libbpf_err(err);
12693 	}
12694 
12695 	for (i = 0; i < s->map_cnt; i++) {
12696 		struct bpf_map *map = *s->maps[i].map;
12697 		size_t mmap_sz = bpf_map_mmap_sz(map);
12698 		int prot, map_fd = bpf_map__fd(map);
12699 		void **mmaped = s->maps[i].mmaped;
12700 
12701 		if (!mmaped)
12702 			continue;
12703 
12704 		if (!(map->def.map_flags & BPF_F_MMAPABLE)) {
12705 			*mmaped = NULL;
12706 			continue;
12707 		}
12708 
12709 		if (map->def.map_flags & BPF_F_RDONLY_PROG)
12710 			prot = PROT_READ;
12711 		else
12712 			prot = PROT_READ | PROT_WRITE;
12713 
12714 		/* Remap anonymous mmap()-ed "map initialization image" as
12715 		 * a BPF map-backed mmap()-ed memory, but preserving the same
12716 		 * memory address. This will cause kernel to change process'
12717 		 * page table to point to a different piece of kernel memory,
12718 		 * but from userspace point of view memory address (and its
12719 		 * contents, being identical at this point) will stay the
12720 		 * same. This mapping will be released by bpf_object__close()
12721 		 * as per normal clean up procedure, so we don't need to worry
12722 		 * about it from skeleton's clean up perspective.
12723 		 */
12724 		*mmaped = mmap(map->mmaped, mmap_sz, prot,
12725 				MAP_SHARED | MAP_FIXED, map_fd, 0);
12726 		if (*mmaped == MAP_FAILED) {
12727 			err = -errno;
12728 			*mmaped = NULL;
12729 			pr_warn("failed to re-mmap() map '%s': %d\n",
12730 				 bpf_map__name(map), err);
12731 			return libbpf_err(err);
12732 		}
12733 	}
12734 
12735 	return 0;
12736 }
12737 
12738 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
12739 {
12740 	int i, err;
12741 
12742 	for (i = 0; i < s->prog_cnt; i++) {
12743 		struct bpf_program *prog = *s->progs[i].prog;
12744 		struct bpf_link **link = s->progs[i].link;
12745 
12746 		if (!prog->autoload || !prog->autoattach)
12747 			continue;
12748 
12749 		/* auto-attaching not supported for this program */
12750 		if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
12751 			continue;
12752 
12753 		/* if user already set the link manually, don't attempt auto-attach */
12754 		if (*link)
12755 			continue;
12756 
12757 		err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, link);
12758 		if (err) {
12759 			pr_warn("prog '%s': failed to auto-attach: %d\n",
12760 				bpf_program__name(prog), err);
12761 			return libbpf_err(err);
12762 		}
12763 
12764 		/* It's possible that for some SEC() definitions auto-attach
12765 		 * is supported in some cases (e.g., if definition completely
12766 		 * specifies target information), but is not in other cases.
12767 		 * SEC("uprobe") is one such case. If user specified target
12768 		 * binary and function name, such BPF program can be
12769 		 * auto-attached. But if not, it shouldn't trigger skeleton's
12770 		 * attach to fail. It should just be skipped.
12771 		 * attach_fn signals such case with returning 0 (no error) and
12772 		 * setting link to NULL.
12773 		 */
12774 	}
12775 
12776 	return 0;
12777 }
12778 
12779 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
12780 {
12781 	int i;
12782 
12783 	for (i = 0; i < s->prog_cnt; i++) {
12784 		struct bpf_link **link = s->progs[i].link;
12785 
12786 		bpf_link__destroy(*link);
12787 		*link = NULL;
12788 	}
12789 }
12790 
12791 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
12792 {
12793 	if (!s)
12794 		return;
12795 
12796 	if (s->progs)
12797 		bpf_object__detach_skeleton(s);
12798 	if (s->obj)
12799 		bpf_object__close(*s->obj);
12800 	free(s->maps);
12801 	free(s->progs);
12802 	free(s);
12803 }
12804