xref: /openbmc/linux/tools/lib/bpf/libbpf.c (revision ac73d4bf)
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 <linux/version.h>
38 #include <sys/epoll.h>
39 #include <sys/ioctl.h>
40 #include <sys/mman.h>
41 #include <sys/stat.h>
42 #include <sys/types.h>
43 #include <sys/vfs.h>
44 #include <sys/utsname.h>
45 #include <sys/resource.h>
46 #include <libelf.h>
47 #include <gelf.h>
48 #include <zlib.h>
49 
50 #include "libbpf.h"
51 #include "bpf.h"
52 #include "btf.h"
53 #include "str_error.h"
54 #include "libbpf_internal.h"
55 #include "hashmap.h"
56 #include "bpf_gen_internal.h"
57 
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 };
120 
121 static const char * const link_type_name[] = {
122 	[BPF_LINK_TYPE_UNSPEC]			= "unspec",
123 	[BPF_LINK_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
124 	[BPF_LINK_TYPE_TRACING]			= "tracing",
125 	[BPF_LINK_TYPE_CGROUP]			= "cgroup",
126 	[BPF_LINK_TYPE_ITER]			= "iter",
127 	[BPF_LINK_TYPE_NETNS]			= "netns",
128 	[BPF_LINK_TYPE_XDP]			= "xdp",
129 	[BPF_LINK_TYPE_PERF_EVENT]		= "perf_event",
130 	[BPF_LINK_TYPE_KPROBE_MULTI]		= "kprobe_multi",
131 	[BPF_LINK_TYPE_STRUCT_OPS]		= "struct_ops",
132 };
133 
134 static const char * const map_type_name[] = {
135 	[BPF_MAP_TYPE_UNSPEC]			= "unspec",
136 	[BPF_MAP_TYPE_HASH]			= "hash",
137 	[BPF_MAP_TYPE_ARRAY]			= "array",
138 	[BPF_MAP_TYPE_PROG_ARRAY]		= "prog_array",
139 	[BPF_MAP_TYPE_PERF_EVENT_ARRAY]		= "perf_event_array",
140 	[BPF_MAP_TYPE_PERCPU_HASH]		= "percpu_hash",
141 	[BPF_MAP_TYPE_PERCPU_ARRAY]		= "percpu_array",
142 	[BPF_MAP_TYPE_STACK_TRACE]		= "stack_trace",
143 	[BPF_MAP_TYPE_CGROUP_ARRAY]		= "cgroup_array",
144 	[BPF_MAP_TYPE_LRU_HASH]			= "lru_hash",
145 	[BPF_MAP_TYPE_LRU_PERCPU_HASH]		= "lru_percpu_hash",
146 	[BPF_MAP_TYPE_LPM_TRIE]			= "lpm_trie",
147 	[BPF_MAP_TYPE_ARRAY_OF_MAPS]		= "array_of_maps",
148 	[BPF_MAP_TYPE_HASH_OF_MAPS]		= "hash_of_maps",
149 	[BPF_MAP_TYPE_DEVMAP]			= "devmap",
150 	[BPF_MAP_TYPE_DEVMAP_HASH]		= "devmap_hash",
151 	[BPF_MAP_TYPE_SOCKMAP]			= "sockmap",
152 	[BPF_MAP_TYPE_CPUMAP]			= "cpumap",
153 	[BPF_MAP_TYPE_XSKMAP]			= "xskmap",
154 	[BPF_MAP_TYPE_SOCKHASH]			= "sockhash",
155 	[BPF_MAP_TYPE_CGROUP_STORAGE]		= "cgroup_storage",
156 	[BPF_MAP_TYPE_REUSEPORT_SOCKARRAY]	= "reuseport_sockarray",
157 	[BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE]	= "percpu_cgroup_storage",
158 	[BPF_MAP_TYPE_QUEUE]			= "queue",
159 	[BPF_MAP_TYPE_STACK]			= "stack",
160 	[BPF_MAP_TYPE_SK_STORAGE]		= "sk_storage",
161 	[BPF_MAP_TYPE_STRUCT_OPS]		= "struct_ops",
162 	[BPF_MAP_TYPE_RINGBUF]			= "ringbuf",
163 	[BPF_MAP_TYPE_INODE_STORAGE]		= "inode_storage",
164 	[BPF_MAP_TYPE_TASK_STORAGE]		= "task_storage",
165 	[BPF_MAP_TYPE_BLOOM_FILTER]		= "bloom_filter",
166 	[BPF_MAP_TYPE_USER_RINGBUF]             = "user_ringbuf",
167 	[BPF_MAP_TYPE_CGRP_STORAGE]		= "cgrp_storage",
168 };
169 
170 static const char * const prog_type_name[] = {
171 	[BPF_PROG_TYPE_UNSPEC]			= "unspec",
172 	[BPF_PROG_TYPE_SOCKET_FILTER]		= "socket_filter",
173 	[BPF_PROG_TYPE_KPROBE]			= "kprobe",
174 	[BPF_PROG_TYPE_SCHED_CLS]		= "sched_cls",
175 	[BPF_PROG_TYPE_SCHED_ACT]		= "sched_act",
176 	[BPF_PROG_TYPE_TRACEPOINT]		= "tracepoint",
177 	[BPF_PROG_TYPE_XDP]			= "xdp",
178 	[BPF_PROG_TYPE_PERF_EVENT]		= "perf_event",
179 	[BPF_PROG_TYPE_CGROUP_SKB]		= "cgroup_skb",
180 	[BPF_PROG_TYPE_CGROUP_SOCK]		= "cgroup_sock",
181 	[BPF_PROG_TYPE_LWT_IN]			= "lwt_in",
182 	[BPF_PROG_TYPE_LWT_OUT]			= "lwt_out",
183 	[BPF_PROG_TYPE_LWT_XMIT]		= "lwt_xmit",
184 	[BPF_PROG_TYPE_SOCK_OPS]		= "sock_ops",
185 	[BPF_PROG_TYPE_SK_SKB]			= "sk_skb",
186 	[BPF_PROG_TYPE_CGROUP_DEVICE]		= "cgroup_device",
187 	[BPF_PROG_TYPE_SK_MSG]			= "sk_msg",
188 	[BPF_PROG_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
189 	[BPF_PROG_TYPE_CGROUP_SOCK_ADDR]	= "cgroup_sock_addr",
190 	[BPF_PROG_TYPE_LWT_SEG6LOCAL]		= "lwt_seg6local",
191 	[BPF_PROG_TYPE_LIRC_MODE2]		= "lirc_mode2",
192 	[BPF_PROG_TYPE_SK_REUSEPORT]		= "sk_reuseport",
193 	[BPF_PROG_TYPE_FLOW_DISSECTOR]		= "flow_dissector",
194 	[BPF_PROG_TYPE_CGROUP_SYSCTL]		= "cgroup_sysctl",
195 	[BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE]	= "raw_tracepoint_writable",
196 	[BPF_PROG_TYPE_CGROUP_SOCKOPT]		= "cgroup_sockopt",
197 	[BPF_PROG_TYPE_TRACING]			= "tracing",
198 	[BPF_PROG_TYPE_STRUCT_OPS]		= "struct_ops",
199 	[BPF_PROG_TYPE_EXT]			= "ext",
200 	[BPF_PROG_TYPE_LSM]			= "lsm",
201 	[BPF_PROG_TYPE_SK_LOOKUP]		= "sk_lookup",
202 	[BPF_PROG_TYPE_SYSCALL]			= "syscall",
203 };
204 
205 static int __base_pr(enum libbpf_print_level level, const char *format,
206 		     va_list args)
207 {
208 	if (level == LIBBPF_DEBUG)
209 		return 0;
210 
211 	return vfprintf(stderr, format, args);
212 }
213 
214 static libbpf_print_fn_t __libbpf_pr = __base_pr;
215 
216 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
217 {
218 	libbpf_print_fn_t old_print_fn = __libbpf_pr;
219 
220 	__libbpf_pr = fn;
221 	return old_print_fn;
222 }
223 
224 __printf(2, 3)
225 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
226 {
227 	va_list args;
228 	int old_errno;
229 
230 	if (!__libbpf_pr)
231 		return;
232 
233 	old_errno = errno;
234 
235 	va_start(args, format);
236 	__libbpf_pr(level, format, args);
237 	va_end(args);
238 
239 	errno = old_errno;
240 }
241 
242 static void pr_perm_msg(int err)
243 {
244 	struct rlimit limit;
245 	char buf[100];
246 
247 	if (err != -EPERM || geteuid() != 0)
248 		return;
249 
250 	err = getrlimit(RLIMIT_MEMLOCK, &limit);
251 	if (err)
252 		return;
253 
254 	if (limit.rlim_cur == RLIM_INFINITY)
255 		return;
256 
257 	if (limit.rlim_cur < 1024)
258 		snprintf(buf, sizeof(buf), "%zu bytes", (size_t)limit.rlim_cur);
259 	else if (limit.rlim_cur < 1024*1024)
260 		snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
261 	else
262 		snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
263 
264 	pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
265 		buf);
266 }
267 
268 #define STRERR_BUFSIZE  128
269 
270 /* Copied from tools/perf/util/util.h */
271 #ifndef zfree
272 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
273 #endif
274 
275 #ifndef zclose
276 # define zclose(fd) ({			\
277 	int ___err = 0;			\
278 	if ((fd) >= 0)			\
279 		___err = close((fd));	\
280 	fd = -1;			\
281 	___err; })
282 #endif
283 
284 static inline __u64 ptr_to_u64(const void *ptr)
285 {
286 	return (__u64) (unsigned long) ptr;
287 }
288 
289 int libbpf_set_strict_mode(enum libbpf_strict_mode mode)
290 {
291 	/* as of v1.0 libbpf_set_strict_mode() is a no-op */
292 	return 0;
293 }
294 
295 __u32 libbpf_major_version(void)
296 {
297 	return LIBBPF_MAJOR_VERSION;
298 }
299 
300 __u32 libbpf_minor_version(void)
301 {
302 	return LIBBPF_MINOR_VERSION;
303 }
304 
305 const char *libbpf_version_string(void)
306 {
307 #define __S(X) #X
308 #define _S(X) __S(X)
309 	return  "v" _S(LIBBPF_MAJOR_VERSION) "." _S(LIBBPF_MINOR_VERSION);
310 #undef _S
311 #undef __S
312 }
313 
314 enum reloc_type {
315 	RELO_LD64,
316 	RELO_CALL,
317 	RELO_DATA,
318 	RELO_EXTERN_VAR,
319 	RELO_EXTERN_FUNC,
320 	RELO_SUBPROG_ADDR,
321 	RELO_CORE,
322 };
323 
324 struct reloc_desc {
325 	enum reloc_type type;
326 	int insn_idx;
327 	union {
328 		const struct bpf_core_relo *core_relo; /* used when type == RELO_CORE */
329 		struct {
330 			int map_idx;
331 			int sym_off;
332 		};
333 	};
334 };
335 
336 /* stored as sec_def->cookie for all libbpf-supported SEC()s */
337 enum sec_def_flags {
338 	SEC_NONE = 0,
339 	/* expected_attach_type is optional, if kernel doesn't support that */
340 	SEC_EXP_ATTACH_OPT = 1,
341 	/* legacy, only used by libbpf_get_type_names() and
342 	 * libbpf_attach_type_by_name(), not used by libbpf itself at all.
343 	 * This used to be associated with cgroup (and few other) BPF programs
344 	 * that were attachable through BPF_PROG_ATTACH command. Pretty
345 	 * meaningless nowadays, though.
346 	 */
347 	SEC_ATTACHABLE = 2,
348 	SEC_ATTACHABLE_OPT = SEC_ATTACHABLE | SEC_EXP_ATTACH_OPT,
349 	/* attachment target is specified through BTF ID in either kernel or
350 	 * other BPF program's BTF object */
351 	SEC_ATTACH_BTF = 4,
352 	/* BPF program type allows sleeping/blocking in kernel */
353 	SEC_SLEEPABLE = 8,
354 	/* BPF program support non-linear XDP buffer */
355 	SEC_XDP_FRAGS = 16,
356 };
357 
358 struct bpf_sec_def {
359 	char *sec;
360 	enum bpf_prog_type prog_type;
361 	enum bpf_attach_type expected_attach_type;
362 	long cookie;
363 	int handler_id;
364 
365 	libbpf_prog_setup_fn_t prog_setup_fn;
366 	libbpf_prog_prepare_load_fn_t prog_prepare_load_fn;
367 	libbpf_prog_attach_fn_t prog_attach_fn;
368 };
369 
370 /*
371  * bpf_prog should be a better name but it has been used in
372  * linux/filter.h.
373  */
374 struct bpf_program {
375 	char *name;
376 	char *sec_name;
377 	size_t sec_idx;
378 	const struct bpf_sec_def *sec_def;
379 	/* this program's instruction offset (in number of instructions)
380 	 * within its containing ELF section
381 	 */
382 	size_t sec_insn_off;
383 	/* number of original instructions in ELF section belonging to this
384 	 * program, not taking into account subprogram instructions possible
385 	 * appended later during relocation
386 	 */
387 	size_t sec_insn_cnt;
388 	/* Offset (in number of instructions) of the start of instruction
389 	 * belonging to this BPF program  within its containing main BPF
390 	 * program. For the entry-point (main) BPF program, this is always
391 	 * zero. For a sub-program, this gets reset before each of main BPF
392 	 * programs are processed and relocated and is used to determined
393 	 * whether sub-program was already appended to the main program, and
394 	 * if yes, at which instruction offset.
395 	 */
396 	size_t sub_insn_off;
397 
398 	/* instructions that belong to BPF program; insns[0] is located at
399 	 * sec_insn_off instruction within its ELF section in ELF file, so
400 	 * when mapping ELF file instruction index to the local instruction,
401 	 * one needs to subtract sec_insn_off; and vice versa.
402 	 */
403 	struct bpf_insn *insns;
404 	/* actual number of instruction in this BPF program's image; for
405 	 * entry-point BPF programs this includes the size of main program
406 	 * itself plus all the used sub-programs, appended at the end
407 	 */
408 	size_t insns_cnt;
409 
410 	struct reloc_desc *reloc_desc;
411 	int nr_reloc;
412 
413 	/* BPF verifier log settings */
414 	char *log_buf;
415 	size_t log_size;
416 	__u32 log_level;
417 
418 	struct bpf_object *obj;
419 
420 	int fd;
421 	bool autoload;
422 	bool autoattach;
423 	bool mark_btf_static;
424 	enum bpf_prog_type type;
425 	enum bpf_attach_type expected_attach_type;
426 
427 	int prog_ifindex;
428 	__u32 attach_btf_obj_fd;
429 	__u32 attach_btf_id;
430 	__u32 attach_prog_fd;
431 
432 	void *func_info;
433 	__u32 func_info_rec_size;
434 	__u32 func_info_cnt;
435 
436 	void *line_info;
437 	__u32 line_info_rec_size;
438 	__u32 line_info_cnt;
439 	__u32 prog_flags;
440 };
441 
442 struct bpf_struct_ops {
443 	const char *tname;
444 	const struct btf_type *type;
445 	struct bpf_program **progs;
446 	__u32 *kern_func_off;
447 	/* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
448 	void *data;
449 	/* e.g. struct bpf_struct_ops_tcp_congestion_ops in
450 	 *      btf_vmlinux's format.
451 	 * struct bpf_struct_ops_tcp_congestion_ops {
452 	 *	[... some other kernel fields ...]
453 	 *	struct tcp_congestion_ops data;
454 	 * }
455 	 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
456 	 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
457 	 * from "data".
458 	 */
459 	void *kern_vdata;
460 	__u32 type_id;
461 };
462 
463 #define DATA_SEC ".data"
464 #define BSS_SEC ".bss"
465 #define RODATA_SEC ".rodata"
466 #define KCONFIG_SEC ".kconfig"
467 #define KSYMS_SEC ".ksyms"
468 #define STRUCT_OPS_SEC ".struct_ops"
469 
470 enum libbpf_map_type {
471 	LIBBPF_MAP_UNSPEC,
472 	LIBBPF_MAP_DATA,
473 	LIBBPF_MAP_BSS,
474 	LIBBPF_MAP_RODATA,
475 	LIBBPF_MAP_KCONFIG,
476 };
477 
478 struct bpf_map_def {
479 	unsigned int type;
480 	unsigned int key_size;
481 	unsigned int value_size;
482 	unsigned int max_entries;
483 	unsigned int map_flags;
484 };
485 
486 struct bpf_map {
487 	struct bpf_object *obj;
488 	char *name;
489 	/* real_name is defined for special internal maps (.rodata*,
490 	 * .data*, .bss, .kconfig) and preserves their original ELF section
491 	 * name. This is important to be be able to find corresponding BTF
492 	 * DATASEC information.
493 	 */
494 	char *real_name;
495 	int fd;
496 	int sec_idx;
497 	size_t sec_offset;
498 	int map_ifindex;
499 	int inner_map_fd;
500 	struct bpf_map_def def;
501 	__u32 numa_node;
502 	__u32 btf_var_idx;
503 	__u32 btf_key_type_id;
504 	__u32 btf_value_type_id;
505 	__u32 btf_vmlinux_value_type_id;
506 	enum libbpf_map_type libbpf_type;
507 	void *mmaped;
508 	struct bpf_struct_ops *st_ops;
509 	struct bpf_map *inner_map;
510 	void **init_slots;
511 	int init_slots_sz;
512 	char *pin_path;
513 	bool pinned;
514 	bool reused;
515 	bool autocreate;
516 	__u64 map_extra;
517 };
518 
519 enum extern_type {
520 	EXT_UNKNOWN,
521 	EXT_KCFG,
522 	EXT_KSYM,
523 };
524 
525 enum kcfg_type {
526 	KCFG_UNKNOWN,
527 	KCFG_CHAR,
528 	KCFG_BOOL,
529 	KCFG_INT,
530 	KCFG_TRISTATE,
531 	KCFG_CHAR_ARR,
532 };
533 
534 struct extern_desc {
535 	enum extern_type type;
536 	int sym_idx;
537 	int btf_id;
538 	int sec_btf_id;
539 	const char *name;
540 	bool is_set;
541 	bool is_weak;
542 	union {
543 		struct {
544 			enum kcfg_type type;
545 			int sz;
546 			int align;
547 			int data_off;
548 			bool is_signed;
549 		} kcfg;
550 		struct {
551 			unsigned long long addr;
552 
553 			/* target btf_id of the corresponding kernel var. */
554 			int kernel_btf_obj_fd;
555 			int kernel_btf_id;
556 
557 			/* local btf_id of the ksym extern's type. */
558 			__u32 type_id;
559 			/* BTF fd index to be patched in for insn->off, this is
560 			 * 0 for vmlinux BTF, index in obj->fd_array for module
561 			 * BTF
562 			 */
563 			__s16 btf_fd_idx;
564 		} ksym;
565 	};
566 };
567 
568 struct module_btf {
569 	struct btf *btf;
570 	char *name;
571 	__u32 id;
572 	int fd;
573 	int fd_array_idx;
574 };
575 
576 enum sec_type {
577 	SEC_UNUSED = 0,
578 	SEC_RELO,
579 	SEC_BSS,
580 	SEC_DATA,
581 	SEC_RODATA,
582 };
583 
584 struct elf_sec_desc {
585 	enum sec_type sec_type;
586 	Elf64_Shdr *shdr;
587 	Elf_Data *data;
588 };
589 
590 struct elf_state {
591 	int fd;
592 	const void *obj_buf;
593 	size_t obj_buf_sz;
594 	Elf *elf;
595 	Elf64_Ehdr *ehdr;
596 	Elf_Data *symbols;
597 	Elf_Data *st_ops_data;
598 	size_t shstrndx; /* section index for section name strings */
599 	size_t strtabidx;
600 	struct elf_sec_desc *secs;
601 	size_t sec_cnt;
602 	int btf_maps_shndx;
603 	__u32 btf_maps_sec_btf_id;
604 	int text_shndx;
605 	int symbols_shndx;
606 	int st_ops_shndx;
607 };
608 
609 struct usdt_manager;
610 
611 struct bpf_object {
612 	char name[BPF_OBJ_NAME_LEN];
613 	char license[64];
614 	__u32 kern_version;
615 
616 	struct bpf_program *programs;
617 	size_t nr_programs;
618 	struct bpf_map *maps;
619 	size_t nr_maps;
620 	size_t maps_cap;
621 
622 	char *kconfig;
623 	struct extern_desc *externs;
624 	int nr_extern;
625 	int kconfig_map_idx;
626 
627 	bool loaded;
628 	bool has_subcalls;
629 	bool has_rodata;
630 
631 	struct bpf_gen *gen_loader;
632 
633 	/* Information when doing ELF related work. Only valid if efile.elf is not NULL */
634 	struct elf_state efile;
635 
636 	struct btf *btf;
637 	struct btf_ext *btf_ext;
638 
639 	/* Parse and load BTF vmlinux if any of the programs in the object need
640 	 * it at load time.
641 	 */
642 	struct btf *btf_vmlinux;
643 	/* Path to the custom BTF to be used for BPF CO-RE relocations as an
644 	 * override for vmlinux BTF.
645 	 */
646 	char *btf_custom_path;
647 	/* vmlinux BTF override for CO-RE relocations */
648 	struct btf *btf_vmlinux_override;
649 	/* Lazily initialized kernel module BTFs */
650 	struct module_btf *btf_modules;
651 	bool btf_modules_loaded;
652 	size_t btf_module_cnt;
653 	size_t btf_module_cap;
654 
655 	/* optional log settings passed to BPF_BTF_LOAD and BPF_PROG_LOAD commands */
656 	char *log_buf;
657 	size_t log_size;
658 	__u32 log_level;
659 
660 	int *fd_array;
661 	size_t fd_array_cap;
662 	size_t fd_array_cnt;
663 
664 	struct usdt_manager *usdt_man;
665 
666 	char path[];
667 };
668 
669 static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
670 static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
671 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
672 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
673 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn);
674 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
675 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
676 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx);
677 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx);
678 
679 void bpf_program__unload(struct bpf_program *prog)
680 {
681 	if (!prog)
682 		return;
683 
684 	zclose(prog->fd);
685 
686 	zfree(&prog->func_info);
687 	zfree(&prog->line_info);
688 }
689 
690 static void bpf_program__exit(struct bpf_program *prog)
691 {
692 	if (!prog)
693 		return;
694 
695 	bpf_program__unload(prog);
696 	zfree(&prog->name);
697 	zfree(&prog->sec_name);
698 	zfree(&prog->insns);
699 	zfree(&prog->reloc_desc);
700 
701 	prog->nr_reloc = 0;
702 	prog->insns_cnt = 0;
703 	prog->sec_idx = -1;
704 }
705 
706 static bool insn_is_subprog_call(const struct bpf_insn *insn)
707 {
708 	return BPF_CLASS(insn->code) == BPF_JMP &&
709 	       BPF_OP(insn->code) == BPF_CALL &&
710 	       BPF_SRC(insn->code) == BPF_K &&
711 	       insn->src_reg == BPF_PSEUDO_CALL &&
712 	       insn->dst_reg == 0 &&
713 	       insn->off == 0;
714 }
715 
716 static bool is_call_insn(const struct bpf_insn *insn)
717 {
718 	return insn->code == (BPF_JMP | BPF_CALL);
719 }
720 
721 static bool insn_is_pseudo_func(struct bpf_insn *insn)
722 {
723 	return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
724 }
725 
726 static int
727 bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
728 		      const char *name, size_t sec_idx, const char *sec_name,
729 		      size_t sec_off, void *insn_data, size_t insn_data_sz)
730 {
731 	if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
732 		pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
733 			sec_name, name, sec_off, insn_data_sz);
734 		return -EINVAL;
735 	}
736 
737 	memset(prog, 0, sizeof(*prog));
738 	prog->obj = obj;
739 
740 	prog->sec_idx = sec_idx;
741 	prog->sec_insn_off = sec_off / BPF_INSN_SZ;
742 	prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
743 	/* insns_cnt can later be increased by appending used subprograms */
744 	prog->insns_cnt = prog->sec_insn_cnt;
745 
746 	prog->type = BPF_PROG_TYPE_UNSPEC;
747 	prog->fd = -1;
748 
749 	/* libbpf's convention for SEC("?abc...") is that it's just like
750 	 * SEC("abc...") but the corresponding bpf_program starts out with
751 	 * autoload set to false.
752 	 */
753 	if (sec_name[0] == '?') {
754 		prog->autoload = false;
755 		/* from now on forget there was ? in section name */
756 		sec_name++;
757 	} else {
758 		prog->autoload = true;
759 	}
760 
761 	prog->autoattach = true;
762 
763 	/* inherit object's log_level */
764 	prog->log_level = obj->log_level;
765 
766 	prog->sec_name = strdup(sec_name);
767 	if (!prog->sec_name)
768 		goto errout;
769 
770 	prog->name = strdup(name);
771 	if (!prog->name)
772 		goto errout;
773 
774 	prog->insns = malloc(insn_data_sz);
775 	if (!prog->insns)
776 		goto errout;
777 	memcpy(prog->insns, insn_data, insn_data_sz);
778 
779 	return 0;
780 errout:
781 	pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
782 	bpf_program__exit(prog);
783 	return -ENOMEM;
784 }
785 
786 static int
787 bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
788 			 const char *sec_name, int sec_idx)
789 {
790 	Elf_Data *symbols = obj->efile.symbols;
791 	struct bpf_program *prog, *progs;
792 	void *data = sec_data->d_buf;
793 	size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
794 	int nr_progs, err, i;
795 	const char *name;
796 	Elf64_Sym *sym;
797 
798 	progs = obj->programs;
799 	nr_progs = obj->nr_programs;
800 	nr_syms = symbols->d_size / sizeof(Elf64_Sym);
801 	sec_off = 0;
802 
803 	for (i = 0; i < nr_syms; i++) {
804 		sym = elf_sym_by_idx(obj, i);
805 
806 		if (sym->st_shndx != sec_idx)
807 			continue;
808 		if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC)
809 			continue;
810 
811 		prog_sz = sym->st_size;
812 		sec_off = sym->st_value;
813 
814 		name = elf_sym_str(obj, sym->st_name);
815 		if (!name) {
816 			pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
817 				sec_name, sec_off);
818 			return -LIBBPF_ERRNO__FORMAT;
819 		}
820 
821 		if (sec_off + prog_sz > sec_sz) {
822 			pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
823 				sec_name, sec_off);
824 			return -LIBBPF_ERRNO__FORMAT;
825 		}
826 
827 		if (sec_idx != obj->efile.text_shndx && ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
828 			pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
829 			return -ENOTSUP;
830 		}
831 
832 		pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
833 			 sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
834 
835 		progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
836 		if (!progs) {
837 			/*
838 			 * In this case the original obj->programs
839 			 * is still valid, so don't need special treat for
840 			 * bpf_close_object().
841 			 */
842 			pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
843 				sec_name, name);
844 			return -ENOMEM;
845 		}
846 		obj->programs = progs;
847 
848 		prog = &progs[nr_progs];
849 
850 		err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
851 					    sec_off, data + sec_off, prog_sz);
852 		if (err)
853 			return err;
854 
855 		/* if function is a global/weak symbol, but has restricted
856 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
857 		 * as static to enable more permissive BPF verification mode
858 		 * with more outside context available to BPF verifier
859 		 */
860 		if (ELF64_ST_BIND(sym->st_info) != STB_LOCAL
861 		    && (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
862 			|| ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL))
863 			prog->mark_btf_static = true;
864 
865 		nr_progs++;
866 		obj->nr_programs = nr_progs;
867 	}
868 
869 	return 0;
870 }
871 
872 __u32 get_kernel_version(void)
873 {
874 	/* On Ubuntu LINUX_VERSION_CODE doesn't correspond to info.release,
875 	 * but Ubuntu provides /proc/version_signature file, as described at
876 	 * https://ubuntu.com/kernel, with an example contents below, which we
877 	 * can use to get a proper LINUX_VERSION_CODE.
878 	 *
879 	 *   Ubuntu 5.4.0-12.15-generic 5.4.8
880 	 *
881 	 * In the above, 5.4.8 is what kernel is actually expecting, while
882 	 * uname() call will return 5.4.0 in info.release.
883 	 */
884 	const char *ubuntu_kver_file = "/proc/version_signature";
885 	__u32 major, minor, patch;
886 	struct utsname info;
887 
888 	if (faccessat(AT_FDCWD, ubuntu_kver_file, R_OK, AT_EACCESS) == 0) {
889 		FILE *f;
890 
891 		f = fopen(ubuntu_kver_file, "r");
892 		if (f) {
893 			if (fscanf(f, "%*s %*s %d.%d.%d\n", &major, &minor, &patch) == 3) {
894 				fclose(f);
895 				return KERNEL_VERSION(major, minor, patch);
896 			}
897 			fclose(f);
898 		}
899 		/* something went wrong, fall back to uname() approach */
900 	}
901 
902 	uname(&info);
903 	if (sscanf(info.release, "%u.%u.%u", &major, &minor, &patch) != 3)
904 		return 0;
905 	return KERNEL_VERSION(major, minor, patch);
906 }
907 
908 static const struct btf_member *
909 find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
910 {
911 	struct btf_member *m;
912 	int i;
913 
914 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
915 		if (btf_member_bit_offset(t, i) == bit_offset)
916 			return m;
917 	}
918 
919 	return NULL;
920 }
921 
922 static const struct btf_member *
923 find_member_by_name(const struct btf *btf, const struct btf_type *t,
924 		    const char *name)
925 {
926 	struct btf_member *m;
927 	int i;
928 
929 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
930 		if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
931 			return m;
932 	}
933 
934 	return NULL;
935 }
936 
937 #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
938 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
939 				   const char *name, __u32 kind);
940 
941 static int
942 find_struct_ops_kern_types(const struct btf *btf, const char *tname,
943 			   const struct btf_type **type, __u32 *type_id,
944 			   const struct btf_type **vtype, __u32 *vtype_id,
945 			   const struct btf_member **data_member)
946 {
947 	const struct btf_type *kern_type, *kern_vtype;
948 	const struct btf_member *kern_data_member;
949 	__s32 kern_vtype_id, kern_type_id;
950 	__u32 i;
951 
952 	kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
953 	if (kern_type_id < 0) {
954 		pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n",
955 			tname);
956 		return kern_type_id;
957 	}
958 	kern_type = btf__type_by_id(btf, kern_type_id);
959 
960 	/* Find the corresponding "map_value" type that will be used
961 	 * in map_update(BPF_MAP_TYPE_STRUCT_OPS).  For example,
962 	 * find "struct bpf_struct_ops_tcp_congestion_ops" from the
963 	 * btf_vmlinux.
964 	 */
965 	kern_vtype_id = find_btf_by_prefix_kind(btf, STRUCT_OPS_VALUE_PREFIX,
966 						tname, BTF_KIND_STRUCT);
967 	if (kern_vtype_id < 0) {
968 		pr_warn("struct_ops init_kern: struct %s%s is not found in kernel BTF\n",
969 			STRUCT_OPS_VALUE_PREFIX, tname);
970 		return kern_vtype_id;
971 	}
972 	kern_vtype = btf__type_by_id(btf, kern_vtype_id);
973 
974 	/* Find "struct tcp_congestion_ops" from
975 	 * struct bpf_struct_ops_tcp_congestion_ops {
976 	 *	[ ... ]
977 	 *	struct tcp_congestion_ops data;
978 	 * }
979 	 */
980 	kern_data_member = btf_members(kern_vtype);
981 	for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
982 		if (kern_data_member->type == kern_type_id)
983 			break;
984 	}
985 	if (i == btf_vlen(kern_vtype)) {
986 		pr_warn("struct_ops init_kern: struct %s data is not found in struct %s%s\n",
987 			tname, STRUCT_OPS_VALUE_PREFIX, tname);
988 		return -EINVAL;
989 	}
990 
991 	*type = kern_type;
992 	*type_id = kern_type_id;
993 	*vtype = kern_vtype;
994 	*vtype_id = kern_vtype_id;
995 	*data_member = kern_data_member;
996 
997 	return 0;
998 }
999 
1000 static bool bpf_map__is_struct_ops(const struct bpf_map *map)
1001 {
1002 	return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
1003 }
1004 
1005 /* Init the map's fields that depend on kern_btf */
1006 static int bpf_map__init_kern_struct_ops(struct bpf_map *map,
1007 					 const struct btf *btf,
1008 					 const struct btf *kern_btf)
1009 {
1010 	const struct btf_member *member, *kern_member, *kern_data_member;
1011 	const struct btf_type *type, *kern_type, *kern_vtype;
1012 	__u32 i, kern_type_id, kern_vtype_id, kern_data_off;
1013 	struct bpf_struct_ops *st_ops;
1014 	void *data, *kern_data;
1015 	const char *tname;
1016 	int err;
1017 
1018 	st_ops = map->st_ops;
1019 	type = st_ops->type;
1020 	tname = st_ops->tname;
1021 	err = find_struct_ops_kern_types(kern_btf, tname,
1022 					 &kern_type, &kern_type_id,
1023 					 &kern_vtype, &kern_vtype_id,
1024 					 &kern_data_member);
1025 	if (err)
1026 		return err;
1027 
1028 	pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
1029 		 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
1030 
1031 	map->def.value_size = kern_vtype->size;
1032 	map->btf_vmlinux_value_type_id = kern_vtype_id;
1033 
1034 	st_ops->kern_vdata = calloc(1, kern_vtype->size);
1035 	if (!st_ops->kern_vdata)
1036 		return -ENOMEM;
1037 
1038 	data = st_ops->data;
1039 	kern_data_off = kern_data_member->offset / 8;
1040 	kern_data = st_ops->kern_vdata + kern_data_off;
1041 
1042 	member = btf_members(type);
1043 	for (i = 0; i < btf_vlen(type); i++, member++) {
1044 		const struct btf_type *mtype, *kern_mtype;
1045 		__u32 mtype_id, kern_mtype_id;
1046 		void *mdata, *kern_mdata;
1047 		__s64 msize, kern_msize;
1048 		__u32 moff, kern_moff;
1049 		__u32 kern_member_idx;
1050 		const char *mname;
1051 
1052 		mname = btf__name_by_offset(btf, member->name_off);
1053 		kern_member = find_member_by_name(kern_btf, kern_type, mname);
1054 		if (!kern_member) {
1055 			pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
1056 				map->name, mname);
1057 			return -ENOTSUP;
1058 		}
1059 
1060 		kern_member_idx = kern_member - btf_members(kern_type);
1061 		if (btf_member_bitfield_size(type, i) ||
1062 		    btf_member_bitfield_size(kern_type, kern_member_idx)) {
1063 			pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
1064 				map->name, mname);
1065 			return -ENOTSUP;
1066 		}
1067 
1068 		moff = member->offset / 8;
1069 		kern_moff = kern_member->offset / 8;
1070 
1071 		mdata = data + moff;
1072 		kern_mdata = kern_data + kern_moff;
1073 
1074 		mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
1075 		kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
1076 						    &kern_mtype_id);
1077 		if (BTF_INFO_KIND(mtype->info) !=
1078 		    BTF_INFO_KIND(kern_mtype->info)) {
1079 			pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
1080 				map->name, mname, BTF_INFO_KIND(mtype->info),
1081 				BTF_INFO_KIND(kern_mtype->info));
1082 			return -ENOTSUP;
1083 		}
1084 
1085 		if (btf_is_ptr(mtype)) {
1086 			struct bpf_program *prog;
1087 
1088 			prog = st_ops->progs[i];
1089 			if (!prog)
1090 				continue;
1091 
1092 			kern_mtype = skip_mods_and_typedefs(kern_btf,
1093 							    kern_mtype->type,
1094 							    &kern_mtype_id);
1095 
1096 			/* mtype->type must be a func_proto which was
1097 			 * guaranteed in bpf_object__collect_st_ops_relos(),
1098 			 * so only check kern_mtype for func_proto here.
1099 			 */
1100 			if (!btf_is_func_proto(kern_mtype)) {
1101 				pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
1102 					map->name, mname);
1103 				return -ENOTSUP;
1104 			}
1105 
1106 			prog->attach_btf_id = kern_type_id;
1107 			prog->expected_attach_type = kern_member_idx;
1108 
1109 			st_ops->kern_func_off[i] = kern_data_off + kern_moff;
1110 
1111 			pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
1112 				 map->name, mname, prog->name, moff,
1113 				 kern_moff);
1114 
1115 			continue;
1116 		}
1117 
1118 		msize = btf__resolve_size(btf, mtype_id);
1119 		kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
1120 		if (msize < 0 || kern_msize < 0 || msize != kern_msize) {
1121 			pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
1122 				map->name, mname, (ssize_t)msize,
1123 				(ssize_t)kern_msize);
1124 			return -ENOTSUP;
1125 		}
1126 
1127 		pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
1128 			 map->name, mname, (unsigned int)msize,
1129 			 moff, kern_moff);
1130 		memcpy(kern_mdata, mdata, msize);
1131 	}
1132 
1133 	return 0;
1134 }
1135 
1136 static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
1137 {
1138 	struct bpf_map *map;
1139 	size_t i;
1140 	int err;
1141 
1142 	for (i = 0; i < obj->nr_maps; i++) {
1143 		map = &obj->maps[i];
1144 
1145 		if (!bpf_map__is_struct_ops(map))
1146 			continue;
1147 
1148 		err = bpf_map__init_kern_struct_ops(map, obj->btf,
1149 						    obj->btf_vmlinux);
1150 		if (err)
1151 			return err;
1152 	}
1153 
1154 	return 0;
1155 }
1156 
1157 static int bpf_object__init_struct_ops_maps(struct bpf_object *obj)
1158 {
1159 	const struct btf_type *type, *datasec;
1160 	const struct btf_var_secinfo *vsi;
1161 	struct bpf_struct_ops *st_ops;
1162 	const char *tname, *var_name;
1163 	__s32 type_id, datasec_id;
1164 	const struct btf *btf;
1165 	struct bpf_map *map;
1166 	__u32 i;
1167 
1168 	if (obj->efile.st_ops_shndx == -1)
1169 		return 0;
1170 
1171 	btf = obj->btf;
1172 	datasec_id = btf__find_by_name_kind(btf, STRUCT_OPS_SEC,
1173 					    BTF_KIND_DATASEC);
1174 	if (datasec_id < 0) {
1175 		pr_warn("struct_ops init: DATASEC %s not found\n",
1176 			STRUCT_OPS_SEC);
1177 		return -EINVAL;
1178 	}
1179 
1180 	datasec = btf__type_by_id(btf, datasec_id);
1181 	vsi = btf_var_secinfos(datasec);
1182 	for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
1183 		type = btf__type_by_id(obj->btf, vsi->type);
1184 		var_name = btf__name_by_offset(obj->btf, type->name_off);
1185 
1186 		type_id = btf__resolve_type(obj->btf, vsi->type);
1187 		if (type_id < 0) {
1188 			pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
1189 				vsi->type, STRUCT_OPS_SEC);
1190 			return -EINVAL;
1191 		}
1192 
1193 		type = btf__type_by_id(obj->btf, type_id);
1194 		tname = btf__name_by_offset(obj->btf, type->name_off);
1195 		if (!tname[0]) {
1196 			pr_warn("struct_ops init: anonymous type is not supported\n");
1197 			return -ENOTSUP;
1198 		}
1199 		if (!btf_is_struct(type)) {
1200 			pr_warn("struct_ops init: %s is not a struct\n", tname);
1201 			return -EINVAL;
1202 		}
1203 
1204 		map = bpf_object__add_map(obj);
1205 		if (IS_ERR(map))
1206 			return PTR_ERR(map);
1207 
1208 		map->sec_idx = obj->efile.st_ops_shndx;
1209 		map->sec_offset = vsi->offset;
1210 		map->name = strdup(var_name);
1211 		if (!map->name)
1212 			return -ENOMEM;
1213 
1214 		map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
1215 		map->def.key_size = sizeof(int);
1216 		map->def.value_size = type->size;
1217 		map->def.max_entries = 1;
1218 
1219 		map->st_ops = calloc(1, sizeof(*map->st_ops));
1220 		if (!map->st_ops)
1221 			return -ENOMEM;
1222 		st_ops = map->st_ops;
1223 		st_ops->data = malloc(type->size);
1224 		st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1225 		st_ops->kern_func_off = malloc(btf_vlen(type) *
1226 					       sizeof(*st_ops->kern_func_off));
1227 		if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1228 			return -ENOMEM;
1229 
1230 		if (vsi->offset + type->size > obj->efile.st_ops_data->d_size) {
1231 			pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1232 				var_name, STRUCT_OPS_SEC);
1233 			return -EINVAL;
1234 		}
1235 
1236 		memcpy(st_ops->data,
1237 		       obj->efile.st_ops_data->d_buf + vsi->offset,
1238 		       type->size);
1239 		st_ops->tname = tname;
1240 		st_ops->type = type;
1241 		st_ops->type_id = type_id;
1242 
1243 		pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
1244 			 tname, type_id, var_name, vsi->offset);
1245 	}
1246 
1247 	return 0;
1248 }
1249 
1250 static struct bpf_object *bpf_object__new(const char *path,
1251 					  const void *obj_buf,
1252 					  size_t obj_buf_sz,
1253 					  const char *obj_name)
1254 {
1255 	struct bpf_object *obj;
1256 	char *end;
1257 
1258 	obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1259 	if (!obj) {
1260 		pr_warn("alloc memory failed for %s\n", path);
1261 		return ERR_PTR(-ENOMEM);
1262 	}
1263 
1264 	strcpy(obj->path, path);
1265 	if (obj_name) {
1266 		libbpf_strlcpy(obj->name, obj_name, sizeof(obj->name));
1267 	} else {
1268 		/* Using basename() GNU version which doesn't modify arg. */
1269 		libbpf_strlcpy(obj->name, basename((void *)path), sizeof(obj->name));
1270 		end = strchr(obj->name, '.');
1271 		if (end)
1272 			*end = 0;
1273 	}
1274 
1275 	obj->efile.fd = -1;
1276 	/*
1277 	 * Caller of this function should also call
1278 	 * bpf_object__elf_finish() after data collection to return
1279 	 * obj_buf to user. If not, we should duplicate the buffer to
1280 	 * avoid user freeing them before elf finish.
1281 	 */
1282 	obj->efile.obj_buf = obj_buf;
1283 	obj->efile.obj_buf_sz = obj_buf_sz;
1284 	obj->efile.btf_maps_shndx = -1;
1285 	obj->efile.st_ops_shndx = -1;
1286 	obj->kconfig_map_idx = -1;
1287 
1288 	obj->kern_version = get_kernel_version();
1289 	obj->loaded = false;
1290 
1291 	return obj;
1292 }
1293 
1294 static void bpf_object__elf_finish(struct bpf_object *obj)
1295 {
1296 	if (!obj->efile.elf)
1297 		return;
1298 
1299 	elf_end(obj->efile.elf);
1300 	obj->efile.elf = NULL;
1301 	obj->efile.symbols = NULL;
1302 	obj->efile.st_ops_data = NULL;
1303 
1304 	zfree(&obj->efile.secs);
1305 	obj->efile.sec_cnt = 0;
1306 	zclose(obj->efile.fd);
1307 	obj->efile.obj_buf = NULL;
1308 	obj->efile.obj_buf_sz = 0;
1309 }
1310 
1311 static int bpf_object__elf_init(struct bpf_object *obj)
1312 {
1313 	Elf64_Ehdr *ehdr;
1314 	int err = 0;
1315 	Elf *elf;
1316 
1317 	if (obj->efile.elf) {
1318 		pr_warn("elf: init internal error\n");
1319 		return -LIBBPF_ERRNO__LIBELF;
1320 	}
1321 
1322 	if (obj->efile.obj_buf_sz > 0) {
1323 		/* obj_buf should have been validated by bpf_object__open_mem(). */
1324 		elf = elf_memory((char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
1325 	} else {
1326 		obj->efile.fd = open(obj->path, O_RDONLY | O_CLOEXEC);
1327 		if (obj->efile.fd < 0) {
1328 			char errmsg[STRERR_BUFSIZE], *cp;
1329 
1330 			err = -errno;
1331 			cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
1332 			pr_warn("elf: failed to open %s: %s\n", obj->path, cp);
1333 			return err;
1334 		}
1335 
1336 		elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1337 	}
1338 
1339 	if (!elf) {
1340 		pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
1341 		err = -LIBBPF_ERRNO__LIBELF;
1342 		goto errout;
1343 	}
1344 
1345 	obj->efile.elf = elf;
1346 
1347 	if (elf_kind(elf) != ELF_K_ELF) {
1348 		err = -LIBBPF_ERRNO__FORMAT;
1349 		pr_warn("elf: '%s' is not a proper ELF object\n", obj->path);
1350 		goto errout;
1351 	}
1352 
1353 	if (gelf_getclass(elf) != ELFCLASS64) {
1354 		err = -LIBBPF_ERRNO__FORMAT;
1355 		pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path);
1356 		goto errout;
1357 	}
1358 
1359 	obj->efile.ehdr = ehdr = elf64_getehdr(elf);
1360 	if (!obj->efile.ehdr) {
1361 		pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
1362 		err = -LIBBPF_ERRNO__FORMAT;
1363 		goto errout;
1364 	}
1365 
1366 	if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
1367 		pr_warn("elf: failed to get section names section index for %s: %s\n",
1368 			obj->path, elf_errmsg(-1));
1369 		err = -LIBBPF_ERRNO__FORMAT;
1370 		goto errout;
1371 	}
1372 
1373 	/* Elf is corrupted/truncated, avoid calling elf_strptr. */
1374 	if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
1375 		pr_warn("elf: failed to get section names strings from %s: %s\n",
1376 			obj->path, elf_errmsg(-1));
1377 		err = -LIBBPF_ERRNO__FORMAT;
1378 		goto errout;
1379 	}
1380 
1381 	/* Old LLVM set e_machine to EM_NONE */
1382 	if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
1383 		pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
1384 		err = -LIBBPF_ERRNO__FORMAT;
1385 		goto errout;
1386 	}
1387 
1388 	return 0;
1389 errout:
1390 	bpf_object__elf_finish(obj);
1391 	return err;
1392 }
1393 
1394 static int bpf_object__check_endianness(struct bpf_object *obj)
1395 {
1396 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1397 	if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2LSB)
1398 		return 0;
1399 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1400 	if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2MSB)
1401 		return 0;
1402 #else
1403 # error "Unrecognized __BYTE_ORDER__"
1404 #endif
1405 	pr_warn("elf: endianness mismatch in %s.\n", obj->path);
1406 	return -LIBBPF_ERRNO__ENDIAN;
1407 }
1408 
1409 static int
1410 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1411 {
1412 	if (!data) {
1413 		pr_warn("invalid license section in %s\n", obj->path);
1414 		return -LIBBPF_ERRNO__FORMAT;
1415 	}
1416 	/* libbpf_strlcpy() only copies first N - 1 bytes, so size + 1 won't
1417 	 * go over allowed ELF data section buffer
1418 	 */
1419 	libbpf_strlcpy(obj->license, data, min(size + 1, sizeof(obj->license)));
1420 	pr_debug("license of %s is %s\n", obj->path, obj->license);
1421 	return 0;
1422 }
1423 
1424 static int
1425 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1426 {
1427 	__u32 kver;
1428 
1429 	if (!data || size != sizeof(kver)) {
1430 		pr_warn("invalid kver section in %s\n", obj->path);
1431 		return -LIBBPF_ERRNO__FORMAT;
1432 	}
1433 	memcpy(&kver, data, sizeof(kver));
1434 	obj->kern_version = kver;
1435 	pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1436 	return 0;
1437 }
1438 
1439 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1440 {
1441 	if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1442 	    type == BPF_MAP_TYPE_HASH_OF_MAPS)
1443 		return true;
1444 	return false;
1445 }
1446 
1447 static int find_elf_sec_sz(const struct bpf_object *obj, const char *name, __u32 *size)
1448 {
1449 	Elf_Data *data;
1450 	Elf_Scn *scn;
1451 
1452 	if (!name)
1453 		return -EINVAL;
1454 
1455 	scn = elf_sec_by_name(obj, name);
1456 	data = elf_sec_data(obj, scn);
1457 	if (data) {
1458 		*size = data->d_size;
1459 		return 0; /* found it */
1460 	}
1461 
1462 	return -ENOENT;
1463 }
1464 
1465 static Elf64_Sym *find_elf_var_sym(const struct bpf_object *obj, const char *name)
1466 {
1467 	Elf_Data *symbols = obj->efile.symbols;
1468 	const char *sname;
1469 	size_t si;
1470 
1471 	for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
1472 		Elf64_Sym *sym = elf_sym_by_idx(obj, si);
1473 
1474 		if (ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)
1475 			continue;
1476 
1477 		if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL &&
1478 		    ELF64_ST_BIND(sym->st_info) != STB_WEAK)
1479 			continue;
1480 
1481 		sname = elf_sym_str(obj, sym->st_name);
1482 		if (!sname) {
1483 			pr_warn("failed to get sym name string for var %s\n", name);
1484 			return ERR_PTR(-EIO);
1485 		}
1486 		if (strcmp(name, sname) == 0)
1487 			return sym;
1488 	}
1489 
1490 	return ERR_PTR(-ENOENT);
1491 }
1492 
1493 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1494 {
1495 	struct bpf_map *map;
1496 	int err;
1497 
1498 	err = libbpf_ensure_mem((void **)&obj->maps, &obj->maps_cap,
1499 				sizeof(*obj->maps), obj->nr_maps + 1);
1500 	if (err)
1501 		return ERR_PTR(err);
1502 
1503 	map = &obj->maps[obj->nr_maps++];
1504 	map->obj = obj;
1505 	map->fd = -1;
1506 	map->inner_map_fd = -1;
1507 	map->autocreate = true;
1508 
1509 	return map;
1510 }
1511 
1512 static size_t bpf_map_mmap_sz(const struct bpf_map *map)
1513 {
1514 	long page_sz = sysconf(_SC_PAGE_SIZE);
1515 	size_t map_sz;
1516 
1517 	map_sz = (size_t)roundup(map->def.value_size, 8) * map->def.max_entries;
1518 	map_sz = roundup(map_sz, page_sz);
1519 	return map_sz;
1520 }
1521 
1522 static char *internal_map_name(struct bpf_object *obj, const char *real_name)
1523 {
1524 	char map_name[BPF_OBJ_NAME_LEN], *p;
1525 	int pfx_len, sfx_len = max((size_t)7, strlen(real_name));
1526 
1527 	/* This is one of the more confusing parts of libbpf for various
1528 	 * reasons, some of which are historical. The original idea for naming
1529 	 * internal names was to include as much of BPF object name prefix as
1530 	 * possible, so that it can be distinguished from similar internal
1531 	 * maps of a different BPF object.
1532 	 * As an example, let's say we have bpf_object named 'my_object_name'
1533 	 * and internal map corresponding to '.rodata' ELF section. The final
1534 	 * map name advertised to user and to the kernel will be
1535 	 * 'my_objec.rodata', taking first 8 characters of object name and
1536 	 * entire 7 characters of '.rodata'.
1537 	 * Somewhat confusingly, if internal map ELF section name is shorter
1538 	 * than 7 characters, e.g., '.bss', we still reserve 7 characters
1539 	 * for the suffix, even though we only have 4 actual characters, and
1540 	 * resulting map will be called 'my_objec.bss', not even using all 15
1541 	 * characters allowed by the kernel. Oh well, at least the truncated
1542 	 * object name is somewhat consistent in this case. But if the map
1543 	 * name is '.kconfig', we'll still have entirety of '.kconfig' added
1544 	 * (8 chars) and thus will be left with only first 7 characters of the
1545 	 * object name ('my_obje'). Happy guessing, user, that the final map
1546 	 * name will be "my_obje.kconfig".
1547 	 * Now, with libbpf starting to support arbitrarily named .rodata.*
1548 	 * and .data.* data sections, it's possible that ELF section name is
1549 	 * longer than allowed 15 chars, so we now need to be careful to take
1550 	 * only up to 15 first characters of ELF name, taking no BPF object
1551 	 * name characters at all. So '.rodata.abracadabra' will result in
1552 	 * '.rodata.abracad' kernel and user-visible name.
1553 	 * We need to keep this convoluted logic intact for .data, .bss and
1554 	 * .rodata maps, but for new custom .data.custom and .rodata.custom
1555 	 * maps we use their ELF names as is, not prepending bpf_object name
1556 	 * in front. We still need to truncate them to 15 characters for the
1557 	 * kernel. Full name can be recovered for such maps by using DATASEC
1558 	 * BTF type associated with such map's value type, though.
1559 	 */
1560 	if (sfx_len >= BPF_OBJ_NAME_LEN)
1561 		sfx_len = BPF_OBJ_NAME_LEN - 1;
1562 
1563 	/* if there are two or more dots in map name, it's a custom dot map */
1564 	if (strchr(real_name + 1, '.') != NULL)
1565 		pfx_len = 0;
1566 	else
1567 		pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
1568 
1569 	snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1570 		 sfx_len, real_name);
1571 
1572 	/* sanitise map name to characters allowed by kernel */
1573 	for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1574 		if (!isalnum(*p) && *p != '_' && *p != '.')
1575 			*p = '_';
1576 
1577 	return strdup(map_name);
1578 }
1579 
1580 static int
1581 map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map);
1582 
1583 /* Internal BPF map is mmap()'able only if at least one of corresponding
1584  * DATASEC's VARs are to be exposed through BPF skeleton. I.e., it's a GLOBAL
1585  * variable and it's not marked as __hidden (which turns it into, effectively,
1586  * a STATIC variable).
1587  */
1588 static bool map_is_mmapable(struct bpf_object *obj, struct bpf_map *map)
1589 {
1590 	const struct btf_type *t, *vt;
1591 	struct btf_var_secinfo *vsi;
1592 	int i, n;
1593 
1594 	if (!map->btf_value_type_id)
1595 		return false;
1596 
1597 	t = btf__type_by_id(obj->btf, map->btf_value_type_id);
1598 	if (!btf_is_datasec(t))
1599 		return false;
1600 
1601 	vsi = btf_var_secinfos(t);
1602 	for (i = 0, n = btf_vlen(t); i < n; i++, vsi++) {
1603 		vt = btf__type_by_id(obj->btf, vsi->type);
1604 		if (!btf_is_var(vt))
1605 			continue;
1606 
1607 		if (btf_var(vt)->linkage != BTF_VAR_STATIC)
1608 			return true;
1609 	}
1610 
1611 	return false;
1612 }
1613 
1614 static int
1615 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
1616 			      const char *real_name, int sec_idx, void *data, size_t data_sz)
1617 {
1618 	struct bpf_map_def *def;
1619 	struct bpf_map *map;
1620 	int err;
1621 
1622 	map = bpf_object__add_map(obj);
1623 	if (IS_ERR(map))
1624 		return PTR_ERR(map);
1625 
1626 	map->libbpf_type = type;
1627 	map->sec_idx = sec_idx;
1628 	map->sec_offset = 0;
1629 	map->real_name = strdup(real_name);
1630 	map->name = internal_map_name(obj, real_name);
1631 	if (!map->real_name || !map->name) {
1632 		zfree(&map->real_name);
1633 		zfree(&map->name);
1634 		return -ENOMEM;
1635 	}
1636 
1637 	def = &map->def;
1638 	def->type = BPF_MAP_TYPE_ARRAY;
1639 	def->key_size = sizeof(int);
1640 	def->value_size = data_sz;
1641 	def->max_entries = 1;
1642 	def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
1643 			 ? BPF_F_RDONLY_PROG : 0;
1644 
1645 	/* failures are fine because of maps like .rodata.str1.1 */
1646 	(void) map_fill_btf_type_info(obj, map);
1647 
1648 	if (map_is_mmapable(obj, map))
1649 		def->map_flags |= BPF_F_MMAPABLE;
1650 
1651 	pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
1652 		 map->name, map->sec_idx, map->sec_offset, def->map_flags);
1653 
1654 	map->mmaped = mmap(NULL, bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
1655 			   MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1656 	if (map->mmaped == MAP_FAILED) {
1657 		err = -errno;
1658 		map->mmaped = NULL;
1659 		pr_warn("failed to alloc map '%s' content buffer: %d\n",
1660 			map->name, err);
1661 		zfree(&map->real_name);
1662 		zfree(&map->name);
1663 		return err;
1664 	}
1665 
1666 	if (data)
1667 		memcpy(map->mmaped, data, data_sz);
1668 
1669 	pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
1670 	return 0;
1671 }
1672 
1673 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
1674 {
1675 	struct elf_sec_desc *sec_desc;
1676 	const char *sec_name;
1677 	int err = 0, sec_idx;
1678 
1679 	/*
1680 	 * Populate obj->maps with libbpf internal maps.
1681 	 */
1682 	for (sec_idx = 1; sec_idx < obj->efile.sec_cnt; sec_idx++) {
1683 		sec_desc = &obj->efile.secs[sec_idx];
1684 
1685 		/* Skip recognized sections with size 0. */
1686 		if (!sec_desc->data || sec_desc->data->d_size == 0)
1687 			continue;
1688 
1689 		switch (sec_desc->sec_type) {
1690 		case SEC_DATA:
1691 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1692 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
1693 							    sec_name, sec_idx,
1694 							    sec_desc->data->d_buf,
1695 							    sec_desc->data->d_size);
1696 			break;
1697 		case SEC_RODATA:
1698 			obj->has_rodata = true;
1699 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1700 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
1701 							    sec_name, sec_idx,
1702 							    sec_desc->data->d_buf,
1703 							    sec_desc->data->d_size);
1704 			break;
1705 		case SEC_BSS:
1706 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1707 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
1708 							    sec_name, sec_idx,
1709 							    NULL,
1710 							    sec_desc->data->d_size);
1711 			break;
1712 		default:
1713 			/* skip */
1714 			break;
1715 		}
1716 		if (err)
1717 			return err;
1718 	}
1719 	return 0;
1720 }
1721 
1722 
1723 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
1724 					       const void *name)
1725 {
1726 	int i;
1727 
1728 	for (i = 0; i < obj->nr_extern; i++) {
1729 		if (strcmp(obj->externs[i].name, name) == 0)
1730 			return &obj->externs[i];
1731 	}
1732 	return NULL;
1733 }
1734 
1735 static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
1736 			      char value)
1737 {
1738 	switch (ext->kcfg.type) {
1739 	case KCFG_BOOL:
1740 		if (value == 'm') {
1741 			pr_warn("extern (kcfg) '%s': value '%c' implies tristate or char type\n",
1742 				ext->name, value);
1743 			return -EINVAL;
1744 		}
1745 		*(bool *)ext_val = value == 'y' ? true : false;
1746 		break;
1747 	case KCFG_TRISTATE:
1748 		if (value == 'y')
1749 			*(enum libbpf_tristate *)ext_val = TRI_YES;
1750 		else if (value == 'm')
1751 			*(enum libbpf_tristate *)ext_val = TRI_MODULE;
1752 		else /* value == 'n' */
1753 			*(enum libbpf_tristate *)ext_val = TRI_NO;
1754 		break;
1755 	case KCFG_CHAR:
1756 		*(char *)ext_val = value;
1757 		break;
1758 	case KCFG_UNKNOWN:
1759 	case KCFG_INT:
1760 	case KCFG_CHAR_ARR:
1761 	default:
1762 		pr_warn("extern (kcfg) '%s': value '%c' implies bool, tristate, or char type\n",
1763 			ext->name, value);
1764 		return -EINVAL;
1765 	}
1766 	ext->is_set = true;
1767 	return 0;
1768 }
1769 
1770 static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
1771 			      const char *value)
1772 {
1773 	size_t len;
1774 
1775 	if (ext->kcfg.type != KCFG_CHAR_ARR) {
1776 		pr_warn("extern (kcfg) '%s': value '%s' implies char array type\n",
1777 			ext->name, value);
1778 		return -EINVAL;
1779 	}
1780 
1781 	len = strlen(value);
1782 	if (value[len - 1] != '"') {
1783 		pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
1784 			ext->name, value);
1785 		return -EINVAL;
1786 	}
1787 
1788 	/* strip quotes */
1789 	len -= 2;
1790 	if (len >= ext->kcfg.sz) {
1791 		pr_warn("extern (kcfg) '%s': long string '%s' of (%zu bytes) truncated to %d bytes\n",
1792 			ext->name, value, len, ext->kcfg.sz - 1);
1793 		len = ext->kcfg.sz - 1;
1794 	}
1795 	memcpy(ext_val, value + 1, len);
1796 	ext_val[len] = '\0';
1797 	ext->is_set = true;
1798 	return 0;
1799 }
1800 
1801 static int parse_u64(const char *value, __u64 *res)
1802 {
1803 	char *value_end;
1804 	int err;
1805 
1806 	errno = 0;
1807 	*res = strtoull(value, &value_end, 0);
1808 	if (errno) {
1809 		err = -errno;
1810 		pr_warn("failed to parse '%s' as integer: %d\n", value, err);
1811 		return err;
1812 	}
1813 	if (*value_end) {
1814 		pr_warn("failed to parse '%s' as integer completely\n", value);
1815 		return -EINVAL;
1816 	}
1817 	return 0;
1818 }
1819 
1820 static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
1821 {
1822 	int bit_sz = ext->kcfg.sz * 8;
1823 
1824 	if (ext->kcfg.sz == 8)
1825 		return true;
1826 
1827 	/* Validate that value stored in u64 fits in integer of `ext->sz`
1828 	 * bytes size without any loss of information. If the target integer
1829 	 * is signed, we rely on the following limits of integer type of
1830 	 * Y bits and subsequent transformation:
1831 	 *
1832 	 *     -2^(Y-1) <= X           <= 2^(Y-1) - 1
1833 	 *            0 <= X + 2^(Y-1) <= 2^Y - 1
1834 	 *            0 <= X + 2^(Y-1) <  2^Y
1835 	 *
1836 	 *  For unsigned target integer, check that all the (64 - Y) bits are
1837 	 *  zero.
1838 	 */
1839 	if (ext->kcfg.is_signed)
1840 		return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
1841 	else
1842 		return (v >> bit_sz) == 0;
1843 }
1844 
1845 static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
1846 			      __u64 value)
1847 {
1848 	if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR &&
1849 	    ext->kcfg.type != KCFG_BOOL) {
1850 		pr_warn("extern (kcfg) '%s': value '%llu' implies integer, char, or boolean type\n",
1851 			ext->name, (unsigned long long)value);
1852 		return -EINVAL;
1853 	}
1854 	if (ext->kcfg.type == KCFG_BOOL && value > 1) {
1855 		pr_warn("extern (kcfg) '%s': value '%llu' isn't boolean compatible\n",
1856 			ext->name, (unsigned long long)value);
1857 		return -EINVAL;
1858 
1859 	}
1860 	if (!is_kcfg_value_in_range(ext, value)) {
1861 		pr_warn("extern (kcfg) '%s': value '%llu' doesn't fit in %d bytes\n",
1862 			ext->name, (unsigned long long)value, ext->kcfg.sz);
1863 		return -ERANGE;
1864 	}
1865 	switch (ext->kcfg.sz) {
1866 		case 1: *(__u8 *)ext_val = value; break;
1867 		case 2: *(__u16 *)ext_val = value; break;
1868 		case 4: *(__u32 *)ext_val = value; break;
1869 		case 8: *(__u64 *)ext_val = value; 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 = 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_maps(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->nr_extern > 0;
2784 }
2785 
2786 static bool kernel_needs_btf(const struct bpf_object *obj)
2787 {
2788 	return obj->efile.st_ops_shndx >= 0;
2789 }
2790 
2791 static int bpf_object__init_btf(struct bpf_object *obj,
2792 				Elf_Data *btf_data,
2793 				Elf_Data *btf_ext_data)
2794 {
2795 	int err = -ENOENT;
2796 
2797 	if (btf_data) {
2798 		obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
2799 		err = libbpf_get_error(obj->btf);
2800 		if (err) {
2801 			obj->btf = NULL;
2802 			pr_warn("Error loading ELF section %s: %d.\n", BTF_ELF_SEC, err);
2803 			goto out;
2804 		}
2805 		/* enforce 8-byte pointers for BPF-targeted BTFs */
2806 		btf__set_pointer_size(obj->btf, 8);
2807 	}
2808 	if (btf_ext_data) {
2809 		struct btf_ext_info *ext_segs[3];
2810 		int seg_num, sec_num;
2811 
2812 		if (!obj->btf) {
2813 			pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
2814 				 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
2815 			goto out;
2816 		}
2817 		obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
2818 		err = libbpf_get_error(obj->btf_ext);
2819 		if (err) {
2820 			pr_warn("Error loading ELF section %s: %d. Ignored and continue.\n",
2821 				BTF_EXT_ELF_SEC, err);
2822 			obj->btf_ext = NULL;
2823 			goto out;
2824 		}
2825 
2826 		/* setup .BTF.ext to ELF section mapping */
2827 		ext_segs[0] = &obj->btf_ext->func_info;
2828 		ext_segs[1] = &obj->btf_ext->line_info;
2829 		ext_segs[2] = &obj->btf_ext->core_relo_info;
2830 		for (seg_num = 0; seg_num < ARRAY_SIZE(ext_segs); seg_num++) {
2831 			struct btf_ext_info *seg = ext_segs[seg_num];
2832 			const struct btf_ext_info_sec *sec;
2833 			const char *sec_name;
2834 			Elf_Scn *scn;
2835 
2836 			if (seg->sec_cnt == 0)
2837 				continue;
2838 
2839 			seg->sec_idxs = calloc(seg->sec_cnt, sizeof(*seg->sec_idxs));
2840 			if (!seg->sec_idxs) {
2841 				err = -ENOMEM;
2842 				goto out;
2843 			}
2844 
2845 			sec_num = 0;
2846 			for_each_btf_ext_sec(seg, sec) {
2847 				/* preventively increment index to avoid doing
2848 				 * this before every continue below
2849 				 */
2850 				sec_num++;
2851 
2852 				sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
2853 				if (str_is_empty(sec_name))
2854 					continue;
2855 				scn = elf_sec_by_name(obj, sec_name);
2856 				if (!scn)
2857 					continue;
2858 
2859 				seg->sec_idxs[sec_num - 1] = elf_ndxscn(scn);
2860 			}
2861 		}
2862 	}
2863 out:
2864 	if (err && libbpf_needs_btf(obj)) {
2865 		pr_warn("BTF is required, but is missing or corrupted.\n");
2866 		return err;
2867 	}
2868 	return 0;
2869 }
2870 
2871 static int compare_vsi_off(const void *_a, const void *_b)
2872 {
2873 	const struct btf_var_secinfo *a = _a;
2874 	const struct btf_var_secinfo *b = _b;
2875 
2876 	return a->offset - b->offset;
2877 }
2878 
2879 static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
2880 			     struct btf_type *t)
2881 {
2882 	__u32 size = 0, i, vars = btf_vlen(t);
2883 	const char *sec_name = btf__name_by_offset(btf, t->name_off);
2884 	struct btf_var_secinfo *vsi;
2885 	bool fixup_offsets = false;
2886 	int err;
2887 
2888 	if (!sec_name) {
2889 		pr_debug("No name found in string section for DATASEC kind.\n");
2890 		return -ENOENT;
2891 	}
2892 
2893 	/* Extern-backing datasecs (.ksyms, .kconfig) have their size and
2894 	 * variable offsets set at the previous step. Further, not every
2895 	 * extern BTF VAR has corresponding ELF symbol preserved, so we skip
2896 	 * all fixups altogether for such sections and go straight to sorting
2897 	 * VARs within their DATASEC.
2898 	 */
2899 	if (strcmp(sec_name, KCONFIG_SEC) == 0 || strcmp(sec_name, KSYMS_SEC) == 0)
2900 		goto sort_vars;
2901 
2902 	/* Clang leaves DATASEC size and VAR offsets as zeroes, so we need to
2903 	 * fix this up. But BPF static linker already fixes this up and fills
2904 	 * all the sizes and offsets during static linking. So this step has
2905 	 * to be optional. But the STV_HIDDEN handling is non-optional for any
2906 	 * non-extern DATASEC, so the variable fixup loop below handles both
2907 	 * functions at the same time, paying the cost of BTF VAR <-> ELF
2908 	 * symbol matching just once.
2909 	 */
2910 	if (t->size == 0) {
2911 		err = find_elf_sec_sz(obj, sec_name, &size);
2912 		if (err || !size) {
2913 			pr_debug("sec '%s': failed to determine size from ELF: size %u, err %d\n",
2914 				 sec_name, size, err);
2915 			return -ENOENT;
2916 		}
2917 
2918 		t->size = size;
2919 		fixup_offsets = true;
2920 	}
2921 
2922 	for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
2923 		const struct btf_type *t_var;
2924 		struct btf_var *var;
2925 		const char *var_name;
2926 		Elf64_Sym *sym;
2927 
2928 		t_var = btf__type_by_id(btf, vsi->type);
2929 		if (!t_var || !btf_is_var(t_var)) {
2930 			pr_debug("sec '%s': unexpected non-VAR type found\n", sec_name);
2931 			return -EINVAL;
2932 		}
2933 
2934 		var = btf_var(t_var);
2935 		if (var->linkage == BTF_VAR_STATIC || var->linkage == BTF_VAR_GLOBAL_EXTERN)
2936 			continue;
2937 
2938 		var_name = btf__name_by_offset(btf, t_var->name_off);
2939 		if (!var_name) {
2940 			pr_debug("sec '%s': failed to find name of DATASEC's member #%d\n",
2941 				 sec_name, i);
2942 			return -ENOENT;
2943 		}
2944 
2945 		sym = find_elf_var_sym(obj, var_name);
2946 		if (IS_ERR(sym)) {
2947 			pr_debug("sec '%s': failed to find ELF symbol for VAR '%s'\n",
2948 				 sec_name, var_name);
2949 			return -ENOENT;
2950 		}
2951 
2952 		if (fixup_offsets)
2953 			vsi->offset = sym->st_value;
2954 
2955 		/* if variable is a global/weak symbol, but has restricted
2956 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF VAR
2957 		 * as static. This follows similar logic for functions (BPF
2958 		 * subprogs) and influences libbpf's further decisions about
2959 		 * whether to make global data BPF array maps as
2960 		 * BPF_F_MMAPABLE.
2961 		 */
2962 		if (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
2963 		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL)
2964 			var->linkage = BTF_VAR_STATIC;
2965 	}
2966 
2967 sort_vars:
2968 	qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
2969 	return 0;
2970 }
2971 
2972 static int bpf_object_fixup_btf(struct bpf_object *obj)
2973 {
2974 	int i, n, err = 0;
2975 
2976 	if (!obj->btf)
2977 		return 0;
2978 
2979 	n = btf__type_cnt(obj->btf);
2980 	for (i = 1; i < n; i++) {
2981 		struct btf_type *t = btf_type_by_id(obj->btf, i);
2982 
2983 		/* Loader needs to fix up some of the things compiler
2984 		 * couldn't get its hands on while emitting BTF. This
2985 		 * is section size and global variable offset. We use
2986 		 * the info from the ELF itself for this purpose.
2987 		 */
2988 		if (btf_is_datasec(t)) {
2989 			err = btf_fixup_datasec(obj, obj->btf, t);
2990 			if (err)
2991 				return err;
2992 		}
2993 	}
2994 
2995 	return 0;
2996 }
2997 
2998 static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
2999 {
3000 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
3001 	    prog->type == BPF_PROG_TYPE_LSM)
3002 		return true;
3003 
3004 	/* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
3005 	 * also need vmlinux BTF
3006 	 */
3007 	if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
3008 		return true;
3009 
3010 	return false;
3011 }
3012 
3013 static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
3014 {
3015 	struct bpf_program *prog;
3016 	int i;
3017 
3018 	/* CO-RE relocations need kernel BTF, only when btf_custom_path
3019 	 * is not specified
3020 	 */
3021 	if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
3022 		return true;
3023 
3024 	/* Support for typed ksyms needs kernel BTF */
3025 	for (i = 0; i < obj->nr_extern; i++) {
3026 		const struct extern_desc *ext;
3027 
3028 		ext = &obj->externs[i];
3029 		if (ext->type == EXT_KSYM && ext->ksym.type_id)
3030 			return true;
3031 	}
3032 
3033 	bpf_object__for_each_program(prog, obj) {
3034 		if (!prog->autoload)
3035 			continue;
3036 		if (prog_needs_vmlinux_btf(prog))
3037 			return true;
3038 	}
3039 
3040 	return false;
3041 }
3042 
3043 static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
3044 {
3045 	int err;
3046 
3047 	/* btf_vmlinux could be loaded earlier */
3048 	if (obj->btf_vmlinux || obj->gen_loader)
3049 		return 0;
3050 
3051 	if (!force && !obj_needs_vmlinux_btf(obj))
3052 		return 0;
3053 
3054 	obj->btf_vmlinux = btf__load_vmlinux_btf();
3055 	err = libbpf_get_error(obj->btf_vmlinux);
3056 	if (err) {
3057 		pr_warn("Error loading vmlinux BTF: %d\n", err);
3058 		obj->btf_vmlinux = NULL;
3059 		return err;
3060 	}
3061 	return 0;
3062 }
3063 
3064 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
3065 {
3066 	struct btf *kern_btf = obj->btf;
3067 	bool btf_mandatory, sanitize;
3068 	int i, err = 0;
3069 
3070 	if (!obj->btf)
3071 		return 0;
3072 
3073 	if (!kernel_supports(obj, FEAT_BTF)) {
3074 		if (kernel_needs_btf(obj)) {
3075 			err = -EOPNOTSUPP;
3076 			goto report;
3077 		}
3078 		pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
3079 		return 0;
3080 	}
3081 
3082 	/* Even though some subprogs are global/weak, user might prefer more
3083 	 * permissive BPF verification process that BPF verifier performs for
3084 	 * static functions, taking into account more context from the caller
3085 	 * functions. In such case, they need to mark such subprogs with
3086 	 * __attribute__((visibility("hidden"))) and libbpf will adjust
3087 	 * corresponding FUNC BTF type to be marked as static and trigger more
3088 	 * involved BPF verification process.
3089 	 */
3090 	for (i = 0; i < obj->nr_programs; i++) {
3091 		struct bpf_program *prog = &obj->programs[i];
3092 		struct btf_type *t;
3093 		const char *name;
3094 		int j, n;
3095 
3096 		if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
3097 			continue;
3098 
3099 		n = btf__type_cnt(obj->btf);
3100 		for (j = 1; j < n; j++) {
3101 			t = btf_type_by_id(obj->btf, j);
3102 			if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
3103 				continue;
3104 
3105 			name = btf__str_by_offset(obj->btf, t->name_off);
3106 			if (strcmp(name, prog->name) != 0)
3107 				continue;
3108 
3109 			t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
3110 			break;
3111 		}
3112 	}
3113 
3114 	sanitize = btf_needs_sanitization(obj);
3115 	if (sanitize) {
3116 		const void *raw_data;
3117 		__u32 sz;
3118 
3119 		/* clone BTF to sanitize a copy and leave the original intact */
3120 		raw_data = btf__raw_data(obj->btf, &sz);
3121 		kern_btf = btf__new(raw_data, sz);
3122 		err = libbpf_get_error(kern_btf);
3123 		if (err)
3124 			return err;
3125 
3126 		/* enforce 8-byte pointers for BPF-targeted BTFs */
3127 		btf__set_pointer_size(obj->btf, 8);
3128 		err = bpf_object__sanitize_btf(obj, kern_btf);
3129 		if (err)
3130 			return err;
3131 	}
3132 
3133 	if (obj->gen_loader) {
3134 		__u32 raw_size = 0;
3135 		const void *raw_data = btf__raw_data(kern_btf, &raw_size);
3136 
3137 		if (!raw_data)
3138 			return -ENOMEM;
3139 		bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
3140 		/* Pretend to have valid FD to pass various fd >= 0 checks.
3141 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
3142 		 */
3143 		btf__set_fd(kern_btf, 0);
3144 	} else {
3145 		/* currently BPF_BTF_LOAD only supports log_level 1 */
3146 		err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
3147 					   obj->log_level ? 1 : 0);
3148 	}
3149 	if (sanitize) {
3150 		if (!err) {
3151 			/* move fd to libbpf's BTF */
3152 			btf__set_fd(obj->btf, btf__fd(kern_btf));
3153 			btf__set_fd(kern_btf, -1);
3154 		}
3155 		btf__free(kern_btf);
3156 	}
3157 report:
3158 	if (err) {
3159 		btf_mandatory = kernel_needs_btf(obj);
3160 		pr_warn("Error loading .BTF into kernel: %d. %s\n", err,
3161 			btf_mandatory ? "BTF is mandatory, can't proceed."
3162 				      : "BTF is optional, ignoring.");
3163 		if (!btf_mandatory)
3164 			err = 0;
3165 	}
3166 	return err;
3167 }
3168 
3169 static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
3170 {
3171 	const char *name;
3172 
3173 	name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
3174 	if (!name) {
3175 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3176 			off, obj->path, elf_errmsg(-1));
3177 		return NULL;
3178 	}
3179 
3180 	return name;
3181 }
3182 
3183 static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
3184 {
3185 	const char *name;
3186 
3187 	name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
3188 	if (!name) {
3189 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3190 			off, obj->path, elf_errmsg(-1));
3191 		return NULL;
3192 	}
3193 
3194 	return name;
3195 }
3196 
3197 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
3198 {
3199 	Elf_Scn *scn;
3200 
3201 	scn = elf_getscn(obj->efile.elf, idx);
3202 	if (!scn) {
3203 		pr_warn("elf: failed to get section(%zu) from %s: %s\n",
3204 			idx, obj->path, elf_errmsg(-1));
3205 		return NULL;
3206 	}
3207 	return scn;
3208 }
3209 
3210 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
3211 {
3212 	Elf_Scn *scn = NULL;
3213 	Elf *elf = obj->efile.elf;
3214 	const char *sec_name;
3215 
3216 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3217 		sec_name = elf_sec_name(obj, scn);
3218 		if (!sec_name)
3219 			return NULL;
3220 
3221 		if (strcmp(sec_name, name) != 0)
3222 			continue;
3223 
3224 		return scn;
3225 	}
3226 	return NULL;
3227 }
3228 
3229 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn)
3230 {
3231 	Elf64_Shdr *shdr;
3232 
3233 	if (!scn)
3234 		return NULL;
3235 
3236 	shdr = elf64_getshdr(scn);
3237 	if (!shdr) {
3238 		pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
3239 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3240 		return NULL;
3241 	}
3242 
3243 	return shdr;
3244 }
3245 
3246 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
3247 {
3248 	const char *name;
3249 	Elf64_Shdr *sh;
3250 
3251 	if (!scn)
3252 		return NULL;
3253 
3254 	sh = elf_sec_hdr(obj, scn);
3255 	if (!sh)
3256 		return NULL;
3257 
3258 	name = elf_sec_str(obj, sh->sh_name);
3259 	if (!name) {
3260 		pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
3261 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3262 		return NULL;
3263 	}
3264 
3265 	return name;
3266 }
3267 
3268 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
3269 {
3270 	Elf_Data *data;
3271 
3272 	if (!scn)
3273 		return NULL;
3274 
3275 	data = elf_getdata(scn, 0);
3276 	if (!data) {
3277 		pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
3278 			elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
3279 			obj->path, elf_errmsg(-1));
3280 		return NULL;
3281 	}
3282 
3283 	return data;
3284 }
3285 
3286 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx)
3287 {
3288 	if (idx >= obj->efile.symbols->d_size / sizeof(Elf64_Sym))
3289 		return NULL;
3290 
3291 	return (Elf64_Sym *)obj->efile.symbols->d_buf + idx;
3292 }
3293 
3294 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx)
3295 {
3296 	if (idx >= data->d_size / sizeof(Elf64_Rel))
3297 		return NULL;
3298 
3299 	return (Elf64_Rel *)data->d_buf + idx;
3300 }
3301 
3302 static bool is_sec_name_dwarf(const char *name)
3303 {
3304 	/* approximation, but the actual list is too long */
3305 	return str_has_pfx(name, ".debug_");
3306 }
3307 
3308 static bool ignore_elf_section(Elf64_Shdr *hdr, const char *name)
3309 {
3310 	/* no special handling of .strtab */
3311 	if (hdr->sh_type == SHT_STRTAB)
3312 		return true;
3313 
3314 	/* ignore .llvm_addrsig section as well */
3315 	if (hdr->sh_type == SHT_LLVM_ADDRSIG)
3316 		return true;
3317 
3318 	/* no subprograms will lead to an empty .text section, ignore it */
3319 	if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
3320 	    strcmp(name, ".text") == 0)
3321 		return true;
3322 
3323 	/* DWARF sections */
3324 	if (is_sec_name_dwarf(name))
3325 		return true;
3326 
3327 	if (str_has_pfx(name, ".rel")) {
3328 		name += sizeof(".rel") - 1;
3329 		/* DWARF section relocations */
3330 		if (is_sec_name_dwarf(name))
3331 			return true;
3332 
3333 		/* .BTF and .BTF.ext don't need relocations */
3334 		if (strcmp(name, BTF_ELF_SEC) == 0 ||
3335 		    strcmp(name, BTF_EXT_ELF_SEC) == 0)
3336 			return true;
3337 	}
3338 
3339 	return false;
3340 }
3341 
3342 static int cmp_progs(const void *_a, const void *_b)
3343 {
3344 	const struct bpf_program *a = _a;
3345 	const struct bpf_program *b = _b;
3346 
3347 	if (a->sec_idx != b->sec_idx)
3348 		return a->sec_idx < b->sec_idx ? -1 : 1;
3349 
3350 	/* sec_insn_off can't be the same within the section */
3351 	return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
3352 }
3353 
3354 static int bpf_object__elf_collect(struct bpf_object *obj)
3355 {
3356 	struct elf_sec_desc *sec_desc;
3357 	Elf *elf = obj->efile.elf;
3358 	Elf_Data *btf_ext_data = NULL;
3359 	Elf_Data *btf_data = NULL;
3360 	int idx = 0, err = 0;
3361 	const char *name;
3362 	Elf_Data *data;
3363 	Elf_Scn *scn;
3364 	Elf64_Shdr *sh;
3365 
3366 	/* ELF section indices are 0-based, but sec #0 is special "invalid"
3367 	 * section. Since section count retrieved by elf_getshdrnum() does
3368 	 * include sec #0, it is already the necessary size of an array to keep
3369 	 * all the sections.
3370 	 */
3371 	if (elf_getshdrnum(obj->efile.elf, &obj->efile.sec_cnt)) {
3372 		pr_warn("elf: failed to get the number of sections for %s: %s\n",
3373 			obj->path, elf_errmsg(-1));
3374 		return -LIBBPF_ERRNO__FORMAT;
3375 	}
3376 	obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs));
3377 	if (!obj->efile.secs)
3378 		return -ENOMEM;
3379 
3380 	/* a bunch of ELF parsing functionality depends on processing symbols,
3381 	 * so do the first pass and find the symbol table
3382 	 */
3383 	scn = NULL;
3384 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3385 		sh = elf_sec_hdr(obj, scn);
3386 		if (!sh)
3387 			return -LIBBPF_ERRNO__FORMAT;
3388 
3389 		if (sh->sh_type == SHT_SYMTAB) {
3390 			if (obj->efile.symbols) {
3391 				pr_warn("elf: multiple symbol tables in %s\n", obj->path);
3392 				return -LIBBPF_ERRNO__FORMAT;
3393 			}
3394 
3395 			data = elf_sec_data(obj, scn);
3396 			if (!data)
3397 				return -LIBBPF_ERRNO__FORMAT;
3398 
3399 			idx = elf_ndxscn(scn);
3400 
3401 			obj->efile.symbols = data;
3402 			obj->efile.symbols_shndx = idx;
3403 			obj->efile.strtabidx = sh->sh_link;
3404 		}
3405 	}
3406 
3407 	if (!obj->efile.symbols) {
3408 		pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
3409 			obj->path);
3410 		return -ENOENT;
3411 	}
3412 
3413 	scn = NULL;
3414 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3415 		idx = elf_ndxscn(scn);
3416 		sec_desc = &obj->efile.secs[idx];
3417 
3418 		sh = elf_sec_hdr(obj, scn);
3419 		if (!sh)
3420 			return -LIBBPF_ERRNO__FORMAT;
3421 
3422 		name = elf_sec_str(obj, sh->sh_name);
3423 		if (!name)
3424 			return -LIBBPF_ERRNO__FORMAT;
3425 
3426 		if (ignore_elf_section(sh, name))
3427 			continue;
3428 
3429 		data = elf_sec_data(obj, scn);
3430 		if (!data)
3431 			return -LIBBPF_ERRNO__FORMAT;
3432 
3433 		pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
3434 			 idx, name, (unsigned long)data->d_size,
3435 			 (int)sh->sh_link, (unsigned long)sh->sh_flags,
3436 			 (int)sh->sh_type);
3437 
3438 		if (strcmp(name, "license") == 0) {
3439 			err = bpf_object__init_license(obj, data->d_buf, data->d_size);
3440 			if (err)
3441 				return err;
3442 		} else if (strcmp(name, "version") == 0) {
3443 			err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
3444 			if (err)
3445 				return err;
3446 		} else if (strcmp(name, "maps") == 0) {
3447 			pr_warn("elf: legacy map definitions in 'maps' section are not supported by libbpf v1.0+\n");
3448 			return -ENOTSUP;
3449 		} else if (strcmp(name, MAPS_ELF_SEC) == 0) {
3450 			obj->efile.btf_maps_shndx = idx;
3451 		} else if (strcmp(name, BTF_ELF_SEC) == 0) {
3452 			if (sh->sh_type != SHT_PROGBITS)
3453 				return -LIBBPF_ERRNO__FORMAT;
3454 			btf_data = data;
3455 		} else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
3456 			if (sh->sh_type != SHT_PROGBITS)
3457 				return -LIBBPF_ERRNO__FORMAT;
3458 			btf_ext_data = data;
3459 		} else if (sh->sh_type == SHT_SYMTAB) {
3460 			/* already processed during the first pass above */
3461 		} else if (sh->sh_type == SHT_PROGBITS && data->d_size > 0) {
3462 			if (sh->sh_flags & SHF_EXECINSTR) {
3463 				if (strcmp(name, ".text") == 0)
3464 					obj->efile.text_shndx = idx;
3465 				err = bpf_object__add_programs(obj, data, name, idx);
3466 				if (err)
3467 					return err;
3468 			} else if (strcmp(name, DATA_SEC) == 0 ||
3469 				   str_has_pfx(name, DATA_SEC ".")) {
3470 				sec_desc->sec_type = SEC_DATA;
3471 				sec_desc->shdr = sh;
3472 				sec_desc->data = data;
3473 			} else if (strcmp(name, RODATA_SEC) == 0 ||
3474 				   str_has_pfx(name, RODATA_SEC ".")) {
3475 				sec_desc->sec_type = SEC_RODATA;
3476 				sec_desc->shdr = sh;
3477 				sec_desc->data = data;
3478 			} else if (strcmp(name, STRUCT_OPS_SEC) == 0) {
3479 				obj->efile.st_ops_data = data;
3480 				obj->efile.st_ops_shndx = idx;
3481 			} else {
3482 				pr_info("elf: skipping unrecognized data section(%d) %s\n",
3483 					idx, name);
3484 			}
3485 		} else if (sh->sh_type == SHT_REL) {
3486 			int targ_sec_idx = sh->sh_info; /* points to other section */
3487 
3488 			if (sh->sh_entsize != sizeof(Elf64_Rel) ||
3489 			    targ_sec_idx >= obj->efile.sec_cnt)
3490 				return -LIBBPF_ERRNO__FORMAT;
3491 
3492 			/* Only do relo for section with exec instructions */
3493 			if (!section_have_execinstr(obj, targ_sec_idx) &&
3494 			    strcmp(name, ".rel" STRUCT_OPS_SEC) &&
3495 			    strcmp(name, ".rel" MAPS_ELF_SEC)) {
3496 				pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
3497 					idx, name, targ_sec_idx,
3498 					elf_sec_name(obj, elf_sec_by_idx(obj, targ_sec_idx)) ?: "<?>");
3499 				continue;
3500 			}
3501 
3502 			sec_desc->sec_type = SEC_RELO;
3503 			sec_desc->shdr = sh;
3504 			sec_desc->data = data;
3505 		} else if (sh->sh_type == SHT_NOBITS && strcmp(name, BSS_SEC) == 0) {
3506 			sec_desc->sec_type = SEC_BSS;
3507 			sec_desc->shdr = sh;
3508 			sec_desc->data = data;
3509 		} else {
3510 			pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
3511 				(size_t)sh->sh_size);
3512 		}
3513 	}
3514 
3515 	if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
3516 		pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
3517 		return -LIBBPF_ERRNO__FORMAT;
3518 	}
3519 
3520 	/* sort BPF programs by section name and in-section instruction offset
3521 	 * for faster search */
3522 	if (obj->nr_programs)
3523 		qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
3524 
3525 	return bpf_object__init_btf(obj, btf_data, btf_ext_data);
3526 }
3527 
3528 static bool sym_is_extern(const Elf64_Sym *sym)
3529 {
3530 	int bind = ELF64_ST_BIND(sym->st_info);
3531 	/* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
3532 	return sym->st_shndx == SHN_UNDEF &&
3533 	       (bind == STB_GLOBAL || bind == STB_WEAK) &&
3534 	       ELF64_ST_TYPE(sym->st_info) == STT_NOTYPE;
3535 }
3536 
3537 static bool sym_is_subprog(const Elf64_Sym *sym, int text_shndx)
3538 {
3539 	int bind = ELF64_ST_BIND(sym->st_info);
3540 	int type = ELF64_ST_TYPE(sym->st_info);
3541 
3542 	/* in .text section */
3543 	if (sym->st_shndx != text_shndx)
3544 		return false;
3545 
3546 	/* local function */
3547 	if (bind == STB_LOCAL && type == STT_SECTION)
3548 		return true;
3549 
3550 	/* global function */
3551 	return bind == STB_GLOBAL && type == STT_FUNC;
3552 }
3553 
3554 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
3555 {
3556 	const struct btf_type *t;
3557 	const char *tname;
3558 	int i, n;
3559 
3560 	if (!btf)
3561 		return -ESRCH;
3562 
3563 	n = btf__type_cnt(btf);
3564 	for (i = 1; i < n; i++) {
3565 		t = btf__type_by_id(btf, i);
3566 
3567 		if (!btf_is_var(t) && !btf_is_func(t))
3568 			continue;
3569 
3570 		tname = btf__name_by_offset(btf, t->name_off);
3571 		if (strcmp(tname, ext_name))
3572 			continue;
3573 
3574 		if (btf_is_var(t) &&
3575 		    btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
3576 			return -EINVAL;
3577 
3578 		if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
3579 			return -EINVAL;
3580 
3581 		return i;
3582 	}
3583 
3584 	return -ENOENT;
3585 }
3586 
3587 static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
3588 	const struct btf_var_secinfo *vs;
3589 	const struct btf_type *t;
3590 	int i, j, n;
3591 
3592 	if (!btf)
3593 		return -ESRCH;
3594 
3595 	n = btf__type_cnt(btf);
3596 	for (i = 1; i < n; i++) {
3597 		t = btf__type_by_id(btf, i);
3598 
3599 		if (!btf_is_datasec(t))
3600 			continue;
3601 
3602 		vs = btf_var_secinfos(t);
3603 		for (j = 0; j < btf_vlen(t); j++, vs++) {
3604 			if (vs->type == ext_btf_id)
3605 				return i;
3606 		}
3607 	}
3608 
3609 	return -ENOENT;
3610 }
3611 
3612 static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
3613 				     bool *is_signed)
3614 {
3615 	const struct btf_type *t;
3616 	const char *name;
3617 
3618 	t = skip_mods_and_typedefs(btf, id, NULL);
3619 	name = btf__name_by_offset(btf, t->name_off);
3620 
3621 	if (is_signed)
3622 		*is_signed = false;
3623 	switch (btf_kind(t)) {
3624 	case BTF_KIND_INT: {
3625 		int enc = btf_int_encoding(t);
3626 
3627 		if (enc & BTF_INT_BOOL)
3628 			return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
3629 		if (is_signed)
3630 			*is_signed = enc & BTF_INT_SIGNED;
3631 		if (t->size == 1)
3632 			return KCFG_CHAR;
3633 		if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
3634 			return KCFG_UNKNOWN;
3635 		return KCFG_INT;
3636 	}
3637 	case BTF_KIND_ENUM:
3638 		if (t->size != 4)
3639 			return KCFG_UNKNOWN;
3640 		if (strcmp(name, "libbpf_tristate"))
3641 			return KCFG_UNKNOWN;
3642 		return KCFG_TRISTATE;
3643 	case BTF_KIND_ENUM64:
3644 		if (strcmp(name, "libbpf_tristate"))
3645 			return KCFG_UNKNOWN;
3646 		return KCFG_TRISTATE;
3647 	case BTF_KIND_ARRAY:
3648 		if (btf_array(t)->nelems == 0)
3649 			return KCFG_UNKNOWN;
3650 		if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
3651 			return KCFG_UNKNOWN;
3652 		return KCFG_CHAR_ARR;
3653 	default:
3654 		return KCFG_UNKNOWN;
3655 	}
3656 }
3657 
3658 static int cmp_externs(const void *_a, const void *_b)
3659 {
3660 	const struct extern_desc *a = _a;
3661 	const struct extern_desc *b = _b;
3662 
3663 	if (a->type != b->type)
3664 		return a->type < b->type ? -1 : 1;
3665 
3666 	if (a->type == EXT_KCFG) {
3667 		/* descending order by alignment requirements */
3668 		if (a->kcfg.align != b->kcfg.align)
3669 			return a->kcfg.align > b->kcfg.align ? -1 : 1;
3670 		/* ascending order by size, within same alignment class */
3671 		if (a->kcfg.sz != b->kcfg.sz)
3672 			return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
3673 	}
3674 
3675 	/* resolve ties by name */
3676 	return strcmp(a->name, b->name);
3677 }
3678 
3679 static int find_int_btf_id(const struct btf *btf)
3680 {
3681 	const struct btf_type *t;
3682 	int i, n;
3683 
3684 	n = btf__type_cnt(btf);
3685 	for (i = 1; i < n; i++) {
3686 		t = btf__type_by_id(btf, i);
3687 
3688 		if (btf_is_int(t) && btf_int_bits(t) == 32)
3689 			return i;
3690 	}
3691 
3692 	return 0;
3693 }
3694 
3695 static int add_dummy_ksym_var(struct btf *btf)
3696 {
3697 	int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
3698 	const struct btf_var_secinfo *vs;
3699 	const struct btf_type *sec;
3700 
3701 	if (!btf)
3702 		return 0;
3703 
3704 	sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
3705 					    BTF_KIND_DATASEC);
3706 	if (sec_btf_id < 0)
3707 		return 0;
3708 
3709 	sec = btf__type_by_id(btf, sec_btf_id);
3710 	vs = btf_var_secinfos(sec);
3711 	for (i = 0; i < btf_vlen(sec); i++, vs++) {
3712 		const struct btf_type *vt;
3713 
3714 		vt = btf__type_by_id(btf, vs->type);
3715 		if (btf_is_func(vt))
3716 			break;
3717 	}
3718 
3719 	/* No func in ksyms sec.  No need to add dummy var. */
3720 	if (i == btf_vlen(sec))
3721 		return 0;
3722 
3723 	int_btf_id = find_int_btf_id(btf);
3724 	dummy_var_btf_id = btf__add_var(btf,
3725 					"dummy_ksym",
3726 					BTF_VAR_GLOBAL_ALLOCATED,
3727 					int_btf_id);
3728 	if (dummy_var_btf_id < 0)
3729 		pr_warn("cannot create a dummy_ksym var\n");
3730 
3731 	return dummy_var_btf_id;
3732 }
3733 
3734 static int bpf_object__collect_externs(struct bpf_object *obj)
3735 {
3736 	struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
3737 	const struct btf_type *t;
3738 	struct extern_desc *ext;
3739 	int i, n, off, dummy_var_btf_id;
3740 	const char *ext_name, *sec_name;
3741 	Elf_Scn *scn;
3742 	Elf64_Shdr *sh;
3743 
3744 	if (!obj->efile.symbols)
3745 		return 0;
3746 
3747 	scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
3748 	sh = elf_sec_hdr(obj, scn);
3749 	if (!sh || sh->sh_entsize != sizeof(Elf64_Sym))
3750 		return -LIBBPF_ERRNO__FORMAT;
3751 
3752 	dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
3753 	if (dummy_var_btf_id < 0)
3754 		return dummy_var_btf_id;
3755 
3756 	n = sh->sh_size / sh->sh_entsize;
3757 	pr_debug("looking for externs among %d symbols...\n", n);
3758 
3759 	for (i = 0; i < n; i++) {
3760 		Elf64_Sym *sym = elf_sym_by_idx(obj, i);
3761 
3762 		if (!sym)
3763 			return -LIBBPF_ERRNO__FORMAT;
3764 		if (!sym_is_extern(sym))
3765 			continue;
3766 		ext_name = elf_sym_str(obj, sym->st_name);
3767 		if (!ext_name || !ext_name[0])
3768 			continue;
3769 
3770 		ext = obj->externs;
3771 		ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
3772 		if (!ext)
3773 			return -ENOMEM;
3774 		obj->externs = ext;
3775 		ext = &ext[obj->nr_extern];
3776 		memset(ext, 0, sizeof(*ext));
3777 		obj->nr_extern++;
3778 
3779 		ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
3780 		if (ext->btf_id <= 0) {
3781 			pr_warn("failed to find BTF for extern '%s': %d\n",
3782 				ext_name, ext->btf_id);
3783 			return ext->btf_id;
3784 		}
3785 		t = btf__type_by_id(obj->btf, ext->btf_id);
3786 		ext->name = btf__name_by_offset(obj->btf, t->name_off);
3787 		ext->sym_idx = i;
3788 		ext->is_weak = ELF64_ST_BIND(sym->st_info) == STB_WEAK;
3789 
3790 		ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
3791 		if (ext->sec_btf_id <= 0) {
3792 			pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
3793 				ext_name, ext->btf_id, ext->sec_btf_id);
3794 			return ext->sec_btf_id;
3795 		}
3796 		sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
3797 		sec_name = btf__name_by_offset(obj->btf, sec->name_off);
3798 
3799 		if (strcmp(sec_name, KCONFIG_SEC) == 0) {
3800 			if (btf_is_func(t)) {
3801 				pr_warn("extern function %s is unsupported under %s section\n",
3802 					ext->name, KCONFIG_SEC);
3803 				return -ENOTSUP;
3804 			}
3805 			kcfg_sec = sec;
3806 			ext->type = EXT_KCFG;
3807 			ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
3808 			if (ext->kcfg.sz <= 0) {
3809 				pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
3810 					ext_name, ext->kcfg.sz);
3811 				return ext->kcfg.sz;
3812 			}
3813 			ext->kcfg.align = btf__align_of(obj->btf, t->type);
3814 			if (ext->kcfg.align <= 0) {
3815 				pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
3816 					ext_name, ext->kcfg.align);
3817 				return -EINVAL;
3818 			}
3819 			ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
3820 						        &ext->kcfg.is_signed);
3821 			if (ext->kcfg.type == KCFG_UNKNOWN) {
3822 				pr_warn("extern (kcfg) '%s': type is unsupported\n", ext_name);
3823 				return -ENOTSUP;
3824 			}
3825 		} else if (strcmp(sec_name, KSYMS_SEC) == 0) {
3826 			ksym_sec = sec;
3827 			ext->type = EXT_KSYM;
3828 			skip_mods_and_typedefs(obj->btf, t->type,
3829 					       &ext->ksym.type_id);
3830 		} else {
3831 			pr_warn("unrecognized extern section '%s'\n", sec_name);
3832 			return -ENOTSUP;
3833 		}
3834 	}
3835 	pr_debug("collected %d externs total\n", obj->nr_extern);
3836 
3837 	if (!obj->nr_extern)
3838 		return 0;
3839 
3840 	/* sort externs by type, for kcfg ones also by (align, size, name) */
3841 	qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
3842 
3843 	/* for .ksyms section, we need to turn all externs into allocated
3844 	 * variables in BTF to pass kernel verification; we do this by
3845 	 * pretending that each extern is a 8-byte variable
3846 	 */
3847 	if (ksym_sec) {
3848 		/* find existing 4-byte integer type in BTF to use for fake
3849 		 * extern variables in DATASEC
3850 		 */
3851 		int int_btf_id = find_int_btf_id(obj->btf);
3852 		/* For extern function, a dummy_var added earlier
3853 		 * will be used to replace the vs->type and
3854 		 * its name string will be used to refill
3855 		 * the missing param's name.
3856 		 */
3857 		const struct btf_type *dummy_var;
3858 
3859 		dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
3860 		for (i = 0; i < obj->nr_extern; i++) {
3861 			ext = &obj->externs[i];
3862 			if (ext->type != EXT_KSYM)
3863 				continue;
3864 			pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
3865 				 i, ext->sym_idx, ext->name);
3866 		}
3867 
3868 		sec = ksym_sec;
3869 		n = btf_vlen(sec);
3870 		for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
3871 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3872 			struct btf_type *vt;
3873 
3874 			vt = (void *)btf__type_by_id(obj->btf, vs->type);
3875 			ext_name = btf__name_by_offset(obj->btf, vt->name_off);
3876 			ext = find_extern_by_name(obj, ext_name);
3877 			if (!ext) {
3878 				pr_warn("failed to find extern definition for BTF %s '%s'\n",
3879 					btf_kind_str(vt), ext_name);
3880 				return -ESRCH;
3881 			}
3882 			if (btf_is_func(vt)) {
3883 				const struct btf_type *func_proto;
3884 				struct btf_param *param;
3885 				int j;
3886 
3887 				func_proto = btf__type_by_id(obj->btf,
3888 							     vt->type);
3889 				param = btf_params(func_proto);
3890 				/* Reuse the dummy_var string if the
3891 				 * func proto does not have param name.
3892 				 */
3893 				for (j = 0; j < btf_vlen(func_proto); j++)
3894 					if (param[j].type && !param[j].name_off)
3895 						param[j].name_off =
3896 							dummy_var->name_off;
3897 				vs->type = dummy_var_btf_id;
3898 				vt->info &= ~0xffff;
3899 				vt->info |= BTF_FUNC_GLOBAL;
3900 			} else {
3901 				btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3902 				vt->type = int_btf_id;
3903 			}
3904 			vs->offset = off;
3905 			vs->size = sizeof(int);
3906 		}
3907 		sec->size = off;
3908 	}
3909 
3910 	if (kcfg_sec) {
3911 		sec = kcfg_sec;
3912 		/* for kcfg externs calculate their offsets within a .kconfig map */
3913 		off = 0;
3914 		for (i = 0; i < obj->nr_extern; i++) {
3915 			ext = &obj->externs[i];
3916 			if (ext->type != EXT_KCFG)
3917 				continue;
3918 
3919 			ext->kcfg.data_off = roundup(off, ext->kcfg.align);
3920 			off = ext->kcfg.data_off + ext->kcfg.sz;
3921 			pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
3922 				 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
3923 		}
3924 		sec->size = off;
3925 		n = btf_vlen(sec);
3926 		for (i = 0; i < n; i++) {
3927 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3928 
3929 			t = btf__type_by_id(obj->btf, vs->type);
3930 			ext_name = btf__name_by_offset(obj->btf, t->name_off);
3931 			ext = find_extern_by_name(obj, ext_name);
3932 			if (!ext) {
3933 				pr_warn("failed to find extern definition for BTF var '%s'\n",
3934 					ext_name);
3935 				return -ESRCH;
3936 			}
3937 			btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3938 			vs->offset = ext->kcfg.data_off;
3939 		}
3940 	}
3941 	return 0;
3942 }
3943 
3944 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog)
3945 {
3946 	return prog->sec_idx == obj->efile.text_shndx && obj->nr_programs > 1;
3947 }
3948 
3949 struct bpf_program *
3950 bpf_object__find_program_by_name(const struct bpf_object *obj,
3951 				 const char *name)
3952 {
3953 	struct bpf_program *prog;
3954 
3955 	bpf_object__for_each_program(prog, obj) {
3956 		if (prog_is_subprog(obj, prog))
3957 			continue;
3958 		if (!strcmp(prog->name, name))
3959 			return prog;
3960 	}
3961 	return errno = ENOENT, NULL;
3962 }
3963 
3964 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
3965 				      int shndx)
3966 {
3967 	switch (obj->efile.secs[shndx].sec_type) {
3968 	case SEC_BSS:
3969 	case SEC_DATA:
3970 	case SEC_RODATA:
3971 		return true;
3972 	default:
3973 		return false;
3974 	}
3975 }
3976 
3977 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
3978 				      int shndx)
3979 {
3980 	return shndx == obj->efile.btf_maps_shndx;
3981 }
3982 
3983 static enum libbpf_map_type
3984 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
3985 {
3986 	if (shndx == obj->efile.symbols_shndx)
3987 		return LIBBPF_MAP_KCONFIG;
3988 
3989 	switch (obj->efile.secs[shndx].sec_type) {
3990 	case SEC_BSS:
3991 		return LIBBPF_MAP_BSS;
3992 	case SEC_DATA:
3993 		return LIBBPF_MAP_DATA;
3994 	case SEC_RODATA:
3995 		return LIBBPF_MAP_RODATA;
3996 	default:
3997 		return LIBBPF_MAP_UNSPEC;
3998 	}
3999 }
4000 
4001 static int bpf_program__record_reloc(struct bpf_program *prog,
4002 				     struct reloc_desc *reloc_desc,
4003 				     __u32 insn_idx, const char *sym_name,
4004 				     const Elf64_Sym *sym, const Elf64_Rel *rel)
4005 {
4006 	struct bpf_insn *insn = &prog->insns[insn_idx];
4007 	size_t map_idx, nr_maps = prog->obj->nr_maps;
4008 	struct bpf_object *obj = prog->obj;
4009 	__u32 shdr_idx = sym->st_shndx;
4010 	enum libbpf_map_type type;
4011 	const char *sym_sec_name;
4012 	struct bpf_map *map;
4013 
4014 	if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
4015 		pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n",
4016 			prog->name, sym_name, insn_idx, insn->code);
4017 		return -LIBBPF_ERRNO__RELOC;
4018 	}
4019 
4020 	if (sym_is_extern(sym)) {
4021 		int sym_idx = ELF64_R_SYM(rel->r_info);
4022 		int i, n = obj->nr_extern;
4023 		struct extern_desc *ext;
4024 
4025 		for (i = 0; i < n; i++) {
4026 			ext = &obj->externs[i];
4027 			if (ext->sym_idx == sym_idx)
4028 				break;
4029 		}
4030 		if (i >= n) {
4031 			pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
4032 				prog->name, sym_name, sym_idx);
4033 			return -LIBBPF_ERRNO__RELOC;
4034 		}
4035 		pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
4036 			 prog->name, i, ext->name, ext->sym_idx, insn_idx);
4037 		if (insn->code == (BPF_JMP | BPF_CALL))
4038 			reloc_desc->type = RELO_EXTERN_FUNC;
4039 		else
4040 			reloc_desc->type = RELO_EXTERN_VAR;
4041 		reloc_desc->insn_idx = insn_idx;
4042 		reloc_desc->sym_off = i; /* sym_off stores extern index */
4043 		return 0;
4044 	}
4045 
4046 	/* sub-program call relocation */
4047 	if (is_call_insn(insn)) {
4048 		if (insn->src_reg != BPF_PSEUDO_CALL) {
4049 			pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
4050 			return -LIBBPF_ERRNO__RELOC;
4051 		}
4052 		/* text_shndx can be 0, if no default "main" program exists */
4053 		if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
4054 			sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4055 			pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
4056 				prog->name, sym_name, sym_sec_name);
4057 			return -LIBBPF_ERRNO__RELOC;
4058 		}
4059 		if (sym->st_value % BPF_INSN_SZ) {
4060 			pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
4061 				prog->name, sym_name, (size_t)sym->st_value);
4062 			return -LIBBPF_ERRNO__RELOC;
4063 		}
4064 		reloc_desc->type = RELO_CALL;
4065 		reloc_desc->insn_idx = insn_idx;
4066 		reloc_desc->sym_off = sym->st_value;
4067 		return 0;
4068 	}
4069 
4070 	if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
4071 		pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
4072 			prog->name, sym_name, shdr_idx);
4073 		return -LIBBPF_ERRNO__RELOC;
4074 	}
4075 
4076 	/* loading subprog addresses */
4077 	if (sym_is_subprog(sym, obj->efile.text_shndx)) {
4078 		/* global_func: sym->st_value = offset in the section, insn->imm = 0.
4079 		 * local_func: sym->st_value = 0, insn->imm = offset in the section.
4080 		 */
4081 		if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
4082 			pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
4083 				prog->name, sym_name, (size_t)sym->st_value, insn->imm);
4084 			return -LIBBPF_ERRNO__RELOC;
4085 		}
4086 
4087 		reloc_desc->type = RELO_SUBPROG_ADDR;
4088 		reloc_desc->insn_idx = insn_idx;
4089 		reloc_desc->sym_off = sym->st_value;
4090 		return 0;
4091 	}
4092 
4093 	type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
4094 	sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4095 
4096 	/* generic map reference relocation */
4097 	if (type == LIBBPF_MAP_UNSPEC) {
4098 		if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
4099 			pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
4100 				prog->name, sym_name, sym_sec_name);
4101 			return -LIBBPF_ERRNO__RELOC;
4102 		}
4103 		for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4104 			map = &obj->maps[map_idx];
4105 			if (map->libbpf_type != type ||
4106 			    map->sec_idx != sym->st_shndx ||
4107 			    map->sec_offset != sym->st_value)
4108 				continue;
4109 			pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n",
4110 				 prog->name, map_idx, map->name, map->sec_idx,
4111 				 map->sec_offset, insn_idx);
4112 			break;
4113 		}
4114 		if (map_idx >= nr_maps) {
4115 			pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
4116 				prog->name, sym_sec_name, (size_t)sym->st_value);
4117 			return -LIBBPF_ERRNO__RELOC;
4118 		}
4119 		reloc_desc->type = RELO_LD64;
4120 		reloc_desc->insn_idx = insn_idx;
4121 		reloc_desc->map_idx = map_idx;
4122 		reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
4123 		return 0;
4124 	}
4125 
4126 	/* global data map relocation */
4127 	if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
4128 		pr_warn("prog '%s': bad data relo against section '%s'\n",
4129 			prog->name, sym_sec_name);
4130 		return -LIBBPF_ERRNO__RELOC;
4131 	}
4132 	for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4133 		map = &obj->maps[map_idx];
4134 		if (map->libbpf_type != type || map->sec_idx != sym->st_shndx)
4135 			continue;
4136 		pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n",
4137 			 prog->name, map_idx, map->name, map->sec_idx,
4138 			 map->sec_offset, insn_idx);
4139 		break;
4140 	}
4141 	if (map_idx >= nr_maps) {
4142 		pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
4143 			prog->name, sym_sec_name);
4144 		return -LIBBPF_ERRNO__RELOC;
4145 	}
4146 
4147 	reloc_desc->type = RELO_DATA;
4148 	reloc_desc->insn_idx = insn_idx;
4149 	reloc_desc->map_idx = map_idx;
4150 	reloc_desc->sym_off = sym->st_value;
4151 	return 0;
4152 }
4153 
4154 static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
4155 {
4156 	return insn_idx >= prog->sec_insn_off &&
4157 	       insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
4158 }
4159 
4160 static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
4161 						 size_t sec_idx, size_t insn_idx)
4162 {
4163 	int l = 0, r = obj->nr_programs - 1, m;
4164 	struct bpf_program *prog;
4165 
4166 	if (!obj->nr_programs)
4167 		return NULL;
4168 
4169 	while (l < r) {
4170 		m = l + (r - l + 1) / 2;
4171 		prog = &obj->programs[m];
4172 
4173 		if (prog->sec_idx < sec_idx ||
4174 		    (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
4175 			l = m;
4176 		else
4177 			r = m - 1;
4178 	}
4179 	/* matching program could be at index l, but it still might be the
4180 	 * wrong one, so we need to double check conditions for the last time
4181 	 */
4182 	prog = &obj->programs[l];
4183 	if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
4184 		return prog;
4185 	return NULL;
4186 }
4187 
4188 static int
4189 bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
4190 {
4191 	const char *relo_sec_name, *sec_name;
4192 	size_t sec_idx = shdr->sh_info, sym_idx;
4193 	struct bpf_program *prog;
4194 	struct reloc_desc *relos;
4195 	int err, i, nrels;
4196 	const char *sym_name;
4197 	__u32 insn_idx;
4198 	Elf_Scn *scn;
4199 	Elf_Data *scn_data;
4200 	Elf64_Sym *sym;
4201 	Elf64_Rel *rel;
4202 
4203 	if (sec_idx >= obj->efile.sec_cnt)
4204 		return -EINVAL;
4205 
4206 	scn = elf_sec_by_idx(obj, sec_idx);
4207 	scn_data = elf_sec_data(obj, scn);
4208 
4209 	relo_sec_name = elf_sec_str(obj, shdr->sh_name);
4210 	sec_name = elf_sec_name(obj, scn);
4211 	if (!relo_sec_name || !sec_name)
4212 		return -EINVAL;
4213 
4214 	pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
4215 		 relo_sec_name, sec_idx, sec_name);
4216 	nrels = shdr->sh_size / shdr->sh_entsize;
4217 
4218 	for (i = 0; i < nrels; i++) {
4219 		rel = elf_rel_by_idx(data, i);
4220 		if (!rel) {
4221 			pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
4222 			return -LIBBPF_ERRNO__FORMAT;
4223 		}
4224 
4225 		sym_idx = ELF64_R_SYM(rel->r_info);
4226 		sym = elf_sym_by_idx(obj, sym_idx);
4227 		if (!sym) {
4228 			pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
4229 				relo_sec_name, sym_idx, i);
4230 			return -LIBBPF_ERRNO__FORMAT;
4231 		}
4232 
4233 		if (sym->st_shndx >= obj->efile.sec_cnt) {
4234 			pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
4235 				relo_sec_name, sym_idx, (size_t)sym->st_shndx, i);
4236 			return -LIBBPF_ERRNO__FORMAT;
4237 		}
4238 
4239 		if (rel->r_offset % BPF_INSN_SZ || rel->r_offset >= scn_data->d_size) {
4240 			pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
4241 				relo_sec_name, (size_t)rel->r_offset, i);
4242 			return -LIBBPF_ERRNO__FORMAT;
4243 		}
4244 
4245 		insn_idx = rel->r_offset / BPF_INSN_SZ;
4246 		/* relocations against static functions are recorded as
4247 		 * relocations against the section that contains a function;
4248 		 * in such case, symbol will be STT_SECTION and sym.st_name
4249 		 * will point to empty string (0), so fetch section name
4250 		 * instead
4251 		 */
4252 		if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
4253 			sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx));
4254 		else
4255 			sym_name = elf_sym_str(obj, sym->st_name);
4256 		sym_name = sym_name ?: "<?";
4257 
4258 		pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
4259 			 relo_sec_name, i, insn_idx, sym_name);
4260 
4261 		prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
4262 		if (!prog) {
4263 			pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
4264 				relo_sec_name, i, sec_name, insn_idx);
4265 			continue;
4266 		}
4267 
4268 		relos = libbpf_reallocarray(prog->reloc_desc,
4269 					    prog->nr_reloc + 1, sizeof(*relos));
4270 		if (!relos)
4271 			return -ENOMEM;
4272 		prog->reloc_desc = relos;
4273 
4274 		/* adjust insn_idx to local BPF program frame of reference */
4275 		insn_idx -= prog->sec_insn_off;
4276 		err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
4277 						insn_idx, sym_name, sym, rel);
4278 		if (err)
4279 			return err;
4280 
4281 		prog->nr_reloc++;
4282 	}
4283 	return 0;
4284 }
4285 
4286 static int map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map)
4287 {
4288 	int id;
4289 
4290 	if (!obj->btf)
4291 		return -ENOENT;
4292 
4293 	/* if it's BTF-defined map, we don't need to search for type IDs.
4294 	 * For struct_ops map, it does not need btf_key_type_id and
4295 	 * btf_value_type_id.
4296 	 */
4297 	if (map->sec_idx == obj->efile.btf_maps_shndx || bpf_map__is_struct_ops(map))
4298 		return 0;
4299 
4300 	/*
4301 	 * LLVM annotates global data differently in BTF, that is,
4302 	 * only as '.data', '.bss' or '.rodata'.
4303 	 */
4304 	if (!bpf_map__is_internal(map))
4305 		return -ENOENT;
4306 
4307 	id = btf__find_by_name(obj->btf, map->real_name);
4308 	if (id < 0)
4309 		return id;
4310 
4311 	map->btf_key_type_id = 0;
4312 	map->btf_value_type_id = id;
4313 	return 0;
4314 }
4315 
4316 static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
4317 {
4318 	char file[PATH_MAX], buff[4096];
4319 	FILE *fp;
4320 	__u32 val;
4321 	int err;
4322 
4323 	snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
4324 	memset(info, 0, sizeof(*info));
4325 
4326 	fp = fopen(file, "r");
4327 	if (!fp) {
4328 		err = -errno;
4329 		pr_warn("failed to open %s: %d. No procfs support?\n", file,
4330 			err);
4331 		return err;
4332 	}
4333 
4334 	while (fgets(buff, sizeof(buff), fp)) {
4335 		if (sscanf(buff, "map_type:\t%u", &val) == 1)
4336 			info->type = val;
4337 		else if (sscanf(buff, "key_size:\t%u", &val) == 1)
4338 			info->key_size = val;
4339 		else if (sscanf(buff, "value_size:\t%u", &val) == 1)
4340 			info->value_size = val;
4341 		else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
4342 			info->max_entries = val;
4343 		else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
4344 			info->map_flags = val;
4345 	}
4346 
4347 	fclose(fp);
4348 
4349 	return 0;
4350 }
4351 
4352 bool bpf_map__autocreate(const struct bpf_map *map)
4353 {
4354 	return map->autocreate;
4355 }
4356 
4357 int bpf_map__set_autocreate(struct bpf_map *map, bool autocreate)
4358 {
4359 	if (map->obj->loaded)
4360 		return libbpf_err(-EBUSY);
4361 
4362 	map->autocreate = autocreate;
4363 	return 0;
4364 }
4365 
4366 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
4367 {
4368 	struct bpf_map_info info;
4369 	__u32 len = sizeof(info), name_len;
4370 	int new_fd, err;
4371 	char *new_name;
4372 
4373 	memset(&info, 0, len);
4374 	err = bpf_obj_get_info_by_fd(fd, &info, &len);
4375 	if (err && errno == EINVAL)
4376 		err = bpf_get_map_info_from_fdinfo(fd, &info);
4377 	if (err)
4378 		return libbpf_err(err);
4379 
4380 	name_len = strlen(info.name);
4381 	if (name_len == BPF_OBJ_NAME_LEN - 1 && strncmp(map->name, info.name, name_len) == 0)
4382 		new_name = strdup(map->name);
4383 	else
4384 		new_name = strdup(info.name);
4385 
4386 	if (!new_name)
4387 		return libbpf_err(-errno);
4388 
4389 	new_fd = open("/", O_RDONLY | O_CLOEXEC);
4390 	if (new_fd < 0) {
4391 		err = -errno;
4392 		goto err_free_new_name;
4393 	}
4394 
4395 	new_fd = dup3(fd, new_fd, O_CLOEXEC);
4396 	if (new_fd < 0) {
4397 		err = -errno;
4398 		goto err_close_new_fd;
4399 	}
4400 
4401 	err = zclose(map->fd);
4402 	if (err) {
4403 		err = -errno;
4404 		goto err_close_new_fd;
4405 	}
4406 	free(map->name);
4407 
4408 	map->fd = new_fd;
4409 	map->name = new_name;
4410 	map->def.type = info.type;
4411 	map->def.key_size = info.key_size;
4412 	map->def.value_size = info.value_size;
4413 	map->def.max_entries = info.max_entries;
4414 	map->def.map_flags = info.map_flags;
4415 	map->btf_key_type_id = info.btf_key_type_id;
4416 	map->btf_value_type_id = info.btf_value_type_id;
4417 	map->reused = true;
4418 	map->map_extra = info.map_extra;
4419 
4420 	return 0;
4421 
4422 err_close_new_fd:
4423 	close(new_fd);
4424 err_free_new_name:
4425 	free(new_name);
4426 	return libbpf_err(err);
4427 }
4428 
4429 __u32 bpf_map__max_entries(const struct bpf_map *map)
4430 {
4431 	return map->def.max_entries;
4432 }
4433 
4434 struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
4435 {
4436 	if (!bpf_map_type__is_map_in_map(map->def.type))
4437 		return errno = EINVAL, NULL;
4438 
4439 	return map->inner_map;
4440 }
4441 
4442 int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
4443 {
4444 	if (map->obj->loaded)
4445 		return libbpf_err(-EBUSY);
4446 
4447 	map->def.max_entries = max_entries;
4448 
4449 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
4450 	if (map_is_ringbuf(map))
4451 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
4452 
4453 	return 0;
4454 }
4455 
4456 static int
4457 bpf_object__probe_loading(struct bpf_object *obj)
4458 {
4459 	char *cp, errmsg[STRERR_BUFSIZE];
4460 	struct bpf_insn insns[] = {
4461 		BPF_MOV64_IMM(BPF_REG_0, 0),
4462 		BPF_EXIT_INSN(),
4463 	};
4464 	int ret, insn_cnt = ARRAY_SIZE(insns);
4465 
4466 	if (obj->gen_loader)
4467 		return 0;
4468 
4469 	ret = bump_rlimit_memlock();
4470 	if (ret)
4471 		pr_warn("Failed to bump RLIMIT_MEMLOCK (err = %d), you might need to do it explicitly!\n", ret);
4472 
4473 	/* make sure basic loading works */
4474 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4475 	if (ret < 0)
4476 		ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
4477 	if (ret < 0) {
4478 		ret = errno;
4479 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4480 		pr_warn("Error in %s():%s(%d). Couldn't load trivial BPF "
4481 			"program. Make sure your kernel supports BPF "
4482 			"(CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is "
4483 			"set to big enough value.\n", __func__, cp, ret);
4484 		return -ret;
4485 	}
4486 	close(ret);
4487 
4488 	return 0;
4489 }
4490 
4491 static int probe_fd(int fd)
4492 {
4493 	if (fd >= 0)
4494 		close(fd);
4495 	return fd >= 0;
4496 }
4497 
4498 static int probe_kern_prog_name(void)
4499 {
4500 	const size_t attr_sz = offsetofend(union bpf_attr, prog_name);
4501 	struct bpf_insn insns[] = {
4502 		BPF_MOV64_IMM(BPF_REG_0, 0),
4503 		BPF_EXIT_INSN(),
4504 	};
4505 	union bpf_attr attr;
4506 	int ret;
4507 
4508 	memset(&attr, 0, attr_sz);
4509 	attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
4510 	attr.license = ptr_to_u64("GPL");
4511 	attr.insns = ptr_to_u64(insns);
4512 	attr.insn_cnt = (__u32)ARRAY_SIZE(insns);
4513 	libbpf_strlcpy(attr.prog_name, "libbpf_nametest", sizeof(attr.prog_name));
4514 
4515 	/* make sure loading with name works */
4516 	ret = sys_bpf_prog_load(&attr, attr_sz, PROG_LOAD_ATTEMPTS);
4517 	return probe_fd(ret);
4518 }
4519 
4520 static int probe_kern_global_data(void)
4521 {
4522 	char *cp, errmsg[STRERR_BUFSIZE];
4523 	struct bpf_insn insns[] = {
4524 		BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
4525 		BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
4526 		BPF_MOV64_IMM(BPF_REG_0, 0),
4527 		BPF_EXIT_INSN(),
4528 	};
4529 	int ret, map, insn_cnt = ARRAY_SIZE(insns);
4530 
4531 	map = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_global", sizeof(int), 32, 1, NULL);
4532 	if (map < 0) {
4533 		ret = -errno;
4534 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4535 		pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4536 			__func__, cp, -ret);
4537 		return ret;
4538 	}
4539 
4540 	insns[0].imm = map;
4541 
4542 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4543 	close(map);
4544 	return probe_fd(ret);
4545 }
4546 
4547 static int probe_kern_btf(void)
4548 {
4549 	static const char strs[] = "\0int";
4550 	__u32 types[] = {
4551 		/* int */
4552 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4553 	};
4554 
4555 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4556 					     strs, sizeof(strs)));
4557 }
4558 
4559 static int probe_kern_btf_func(void)
4560 {
4561 	static const char strs[] = "\0int\0x\0a";
4562 	/* void x(int a) {} */
4563 	__u32 types[] = {
4564 		/* int */
4565 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4566 		/* FUNC_PROTO */                                /* [2] */
4567 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4568 		BTF_PARAM_ENC(7, 1),
4569 		/* FUNC x */                                    /* [3] */
4570 		BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
4571 	};
4572 
4573 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4574 					     strs, sizeof(strs)));
4575 }
4576 
4577 static int probe_kern_btf_func_global(void)
4578 {
4579 	static const char strs[] = "\0int\0x\0a";
4580 	/* static void x(int a) {} */
4581 	__u32 types[] = {
4582 		/* int */
4583 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4584 		/* FUNC_PROTO */                                /* [2] */
4585 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4586 		BTF_PARAM_ENC(7, 1),
4587 		/* FUNC x BTF_FUNC_GLOBAL */                    /* [3] */
4588 		BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, BTF_FUNC_GLOBAL), 2),
4589 	};
4590 
4591 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4592 					     strs, sizeof(strs)));
4593 }
4594 
4595 static int probe_kern_btf_datasec(void)
4596 {
4597 	static const char strs[] = "\0x\0.data";
4598 	/* static int a; */
4599 	__u32 types[] = {
4600 		/* int */
4601 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4602 		/* VAR x */                                     /* [2] */
4603 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4604 		BTF_VAR_STATIC,
4605 		/* DATASEC val */                               /* [3] */
4606 		BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
4607 		BTF_VAR_SECINFO_ENC(2, 0, 4),
4608 	};
4609 
4610 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4611 					     strs, sizeof(strs)));
4612 }
4613 
4614 static int probe_kern_btf_float(void)
4615 {
4616 	static const char strs[] = "\0float";
4617 	__u32 types[] = {
4618 		/* float */
4619 		BTF_TYPE_FLOAT_ENC(1, 4),
4620 	};
4621 
4622 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4623 					     strs, sizeof(strs)));
4624 }
4625 
4626 static int probe_kern_btf_decl_tag(void)
4627 {
4628 	static const char strs[] = "\0tag";
4629 	__u32 types[] = {
4630 		/* int */
4631 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4632 		/* VAR x */                                     /* [2] */
4633 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4634 		BTF_VAR_STATIC,
4635 		/* attr */
4636 		BTF_TYPE_DECL_TAG_ENC(1, 2, -1),
4637 	};
4638 
4639 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4640 					     strs, sizeof(strs)));
4641 }
4642 
4643 static int probe_kern_btf_type_tag(void)
4644 {
4645 	static const char strs[] = "\0tag";
4646 	__u32 types[] = {
4647 		/* int */
4648 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),		/* [1] */
4649 		/* attr */
4650 		BTF_TYPE_TYPE_TAG_ENC(1, 1),				/* [2] */
4651 		/* ptr */
4652 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_PTR, 0, 0), 2),	/* [3] */
4653 	};
4654 
4655 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4656 					     strs, sizeof(strs)));
4657 }
4658 
4659 static int probe_kern_array_mmap(void)
4660 {
4661 	LIBBPF_OPTS(bpf_map_create_opts, opts, .map_flags = BPF_F_MMAPABLE);
4662 	int fd;
4663 
4664 	fd = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_mmap", sizeof(int), sizeof(int), 1, &opts);
4665 	return probe_fd(fd);
4666 }
4667 
4668 static int probe_kern_exp_attach_type(void)
4669 {
4670 	LIBBPF_OPTS(bpf_prog_load_opts, opts, .expected_attach_type = BPF_CGROUP_INET_SOCK_CREATE);
4671 	struct bpf_insn insns[] = {
4672 		BPF_MOV64_IMM(BPF_REG_0, 0),
4673 		BPF_EXIT_INSN(),
4674 	};
4675 	int fd, insn_cnt = ARRAY_SIZE(insns);
4676 
4677 	/* use any valid combination of program type and (optional)
4678 	 * non-zero expected attach type (i.e., not a BPF_CGROUP_INET_INGRESS)
4679 	 * to see if kernel supports expected_attach_type field for
4680 	 * BPF_PROG_LOAD command
4681 	 */
4682 	fd = bpf_prog_load(BPF_PROG_TYPE_CGROUP_SOCK, NULL, "GPL", insns, insn_cnt, &opts);
4683 	return probe_fd(fd);
4684 }
4685 
4686 static int probe_kern_probe_read_kernel(void)
4687 {
4688 	struct bpf_insn insns[] = {
4689 		BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),	/* r1 = r10 (fp) */
4690 		BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -8),	/* r1 += -8 */
4691 		BPF_MOV64_IMM(BPF_REG_2, 8),		/* r2 = 8 */
4692 		BPF_MOV64_IMM(BPF_REG_3, 0),		/* r3 = 0 */
4693 		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_probe_read_kernel),
4694 		BPF_EXIT_INSN(),
4695 	};
4696 	int fd, insn_cnt = ARRAY_SIZE(insns);
4697 
4698 	fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
4699 	return probe_fd(fd);
4700 }
4701 
4702 static int probe_prog_bind_map(void)
4703 {
4704 	char *cp, errmsg[STRERR_BUFSIZE];
4705 	struct bpf_insn insns[] = {
4706 		BPF_MOV64_IMM(BPF_REG_0, 0),
4707 		BPF_EXIT_INSN(),
4708 	};
4709 	int ret, map, prog, insn_cnt = ARRAY_SIZE(insns);
4710 
4711 	map = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_det_bind", sizeof(int), 32, 1, NULL);
4712 	if (map < 0) {
4713 		ret = -errno;
4714 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4715 		pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4716 			__func__, cp, -ret);
4717 		return ret;
4718 	}
4719 
4720 	prog = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4721 	if (prog < 0) {
4722 		close(map);
4723 		return 0;
4724 	}
4725 
4726 	ret = bpf_prog_bind_map(prog, map, NULL);
4727 
4728 	close(map);
4729 	close(prog);
4730 
4731 	return ret >= 0;
4732 }
4733 
4734 static int probe_module_btf(void)
4735 {
4736 	static const char strs[] = "\0int";
4737 	__u32 types[] = {
4738 		/* int */
4739 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4740 	};
4741 	struct bpf_btf_info info;
4742 	__u32 len = sizeof(info);
4743 	char name[16];
4744 	int fd, err;
4745 
4746 	fd = libbpf__load_raw_btf((char *)types, sizeof(types), strs, sizeof(strs));
4747 	if (fd < 0)
4748 		return 0; /* BTF not supported at all */
4749 
4750 	memset(&info, 0, sizeof(info));
4751 	info.name = ptr_to_u64(name);
4752 	info.name_len = sizeof(name);
4753 
4754 	/* check that BPF_OBJ_GET_INFO_BY_FD supports specifying name pointer;
4755 	 * kernel's module BTF support coincides with support for
4756 	 * name/name_len fields in struct bpf_btf_info.
4757 	 */
4758 	err = bpf_obj_get_info_by_fd(fd, &info, &len);
4759 	close(fd);
4760 	return !err;
4761 }
4762 
4763 static int probe_perf_link(void)
4764 {
4765 	struct bpf_insn insns[] = {
4766 		BPF_MOV64_IMM(BPF_REG_0, 0),
4767 		BPF_EXIT_INSN(),
4768 	};
4769 	int prog_fd, link_fd, err;
4770 
4771 	prog_fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL",
4772 				insns, ARRAY_SIZE(insns), NULL);
4773 	if (prog_fd < 0)
4774 		return -errno;
4775 
4776 	/* use invalid perf_event FD to get EBADF, if link is supported;
4777 	 * otherwise EINVAL should be returned
4778 	 */
4779 	link_fd = bpf_link_create(prog_fd, -1, BPF_PERF_EVENT, NULL);
4780 	err = -errno; /* close() can clobber errno */
4781 
4782 	if (link_fd >= 0)
4783 		close(link_fd);
4784 	close(prog_fd);
4785 
4786 	return link_fd < 0 && err == -EBADF;
4787 }
4788 
4789 static int probe_kern_bpf_cookie(void)
4790 {
4791 	struct bpf_insn insns[] = {
4792 		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_get_attach_cookie),
4793 		BPF_EXIT_INSN(),
4794 	};
4795 	int ret, insn_cnt = ARRAY_SIZE(insns);
4796 
4797 	ret = bpf_prog_load(BPF_PROG_TYPE_KPROBE, NULL, "GPL", insns, insn_cnt, NULL);
4798 	return probe_fd(ret);
4799 }
4800 
4801 static int probe_kern_btf_enum64(void)
4802 {
4803 	static const char strs[] = "\0enum64";
4804 	__u32 types[] = {
4805 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_ENUM64, 0, 0), 8),
4806 	};
4807 
4808 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4809 					     strs, sizeof(strs)));
4810 }
4811 
4812 static int probe_kern_syscall_wrapper(void);
4813 
4814 enum kern_feature_result {
4815 	FEAT_UNKNOWN = 0,
4816 	FEAT_SUPPORTED = 1,
4817 	FEAT_MISSING = 2,
4818 };
4819 
4820 typedef int (*feature_probe_fn)(void);
4821 
4822 static struct kern_feature_desc {
4823 	const char *desc;
4824 	feature_probe_fn probe;
4825 	enum kern_feature_result res;
4826 } feature_probes[__FEAT_CNT] = {
4827 	[FEAT_PROG_NAME] = {
4828 		"BPF program name", probe_kern_prog_name,
4829 	},
4830 	[FEAT_GLOBAL_DATA] = {
4831 		"global variables", probe_kern_global_data,
4832 	},
4833 	[FEAT_BTF] = {
4834 		"minimal BTF", probe_kern_btf,
4835 	},
4836 	[FEAT_BTF_FUNC] = {
4837 		"BTF functions", probe_kern_btf_func,
4838 	},
4839 	[FEAT_BTF_GLOBAL_FUNC] = {
4840 		"BTF global function", probe_kern_btf_func_global,
4841 	},
4842 	[FEAT_BTF_DATASEC] = {
4843 		"BTF data section and variable", probe_kern_btf_datasec,
4844 	},
4845 	[FEAT_ARRAY_MMAP] = {
4846 		"ARRAY map mmap()", probe_kern_array_mmap,
4847 	},
4848 	[FEAT_EXP_ATTACH_TYPE] = {
4849 		"BPF_PROG_LOAD expected_attach_type attribute",
4850 		probe_kern_exp_attach_type,
4851 	},
4852 	[FEAT_PROBE_READ_KERN] = {
4853 		"bpf_probe_read_kernel() helper", probe_kern_probe_read_kernel,
4854 	},
4855 	[FEAT_PROG_BIND_MAP] = {
4856 		"BPF_PROG_BIND_MAP support", probe_prog_bind_map,
4857 	},
4858 	[FEAT_MODULE_BTF] = {
4859 		"module BTF support", probe_module_btf,
4860 	},
4861 	[FEAT_BTF_FLOAT] = {
4862 		"BTF_KIND_FLOAT support", probe_kern_btf_float,
4863 	},
4864 	[FEAT_PERF_LINK] = {
4865 		"BPF perf link support", probe_perf_link,
4866 	},
4867 	[FEAT_BTF_DECL_TAG] = {
4868 		"BTF_KIND_DECL_TAG support", probe_kern_btf_decl_tag,
4869 	},
4870 	[FEAT_BTF_TYPE_TAG] = {
4871 		"BTF_KIND_TYPE_TAG support", probe_kern_btf_type_tag,
4872 	},
4873 	[FEAT_MEMCG_ACCOUNT] = {
4874 		"memcg-based memory accounting", probe_memcg_account,
4875 	},
4876 	[FEAT_BPF_COOKIE] = {
4877 		"BPF cookie support", probe_kern_bpf_cookie,
4878 	},
4879 	[FEAT_BTF_ENUM64] = {
4880 		"BTF_KIND_ENUM64 support", probe_kern_btf_enum64,
4881 	},
4882 	[FEAT_SYSCALL_WRAPPER] = {
4883 		"Kernel using syscall wrapper", probe_kern_syscall_wrapper,
4884 	},
4885 };
4886 
4887 bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
4888 {
4889 	struct kern_feature_desc *feat = &feature_probes[feat_id];
4890 	int ret;
4891 
4892 	if (obj && obj->gen_loader)
4893 		/* To generate loader program assume the latest kernel
4894 		 * to avoid doing extra prog_load, map_create syscalls.
4895 		 */
4896 		return true;
4897 
4898 	if (READ_ONCE(feat->res) == FEAT_UNKNOWN) {
4899 		ret = feat->probe();
4900 		if (ret > 0) {
4901 			WRITE_ONCE(feat->res, FEAT_SUPPORTED);
4902 		} else if (ret == 0) {
4903 			WRITE_ONCE(feat->res, FEAT_MISSING);
4904 		} else {
4905 			pr_warn("Detection of kernel %s support failed: %d\n", feat->desc, ret);
4906 			WRITE_ONCE(feat->res, FEAT_MISSING);
4907 		}
4908 	}
4909 
4910 	return READ_ONCE(feat->res) == FEAT_SUPPORTED;
4911 }
4912 
4913 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
4914 {
4915 	struct bpf_map_info map_info;
4916 	char msg[STRERR_BUFSIZE];
4917 	__u32 map_info_len = sizeof(map_info);
4918 	int err;
4919 
4920 	memset(&map_info, 0, map_info_len);
4921 	err = bpf_obj_get_info_by_fd(map_fd, &map_info, &map_info_len);
4922 	if (err && errno == EINVAL)
4923 		err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
4924 	if (err) {
4925 		pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
4926 			libbpf_strerror_r(errno, msg, sizeof(msg)));
4927 		return false;
4928 	}
4929 
4930 	return (map_info.type == map->def.type &&
4931 		map_info.key_size == map->def.key_size &&
4932 		map_info.value_size == map->def.value_size &&
4933 		map_info.max_entries == map->def.max_entries &&
4934 		map_info.map_flags == map->def.map_flags &&
4935 		map_info.map_extra == map->map_extra);
4936 }
4937 
4938 static int
4939 bpf_object__reuse_map(struct bpf_map *map)
4940 {
4941 	char *cp, errmsg[STRERR_BUFSIZE];
4942 	int err, pin_fd;
4943 
4944 	pin_fd = bpf_obj_get(map->pin_path);
4945 	if (pin_fd < 0) {
4946 		err = -errno;
4947 		if (err == -ENOENT) {
4948 			pr_debug("found no pinned map to reuse at '%s'\n",
4949 				 map->pin_path);
4950 			return 0;
4951 		}
4952 
4953 		cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
4954 		pr_warn("couldn't retrieve pinned map '%s': %s\n",
4955 			map->pin_path, cp);
4956 		return err;
4957 	}
4958 
4959 	if (!map_is_reuse_compat(map, pin_fd)) {
4960 		pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
4961 			map->pin_path);
4962 		close(pin_fd);
4963 		return -EINVAL;
4964 	}
4965 
4966 	err = bpf_map__reuse_fd(map, pin_fd);
4967 	close(pin_fd);
4968 	if (err) {
4969 		return err;
4970 	}
4971 	map->pinned = true;
4972 	pr_debug("reused pinned map at '%s'\n", map->pin_path);
4973 
4974 	return 0;
4975 }
4976 
4977 static int
4978 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
4979 {
4980 	enum libbpf_map_type map_type = map->libbpf_type;
4981 	char *cp, errmsg[STRERR_BUFSIZE];
4982 	int err, zero = 0;
4983 
4984 	if (obj->gen_loader) {
4985 		bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
4986 					 map->mmaped, map->def.value_size);
4987 		if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
4988 			bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
4989 		return 0;
4990 	}
4991 	err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
4992 	if (err) {
4993 		err = -errno;
4994 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
4995 		pr_warn("Error setting initial map(%s) contents: %s\n",
4996 			map->name, cp);
4997 		return err;
4998 	}
4999 
5000 	/* Freeze .rodata and .kconfig map as read-only from syscall side. */
5001 	if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
5002 		err = bpf_map_freeze(map->fd);
5003 		if (err) {
5004 			err = -errno;
5005 			cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5006 			pr_warn("Error freezing map(%s) as read-only: %s\n",
5007 				map->name, cp);
5008 			return err;
5009 		}
5010 	}
5011 	return 0;
5012 }
5013 
5014 static void bpf_map__destroy(struct bpf_map *map);
5015 
5016 static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
5017 {
5018 	LIBBPF_OPTS(bpf_map_create_opts, create_attr);
5019 	struct bpf_map_def *def = &map->def;
5020 	const char *map_name = NULL;
5021 	int err = 0;
5022 
5023 	if (kernel_supports(obj, FEAT_PROG_NAME))
5024 		map_name = map->name;
5025 	create_attr.map_ifindex = map->map_ifindex;
5026 	create_attr.map_flags = def->map_flags;
5027 	create_attr.numa_node = map->numa_node;
5028 	create_attr.map_extra = map->map_extra;
5029 
5030 	if (bpf_map__is_struct_ops(map))
5031 		create_attr.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
5032 
5033 	if (obj->btf && btf__fd(obj->btf) >= 0) {
5034 		create_attr.btf_fd = btf__fd(obj->btf);
5035 		create_attr.btf_key_type_id = map->btf_key_type_id;
5036 		create_attr.btf_value_type_id = map->btf_value_type_id;
5037 	}
5038 
5039 	if (bpf_map_type__is_map_in_map(def->type)) {
5040 		if (map->inner_map) {
5041 			err = bpf_object__create_map(obj, map->inner_map, true);
5042 			if (err) {
5043 				pr_warn("map '%s': failed to create inner map: %d\n",
5044 					map->name, err);
5045 				return err;
5046 			}
5047 			map->inner_map_fd = bpf_map__fd(map->inner_map);
5048 		}
5049 		if (map->inner_map_fd >= 0)
5050 			create_attr.inner_map_fd = map->inner_map_fd;
5051 	}
5052 
5053 	switch (def->type) {
5054 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5055 	case BPF_MAP_TYPE_CGROUP_ARRAY:
5056 	case BPF_MAP_TYPE_STACK_TRACE:
5057 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5058 	case BPF_MAP_TYPE_HASH_OF_MAPS:
5059 	case BPF_MAP_TYPE_DEVMAP:
5060 	case BPF_MAP_TYPE_DEVMAP_HASH:
5061 	case BPF_MAP_TYPE_CPUMAP:
5062 	case BPF_MAP_TYPE_XSKMAP:
5063 	case BPF_MAP_TYPE_SOCKMAP:
5064 	case BPF_MAP_TYPE_SOCKHASH:
5065 	case BPF_MAP_TYPE_QUEUE:
5066 	case BPF_MAP_TYPE_STACK:
5067 		create_attr.btf_fd = 0;
5068 		create_attr.btf_key_type_id = 0;
5069 		create_attr.btf_value_type_id = 0;
5070 		map->btf_key_type_id = 0;
5071 		map->btf_value_type_id = 0;
5072 	default:
5073 		break;
5074 	}
5075 
5076 	if (obj->gen_loader) {
5077 		bpf_gen__map_create(obj->gen_loader, def->type, map_name,
5078 				    def->key_size, def->value_size, def->max_entries,
5079 				    &create_attr, is_inner ? -1 : map - obj->maps);
5080 		/* Pretend to have valid FD to pass various fd >= 0 checks.
5081 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
5082 		 */
5083 		map->fd = 0;
5084 	} else {
5085 		map->fd = bpf_map_create(def->type, map_name,
5086 					 def->key_size, def->value_size,
5087 					 def->max_entries, &create_attr);
5088 	}
5089 	if (map->fd < 0 && (create_attr.btf_key_type_id ||
5090 			    create_attr.btf_value_type_id)) {
5091 		char *cp, errmsg[STRERR_BUFSIZE];
5092 
5093 		err = -errno;
5094 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5095 		pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
5096 			map->name, cp, err);
5097 		create_attr.btf_fd = 0;
5098 		create_attr.btf_key_type_id = 0;
5099 		create_attr.btf_value_type_id = 0;
5100 		map->btf_key_type_id = 0;
5101 		map->btf_value_type_id = 0;
5102 		map->fd = bpf_map_create(def->type, map_name,
5103 					 def->key_size, def->value_size,
5104 					 def->max_entries, &create_attr);
5105 	}
5106 
5107 	err = map->fd < 0 ? -errno : 0;
5108 
5109 	if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
5110 		if (obj->gen_loader)
5111 			map->inner_map->fd = -1;
5112 		bpf_map__destroy(map->inner_map);
5113 		zfree(&map->inner_map);
5114 	}
5115 
5116 	return err;
5117 }
5118 
5119 static int init_map_in_map_slots(struct bpf_object *obj, struct bpf_map *map)
5120 {
5121 	const struct bpf_map *targ_map;
5122 	unsigned int i;
5123 	int fd, err = 0;
5124 
5125 	for (i = 0; i < map->init_slots_sz; i++) {
5126 		if (!map->init_slots[i])
5127 			continue;
5128 
5129 		targ_map = map->init_slots[i];
5130 		fd = bpf_map__fd(targ_map);
5131 
5132 		if (obj->gen_loader) {
5133 			bpf_gen__populate_outer_map(obj->gen_loader,
5134 						    map - obj->maps, i,
5135 						    targ_map - obj->maps);
5136 		} else {
5137 			err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5138 		}
5139 		if (err) {
5140 			err = -errno;
5141 			pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %d\n",
5142 				map->name, i, targ_map->name, fd, err);
5143 			return err;
5144 		}
5145 		pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
5146 			 map->name, i, targ_map->name, fd);
5147 	}
5148 
5149 	zfree(&map->init_slots);
5150 	map->init_slots_sz = 0;
5151 
5152 	return 0;
5153 }
5154 
5155 static int init_prog_array_slots(struct bpf_object *obj, struct bpf_map *map)
5156 {
5157 	const struct bpf_program *targ_prog;
5158 	unsigned int i;
5159 	int fd, err;
5160 
5161 	if (obj->gen_loader)
5162 		return -ENOTSUP;
5163 
5164 	for (i = 0; i < map->init_slots_sz; i++) {
5165 		if (!map->init_slots[i])
5166 			continue;
5167 
5168 		targ_prog = map->init_slots[i];
5169 		fd = bpf_program__fd(targ_prog);
5170 
5171 		err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5172 		if (err) {
5173 			err = -errno;
5174 			pr_warn("map '%s': failed to initialize slot [%d] to prog '%s' fd=%d: %d\n",
5175 				map->name, i, targ_prog->name, fd, err);
5176 			return err;
5177 		}
5178 		pr_debug("map '%s': slot [%d] set to prog '%s' fd=%d\n",
5179 			 map->name, i, targ_prog->name, fd);
5180 	}
5181 
5182 	zfree(&map->init_slots);
5183 	map->init_slots_sz = 0;
5184 
5185 	return 0;
5186 }
5187 
5188 static int bpf_object_init_prog_arrays(struct bpf_object *obj)
5189 {
5190 	struct bpf_map *map;
5191 	int i, err;
5192 
5193 	for (i = 0; i < obj->nr_maps; i++) {
5194 		map = &obj->maps[i];
5195 
5196 		if (!map->init_slots_sz || map->def.type != BPF_MAP_TYPE_PROG_ARRAY)
5197 			continue;
5198 
5199 		err = init_prog_array_slots(obj, map);
5200 		if (err < 0) {
5201 			zclose(map->fd);
5202 			return err;
5203 		}
5204 	}
5205 	return 0;
5206 }
5207 
5208 static int map_set_def_max_entries(struct bpf_map *map)
5209 {
5210 	if (map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !map->def.max_entries) {
5211 		int nr_cpus;
5212 
5213 		nr_cpus = libbpf_num_possible_cpus();
5214 		if (nr_cpus < 0) {
5215 			pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
5216 				map->name, nr_cpus);
5217 			return nr_cpus;
5218 		}
5219 		pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
5220 		map->def.max_entries = nr_cpus;
5221 	}
5222 
5223 	return 0;
5224 }
5225 
5226 static int
5227 bpf_object__create_maps(struct bpf_object *obj)
5228 {
5229 	struct bpf_map *map;
5230 	char *cp, errmsg[STRERR_BUFSIZE];
5231 	unsigned int i, j;
5232 	int err;
5233 	bool retried;
5234 
5235 	for (i = 0; i < obj->nr_maps; i++) {
5236 		map = &obj->maps[i];
5237 
5238 		/* To support old kernels, we skip creating global data maps
5239 		 * (.rodata, .data, .kconfig, etc); later on, during program
5240 		 * loading, if we detect that at least one of the to-be-loaded
5241 		 * programs is referencing any global data map, we'll error
5242 		 * out with program name and relocation index logged.
5243 		 * This approach allows to accommodate Clang emitting
5244 		 * unnecessary .rodata.str1.1 sections for string literals,
5245 		 * but also it allows to have CO-RE applications that use
5246 		 * global variables in some of BPF programs, but not others.
5247 		 * If those global variable-using programs are not loaded at
5248 		 * runtime due to bpf_program__set_autoload(prog, false),
5249 		 * bpf_object loading will succeed just fine even on old
5250 		 * kernels.
5251 		 */
5252 		if (bpf_map__is_internal(map) && !kernel_supports(obj, FEAT_GLOBAL_DATA))
5253 			map->autocreate = false;
5254 
5255 		if (!map->autocreate) {
5256 			pr_debug("map '%s': skipped auto-creating...\n", map->name);
5257 			continue;
5258 		}
5259 
5260 		err = map_set_def_max_entries(map);
5261 		if (err)
5262 			goto err_out;
5263 
5264 		retried = false;
5265 retry:
5266 		if (map->pin_path) {
5267 			err = bpf_object__reuse_map(map);
5268 			if (err) {
5269 				pr_warn("map '%s': error reusing pinned map\n",
5270 					map->name);
5271 				goto err_out;
5272 			}
5273 			if (retried && map->fd < 0) {
5274 				pr_warn("map '%s': cannot find pinned map\n",
5275 					map->name);
5276 				err = -ENOENT;
5277 				goto err_out;
5278 			}
5279 		}
5280 
5281 		if (map->fd >= 0) {
5282 			pr_debug("map '%s': skipping creation (preset fd=%d)\n",
5283 				 map->name, map->fd);
5284 		} else {
5285 			err = bpf_object__create_map(obj, map, false);
5286 			if (err)
5287 				goto err_out;
5288 
5289 			pr_debug("map '%s': created successfully, fd=%d\n",
5290 				 map->name, map->fd);
5291 
5292 			if (bpf_map__is_internal(map)) {
5293 				err = bpf_object__populate_internal_map(obj, map);
5294 				if (err < 0) {
5295 					zclose(map->fd);
5296 					goto err_out;
5297 				}
5298 			}
5299 
5300 			if (map->init_slots_sz && map->def.type != BPF_MAP_TYPE_PROG_ARRAY) {
5301 				err = init_map_in_map_slots(obj, map);
5302 				if (err < 0) {
5303 					zclose(map->fd);
5304 					goto err_out;
5305 				}
5306 			}
5307 		}
5308 
5309 		if (map->pin_path && !map->pinned) {
5310 			err = bpf_map__pin(map, NULL);
5311 			if (err) {
5312 				zclose(map->fd);
5313 				if (!retried && err == -EEXIST) {
5314 					retried = true;
5315 					goto retry;
5316 				}
5317 				pr_warn("map '%s': failed to auto-pin at '%s': %d\n",
5318 					map->name, map->pin_path, err);
5319 				goto err_out;
5320 			}
5321 		}
5322 	}
5323 
5324 	return 0;
5325 
5326 err_out:
5327 	cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5328 	pr_warn("map '%s': failed to create: %s(%d)\n", map->name, cp, err);
5329 	pr_perm_msg(err);
5330 	for (j = 0; j < i; j++)
5331 		zclose(obj->maps[j].fd);
5332 	return err;
5333 }
5334 
5335 static bool bpf_core_is_flavor_sep(const char *s)
5336 {
5337 	/* check X___Y name pattern, where X and Y are not underscores */
5338 	return s[0] != '_' &&				      /* X */
5339 	       s[1] == '_' && s[2] == '_' && s[3] == '_' &&   /* ___ */
5340 	       s[4] != '_';				      /* Y */
5341 }
5342 
5343 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
5344  * before last triple underscore. Struct name part after last triple
5345  * underscore is ignored by BPF CO-RE relocation during relocation matching.
5346  */
5347 size_t bpf_core_essential_name_len(const char *name)
5348 {
5349 	size_t n = strlen(name);
5350 	int i;
5351 
5352 	for (i = n - 5; i >= 0; i--) {
5353 		if (bpf_core_is_flavor_sep(name + i))
5354 			return i + 1;
5355 	}
5356 	return n;
5357 }
5358 
5359 void bpf_core_free_cands(struct bpf_core_cand_list *cands)
5360 {
5361 	if (!cands)
5362 		return;
5363 
5364 	free(cands->cands);
5365 	free(cands);
5366 }
5367 
5368 int bpf_core_add_cands(struct bpf_core_cand *local_cand,
5369 		       size_t local_essent_len,
5370 		       const struct btf *targ_btf,
5371 		       const char *targ_btf_name,
5372 		       int targ_start_id,
5373 		       struct bpf_core_cand_list *cands)
5374 {
5375 	struct bpf_core_cand *new_cands, *cand;
5376 	const struct btf_type *t, *local_t;
5377 	const char *targ_name, *local_name;
5378 	size_t targ_essent_len;
5379 	int n, i;
5380 
5381 	local_t = btf__type_by_id(local_cand->btf, local_cand->id);
5382 	local_name = btf__str_by_offset(local_cand->btf, local_t->name_off);
5383 
5384 	n = btf__type_cnt(targ_btf);
5385 	for (i = targ_start_id; i < n; i++) {
5386 		t = btf__type_by_id(targ_btf, i);
5387 		if (!btf_kind_core_compat(t, local_t))
5388 			continue;
5389 
5390 		targ_name = btf__name_by_offset(targ_btf, t->name_off);
5391 		if (str_is_empty(targ_name))
5392 			continue;
5393 
5394 		targ_essent_len = bpf_core_essential_name_len(targ_name);
5395 		if (targ_essent_len != local_essent_len)
5396 			continue;
5397 
5398 		if (strncmp(local_name, targ_name, local_essent_len) != 0)
5399 			continue;
5400 
5401 		pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s in [%s]\n",
5402 			 local_cand->id, btf_kind_str(local_t),
5403 			 local_name, i, btf_kind_str(t), targ_name,
5404 			 targ_btf_name);
5405 		new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
5406 					      sizeof(*cands->cands));
5407 		if (!new_cands)
5408 			return -ENOMEM;
5409 
5410 		cand = &new_cands[cands->len];
5411 		cand->btf = targ_btf;
5412 		cand->id = i;
5413 
5414 		cands->cands = new_cands;
5415 		cands->len++;
5416 	}
5417 	return 0;
5418 }
5419 
5420 static int load_module_btfs(struct bpf_object *obj)
5421 {
5422 	struct bpf_btf_info info;
5423 	struct module_btf *mod_btf;
5424 	struct btf *btf;
5425 	char name[64];
5426 	__u32 id = 0, len;
5427 	int err, fd;
5428 
5429 	if (obj->btf_modules_loaded)
5430 		return 0;
5431 
5432 	if (obj->gen_loader)
5433 		return 0;
5434 
5435 	/* don't do this again, even if we find no module BTFs */
5436 	obj->btf_modules_loaded = true;
5437 
5438 	/* kernel too old to support module BTFs */
5439 	if (!kernel_supports(obj, FEAT_MODULE_BTF))
5440 		return 0;
5441 
5442 	while (true) {
5443 		err = bpf_btf_get_next_id(id, &id);
5444 		if (err && errno == ENOENT)
5445 			return 0;
5446 		if (err) {
5447 			err = -errno;
5448 			pr_warn("failed to iterate BTF objects: %d\n", err);
5449 			return err;
5450 		}
5451 
5452 		fd = bpf_btf_get_fd_by_id(id);
5453 		if (fd < 0) {
5454 			if (errno == ENOENT)
5455 				continue; /* expected race: BTF was unloaded */
5456 			err = -errno;
5457 			pr_warn("failed to get BTF object #%d FD: %d\n", id, err);
5458 			return err;
5459 		}
5460 
5461 		len = sizeof(info);
5462 		memset(&info, 0, sizeof(info));
5463 		info.name = ptr_to_u64(name);
5464 		info.name_len = sizeof(name);
5465 
5466 		err = bpf_obj_get_info_by_fd(fd, &info, &len);
5467 		if (err) {
5468 			err = -errno;
5469 			pr_warn("failed to get BTF object #%d info: %d\n", id, err);
5470 			goto err_out;
5471 		}
5472 
5473 		/* ignore non-module BTFs */
5474 		if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
5475 			close(fd);
5476 			continue;
5477 		}
5478 
5479 		btf = btf_get_from_fd(fd, obj->btf_vmlinux);
5480 		err = libbpf_get_error(btf);
5481 		if (err) {
5482 			pr_warn("failed to load module [%s]'s BTF object #%d: %d\n",
5483 				name, id, err);
5484 			goto err_out;
5485 		}
5486 
5487 		err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
5488 				        sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
5489 		if (err)
5490 			goto err_out;
5491 
5492 		mod_btf = &obj->btf_modules[obj->btf_module_cnt++];
5493 
5494 		mod_btf->btf = btf;
5495 		mod_btf->id = id;
5496 		mod_btf->fd = fd;
5497 		mod_btf->name = strdup(name);
5498 		if (!mod_btf->name) {
5499 			err = -ENOMEM;
5500 			goto err_out;
5501 		}
5502 		continue;
5503 
5504 err_out:
5505 		close(fd);
5506 		return err;
5507 	}
5508 
5509 	return 0;
5510 }
5511 
5512 static struct bpf_core_cand_list *
5513 bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
5514 {
5515 	struct bpf_core_cand local_cand = {};
5516 	struct bpf_core_cand_list *cands;
5517 	const struct btf *main_btf;
5518 	const struct btf_type *local_t;
5519 	const char *local_name;
5520 	size_t local_essent_len;
5521 	int err, i;
5522 
5523 	local_cand.btf = local_btf;
5524 	local_cand.id = local_type_id;
5525 	local_t = btf__type_by_id(local_btf, local_type_id);
5526 	if (!local_t)
5527 		return ERR_PTR(-EINVAL);
5528 
5529 	local_name = btf__name_by_offset(local_btf, local_t->name_off);
5530 	if (str_is_empty(local_name))
5531 		return ERR_PTR(-EINVAL);
5532 	local_essent_len = bpf_core_essential_name_len(local_name);
5533 
5534 	cands = calloc(1, sizeof(*cands));
5535 	if (!cands)
5536 		return ERR_PTR(-ENOMEM);
5537 
5538 	/* Attempt to find target candidates in vmlinux BTF first */
5539 	main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
5540 	err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
5541 	if (err)
5542 		goto err_out;
5543 
5544 	/* if vmlinux BTF has any candidate, don't got for module BTFs */
5545 	if (cands->len)
5546 		return cands;
5547 
5548 	/* if vmlinux BTF was overridden, don't attempt to load module BTFs */
5549 	if (obj->btf_vmlinux_override)
5550 		return cands;
5551 
5552 	/* now look through module BTFs, trying to still find candidates */
5553 	err = load_module_btfs(obj);
5554 	if (err)
5555 		goto err_out;
5556 
5557 	for (i = 0; i < obj->btf_module_cnt; i++) {
5558 		err = bpf_core_add_cands(&local_cand, local_essent_len,
5559 					 obj->btf_modules[i].btf,
5560 					 obj->btf_modules[i].name,
5561 					 btf__type_cnt(obj->btf_vmlinux),
5562 					 cands);
5563 		if (err)
5564 			goto err_out;
5565 	}
5566 
5567 	return cands;
5568 err_out:
5569 	bpf_core_free_cands(cands);
5570 	return ERR_PTR(err);
5571 }
5572 
5573 /* Check local and target types for compatibility. This check is used for
5574  * type-based CO-RE relocations and follow slightly different rules than
5575  * field-based relocations. This function assumes that root types were already
5576  * checked for name match. Beyond that initial root-level name check, names
5577  * are completely ignored. Compatibility rules are as follows:
5578  *   - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
5579  *     kind should match for local and target types (i.e., STRUCT is not
5580  *     compatible with UNION);
5581  *   - for ENUMs, the size is ignored;
5582  *   - for INT, size and signedness are ignored;
5583  *   - for ARRAY, dimensionality is ignored, element types are checked for
5584  *     compatibility recursively;
5585  *   - CONST/VOLATILE/RESTRICT modifiers are ignored;
5586  *   - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
5587  *   - FUNC_PROTOs are compatible if they have compatible signature: same
5588  *     number of input args and compatible return and argument types.
5589  * These rules are not set in stone and probably will be adjusted as we get
5590  * more experience with using BPF CO-RE relocations.
5591  */
5592 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
5593 			      const struct btf *targ_btf, __u32 targ_id)
5594 {
5595 	return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id, 32);
5596 }
5597 
5598 int bpf_core_types_match(const struct btf *local_btf, __u32 local_id,
5599 			 const struct btf *targ_btf, __u32 targ_id)
5600 {
5601 	return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false, 32);
5602 }
5603 
5604 static size_t bpf_core_hash_fn(const void *key, void *ctx)
5605 {
5606 	return (size_t)key;
5607 }
5608 
5609 static bool bpf_core_equal_fn(const void *k1, const void *k2, void *ctx)
5610 {
5611 	return k1 == k2;
5612 }
5613 
5614 static void *u32_as_hash_key(__u32 x)
5615 {
5616 	return (void *)(uintptr_t)x;
5617 }
5618 
5619 static int record_relo_core(struct bpf_program *prog,
5620 			    const struct bpf_core_relo *core_relo, int insn_idx)
5621 {
5622 	struct reloc_desc *relos, *relo;
5623 
5624 	relos = libbpf_reallocarray(prog->reloc_desc,
5625 				    prog->nr_reloc + 1, sizeof(*relos));
5626 	if (!relos)
5627 		return -ENOMEM;
5628 	relo = &relos[prog->nr_reloc];
5629 	relo->type = RELO_CORE;
5630 	relo->insn_idx = insn_idx;
5631 	relo->core_relo = core_relo;
5632 	prog->reloc_desc = relos;
5633 	prog->nr_reloc++;
5634 	return 0;
5635 }
5636 
5637 static const struct bpf_core_relo *find_relo_core(struct bpf_program *prog, int insn_idx)
5638 {
5639 	struct reloc_desc *relo;
5640 	int i;
5641 
5642 	for (i = 0; i < prog->nr_reloc; i++) {
5643 		relo = &prog->reloc_desc[i];
5644 		if (relo->type != RELO_CORE || relo->insn_idx != insn_idx)
5645 			continue;
5646 
5647 		return relo->core_relo;
5648 	}
5649 
5650 	return NULL;
5651 }
5652 
5653 static int bpf_core_resolve_relo(struct bpf_program *prog,
5654 				 const struct bpf_core_relo *relo,
5655 				 int relo_idx,
5656 				 const struct btf *local_btf,
5657 				 struct hashmap *cand_cache,
5658 				 struct bpf_core_relo_res *targ_res)
5659 {
5660 	struct bpf_core_spec specs_scratch[3] = {};
5661 	const void *type_key = u32_as_hash_key(relo->type_id);
5662 	struct bpf_core_cand_list *cands = NULL;
5663 	const char *prog_name = prog->name;
5664 	const struct btf_type *local_type;
5665 	const char *local_name;
5666 	__u32 local_id = relo->type_id;
5667 	int err;
5668 
5669 	local_type = btf__type_by_id(local_btf, local_id);
5670 	if (!local_type)
5671 		return -EINVAL;
5672 
5673 	local_name = btf__name_by_offset(local_btf, local_type->name_off);
5674 	if (!local_name)
5675 		return -EINVAL;
5676 
5677 	if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
5678 	    !hashmap__find(cand_cache, type_key, (void **)&cands)) {
5679 		cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
5680 		if (IS_ERR(cands)) {
5681 			pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n",
5682 				prog_name, relo_idx, local_id, btf_kind_str(local_type),
5683 				local_name, PTR_ERR(cands));
5684 			return PTR_ERR(cands);
5685 		}
5686 		err = hashmap__set(cand_cache, type_key, cands, NULL, NULL);
5687 		if (err) {
5688 			bpf_core_free_cands(cands);
5689 			return err;
5690 		}
5691 	}
5692 
5693 	return bpf_core_calc_relo_insn(prog_name, relo, relo_idx, local_btf, cands, specs_scratch,
5694 				       targ_res);
5695 }
5696 
5697 static int
5698 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
5699 {
5700 	const struct btf_ext_info_sec *sec;
5701 	struct bpf_core_relo_res targ_res;
5702 	const struct bpf_core_relo *rec;
5703 	const struct btf_ext_info *seg;
5704 	struct hashmap_entry *entry;
5705 	struct hashmap *cand_cache = NULL;
5706 	struct bpf_program *prog;
5707 	struct bpf_insn *insn;
5708 	const char *sec_name;
5709 	int i, err = 0, insn_idx, sec_idx, sec_num;
5710 
5711 	if (obj->btf_ext->core_relo_info.len == 0)
5712 		return 0;
5713 
5714 	if (targ_btf_path) {
5715 		obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
5716 		err = libbpf_get_error(obj->btf_vmlinux_override);
5717 		if (err) {
5718 			pr_warn("failed to parse target BTF: %d\n", err);
5719 			return err;
5720 		}
5721 	}
5722 
5723 	cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
5724 	if (IS_ERR(cand_cache)) {
5725 		err = PTR_ERR(cand_cache);
5726 		goto out;
5727 	}
5728 
5729 	seg = &obj->btf_ext->core_relo_info;
5730 	sec_num = 0;
5731 	for_each_btf_ext_sec(seg, sec) {
5732 		sec_idx = seg->sec_idxs[sec_num];
5733 		sec_num++;
5734 
5735 		sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
5736 		if (str_is_empty(sec_name)) {
5737 			err = -EINVAL;
5738 			goto out;
5739 		}
5740 
5741 		pr_debug("sec '%s': found %d CO-RE relocations\n", sec_name, sec->num_info);
5742 
5743 		for_each_btf_ext_rec(seg, sec, i, rec) {
5744 			if (rec->insn_off % BPF_INSN_SZ)
5745 				return -EINVAL;
5746 			insn_idx = rec->insn_off / BPF_INSN_SZ;
5747 			prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
5748 			if (!prog) {
5749 				/* When __weak subprog is "overridden" by another instance
5750 				 * of the subprog from a different object file, linker still
5751 				 * appends all the .BTF.ext info that used to belong to that
5752 				 * eliminated subprogram.
5753 				 * This is similar to what x86-64 linker does for relocations.
5754 				 * So just ignore such relocations just like we ignore
5755 				 * subprog instructions when discovering subprograms.
5756 				 */
5757 				pr_debug("sec '%s': skipping CO-RE relocation #%d for insn #%d belonging to eliminated weak subprogram\n",
5758 					 sec_name, i, insn_idx);
5759 				continue;
5760 			}
5761 			/* no need to apply CO-RE relocation if the program is
5762 			 * not going to be loaded
5763 			 */
5764 			if (!prog->autoload)
5765 				continue;
5766 
5767 			/* adjust insn_idx from section frame of reference to the local
5768 			 * program's frame of reference; (sub-)program code is not yet
5769 			 * relocated, so it's enough to just subtract in-section offset
5770 			 */
5771 			insn_idx = insn_idx - prog->sec_insn_off;
5772 			if (insn_idx >= prog->insns_cnt)
5773 				return -EINVAL;
5774 			insn = &prog->insns[insn_idx];
5775 
5776 			err = record_relo_core(prog, rec, insn_idx);
5777 			if (err) {
5778 				pr_warn("prog '%s': relo #%d: failed to record relocation: %d\n",
5779 					prog->name, i, err);
5780 				goto out;
5781 			}
5782 
5783 			if (prog->obj->gen_loader)
5784 				continue;
5785 
5786 			err = bpf_core_resolve_relo(prog, rec, i, obj->btf, cand_cache, &targ_res);
5787 			if (err) {
5788 				pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
5789 					prog->name, i, err);
5790 				goto out;
5791 			}
5792 
5793 			err = bpf_core_patch_insn(prog->name, insn, insn_idx, rec, i, &targ_res);
5794 			if (err) {
5795 				pr_warn("prog '%s': relo #%d: failed to patch insn #%u: %d\n",
5796 					prog->name, i, insn_idx, err);
5797 				goto out;
5798 			}
5799 		}
5800 	}
5801 
5802 out:
5803 	/* obj->btf_vmlinux and module BTFs are freed after object load */
5804 	btf__free(obj->btf_vmlinux_override);
5805 	obj->btf_vmlinux_override = NULL;
5806 
5807 	if (!IS_ERR_OR_NULL(cand_cache)) {
5808 		hashmap__for_each_entry(cand_cache, entry, i) {
5809 			bpf_core_free_cands(entry->value);
5810 		}
5811 		hashmap__free(cand_cache);
5812 	}
5813 	return err;
5814 }
5815 
5816 /* base map load ldimm64 special constant, used also for log fixup logic */
5817 #define MAP_LDIMM64_POISON_BASE 2001000000
5818 #define MAP_LDIMM64_POISON_PFX "200100"
5819 
5820 static void poison_map_ldimm64(struct bpf_program *prog, int relo_idx,
5821 			       int insn_idx, struct bpf_insn *insn,
5822 			       int map_idx, const struct bpf_map *map)
5823 {
5824 	int i;
5825 
5826 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that loads map #%d '%s'\n",
5827 		 prog->name, relo_idx, insn_idx, map_idx, map->name);
5828 
5829 	/* we turn single ldimm64 into two identical invalid calls */
5830 	for (i = 0; i < 2; i++) {
5831 		insn->code = BPF_JMP | BPF_CALL;
5832 		insn->dst_reg = 0;
5833 		insn->src_reg = 0;
5834 		insn->off = 0;
5835 		/* if this instruction is reachable (not a dead code),
5836 		 * verifier will complain with something like:
5837 		 * invalid func unknown#2001000123
5838 		 * where lower 123 is map index into obj->maps[] array
5839 		 */
5840 		insn->imm = MAP_LDIMM64_POISON_BASE + map_idx;
5841 
5842 		insn++;
5843 	}
5844 }
5845 
5846 /* Relocate data references within program code:
5847  *  - map references;
5848  *  - global variable references;
5849  *  - extern references.
5850  */
5851 static int
5852 bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
5853 {
5854 	int i;
5855 
5856 	for (i = 0; i < prog->nr_reloc; i++) {
5857 		struct reloc_desc *relo = &prog->reloc_desc[i];
5858 		struct bpf_insn *insn = &prog->insns[relo->insn_idx];
5859 		const struct bpf_map *map;
5860 		struct extern_desc *ext;
5861 
5862 		switch (relo->type) {
5863 		case RELO_LD64:
5864 			map = &obj->maps[relo->map_idx];
5865 			if (obj->gen_loader) {
5866 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
5867 				insn[0].imm = relo->map_idx;
5868 			} else if (map->autocreate) {
5869 				insn[0].src_reg = BPF_PSEUDO_MAP_FD;
5870 				insn[0].imm = map->fd;
5871 			} else {
5872 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
5873 						   relo->map_idx, map);
5874 			}
5875 			break;
5876 		case RELO_DATA:
5877 			map = &obj->maps[relo->map_idx];
5878 			insn[1].imm = insn[0].imm + relo->sym_off;
5879 			if (obj->gen_loader) {
5880 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
5881 				insn[0].imm = relo->map_idx;
5882 			} else if (map->autocreate) {
5883 				insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
5884 				insn[0].imm = map->fd;
5885 			} else {
5886 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
5887 						   relo->map_idx, map);
5888 			}
5889 			break;
5890 		case RELO_EXTERN_VAR:
5891 			ext = &obj->externs[relo->sym_off];
5892 			if (ext->type == EXT_KCFG) {
5893 				if (obj->gen_loader) {
5894 					insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
5895 					insn[0].imm = obj->kconfig_map_idx;
5896 				} else {
5897 					insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
5898 					insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
5899 				}
5900 				insn[1].imm = ext->kcfg.data_off;
5901 			} else /* EXT_KSYM */ {
5902 				if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
5903 					insn[0].src_reg = BPF_PSEUDO_BTF_ID;
5904 					insn[0].imm = ext->ksym.kernel_btf_id;
5905 					insn[1].imm = ext->ksym.kernel_btf_obj_fd;
5906 				} else { /* typeless ksyms or unresolved typed ksyms */
5907 					insn[0].imm = (__u32)ext->ksym.addr;
5908 					insn[1].imm = ext->ksym.addr >> 32;
5909 				}
5910 			}
5911 			break;
5912 		case RELO_EXTERN_FUNC:
5913 			ext = &obj->externs[relo->sym_off];
5914 			insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
5915 			if (ext->is_set) {
5916 				insn[0].imm = ext->ksym.kernel_btf_id;
5917 				insn[0].off = ext->ksym.btf_fd_idx;
5918 			} else { /* unresolved weak kfunc */
5919 				insn[0].imm = 0;
5920 				insn[0].off = 0;
5921 			}
5922 			break;
5923 		case RELO_SUBPROG_ADDR:
5924 			if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
5925 				pr_warn("prog '%s': relo #%d: bad insn\n",
5926 					prog->name, i);
5927 				return -EINVAL;
5928 			}
5929 			/* handled already */
5930 			break;
5931 		case RELO_CALL:
5932 			/* handled already */
5933 			break;
5934 		case RELO_CORE:
5935 			/* will be handled by bpf_program_record_relos() */
5936 			break;
5937 		default:
5938 			pr_warn("prog '%s': relo #%d: bad relo type %d\n",
5939 				prog->name, i, relo->type);
5940 			return -EINVAL;
5941 		}
5942 	}
5943 
5944 	return 0;
5945 }
5946 
5947 static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
5948 				    const struct bpf_program *prog,
5949 				    const struct btf_ext_info *ext_info,
5950 				    void **prog_info, __u32 *prog_rec_cnt,
5951 				    __u32 *prog_rec_sz)
5952 {
5953 	void *copy_start = NULL, *copy_end = NULL;
5954 	void *rec, *rec_end, *new_prog_info;
5955 	const struct btf_ext_info_sec *sec;
5956 	size_t old_sz, new_sz;
5957 	int i, sec_num, sec_idx, off_adj;
5958 
5959 	sec_num = 0;
5960 	for_each_btf_ext_sec(ext_info, sec) {
5961 		sec_idx = ext_info->sec_idxs[sec_num];
5962 		sec_num++;
5963 		if (prog->sec_idx != sec_idx)
5964 			continue;
5965 
5966 		for_each_btf_ext_rec(ext_info, sec, i, rec) {
5967 			__u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
5968 
5969 			if (insn_off < prog->sec_insn_off)
5970 				continue;
5971 			if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
5972 				break;
5973 
5974 			if (!copy_start)
5975 				copy_start = rec;
5976 			copy_end = rec + ext_info->rec_size;
5977 		}
5978 
5979 		if (!copy_start)
5980 			return -ENOENT;
5981 
5982 		/* append func/line info of a given (sub-)program to the main
5983 		 * program func/line info
5984 		 */
5985 		old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
5986 		new_sz = old_sz + (copy_end - copy_start);
5987 		new_prog_info = realloc(*prog_info, new_sz);
5988 		if (!new_prog_info)
5989 			return -ENOMEM;
5990 		*prog_info = new_prog_info;
5991 		*prog_rec_cnt = new_sz / ext_info->rec_size;
5992 		memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
5993 
5994 		/* Kernel instruction offsets are in units of 8-byte
5995 		 * instructions, while .BTF.ext instruction offsets generated
5996 		 * by Clang are in units of bytes. So convert Clang offsets
5997 		 * into kernel offsets and adjust offset according to program
5998 		 * relocated position.
5999 		 */
6000 		off_adj = prog->sub_insn_off - prog->sec_insn_off;
6001 		rec = new_prog_info + old_sz;
6002 		rec_end = new_prog_info + new_sz;
6003 		for (; rec < rec_end; rec += ext_info->rec_size) {
6004 			__u32 *insn_off = rec;
6005 
6006 			*insn_off = *insn_off / BPF_INSN_SZ + off_adj;
6007 		}
6008 		*prog_rec_sz = ext_info->rec_size;
6009 		return 0;
6010 	}
6011 
6012 	return -ENOENT;
6013 }
6014 
6015 static int
6016 reloc_prog_func_and_line_info(const struct bpf_object *obj,
6017 			      struct bpf_program *main_prog,
6018 			      const struct bpf_program *prog)
6019 {
6020 	int err;
6021 
6022 	/* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
6023 	 * supprot func/line info
6024 	 */
6025 	if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
6026 		return 0;
6027 
6028 	/* only attempt func info relocation if main program's func_info
6029 	 * relocation was successful
6030 	 */
6031 	if (main_prog != prog && !main_prog->func_info)
6032 		goto line_info;
6033 
6034 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
6035 				       &main_prog->func_info,
6036 				       &main_prog->func_info_cnt,
6037 				       &main_prog->func_info_rec_size);
6038 	if (err) {
6039 		if (err != -ENOENT) {
6040 			pr_warn("prog '%s': error relocating .BTF.ext function info: %d\n",
6041 				prog->name, err);
6042 			return err;
6043 		}
6044 		if (main_prog->func_info) {
6045 			/*
6046 			 * Some info has already been found but has problem
6047 			 * in the last btf_ext reloc. Must have to error out.
6048 			 */
6049 			pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
6050 			return err;
6051 		}
6052 		/* Have problem loading the very first info. Ignore the rest. */
6053 		pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
6054 			prog->name);
6055 	}
6056 
6057 line_info:
6058 	/* don't relocate line info if main program's relocation failed */
6059 	if (main_prog != prog && !main_prog->line_info)
6060 		return 0;
6061 
6062 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
6063 				       &main_prog->line_info,
6064 				       &main_prog->line_info_cnt,
6065 				       &main_prog->line_info_rec_size);
6066 	if (err) {
6067 		if (err != -ENOENT) {
6068 			pr_warn("prog '%s': error relocating .BTF.ext line info: %d\n",
6069 				prog->name, err);
6070 			return err;
6071 		}
6072 		if (main_prog->line_info) {
6073 			/*
6074 			 * Some info has already been found but has problem
6075 			 * in the last btf_ext reloc. Must have to error out.
6076 			 */
6077 			pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
6078 			return err;
6079 		}
6080 		/* Have problem loading the very first info. Ignore the rest. */
6081 		pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
6082 			prog->name);
6083 	}
6084 	return 0;
6085 }
6086 
6087 static int cmp_relo_by_insn_idx(const void *key, const void *elem)
6088 {
6089 	size_t insn_idx = *(const size_t *)key;
6090 	const struct reloc_desc *relo = elem;
6091 
6092 	if (insn_idx == relo->insn_idx)
6093 		return 0;
6094 	return insn_idx < relo->insn_idx ? -1 : 1;
6095 }
6096 
6097 static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
6098 {
6099 	if (!prog->nr_reloc)
6100 		return NULL;
6101 	return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
6102 		       sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
6103 }
6104 
6105 static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
6106 {
6107 	int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
6108 	struct reloc_desc *relos;
6109 	int i;
6110 
6111 	if (main_prog == subprog)
6112 		return 0;
6113 	relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
6114 	if (!relos)
6115 		return -ENOMEM;
6116 	if (subprog->nr_reloc)
6117 		memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
6118 		       sizeof(*relos) * subprog->nr_reloc);
6119 
6120 	for (i = main_prog->nr_reloc; i < new_cnt; i++)
6121 		relos[i].insn_idx += subprog->sub_insn_off;
6122 	/* After insn_idx adjustment the 'relos' array is still sorted
6123 	 * by insn_idx and doesn't break bsearch.
6124 	 */
6125 	main_prog->reloc_desc = relos;
6126 	main_prog->nr_reloc = new_cnt;
6127 	return 0;
6128 }
6129 
6130 static int
6131 bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
6132 		       struct bpf_program *prog)
6133 {
6134 	size_t sub_insn_idx, insn_idx, new_cnt;
6135 	struct bpf_program *subprog;
6136 	struct bpf_insn *insns, *insn;
6137 	struct reloc_desc *relo;
6138 	int err;
6139 
6140 	err = reloc_prog_func_and_line_info(obj, main_prog, prog);
6141 	if (err)
6142 		return err;
6143 
6144 	for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
6145 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6146 		if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
6147 			continue;
6148 
6149 		relo = find_prog_insn_relo(prog, insn_idx);
6150 		if (relo && relo->type == RELO_EXTERN_FUNC)
6151 			/* kfunc relocations will be handled later
6152 			 * in bpf_object__relocate_data()
6153 			 */
6154 			continue;
6155 		if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
6156 			pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
6157 				prog->name, insn_idx, relo->type);
6158 			return -LIBBPF_ERRNO__RELOC;
6159 		}
6160 		if (relo) {
6161 			/* sub-program instruction index is a combination of
6162 			 * an offset of a symbol pointed to by relocation and
6163 			 * call instruction's imm field; for global functions,
6164 			 * call always has imm = -1, but for static functions
6165 			 * relocation is against STT_SECTION and insn->imm
6166 			 * points to a start of a static function
6167 			 *
6168 			 * for subprog addr relocation, the relo->sym_off + insn->imm is
6169 			 * the byte offset in the corresponding section.
6170 			 */
6171 			if (relo->type == RELO_CALL)
6172 				sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
6173 			else
6174 				sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
6175 		} else if (insn_is_pseudo_func(insn)) {
6176 			/*
6177 			 * RELO_SUBPROG_ADDR relo is always emitted even if both
6178 			 * functions are in the same section, so it shouldn't reach here.
6179 			 */
6180 			pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
6181 				prog->name, insn_idx);
6182 			return -LIBBPF_ERRNO__RELOC;
6183 		} else {
6184 			/* if subprogram call is to a static function within
6185 			 * the same ELF section, there won't be any relocation
6186 			 * emitted, but it also means there is no additional
6187 			 * offset necessary, insns->imm is relative to
6188 			 * instruction's original position within the section
6189 			 */
6190 			sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
6191 		}
6192 
6193 		/* we enforce that sub-programs should be in .text section */
6194 		subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
6195 		if (!subprog) {
6196 			pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
6197 				prog->name);
6198 			return -LIBBPF_ERRNO__RELOC;
6199 		}
6200 
6201 		/* if it's the first call instruction calling into this
6202 		 * subprogram (meaning this subprog hasn't been processed
6203 		 * yet) within the context of current main program:
6204 		 *   - append it at the end of main program's instructions blog;
6205 		 *   - process is recursively, while current program is put on hold;
6206 		 *   - if that subprogram calls some other not yet processes
6207 		 *   subprogram, same thing will happen recursively until
6208 		 *   there are no more unprocesses subprograms left to append
6209 		 *   and relocate.
6210 		 */
6211 		if (subprog->sub_insn_off == 0) {
6212 			subprog->sub_insn_off = main_prog->insns_cnt;
6213 
6214 			new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
6215 			insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
6216 			if (!insns) {
6217 				pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
6218 				return -ENOMEM;
6219 			}
6220 			main_prog->insns = insns;
6221 			main_prog->insns_cnt = new_cnt;
6222 
6223 			memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
6224 			       subprog->insns_cnt * sizeof(*insns));
6225 
6226 			pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
6227 				 main_prog->name, subprog->insns_cnt, subprog->name);
6228 
6229 			/* The subprog insns are now appended. Append its relos too. */
6230 			err = append_subprog_relos(main_prog, subprog);
6231 			if (err)
6232 				return err;
6233 			err = bpf_object__reloc_code(obj, main_prog, subprog);
6234 			if (err)
6235 				return err;
6236 		}
6237 
6238 		/* main_prog->insns memory could have been re-allocated, so
6239 		 * calculate pointer again
6240 		 */
6241 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6242 		/* calculate correct instruction position within current main
6243 		 * prog; each main prog can have a different set of
6244 		 * subprograms appended (potentially in different order as
6245 		 * well), so position of any subprog can be different for
6246 		 * different main programs */
6247 		insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
6248 
6249 		pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
6250 			 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
6251 	}
6252 
6253 	return 0;
6254 }
6255 
6256 /*
6257  * Relocate sub-program calls.
6258  *
6259  * Algorithm operates as follows. Each entry-point BPF program (referred to as
6260  * main prog) is processed separately. For each subprog (non-entry functions,
6261  * that can be called from either entry progs or other subprogs) gets their
6262  * sub_insn_off reset to zero. This serves as indicator that this subprogram
6263  * hasn't been yet appended and relocated within current main prog. Once its
6264  * relocated, sub_insn_off will point at the position within current main prog
6265  * where given subprog was appended. This will further be used to relocate all
6266  * the call instructions jumping into this subprog.
6267  *
6268  * We start with main program and process all call instructions. If the call
6269  * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
6270  * is zero), subprog instructions are appended at the end of main program's
6271  * instruction array. Then main program is "put on hold" while we recursively
6272  * process newly appended subprogram. If that subprogram calls into another
6273  * subprogram that hasn't been appended, new subprogram is appended again to
6274  * the *main* prog's instructions (subprog's instructions are always left
6275  * untouched, as they need to be in unmodified state for subsequent main progs
6276  * and subprog instructions are always sent only as part of a main prog) and
6277  * the process continues recursively. Once all the subprogs called from a main
6278  * prog or any of its subprogs are appended (and relocated), all their
6279  * positions within finalized instructions array are known, so it's easy to
6280  * rewrite call instructions with correct relative offsets, corresponding to
6281  * desired target subprog.
6282  *
6283  * Its important to realize that some subprogs might not be called from some
6284  * main prog and any of its called/used subprogs. Those will keep their
6285  * subprog->sub_insn_off as zero at all times and won't be appended to current
6286  * main prog and won't be relocated within the context of current main prog.
6287  * They might still be used from other main progs later.
6288  *
6289  * Visually this process can be shown as below. Suppose we have two main
6290  * programs mainA and mainB and BPF object contains three subprogs: subA,
6291  * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
6292  * subC both call subB:
6293  *
6294  *        +--------+ +-------+
6295  *        |        v v       |
6296  *     +--+---+ +--+-+-+ +---+--+
6297  *     | subA | | subB | | subC |
6298  *     +--+---+ +------+ +---+--+
6299  *        ^                  ^
6300  *        |                  |
6301  *    +---+-------+   +------+----+
6302  *    |   mainA   |   |   mainB   |
6303  *    +-----------+   +-----------+
6304  *
6305  * We'll start relocating mainA, will find subA, append it and start
6306  * processing sub A recursively:
6307  *
6308  *    +-----------+------+
6309  *    |   mainA   | subA |
6310  *    +-----------+------+
6311  *
6312  * At this point we notice that subB is used from subA, so we append it and
6313  * relocate (there are no further subcalls from subB):
6314  *
6315  *    +-----------+------+------+
6316  *    |   mainA   | subA | subB |
6317  *    +-----------+------+------+
6318  *
6319  * At this point, we relocate subA calls, then go one level up and finish with
6320  * relocatin mainA calls. mainA is done.
6321  *
6322  * For mainB process is similar but results in different order. We start with
6323  * mainB and skip subA and subB, as mainB never calls them (at least
6324  * directly), but we see subC is needed, so we append and start processing it:
6325  *
6326  *    +-----------+------+
6327  *    |   mainB   | subC |
6328  *    +-----------+------+
6329  * Now we see subC needs subB, so we go back to it, append and relocate it:
6330  *
6331  *    +-----------+------+------+
6332  *    |   mainB   | subC | subB |
6333  *    +-----------+------+------+
6334  *
6335  * At this point we unwind recursion, relocate calls in subC, then in mainB.
6336  */
6337 static int
6338 bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
6339 {
6340 	struct bpf_program *subprog;
6341 	int i, err;
6342 
6343 	/* mark all subprogs as not relocated (yet) within the context of
6344 	 * current main program
6345 	 */
6346 	for (i = 0; i < obj->nr_programs; i++) {
6347 		subprog = &obj->programs[i];
6348 		if (!prog_is_subprog(obj, subprog))
6349 			continue;
6350 
6351 		subprog->sub_insn_off = 0;
6352 	}
6353 
6354 	err = bpf_object__reloc_code(obj, prog, prog);
6355 	if (err)
6356 		return err;
6357 
6358 	return 0;
6359 }
6360 
6361 static void
6362 bpf_object__free_relocs(struct bpf_object *obj)
6363 {
6364 	struct bpf_program *prog;
6365 	int i;
6366 
6367 	/* free up relocation descriptors */
6368 	for (i = 0; i < obj->nr_programs; i++) {
6369 		prog = &obj->programs[i];
6370 		zfree(&prog->reloc_desc);
6371 		prog->nr_reloc = 0;
6372 	}
6373 }
6374 
6375 static int cmp_relocs(const void *_a, const void *_b)
6376 {
6377 	const struct reloc_desc *a = _a;
6378 	const struct reloc_desc *b = _b;
6379 
6380 	if (a->insn_idx != b->insn_idx)
6381 		return a->insn_idx < b->insn_idx ? -1 : 1;
6382 
6383 	/* no two relocations should have the same insn_idx, but ... */
6384 	if (a->type != b->type)
6385 		return a->type < b->type ? -1 : 1;
6386 
6387 	return 0;
6388 }
6389 
6390 static void bpf_object__sort_relos(struct bpf_object *obj)
6391 {
6392 	int i;
6393 
6394 	for (i = 0; i < obj->nr_programs; i++) {
6395 		struct bpf_program *p = &obj->programs[i];
6396 
6397 		if (!p->nr_reloc)
6398 			continue;
6399 
6400 		qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
6401 	}
6402 }
6403 
6404 static int
6405 bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
6406 {
6407 	struct bpf_program *prog;
6408 	size_t i, j;
6409 	int err;
6410 
6411 	if (obj->btf_ext) {
6412 		err = bpf_object__relocate_core(obj, targ_btf_path);
6413 		if (err) {
6414 			pr_warn("failed to perform CO-RE relocations: %d\n",
6415 				err);
6416 			return err;
6417 		}
6418 		bpf_object__sort_relos(obj);
6419 	}
6420 
6421 	/* Before relocating calls pre-process relocations and mark
6422 	 * few ld_imm64 instructions that points to subprogs.
6423 	 * Otherwise bpf_object__reloc_code() later would have to consider
6424 	 * all ld_imm64 insns as relocation candidates. That would
6425 	 * reduce relocation speed, since amount of find_prog_insn_relo()
6426 	 * would increase and most of them will fail to find a relo.
6427 	 */
6428 	for (i = 0; i < obj->nr_programs; i++) {
6429 		prog = &obj->programs[i];
6430 		for (j = 0; j < prog->nr_reloc; j++) {
6431 			struct reloc_desc *relo = &prog->reloc_desc[j];
6432 			struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6433 
6434 			/* mark the insn, so it's recognized by insn_is_pseudo_func() */
6435 			if (relo->type == RELO_SUBPROG_ADDR)
6436 				insn[0].src_reg = BPF_PSEUDO_FUNC;
6437 		}
6438 	}
6439 
6440 	/* relocate subprogram calls and append used subprograms to main
6441 	 * programs; each copy of subprogram code needs to be relocated
6442 	 * differently for each main program, because its code location might
6443 	 * have changed.
6444 	 * Append subprog relos to main programs to allow data relos to be
6445 	 * processed after text is completely relocated.
6446 	 */
6447 	for (i = 0; i < obj->nr_programs; i++) {
6448 		prog = &obj->programs[i];
6449 		/* sub-program's sub-calls are relocated within the context of
6450 		 * its main program only
6451 		 */
6452 		if (prog_is_subprog(obj, prog))
6453 			continue;
6454 		if (!prog->autoload)
6455 			continue;
6456 
6457 		err = bpf_object__relocate_calls(obj, prog);
6458 		if (err) {
6459 			pr_warn("prog '%s': failed to relocate calls: %d\n",
6460 				prog->name, err);
6461 			return err;
6462 		}
6463 	}
6464 	/* Process data relos for main programs */
6465 	for (i = 0; i < obj->nr_programs; i++) {
6466 		prog = &obj->programs[i];
6467 		if (prog_is_subprog(obj, prog))
6468 			continue;
6469 		if (!prog->autoload)
6470 			continue;
6471 		err = bpf_object__relocate_data(obj, prog);
6472 		if (err) {
6473 			pr_warn("prog '%s': failed to relocate data references: %d\n",
6474 				prog->name, err);
6475 			return err;
6476 		}
6477 	}
6478 
6479 	return 0;
6480 }
6481 
6482 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
6483 					    Elf64_Shdr *shdr, Elf_Data *data);
6484 
6485 static int bpf_object__collect_map_relos(struct bpf_object *obj,
6486 					 Elf64_Shdr *shdr, Elf_Data *data)
6487 {
6488 	const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
6489 	int i, j, nrels, new_sz;
6490 	const struct btf_var_secinfo *vi = NULL;
6491 	const struct btf_type *sec, *var, *def;
6492 	struct bpf_map *map = NULL, *targ_map = NULL;
6493 	struct bpf_program *targ_prog = NULL;
6494 	bool is_prog_array, is_map_in_map;
6495 	const struct btf_member *member;
6496 	const char *name, *mname, *type;
6497 	unsigned int moff;
6498 	Elf64_Sym *sym;
6499 	Elf64_Rel *rel;
6500 	void *tmp;
6501 
6502 	if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
6503 		return -EINVAL;
6504 	sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
6505 	if (!sec)
6506 		return -EINVAL;
6507 
6508 	nrels = shdr->sh_size / shdr->sh_entsize;
6509 	for (i = 0; i < nrels; i++) {
6510 		rel = elf_rel_by_idx(data, i);
6511 		if (!rel) {
6512 			pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
6513 			return -LIBBPF_ERRNO__FORMAT;
6514 		}
6515 
6516 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
6517 		if (!sym) {
6518 			pr_warn(".maps relo #%d: symbol %zx not found\n",
6519 				i, (size_t)ELF64_R_SYM(rel->r_info));
6520 			return -LIBBPF_ERRNO__FORMAT;
6521 		}
6522 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
6523 
6524 		pr_debug(".maps relo #%d: for %zd value %zd rel->r_offset %zu name %d ('%s')\n",
6525 			 i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
6526 			 (size_t)rel->r_offset, sym->st_name, name);
6527 
6528 		for (j = 0; j < obj->nr_maps; j++) {
6529 			map = &obj->maps[j];
6530 			if (map->sec_idx != obj->efile.btf_maps_shndx)
6531 				continue;
6532 
6533 			vi = btf_var_secinfos(sec) + map->btf_var_idx;
6534 			if (vi->offset <= rel->r_offset &&
6535 			    rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size)
6536 				break;
6537 		}
6538 		if (j == obj->nr_maps) {
6539 			pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
6540 				i, name, (size_t)rel->r_offset);
6541 			return -EINVAL;
6542 		}
6543 
6544 		is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
6545 		is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
6546 		type = is_map_in_map ? "map" : "prog";
6547 		if (is_map_in_map) {
6548 			if (sym->st_shndx != obj->efile.btf_maps_shndx) {
6549 				pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
6550 					i, name);
6551 				return -LIBBPF_ERRNO__RELOC;
6552 			}
6553 			if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
6554 			    map->def.key_size != sizeof(int)) {
6555 				pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
6556 					i, map->name, sizeof(int));
6557 				return -EINVAL;
6558 			}
6559 			targ_map = bpf_object__find_map_by_name(obj, name);
6560 			if (!targ_map) {
6561 				pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
6562 					i, name);
6563 				return -ESRCH;
6564 			}
6565 		} else if (is_prog_array) {
6566 			targ_prog = bpf_object__find_program_by_name(obj, name);
6567 			if (!targ_prog) {
6568 				pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
6569 					i, name);
6570 				return -ESRCH;
6571 			}
6572 			if (targ_prog->sec_idx != sym->st_shndx ||
6573 			    targ_prog->sec_insn_off * 8 != sym->st_value ||
6574 			    prog_is_subprog(obj, targ_prog)) {
6575 				pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
6576 					i, name);
6577 				return -LIBBPF_ERRNO__RELOC;
6578 			}
6579 		} else {
6580 			return -EINVAL;
6581 		}
6582 
6583 		var = btf__type_by_id(obj->btf, vi->type);
6584 		def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
6585 		if (btf_vlen(def) == 0)
6586 			return -EINVAL;
6587 		member = btf_members(def) + btf_vlen(def) - 1;
6588 		mname = btf__name_by_offset(obj->btf, member->name_off);
6589 		if (strcmp(mname, "values"))
6590 			return -EINVAL;
6591 
6592 		moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
6593 		if (rel->r_offset - vi->offset < moff)
6594 			return -EINVAL;
6595 
6596 		moff = rel->r_offset - vi->offset - moff;
6597 		/* here we use BPF pointer size, which is always 64 bit, as we
6598 		 * are parsing ELF that was built for BPF target
6599 		 */
6600 		if (moff % bpf_ptr_sz)
6601 			return -EINVAL;
6602 		moff /= bpf_ptr_sz;
6603 		if (moff >= map->init_slots_sz) {
6604 			new_sz = moff + 1;
6605 			tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
6606 			if (!tmp)
6607 				return -ENOMEM;
6608 			map->init_slots = tmp;
6609 			memset(map->init_slots + map->init_slots_sz, 0,
6610 			       (new_sz - map->init_slots_sz) * host_ptr_sz);
6611 			map->init_slots_sz = new_sz;
6612 		}
6613 		map->init_slots[moff] = is_map_in_map ? (void *)targ_map : (void *)targ_prog;
6614 
6615 		pr_debug(".maps relo #%d: map '%s' slot [%d] points to %s '%s'\n",
6616 			 i, map->name, moff, type, name);
6617 	}
6618 
6619 	return 0;
6620 }
6621 
6622 static int bpf_object__collect_relos(struct bpf_object *obj)
6623 {
6624 	int i, err;
6625 
6626 	for (i = 0; i < obj->efile.sec_cnt; i++) {
6627 		struct elf_sec_desc *sec_desc = &obj->efile.secs[i];
6628 		Elf64_Shdr *shdr;
6629 		Elf_Data *data;
6630 		int idx;
6631 
6632 		if (sec_desc->sec_type != SEC_RELO)
6633 			continue;
6634 
6635 		shdr = sec_desc->shdr;
6636 		data = sec_desc->data;
6637 		idx = shdr->sh_info;
6638 
6639 		if (shdr->sh_type != SHT_REL) {
6640 			pr_warn("internal error at %d\n", __LINE__);
6641 			return -LIBBPF_ERRNO__INTERNAL;
6642 		}
6643 
6644 		if (idx == obj->efile.st_ops_shndx)
6645 			err = bpf_object__collect_st_ops_relos(obj, shdr, data);
6646 		else if (idx == obj->efile.btf_maps_shndx)
6647 			err = bpf_object__collect_map_relos(obj, shdr, data);
6648 		else
6649 			err = bpf_object__collect_prog_relos(obj, shdr, data);
6650 		if (err)
6651 			return err;
6652 	}
6653 
6654 	bpf_object__sort_relos(obj);
6655 	return 0;
6656 }
6657 
6658 static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
6659 {
6660 	if (BPF_CLASS(insn->code) == BPF_JMP &&
6661 	    BPF_OP(insn->code) == BPF_CALL &&
6662 	    BPF_SRC(insn->code) == BPF_K &&
6663 	    insn->src_reg == 0 &&
6664 	    insn->dst_reg == 0) {
6665 		    *func_id = insn->imm;
6666 		    return true;
6667 	}
6668 	return false;
6669 }
6670 
6671 static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
6672 {
6673 	struct bpf_insn *insn = prog->insns;
6674 	enum bpf_func_id func_id;
6675 	int i;
6676 
6677 	if (obj->gen_loader)
6678 		return 0;
6679 
6680 	for (i = 0; i < prog->insns_cnt; i++, insn++) {
6681 		if (!insn_is_helper_call(insn, &func_id))
6682 			continue;
6683 
6684 		/* on kernels that don't yet support
6685 		 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
6686 		 * to bpf_probe_read() which works well for old kernels
6687 		 */
6688 		switch (func_id) {
6689 		case BPF_FUNC_probe_read_kernel:
6690 		case BPF_FUNC_probe_read_user:
6691 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6692 				insn->imm = BPF_FUNC_probe_read;
6693 			break;
6694 		case BPF_FUNC_probe_read_kernel_str:
6695 		case BPF_FUNC_probe_read_user_str:
6696 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6697 				insn->imm = BPF_FUNC_probe_read_str;
6698 			break;
6699 		default:
6700 			break;
6701 		}
6702 	}
6703 	return 0;
6704 }
6705 
6706 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
6707 				     int *btf_obj_fd, int *btf_type_id);
6708 
6709 /* this is called as prog->sec_def->prog_prepare_load_fn for libbpf-supported sec_defs */
6710 static int libbpf_prepare_prog_load(struct bpf_program *prog,
6711 				    struct bpf_prog_load_opts *opts, long cookie)
6712 {
6713 	enum sec_def_flags def = cookie;
6714 
6715 	/* old kernels might not support specifying expected_attach_type */
6716 	if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
6717 		opts->expected_attach_type = 0;
6718 
6719 	if (def & SEC_SLEEPABLE)
6720 		opts->prog_flags |= BPF_F_SLEEPABLE;
6721 
6722 	if (prog->type == BPF_PROG_TYPE_XDP && (def & SEC_XDP_FRAGS))
6723 		opts->prog_flags |= BPF_F_XDP_HAS_FRAGS;
6724 
6725 	if ((def & SEC_ATTACH_BTF) && !prog->attach_btf_id) {
6726 		int btf_obj_fd = 0, btf_type_id = 0, err;
6727 		const char *attach_name;
6728 
6729 		attach_name = strchr(prog->sec_name, '/');
6730 		if (!attach_name) {
6731 			/* if BPF program is annotated with just SEC("fentry")
6732 			 * (or similar) without declaratively specifying
6733 			 * target, then it is expected that target will be
6734 			 * specified with bpf_program__set_attach_target() at
6735 			 * runtime before BPF object load step. If not, then
6736 			 * there is nothing to load into the kernel as BPF
6737 			 * verifier won't be able to validate BPF program
6738 			 * correctness anyways.
6739 			 */
6740 			pr_warn("prog '%s': no BTF-based attach target is specified, use bpf_program__set_attach_target()\n",
6741 				prog->name);
6742 			return -EINVAL;
6743 		}
6744 		attach_name++; /* skip over / */
6745 
6746 		err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
6747 		if (err)
6748 			return err;
6749 
6750 		/* cache resolved BTF FD and BTF type ID in the prog */
6751 		prog->attach_btf_obj_fd = btf_obj_fd;
6752 		prog->attach_btf_id = btf_type_id;
6753 
6754 		/* but by now libbpf common logic is not utilizing
6755 		 * prog->atach_btf_obj_fd/prog->attach_btf_id anymore because
6756 		 * this callback is called after opts were populated by
6757 		 * libbpf, so this callback has to update opts explicitly here
6758 		 */
6759 		opts->attach_btf_obj_fd = btf_obj_fd;
6760 		opts->attach_btf_id = btf_type_id;
6761 	}
6762 	return 0;
6763 }
6764 
6765 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz);
6766 
6767 static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
6768 				struct bpf_insn *insns, int insns_cnt,
6769 				const char *license, __u32 kern_version, int *prog_fd)
6770 {
6771 	LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
6772 	const char *prog_name = NULL;
6773 	char *cp, errmsg[STRERR_BUFSIZE];
6774 	size_t log_buf_size = 0;
6775 	char *log_buf = NULL, *tmp;
6776 	int btf_fd, ret, err;
6777 	bool own_log_buf = true;
6778 	__u32 log_level = prog->log_level;
6779 
6780 	if (prog->type == BPF_PROG_TYPE_UNSPEC) {
6781 		/*
6782 		 * The program type must be set.  Most likely we couldn't find a proper
6783 		 * section definition at load time, and thus we didn't infer the type.
6784 		 */
6785 		pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
6786 			prog->name, prog->sec_name);
6787 		return -EINVAL;
6788 	}
6789 
6790 	if (!insns || !insns_cnt)
6791 		return -EINVAL;
6792 
6793 	load_attr.expected_attach_type = prog->expected_attach_type;
6794 	if (kernel_supports(obj, FEAT_PROG_NAME))
6795 		prog_name = prog->name;
6796 	load_attr.attach_prog_fd = prog->attach_prog_fd;
6797 	load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
6798 	load_attr.attach_btf_id = prog->attach_btf_id;
6799 	load_attr.kern_version = kern_version;
6800 	load_attr.prog_ifindex = prog->prog_ifindex;
6801 
6802 	/* specify func_info/line_info only if kernel supports them */
6803 	btf_fd = bpf_object__btf_fd(obj);
6804 	if (btf_fd >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
6805 		load_attr.prog_btf_fd = btf_fd;
6806 		load_attr.func_info = prog->func_info;
6807 		load_attr.func_info_rec_size = prog->func_info_rec_size;
6808 		load_attr.func_info_cnt = prog->func_info_cnt;
6809 		load_attr.line_info = prog->line_info;
6810 		load_attr.line_info_rec_size = prog->line_info_rec_size;
6811 		load_attr.line_info_cnt = prog->line_info_cnt;
6812 	}
6813 	load_attr.log_level = log_level;
6814 	load_attr.prog_flags = prog->prog_flags;
6815 	load_attr.fd_array = obj->fd_array;
6816 
6817 	/* adjust load_attr if sec_def provides custom preload callback */
6818 	if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
6819 		err = prog->sec_def->prog_prepare_load_fn(prog, &load_attr, prog->sec_def->cookie);
6820 		if (err < 0) {
6821 			pr_warn("prog '%s': failed to prepare load attributes: %d\n",
6822 				prog->name, err);
6823 			return err;
6824 		}
6825 		insns = prog->insns;
6826 		insns_cnt = prog->insns_cnt;
6827 	}
6828 
6829 	if (obj->gen_loader) {
6830 		bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
6831 				   license, insns, insns_cnt, &load_attr,
6832 				   prog - obj->programs);
6833 		*prog_fd = -1;
6834 		return 0;
6835 	}
6836 
6837 retry_load:
6838 	/* if log_level is zero, we don't request logs initially even if
6839 	 * custom log_buf is specified; if the program load fails, then we'll
6840 	 * bump log_level to 1 and use either custom log_buf or we'll allocate
6841 	 * our own and retry the load to get details on what failed
6842 	 */
6843 	if (log_level) {
6844 		if (prog->log_buf) {
6845 			log_buf = prog->log_buf;
6846 			log_buf_size = prog->log_size;
6847 			own_log_buf = false;
6848 		} else if (obj->log_buf) {
6849 			log_buf = obj->log_buf;
6850 			log_buf_size = obj->log_size;
6851 			own_log_buf = false;
6852 		} else {
6853 			log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
6854 			tmp = realloc(log_buf, log_buf_size);
6855 			if (!tmp) {
6856 				ret = -ENOMEM;
6857 				goto out;
6858 			}
6859 			log_buf = tmp;
6860 			log_buf[0] = '\0';
6861 			own_log_buf = true;
6862 		}
6863 	}
6864 
6865 	load_attr.log_buf = log_buf;
6866 	load_attr.log_size = log_buf_size;
6867 	load_attr.log_level = log_level;
6868 
6869 	ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
6870 	if (ret >= 0) {
6871 		if (log_level && own_log_buf) {
6872 			pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
6873 				 prog->name, log_buf);
6874 		}
6875 
6876 		if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
6877 			struct bpf_map *map;
6878 			int i;
6879 
6880 			for (i = 0; i < obj->nr_maps; i++) {
6881 				map = &prog->obj->maps[i];
6882 				if (map->libbpf_type != LIBBPF_MAP_RODATA)
6883 					continue;
6884 
6885 				if (bpf_prog_bind_map(ret, bpf_map__fd(map), NULL)) {
6886 					cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
6887 					pr_warn("prog '%s': failed to bind map '%s': %s\n",
6888 						prog->name, map->real_name, cp);
6889 					/* Don't fail hard if can't bind rodata. */
6890 				}
6891 			}
6892 		}
6893 
6894 		*prog_fd = ret;
6895 		ret = 0;
6896 		goto out;
6897 	}
6898 
6899 	if (log_level == 0) {
6900 		log_level = 1;
6901 		goto retry_load;
6902 	}
6903 	/* On ENOSPC, increase log buffer size and retry, unless custom
6904 	 * log_buf is specified.
6905 	 * Be careful to not overflow u32, though. Kernel's log buf size limit
6906 	 * isn't part of UAPI so it can always be bumped to full 4GB. So don't
6907 	 * multiply by 2 unless we are sure we'll fit within 32 bits.
6908 	 * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
6909 	 */
6910 	if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
6911 		goto retry_load;
6912 
6913 	ret = -errno;
6914 
6915 	/* post-process verifier log to improve error descriptions */
6916 	fixup_verifier_log(prog, log_buf, log_buf_size);
6917 
6918 	cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
6919 	pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, cp);
6920 	pr_perm_msg(ret);
6921 
6922 	if (own_log_buf && log_buf && log_buf[0] != '\0') {
6923 		pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
6924 			prog->name, log_buf);
6925 	}
6926 
6927 out:
6928 	if (own_log_buf)
6929 		free(log_buf);
6930 	return ret;
6931 }
6932 
6933 static char *find_prev_line(char *buf, char *cur)
6934 {
6935 	char *p;
6936 
6937 	if (cur == buf) /* end of a log buf */
6938 		return NULL;
6939 
6940 	p = cur - 1;
6941 	while (p - 1 >= buf && *(p - 1) != '\n')
6942 		p--;
6943 
6944 	return p;
6945 }
6946 
6947 static void patch_log(char *buf, size_t buf_sz, size_t log_sz,
6948 		      char *orig, size_t orig_sz, const char *patch)
6949 {
6950 	/* size of the remaining log content to the right from the to-be-replaced part */
6951 	size_t rem_sz = (buf + log_sz) - (orig + orig_sz);
6952 	size_t patch_sz = strlen(patch);
6953 
6954 	if (patch_sz != orig_sz) {
6955 		/* If patch line(s) are longer than original piece of verifier log,
6956 		 * shift log contents by (patch_sz - orig_sz) bytes to the right
6957 		 * starting from after to-be-replaced part of the log.
6958 		 *
6959 		 * If patch line(s) are shorter than original piece of verifier log,
6960 		 * shift log contents by (orig_sz - patch_sz) bytes to the left
6961 		 * starting from after to-be-replaced part of the log
6962 		 *
6963 		 * We need to be careful about not overflowing available
6964 		 * buf_sz capacity. If that's the case, we'll truncate the end
6965 		 * of the original log, as necessary.
6966 		 */
6967 		if (patch_sz > orig_sz) {
6968 			if (orig + patch_sz >= buf + buf_sz) {
6969 				/* patch is big enough to cover remaining space completely */
6970 				patch_sz -= (orig + patch_sz) - (buf + buf_sz) + 1;
6971 				rem_sz = 0;
6972 			} else if (patch_sz - orig_sz > buf_sz - log_sz) {
6973 				/* patch causes part of remaining log to be truncated */
6974 				rem_sz -= (patch_sz - orig_sz) - (buf_sz - log_sz);
6975 			}
6976 		}
6977 		/* shift remaining log to the right by calculated amount */
6978 		memmove(orig + patch_sz, orig + orig_sz, rem_sz);
6979 	}
6980 
6981 	memcpy(orig, patch, patch_sz);
6982 }
6983 
6984 static void fixup_log_failed_core_relo(struct bpf_program *prog,
6985 				       char *buf, size_t buf_sz, size_t log_sz,
6986 				       char *line1, char *line2, char *line3)
6987 {
6988 	/* Expected log for failed and not properly guarded CO-RE relocation:
6989 	 * line1 -> 123: (85) call unknown#195896080
6990 	 * line2 -> invalid func unknown#195896080
6991 	 * line3 -> <anything else or end of buffer>
6992 	 *
6993 	 * "123" is the index of the instruction that was poisoned. We extract
6994 	 * instruction index to find corresponding CO-RE relocation and
6995 	 * replace this part of the log with more relevant information about
6996 	 * failed CO-RE relocation.
6997 	 */
6998 	const struct bpf_core_relo *relo;
6999 	struct bpf_core_spec spec;
7000 	char patch[512], spec_buf[256];
7001 	int insn_idx, err, spec_len;
7002 
7003 	if (sscanf(line1, "%d: (%*d) call unknown#195896080\n", &insn_idx) != 1)
7004 		return;
7005 
7006 	relo = find_relo_core(prog, insn_idx);
7007 	if (!relo)
7008 		return;
7009 
7010 	err = bpf_core_parse_spec(prog->name, prog->obj->btf, relo, &spec);
7011 	if (err)
7012 		return;
7013 
7014 	spec_len = bpf_core_format_spec(spec_buf, sizeof(spec_buf), &spec);
7015 	snprintf(patch, sizeof(patch),
7016 		 "%d: <invalid CO-RE relocation>\n"
7017 		 "failed to resolve CO-RE relocation %s%s\n",
7018 		 insn_idx, spec_buf, spec_len >= sizeof(spec_buf) ? "..." : "");
7019 
7020 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7021 }
7022 
7023 static void fixup_log_missing_map_load(struct bpf_program *prog,
7024 				       char *buf, size_t buf_sz, size_t log_sz,
7025 				       char *line1, char *line2, char *line3)
7026 {
7027 	/* Expected log for failed and not properly guarded CO-RE relocation:
7028 	 * line1 -> 123: (85) call unknown#2001000345
7029 	 * line2 -> invalid func unknown#2001000345
7030 	 * line3 -> <anything else or end of buffer>
7031 	 *
7032 	 * "123" is the index of the instruction that was poisoned.
7033 	 * "345" in "2001000345" are map index in obj->maps to fetch map name.
7034 	 */
7035 	struct bpf_object *obj = prog->obj;
7036 	const struct bpf_map *map;
7037 	int insn_idx, map_idx;
7038 	char patch[128];
7039 
7040 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &map_idx) != 2)
7041 		return;
7042 
7043 	map_idx -= MAP_LDIMM64_POISON_BASE;
7044 	if (map_idx < 0 || map_idx >= obj->nr_maps)
7045 		return;
7046 	map = &obj->maps[map_idx];
7047 
7048 	snprintf(patch, sizeof(patch),
7049 		 "%d: <invalid BPF map reference>\n"
7050 		 "BPF map '%s' is referenced but wasn't created\n",
7051 		 insn_idx, map->name);
7052 
7053 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7054 }
7055 
7056 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz)
7057 {
7058 	/* look for familiar error patterns in last N lines of the log */
7059 	const size_t max_last_line_cnt = 10;
7060 	char *prev_line, *cur_line, *next_line;
7061 	size_t log_sz;
7062 	int i;
7063 
7064 	if (!buf)
7065 		return;
7066 
7067 	log_sz = strlen(buf) + 1;
7068 	next_line = buf + log_sz - 1;
7069 
7070 	for (i = 0; i < max_last_line_cnt; i++, next_line = cur_line) {
7071 		cur_line = find_prev_line(buf, next_line);
7072 		if (!cur_line)
7073 			return;
7074 
7075 		/* failed CO-RE relocation case */
7076 		if (str_has_pfx(cur_line, "invalid func unknown#195896080\n")) {
7077 			prev_line = find_prev_line(buf, cur_line);
7078 			if (!prev_line)
7079 				continue;
7080 
7081 			fixup_log_failed_core_relo(prog, buf, buf_sz, log_sz,
7082 						   prev_line, cur_line, next_line);
7083 			return;
7084 		} else if (str_has_pfx(cur_line, "invalid func unknown#"MAP_LDIMM64_POISON_PFX)) {
7085 			prev_line = find_prev_line(buf, cur_line);
7086 			if (!prev_line)
7087 				continue;
7088 
7089 			fixup_log_missing_map_load(prog, buf, buf_sz, log_sz,
7090 						   prev_line, cur_line, next_line);
7091 			return;
7092 		}
7093 	}
7094 }
7095 
7096 static int bpf_program_record_relos(struct bpf_program *prog)
7097 {
7098 	struct bpf_object *obj = prog->obj;
7099 	int i;
7100 
7101 	for (i = 0; i < prog->nr_reloc; i++) {
7102 		struct reloc_desc *relo = &prog->reloc_desc[i];
7103 		struct extern_desc *ext = &obj->externs[relo->sym_off];
7104 
7105 		switch (relo->type) {
7106 		case RELO_EXTERN_VAR:
7107 			if (ext->type != EXT_KSYM)
7108 				continue;
7109 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7110 					       ext->is_weak, !ext->ksym.type_id,
7111 					       BTF_KIND_VAR, relo->insn_idx);
7112 			break;
7113 		case RELO_EXTERN_FUNC:
7114 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7115 					       ext->is_weak, false, BTF_KIND_FUNC,
7116 					       relo->insn_idx);
7117 			break;
7118 		case RELO_CORE: {
7119 			struct bpf_core_relo cr = {
7120 				.insn_off = relo->insn_idx * 8,
7121 				.type_id = relo->core_relo->type_id,
7122 				.access_str_off = relo->core_relo->access_str_off,
7123 				.kind = relo->core_relo->kind,
7124 			};
7125 
7126 			bpf_gen__record_relo_core(obj->gen_loader, &cr);
7127 			break;
7128 		}
7129 		default:
7130 			continue;
7131 		}
7132 	}
7133 	return 0;
7134 }
7135 
7136 static int
7137 bpf_object__load_progs(struct bpf_object *obj, int log_level)
7138 {
7139 	struct bpf_program *prog;
7140 	size_t i;
7141 	int err;
7142 
7143 	for (i = 0; i < obj->nr_programs; i++) {
7144 		prog = &obj->programs[i];
7145 		err = bpf_object__sanitize_prog(obj, prog);
7146 		if (err)
7147 			return err;
7148 	}
7149 
7150 	for (i = 0; i < obj->nr_programs; i++) {
7151 		prog = &obj->programs[i];
7152 		if (prog_is_subprog(obj, prog))
7153 			continue;
7154 		if (!prog->autoload) {
7155 			pr_debug("prog '%s': skipped loading\n", prog->name);
7156 			continue;
7157 		}
7158 		prog->log_level |= log_level;
7159 
7160 		if (obj->gen_loader)
7161 			bpf_program_record_relos(prog);
7162 
7163 		err = bpf_object_load_prog(obj, prog, prog->insns, prog->insns_cnt,
7164 					   obj->license, obj->kern_version, &prog->fd);
7165 		if (err) {
7166 			pr_warn("prog '%s': failed to load: %d\n", prog->name, err);
7167 			return err;
7168 		}
7169 	}
7170 
7171 	bpf_object__free_relocs(obj);
7172 	return 0;
7173 }
7174 
7175 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
7176 
7177 static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
7178 {
7179 	struct bpf_program *prog;
7180 	int err;
7181 
7182 	bpf_object__for_each_program(prog, obj) {
7183 		prog->sec_def = find_sec_def(prog->sec_name);
7184 		if (!prog->sec_def) {
7185 			/* couldn't guess, but user might manually specify */
7186 			pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
7187 				prog->name, prog->sec_name);
7188 			continue;
7189 		}
7190 
7191 		prog->type = prog->sec_def->prog_type;
7192 		prog->expected_attach_type = prog->sec_def->expected_attach_type;
7193 
7194 		/* sec_def can have custom callback which should be called
7195 		 * after bpf_program is initialized to adjust its properties
7196 		 */
7197 		if (prog->sec_def->prog_setup_fn) {
7198 			err = prog->sec_def->prog_setup_fn(prog, prog->sec_def->cookie);
7199 			if (err < 0) {
7200 				pr_warn("prog '%s': failed to initialize: %d\n",
7201 					prog->name, err);
7202 				return err;
7203 			}
7204 		}
7205 	}
7206 
7207 	return 0;
7208 }
7209 
7210 static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
7211 					  const struct bpf_object_open_opts *opts)
7212 {
7213 	const char *obj_name, *kconfig, *btf_tmp_path;
7214 	struct bpf_object *obj;
7215 	char tmp_name[64];
7216 	int err;
7217 	char *log_buf;
7218 	size_t log_size;
7219 	__u32 log_level;
7220 
7221 	if (elf_version(EV_CURRENT) == EV_NONE) {
7222 		pr_warn("failed to init libelf for %s\n",
7223 			path ? : "(mem buf)");
7224 		return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
7225 	}
7226 
7227 	if (!OPTS_VALID(opts, bpf_object_open_opts))
7228 		return ERR_PTR(-EINVAL);
7229 
7230 	obj_name = OPTS_GET(opts, object_name, NULL);
7231 	if (obj_buf) {
7232 		if (!obj_name) {
7233 			snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
7234 				 (unsigned long)obj_buf,
7235 				 (unsigned long)obj_buf_sz);
7236 			obj_name = tmp_name;
7237 		}
7238 		path = obj_name;
7239 		pr_debug("loading object '%s' from buffer\n", obj_name);
7240 	}
7241 
7242 	log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
7243 	log_size = OPTS_GET(opts, kernel_log_size, 0);
7244 	log_level = OPTS_GET(opts, kernel_log_level, 0);
7245 	if (log_size > UINT_MAX)
7246 		return ERR_PTR(-EINVAL);
7247 	if (log_size && !log_buf)
7248 		return ERR_PTR(-EINVAL);
7249 
7250 	obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
7251 	if (IS_ERR(obj))
7252 		return obj;
7253 
7254 	obj->log_buf = log_buf;
7255 	obj->log_size = log_size;
7256 	obj->log_level = log_level;
7257 
7258 	btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
7259 	if (btf_tmp_path) {
7260 		if (strlen(btf_tmp_path) >= PATH_MAX) {
7261 			err = -ENAMETOOLONG;
7262 			goto out;
7263 		}
7264 		obj->btf_custom_path = strdup(btf_tmp_path);
7265 		if (!obj->btf_custom_path) {
7266 			err = -ENOMEM;
7267 			goto out;
7268 		}
7269 	}
7270 
7271 	kconfig = OPTS_GET(opts, kconfig, NULL);
7272 	if (kconfig) {
7273 		obj->kconfig = strdup(kconfig);
7274 		if (!obj->kconfig) {
7275 			err = -ENOMEM;
7276 			goto out;
7277 		}
7278 	}
7279 
7280 	err = bpf_object__elf_init(obj);
7281 	err = err ? : bpf_object__check_endianness(obj);
7282 	err = err ? : bpf_object__elf_collect(obj);
7283 	err = err ? : bpf_object__collect_externs(obj);
7284 	err = err ? : bpf_object_fixup_btf(obj);
7285 	err = err ? : bpf_object__init_maps(obj, opts);
7286 	err = err ? : bpf_object_init_progs(obj, opts);
7287 	err = err ? : bpf_object__collect_relos(obj);
7288 	if (err)
7289 		goto out;
7290 
7291 	bpf_object__elf_finish(obj);
7292 
7293 	return obj;
7294 out:
7295 	bpf_object__close(obj);
7296 	return ERR_PTR(err);
7297 }
7298 
7299 struct bpf_object *
7300 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
7301 {
7302 	if (!path)
7303 		return libbpf_err_ptr(-EINVAL);
7304 
7305 	pr_debug("loading %s\n", path);
7306 
7307 	return libbpf_ptr(bpf_object_open(path, NULL, 0, opts));
7308 }
7309 
7310 struct bpf_object *bpf_object__open(const char *path)
7311 {
7312 	return bpf_object__open_file(path, NULL);
7313 }
7314 
7315 struct bpf_object *
7316 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
7317 		     const struct bpf_object_open_opts *opts)
7318 {
7319 	if (!obj_buf || obj_buf_sz == 0)
7320 		return libbpf_err_ptr(-EINVAL);
7321 
7322 	return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, opts));
7323 }
7324 
7325 static int bpf_object_unload(struct bpf_object *obj)
7326 {
7327 	size_t i;
7328 
7329 	if (!obj)
7330 		return libbpf_err(-EINVAL);
7331 
7332 	for (i = 0; i < obj->nr_maps; i++) {
7333 		zclose(obj->maps[i].fd);
7334 		if (obj->maps[i].st_ops)
7335 			zfree(&obj->maps[i].st_ops->kern_vdata);
7336 	}
7337 
7338 	for (i = 0; i < obj->nr_programs; i++)
7339 		bpf_program__unload(&obj->programs[i]);
7340 
7341 	return 0;
7342 }
7343 
7344 static int bpf_object__sanitize_maps(struct bpf_object *obj)
7345 {
7346 	struct bpf_map *m;
7347 
7348 	bpf_object__for_each_map(m, obj) {
7349 		if (!bpf_map__is_internal(m))
7350 			continue;
7351 		if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
7352 			m->def.map_flags ^= BPF_F_MMAPABLE;
7353 	}
7354 
7355 	return 0;
7356 }
7357 
7358 int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
7359 {
7360 	char sym_type, sym_name[500];
7361 	unsigned long long sym_addr;
7362 	int ret, err = 0;
7363 	FILE *f;
7364 
7365 	f = fopen("/proc/kallsyms", "r");
7366 	if (!f) {
7367 		err = -errno;
7368 		pr_warn("failed to open /proc/kallsyms: %d\n", err);
7369 		return err;
7370 	}
7371 
7372 	while (true) {
7373 		ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
7374 			     &sym_addr, &sym_type, sym_name);
7375 		if (ret == EOF && feof(f))
7376 			break;
7377 		if (ret != 3) {
7378 			pr_warn("failed to read kallsyms entry: %d\n", ret);
7379 			err = -EINVAL;
7380 			break;
7381 		}
7382 
7383 		err = cb(sym_addr, sym_type, sym_name, ctx);
7384 		if (err)
7385 			break;
7386 	}
7387 
7388 	fclose(f);
7389 	return err;
7390 }
7391 
7392 static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
7393 		       const char *sym_name, void *ctx)
7394 {
7395 	struct bpf_object *obj = ctx;
7396 	const struct btf_type *t;
7397 	struct extern_desc *ext;
7398 
7399 	ext = find_extern_by_name(obj, sym_name);
7400 	if (!ext || ext->type != EXT_KSYM)
7401 		return 0;
7402 
7403 	t = btf__type_by_id(obj->btf, ext->btf_id);
7404 	if (!btf_is_var(t))
7405 		return 0;
7406 
7407 	if (ext->is_set && ext->ksym.addr != sym_addr) {
7408 		pr_warn("extern (ksym) '%s': resolution is ambiguous: 0x%llx or 0x%llx\n",
7409 			sym_name, ext->ksym.addr, sym_addr);
7410 		return -EINVAL;
7411 	}
7412 	if (!ext->is_set) {
7413 		ext->is_set = true;
7414 		ext->ksym.addr = sym_addr;
7415 		pr_debug("extern (ksym) '%s': set to 0x%llx\n", sym_name, sym_addr);
7416 	}
7417 	return 0;
7418 }
7419 
7420 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
7421 {
7422 	return libbpf_kallsyms_parse(kallsyms_cb, obj);
7423 }
7424 
7425 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
7426 			    __u16 kind, struct btf **res_btf,
7427 			    struct module_btf **res_mod_btf)
7428 {
7429 	struct module_btf *mod_btf;
7430 	struct btf *btf;
7431 	int i, id, err;
7432 
7433 	btf = obj->btf_vmlinux;
7434 	mod_btf = NULL;
7435 	id = btf__find_by_name_kind(btf, ksym_name, kind);
7436 
7437 	if (id == -ENOENT) {
7438 		err = load_module_btfs(obj);
7439 		if (err)
7440 			return err;
7441 
7442 		for (i = 0; i < obj->btf_module_cnt; i++) {
7443 			/* we assume module_btf's BTF FD is always >0 */
7444 			mod_btf = &obj->btf_modules[i];
7445 			btf = mod_btf->btf;
7446 			id = btf__find_by_name_kind_own(btf, ksym_name, kind);
7447 			if (id != -ENOENT)
7448 				break;
7449 		}
7450 	}
7451 	if (id <= 0)
7452 		return -ESRCH;
7453 
7454 	*res_btf = btf;
7455 	*res_mod_btf = mod_btf;
7456 	return id;
7457 }
7458 
7459 static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
7460 					       struct extern_desc *ext)
7461 {
7462 	const struct btf_type *targ_var, *targ_type;
7463 	__u32 targ_type_id, local_type_id;
7464 	struct module_btf *mod_btf = NULL;
7465 	const char *targ_var_name;
7466 	struct btf *btf = NULL;
7467 	int id, err;
7468 
7469 	id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
7470 	if (id < 0) {
7471 		if (id == -ESRCH && ext->is_weak)
7472 			return 0;
7473 		pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
7474 			ext->name);
7475 		return id;
7476 	}
7477 
7478 	/* find local type_id */
7479 	local_type_id = ext->ksym.type_id;
7480 
7481 	/* find target type_id */
7482 	targ_var = btf__type_by_id(btf, id);
7483 	targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
7484 	targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
7485 
7486 	err = bpf_core_types_are_compat(obj->btf, local_type_id,
7487 					btf, targ_type_id);
7488 	if (err <= 0) {
7489 		const struct btf_type *local_type;
7490 		const char *targ_name, *local_name;
7491 
7492 		local_type = btf__type_by_id(obj->btf, local_type_id);
7493 		local_name = btf__name_by_offset(obj->btf, local_type->name_off);
7494 		targ_name = btf__name_by_offset(btf, targ_type->name_off);
7495 
7496 		pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
7497 			ext->name, local_type_id,
7498 			btf_kind_str(local_type), local_name, targ_type_id,
7499 			btf_kind_str(targ_type), targ_name);
7500 		return -EINVAL;
7501 	}
7502 
7503 	ext->is_set = true;
7504 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
7505 	ext->ksym.kernel_btf_id = id;
7506 	pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
7507 		 ext->name, id, btf_kind_str(targ_var), targ_var_name);
7508 
7509 	return 0;
7510 }
7511 
7512 static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
7513 						struct extern_desc *ext)
7514 {
7515 	int local_func_proto_id, kfunc_proto_id, kfunc_id;
7516 	struct module_btf *mod_btf = NULL;
7517 	const struct btf_type *kern_func;
7518 	struct btf *kern_btf = NULL;
7519 	int ret;
7520 
7521 	local_func_proto_id = ext->ksym.type_id;
7522 
7523 	kfunc_id = find_ksym_btf_id(obj, ext->name, BTF_KIND_FUNC, &kern_btf, &mod_btf);
7524 	if (kfunc_id < 0) {
7525 		if (kfunc_id == -ESRCH && ext->is_weak)
7526 			return 0;
7527 		pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
7528 			ext->name);
7529 		return kfunc_id;
7530 	}
7531 
7532 	kern_func = btf__type_by_id(kern_btf, kfunc_id);
7533 	kfunc_proto_id = kern_func->type;
7534 
7535 	ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
7536 					kern_btf, kfunc_proto_id);
7537 	if (ret <= 0) {
7538 		pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with kernel [%d]\n",
7539 			ext->name, local_func_proto_id, kfunc_proto_id);
7540 		return -EINVAL;
7541 	}
7542 
7543 	/* set index for module BTF fd in fd_array, if unset */
7544 	if (mod_btf && !mod_btf->fd_array_idx) {
7545 		/* insn->off is s16 */
7546 		if (obj->fd_array_cnt == INT16_MAX) {
7547 			pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
7548 				ext->name, mod_btf->fd_array_idx);
7549 			return -E2BIG;
7550 		}
7551 		/* Cannot use index 0 for module BTF fd */
7552 		if (!obj->fd_array_cnt)
7553 			obj->fd_array_cnt = 1;
7554 
7555 		ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
7556 					obj->fd_array_cnt + 1);
7557 		if (ret)
7558 			return ret;
7559 		mod_btf->fd_array_idx = obj->fd_array_cnt;
7560 		/* we assume module BTF FD is always >0 */
7561 		obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
7562 	}
7563 
7564 	ext->is_set = true;
7565 	ext->ksym.kernel_btf_id = kfunc_id;
7566 	ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
7567 	pr_debug("extern (func ksym) '%s': resolved to kernel [%d]\n",
7568 		 ext->name, kfunc_id);
7569 
7570 	return 0;
7571 }
7572 
7573 static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
7574 {
7575 	const struct btf_type *t;
7576 	struct extern_desc *ext;
7577 	int i, err;
7578 
7579 	for (i = 0; i < obj->nr_extern; i++) {
7580 		ext = &obj->externs[i];
7581 		if (ext->type != EXT_KSYM || !ext->ksym.type_id)
7582 			continue;
7583 
7584 		if (obj->gen_loader) {
7585 			ext->is_set = true;
7586 			ext->ksym.kernel_btf_obj_fd = 0;
7587 			ext->ksym.kernel_btf_id = 0;
7588 			continue;
7589 		}
7590 		t = btf__type_by_id(obj->btf, ext->btf_id);
7591 		if (btf_is_var(t))
7592 			err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
7593 		else
7594 			err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
7595 		if (err)
7596 			return err;
7597 	}
7598 	return 0;
7599 }
7600 
7601 static int bpf_object__resolve_externs(struct bpf_object *obj,
7602 				       const char *extra_kconfig)
7603 {
7604 	bool need_config = false, need_kallsyms = false;
7605 	bool need_vmlinux_btf = false;
7606 	struct extern_desc *ext;
7607 	void *kcfg_data = NULL;
7608 	int err, i;
7609 
7610 	if (obj->nr_extern == 0)
7611 		return 0;
7612 
7613 	if (obj->kconfig_map_idx >= 0)
7614 		kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
7615 
7616 	for (i = 0; i < obj->nr_extern; i++) {
7617 		ext = &obj->externs[i];
7618 
7619 		if (ext->type == EXT_KSYM) {
7620 			if (ext->ksym.type_id)
7621 				need_vmlinux_btf = true;
7622 			else
7623 				need_kallsyms = true;
7624 			continue;
7625 		} else if (ext->type == EXT_KCFG) {
7626 			void *ext_ptr = kcfg_data + ext->kcfg.data_off;
7627 			__u64 value = 0;
7628 
7629 			/* Kconfig externs need actual /proc/config.gz */
7630 			if (str_has_pfx(ext->name, "CONFIG_")) {
7631 				need_config = true;
7632 				continue;
7633 			}
7634 
7635 			/* Virtual kcfg externs are customly handled by libbpf */
7636 			if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
7637 				value = get_kernel_version();
7638 				if (!value) {
7639 					pr_warn("extern (kcfg) '%s': failed to get kernel version\n", ext->name);
7640 					return -EINVAL;
7641 				}
7642 			} else if (strcmp(ext->name, "LINUX_HAS_BPF_COOKIE") == 0) {
7643 				value = kernel_supports(obj, FEAT_BPF_COOKIE);
7644 			} else if (strcmp(ext->name, "LINUX_HAS_SYSCALL_WRAPPER") == 0) {
7645 				value = kernel_supports(obj, FEAT_SYSCALL_WRAPPER);
7646 			} else if (!str_has_pfx(ext->name, "LINUX_") || !ext->is_weak) {
7647 				/* Currently libbpf supports only CONFIG_ and LINUX_ prefixed
7648 				 * __kconfig externs, where LINUX_ ones are virtual and filled out
7649 				 * customly by libbpf (their values don't come from Kconfig).
7650 				 * If LINUX_xxx variable is not recognized by libbpf, but is marked
7651 				 * __weak, it defaults to zero value, just like for CONFIG_xxx
7652 				 * externs.
7653 				 */
7654 				pr_warn("extern (kcfg) '%s': unrecognized virtual extern\n", ext->name);
7655 				return -EINVAL;
7656 			}
7657 
7658 			err = set_kcfg_value_num(ext, ext_ptr, value);
7659 			if (err)
7660 				return err;
7661 			pr_debug("extern (kcfg) '%s': set to 0x%llx\n",
7662 				 ext->name, (long long)value);
7663 		} else {
7664 			pr_warn("extern '%s': unrecognized extern kind\n", ext->name);
7665 			return -EINVAL;
7666 		}
7667 	}
7668 	if (need_config && extra_kconfig) {
7669 		err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
7670 		if (err)
7671 			return -EINVAL;
7672 		need_config = false;
7673 		for (i = 0; i < obj->nr_extern; i++) {
7674 			ext = &obj->externs[i];
7675 			if (ext->type == EXT_KCFG && !ext->is_set) {
7676 				need_config = true;
7677 				break;
7678 			}
7679 		}
7680 	}
7681 	if (need_config) {
7682 		err = bpf_object__read_kconfig_file(obj, kcfg_data);
7683 		if (err)
7684 			return -EINVAL;
7685 	}
7686 	if (need_kallsyms) {
7687 		err = bpf_object__read_kallsyms_file(obj);
7688 		if (err)
7689 			return -EINVAL;
7690 	}
7691 	if (need_vmlinux_btf) {
7692 		err = bpf_object__resolve_ksyms_btf_id(obj);
7693 		if (err)
7694 			return -EINVAL;
7695 	}
7696 	for (i = 0; i < obj->nr_extern; i++) {
7697 		ext = &obj->externs[i];
7698 
7699 		if (!ext->is_set && !ext->is_weak) {
7700 			pr_warn("extern '%s' (strong): not resolved\n", ext->name);
7701 			return -ESRCH;
7702 		} else if (!ext->is_set) {
7703 			pr_debug("extern '%s' (weak): not resolved, defaulting to zero\n",
7704 				 ext->name);
7705 		}
7706 	}
7707 
7708 	return 0;
7709 }
7710 
7711 static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
7712 {
7713 	int err, i;
7714 
7715 	if (!obj)
7716 		return libbpf_err(-EINVAL);
7717 
7718 	if (obj->loaded) {
7719 		pr_warn("object '%s': load can't be attempted twice\n", obj->name);
7720 		return libbpf_err(-EINVAL);
7721 	}
7722 
7723 	if (obj->gen_loader)
7724 		bpf_gen__init(obj->gen_loader, extra_log_level, obj->nr_programs, obj->nr_maps);
7725 
7726 	err = bpf_object__probe_loading(obj);
7727 	err = err ? : bpf_object__load_vmlinux_btf(obj, false);
7728 	err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
7729 	err = err ? : bpf_object__sanitize_and_load_btf(obj);
7730 	err = err ? : bpf_object__sanitize_maps(obj);
7731 	err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
7732 	err = err ? : bpf_object__create_maps(obj);
7733 	err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
7734 	err = err ? : bpf_object__load_progs(obj, extra_log_level);
7735 	err = err ? : bpf_object_init_prog_arrays(obj);
7736 
7737 	if (obj->gen_loader) {
7738 		/* reset FDs */
7739 		if (obj->btf)
7740 			btf__set_fd(obj->btf, -1);
7741 		for (i = 0; i < obj->nr_maps; i++)
7742 			obj->maps[i].fd = -1;
7743 		if (!err)
7744 			err = bpf_gen__finish(obj->gen_loader, obj->nr_programs, obj->nr_maps);
7745 	}
7746 
7747 	/* clean up fd_array */
7748 	zfree(&obj->fd_array);
7749 
7750 	/* clean up module BTFs */
7751 	for (i = 0; i < obj->btf_module_cnt; i++) {
7752 		close(obj->btf_modules[i].fd);
7753 		btf__free(obj->btf_modules[i].btf);
7754 		free(obj->btf_modules[i].name);
7755 	}
7756 	free(obj->btf_modules);
7757 
7758 	/* clean up vmlinux BTF */
7759 	btf__free(obj->btf_vmlinux);
7760 	obj->btf_vmlinux = NULL;
7761 
7762 	obj->loaded = true; /* doesn't matter if successfully or not */
7763 
7764 	if (err)
7765 		goto out;
7766 
7767 	return 0;
7768 out:
7769 	/* unpin any maps that were auto-pinned during load */
7770 	for (i = 0; i < obj->nr_maps; i++)
7771 		if (obj->maps[i].pinned && !obj->maps[i].reused)
7772 			bpf_map__unpin(&obj->maps[i], NULL);
7773 
7774 	bpf_object_unload(obj);
7775 	pr_warn("failed to load object '%s'\n", obj->path);
7776 	return libbpf_err(err);
7777 }
7778 
7779 int bpf_object__load(struct bpf_object *obj)
7780 {
7781 	return bpf_object_load(obj, 0, NULL);
7782 }
7783 
7784 static int make_parent_dir(const char *path)
7785 {
7786 	char *cp, errmsg[STRERR_BUFSIZE];
7787 	char *dname, *dir;
7788 	int err = 0;
7789 
7790 	dname = strdup(path);
7791 	if (dname == NULL)
7792 		return -ENOMEM;
7793 
7794 	dir = dirname(dname);
7795 	if (mkdir(dir, 0700) && errno != EEXIST)
7796 		err = -errno;
7797 
7798 	free(dname);
7799 	if (err) {
7800 		cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
7801 		pr_warn("failed to mkdir %s: %s\n", path, cp);
7802 	}
7803 	return err;
7804 }
7805 
7806 static int check_path(const char *path)
7807 {
7808 	char *cp, errmsg[STRERR_BUFSIZE];
7809 	struct statfs st_fs;
7810 	char *dname, *dir;
7811 	int err = 0;
7812 
7813 	if (path == NULL)
7814 		return -EINVAL;
7815 
7816 	dname = strdup(path);
7817 	if (dname == NULL)
7818 		return -ENOMEM;
7819 
7820 	dir = dirname(dname);
7821 	if (statfs(dir, &st_fs)) {
7822 		cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
7823 		pr_warn("failed to statfs %s: %s\n", dir, cp);
7824 		err = -errno;
7825 	}
7826 	free(dname);
7827 
7828 	if (!err && st_fs.f_type != BPF_FS_MAGIC) {
7829 		pr_warn("specified path %s is not on BPF FS\n", path);
7830 		err = -EINVAL;
7831 	}
7832 
7833 	return err;
7834 }
7835 
7836 int bpf_program__pin(struct bpf_program *prog, const char *path)
7837 {
7838 	char *cp, errmsg[STRERR_BUFSIZE];
7839 	int err;
7840 
7841 	if (prog->fd < 0) {
7842 		pr_warn("prog '%s': can't pin program that wasn't loaded\n", prog->name);
7843 		return libbpf_err(-EINVAL);
7844 	}
7845 
7846 	err = make_parent_dir(path);
7847 	if (err)
7848 		return libbpf_err(err);
7849 
7850 	err = check_path(path);
7851 	if (err)
7852 		return libbpf_err(err);
7853 
7854 	if (bpf_obj_pin(prog->fd, path)) {
7855 		err = -errno;
7856 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
7857 		pr_warn("prog '%s': failed to pin at '%s': %s\n", prog->name, path, cp);
7858 		return libbpf_err(err);
7859 	}
7860 
7861 	pr_debug("prog '%s': pinned at '%s'\n", prog->name, path);
7862 	return 0;
7863 }
7864 
7865 int bpf_program__unpin(struct bpf_program *prog, const char *path)
7866 {
7867 	int err;
7868 
7869 	if (prog->fd < 0) {
7870 		pr_warn("prog '%s': can't unpin program that wasn't loaded\n", prog->name);
7871 		return libbpf_err(-EINVAL);
7872 	}
7873 
7874 	err = check_path(path);
7875 	if (err)
7876 		return libbpf_err(err);
7877 
7878 	err = unlink(path);
7879 	if (err)
7880 		return libbpf_err(-errno);
7881 
7882 	pr_debug("prog '%s': unpinned from '%s'\n", prog->name, path);
7883 	return 0;
7884 }
7885 
7886 int bpf_map__pin(struct bpf_map *map, const char *path)
7887 {
7888 	char *cp, errmsg[STRERR_BUFSIZE];
7889 	int err;
7890 
7891 	if (map == NULL) {
7892 		pr_warn("invalid map pointer\n");
7893 		return libbpf_err(-EINVAL);
7894 	}
7895 
7896 	if (map->pin_path) {
7897 		if (path && strcmp(path, map->pin_path)) {
7898 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
7899 				bpf_map__name(map), map->pin_path, path);
7900 			return libbpf_err(-EINVAL);
7901 		} else if (map->pinned) {
7902 			pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
7903 				 bpf_map__name(map), map->pin_path);
7904 			return 0;
7905 		}
7906 	} else {
7907 		if (!path) {
7908 			pr_warn("missing a path to pin map '%s' at\n",
7909 				bpf_map__name(map));
7910 			return libbpf_err(-EINVAL);
7911 		} else if (map->pinned) {
7912 			pr_warn("map '%s' already pinned\n", bpf_map__name(map));
7913 			return libbpf_err(-EEXIST);
7914 		}
7915 
7916 		map->pin_path = strdup(path);
7917 		if (!map->pin_path) {
7918 			err = -errno;
7919 			goto out_err;
7920 		}
7921 	}
7922 
7923 	err = make_parent_dir(map->pin_path);
7924 	if (err)
7925 		return libbpf_err(err);
7926 
7927 	err = check_path(map->pin_path);
7928 	if (err)
7929 		return libbpf_err(err);
7930 
7931 	if (bpf_obj_pin(map->fd, map->pin_path)) {
7932 		err = -errno;
7933 		goto out_err;
7934 	}
7935 
7936 	map->pinned = true;
7937 	pr_debug("pinned map '%s'\n", map->pin_path);
7938 
7939 	return 0;
7940 
7941 out_err:
7942 	cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
7943 	pr_warn("failed to pin map: %s\n", cp);
7944 	return libbpf_err(err);
7945 }
7946 
7947 int bpf_map__unpin(struct bpf_map *map, const char *path)
7948 {
7949 	int err;
7950 
7951 	if (map == NULL) {
7952 		pr_warn("invalid map pointer\n");
7953 		return libbpf_err(-EINVAL);
7954 	}
7955 
7956 	if (map->pin_path) {
7957 		if (path && strcmp(path, map->pin_path)) {
7958 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
7959 				bpf_map__name(map), map->pin_path, path);
7960 			return libbpf_err(-EINVAL);
7961 		}
7962 		path = map->pin_path;
7963 	} else if (!path) {
7964 		pr_warn("no path to unpin map '%s' from\n",
7965 			bpf_map__name(map));
7966 		return libbpf_err(-EINVAL);
7967 	}
7968 
7969 	err = check_path(path);
7970 	if (err)
7971 		return libbpf_err(err);
7972 
7973 	err = unlink(path);
7974 	if (err != 0)
7975 		return libbpf_err(-errno);
7976 
7977 	map->pinned = false;
7978 	pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
7979 
7980 	return 0;
7981 }
7982 
7983 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
7984 {
7985 	char *new = NULL;
7986 
7987 	if (path) {
7988 		new = strdup(path);
7989 		if (!new)
7990 			return libbpf_err(-errno);
7991 	}
7992 
7993 	free(map->pin_path);
7994 	map->pin_path = new;
7995 	return 0;
7996 }
7997 
7998 __alias(bpf_map__pin_path)
7999 const char *bpf_map__get_pin_path(const struct bpf_map *map);
8000 
8001 const char *bpf_map__pin_path(const struct bpf_map *map)
8002 {
8003 	return map->pin_path;
8004 }
8005 
8006 bool bpf_map__is_pinned(const struct bpf_map *map)
8007 {
8008 	return map->pinned;
8009 }
8010 
8011 static void sanitize_pin_path(char *s)
8012 {
8013 	/* bpffs disallows periods in path names */
8014 	while (*s) {
8015 		if (*s == '.')
8016 			*s = '_';
8017 		s++;
8018 	}
8019 }
8020 
8021 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
8022 {
8023 	struct bpf_map *map;
8024 	int err;
8025 
8026 	if (!obj)
8027 		return libbpf_err(-ENOENT);
8028 
8029 	if (!obj->loaded) {
8030 		pr_warn("object not yet loaded; load it first\n");
8031 		return libbpf_err(-ENOENT);
8032 	}
8033 
8034 	bpf_object__for_each_map(map, obj) {
8035 		char *pin_path = NULL;
8036 		char buf[PATH_MAX];
8037 
8038 		if (!map->autocreate)
8039 			continue;
8040 
8041 		if (path) {
8042 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8043 			if (err)
8044 				goto err_unpin_maps;
8045 			sanitize_pin_path(buf);
8046 			pin_path = buf;
8047 		} else if (!map->pin_path) {
8048 			continue;
8049 		}
8050 
8051 		err = bpf_map__pin(map, pin_path);
8052 		if (err)
8053 			goto err_unpin_maps;
8054 	}
8055 
8056 	return 0;
8057 
8058 err_unpin_maps:
8059 	while ((map = bpf_object__prev_map(obj, map))) {
8060 		if (!map->pin_path)
8061 			continue;
8062 
8063 		bpf_map__unpin(map, NULL);
8064 	}
8065 
8066 	return libbpf_err(err);
8067 }
8068 
8069 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
8070 {
8071 	struct bpf_map *map;
8072 	int err;
8073 
8074 	if (!obj)
8075 		return libbpf_err(-ENOENT);
8076 
8077 	bpf_object__for_each_map(map, obj) {
8078 		char *pin_path = NULL;
8079 		char buf[PATH_MAX];
8080 
8081 		if (path) {
8082 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8083 			if (err)
8084 				return libbpf_err(err);
8085 			sanitize_pin_path(buf);
8086 			pin_path = buf;
8087 		} else if (!map->pin_path) {
8088 			continue;
8089 		}
8090 
8091 		err = bpf_map__unpin(map, pin_path);
8092 		if (err)
8093 			return libbpf_err(err);
8094 	}
8095 
8096 	return 0;
8097 }
8098 
8099 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
8100 {
8101 	struct bpf_program *prog;
8102 	char buf[PATH_MAX];
8103 	int err;
8104 
8105 	if (!obj)
8106 		return libbpf_err(-ENOENT);
8107 
8108 	if (!obj->loaded) {
8109 		pr_warn("object not yet loaded; load it first\n");
8110 		return libbpf_err(-ENOENT);
8111 	}
8112 
8113 	bpf_object__for_each_program(prog, obj) {
8114 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
8115 		if (err)
8116 			goto err_unpin_programs;
8117 
8118 		err = bpf_program__pin(prog, buf);
8119 		if (err)
8120 			goto err_unpin_programs;
8121 	}
8122 
8123 	return 0;
8124 
8125 err_unpin_programs:
8126 	while ((prog = bpf_object__prev_program(obj, prog))) {
8127 		if (pathname_concat(buf, sizeof(buf), path, prog->name))
8128 			continue;
8129 
8130 		bpf_program__unpin(prog, buf);
8131 	}
8132 
8133 	return libbpf_err(err);
8134 }
8135 
8136 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
8137 {
8138 	struct bpf_program *prog;
8139 	int err;
8140 
8141 	if (!obj)
8142 		return libbpf_err(-ENOENT);
8143 
8144 	bpf_object__for_each_program(prog, obj) {
8145 		char buf[PATH_MAX];
8146 
8147 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
8148 		if (err)
8149 			return libbpf_err(err);
8150 
8151 		err = bpf_program__unpin(prog, buf);
8152 		if (err)
8153 			return libbpf_err(err);
8154 	}
8155 
8156 	return 0;
8157 }
8158 
8159 int bpf_object__pin(struct bpf_object *obj, const char *path)
8160 {
8161 	int err;
8162 
8163 	err = bpf_object__pin_maps(obj, path);
8164 	if (err)
8165 		return libbpf_err(err);
8166 
8167 	err = bpf_object__pin_programs(obj, path);
8168 	if (err) {
8169 		bpf_object__unpin_maps(obj, path);
8170 		return libbpf_err(err);
8171 	}
8172 
8173 	return 0;
8174 }
8175 
8176 static void bpf_map__destroy(struct bpf_map *map)
8177 {
8178 	if (map->inner_map) {
8179 		bpf_map__destroy(map->inner_map);
8180 		zfree(&map->inner_map);
8181 	}
8182 
8183 	zfree(&map->init_slots);
8184 	map->init_slots_sz = 0;
8185 
8186 	if (map->mmaped) {
8187 		munmap(map->mmaped, bpf_map_mmap_sz(map));
8188 		map->mmaped = NULL;
8189 	}
8190 
8191 	if (map->st_ops) {
8192 		zfree(&map->st_ops->data);
8193 		zfree(&map->st_ops->progs);
8194 		zfree(&map->st_ops->kern_func_off);
8195 		zfree(&map->st_ops);
8196 	}
8197 
8198 	zfree(&map->name);
8199 	zfree(&map->real_name);
8200 	zfree(&map->pin_path);
8201 
8202 	if (map->fd >= 0)
8203 		zclose(map->fd);
8204 }
8205 
8206 void bpf_object__close(struct bpf_object *obj)
8207 {
8208 	size_t i;
8209 
8210 	if (IS_ERR_OR_NULL(obj))
8211 		return;
8212 
8213 	usdt_manager_free(obj->usdt_man);
8214 	obj->usdt_man = NULL;
8215 
8216 	bpf_gen__free(obj->gen_loader);
8217 	bpf_object__elf_finish(obj);
8218 	bpf_object_unload(obj);
8219 	btf__free(obj->btf);
8220 	btf_ext__free(obj->btf_ext);
8221 
8222 	for (i = 0; i < obj->nr_maps; i++)
8223 		bpf_map__destroy(&obj->maps[i]);
8224 
8225 	zfree(&obj->btf_custom_path);
8226 	zfree(&obj->kconfig);
8227 	zfree(&obj->externs);
8228 	obj->nr_extern = 0;
8229 
8230 	zfree(&obj->maps);
8231 	obj->nr_maps = 0;
8232 
8233 	if (obj->programs && obj->nr_programs) {
8234 		for (i = 0; i < obj->nr_programs; i++)
8235 			bpf_program__exit(&obj->programs[i]);
8236 	}
8237 	zfree(&obj->programs);
8238 
8239 	free(obj);
8240 }
8241 
8242 const char *bpf_object__name(const struct bpf_object *obj)
8243 {
8244 	return obj ? obj->name : libbpf_err_ptr(-EINVAL);
8245 }
8246 
8247 unsigned int bpf_object__kversion(const struct bpf_object *obj)
8248 {
8249 	return obj ? obj->kern_version : 0;
8250 }
8251 
8252 struct btf *bpf_object__btf(const struct bpf_object *obj)
8253 {
8254 	return obj ? obj->btf : NULL;
8255 }
8256 
8257 int bpf_object__btf_fd(const struct bpf_object *obj)
8258 {
8259 	return obj->btf ? btf__fd(obj->btf) : -1;
8260 }
8261 
8262 int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
8263 {
8264 	if (obj->loaded)
8265 		return libbpf_err(-EINVAL);
8266 
8267 	obj->kern_version = kern_version;
8268 
8269 	return 0;
8270 }
8271 
8272 int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
8273 {
8274 	struct bpf_gen *gen;
8275 
8276 	if (!opts)
8277 		return -EFAULT;
8278 	if (!OPTS_VALID(opts, gen_loader_opts))
8279 		return -EINVAL;
8280 	gen = calloc(sizeof(*gen), 1);
8281 	if (!gen)
8282 		return -ENOMEM;
8283 	gen->opts = opts;
8284 	obj->gen_loader = gen;
8285 	return 0;
8286 }
8287 
8288 static struct bpf_program *
8289 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
8290 		    bool forward)
8291 {
8292 	size_t nr_programs = obj->nr_programs;
8293 	ssize_t idx;
8294 
8295 	if (!nr_programs)
8296 		return NULL;
8297 
8298 	if (!p)
8299 		/* Iter from the beginning */
8300 		return forward ? &obj->programs[0] :
8301 			&obj->programs[nr_programs - 1];
8302 
8303 	if (p->obj != obj) {
8304 		pr_warn("error: program handler doesn't match object\n");
8305 		return errno = EINVAL, NULL;
8306 	}
8307 
8308 	idx = (p - obj->programs) + (forward ? 1 : -1);
8309 	if (idx >= obj->nr_programs || idx < 0)
8310 		return NULL;
8311 	return &obj->programs[idx];
8312 }
8313 
8314 struct bpf_program *
8315 bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
8316 {
8317 	struct bpf_program *prog = prev;
8318 
8319 	do {
8320 		prog = __bpf_program__iter(prog, obj, true);
8321 	} while (prog && prog_is_subprog(obj, prog));
8322 
8323 	return prog;
8324 }
8325 
8326 struct bpf_program *
8327 bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
8328 {
8329 	struct bpf_program *prog = next;
8330 
8331 	do {
8332 		prog = __bpf_program__iter(prog, obj, false);
8333 	} while (prog && prog_is_subprog(obj, prog));
8334 
8335 	return prog;
8336 }
8337 
8338 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
8339 {
8340 	prog->prog_ifindex = ifindex;
8341 }
8342 
8343 const char *bpf_program__name(const struct bpf_program *prog)
8344 {
8345 	return prog->name;
8346 }
8347 
8348 const char *bpf_program__section_name(const struct bpf_program *prog)
8349 {
8350 	return prog->sec_name;
8351 }
8352 
8353 bool bpf_program__autoload(const struct bpf_program *prog)
8354 {
8355 	return prog->autoload;
8356 }
8357 
8358 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
8359 {
8360 	if (prog->obj->loaded)
8361 		return libbpf_err(-EINVAL);
8362 
8363 	prog->autoload = autoload;
8364 	return 0;
8365 }
8366 
8367 bool bpf_program__autoattach(const struct bpf_program *prog)
8368 {
8369 	return prog->autoattach;
8370 }
8371 
8372 void bpf_program__set_autoattach(struct bpf_program *prog, bool autoattach)
8373 {
8374 	prog->autoattach = autoattach;
8375 }
8376 
8377 const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
8378 {
8379 	return prog->insns;
8380 }
8381 
8382 size_t bpf_program__insn_cnt(const struct bpf_program *prog)
8383 {
8384 	return prog->insns_cnt;
8385 }
8386 
8387 int bpf_program__set_insns(struct bpf_program *prog,
8388 			   struct bpf_insn *new_insns, size_t new_insn_cnt)
8389 {
8390 	struct bpf_insn *insns;
8391 
8392 	if (prog->obj->loaded)
8393 		return -EBUSY;
8394 
8395 	insns = libbpf_reallocarray(prog->insns, new_insn_cnt, sizeof(*insns));
8396 	if (!insns) {
8397 		pr_warn("prog '%s': failed to realloc prog code\n", prog->name);
8398 		return -ENOMEM;
8399 	}
8400 	memcpy(insns, new_insns, new_insn_cnt * sizeof(*insns));
8401 
8402 	prog->insns = insns;
8403 	prog->insns_cnt = new_insn_cnt;
8404 	return 0;
8405 }
8406 
8407 int bpf_program__fd(const struct bpf_program *prog)
8408 {
8409 	if (!prog)
8410 		return libbpf_err(-EINVAL);
8411 
8412 	if (prog->fd < 0)
8413 		return libbpf_err(-ENOENT);
8414 
8415 	return prog->fd;
8416 }
8417 
8418 __alias(bpf_program__type)
8419 enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog);
8420 
8421 enum bpf_prog_type bpf_program__type(const struct bpf_program *prog)
8422 {
8423 	return prog->type;
8424 }
8425 
8426 int bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
8427 {
8428 	if (prog->obj->loaded)
8429 		return libbpf_err(-EBUSY);
8430 
8431 	prog->type = type;
8432 	return 0;
8433 }
8434 
8435 __alias(bpf_program__expected_attach_type)
8436 enum bpf_attach_type bpf_program__get_expected_attach_type(const struct bpf_program *prog);
8437 
8438 enum bpf_attach_type bpf_program__expected_attach_type(const struct bpf_program *prog)
8439 {
8440 	return prog->expected_attach_type;
8441 }
8442 
8443 int bpf_program__set_expected_attach_type(struct bpf_program *prog,
8444 					   enum bpf_attach_type type)
8445 {
8446 	if (prog->obj->loaded)
8447 		return libbpf_err(-EBUSY);
8448 
8449 	prog->expected_attach_type = type;
8450 	return 0;
8451 }
8452 
8453 __u32 bpf_program__flags(const struct bpf_program *prog)
8454 {
8455 	return prog->prog_flags;
8456 }
8457 
8458 int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
8459 {
8460 	if (prog->obj->loaded)
8461 		return libbpf_err(-EBUSY);
8462 
8463 	prog->prog_flags = flags;
8464 	return 0;
8465 }
8466 
8467 __u32 bpf_program__log_level(const struct bpf_program *prog)
8468 {
8469 	return prog->log_level;
8470 }
8471 
8472 int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
8473 {
8474 	if (prog->obj->loaded)
8475 		return libbpf_err(-EBUSY);
8476 
8477 	prog->log_level = log_level;
8478 	return 0;
8479 }
8480 
8481 const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
8482 {
8483 	*log_size = prog->log_size;
8484 	return prog->log_buf;
8485 }
8486 
8487 int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
8488 {
8489 	if (log_size && !log_buf)
8490 		return -EINVAL;
8491 	if (prog->log_size > UINT_MAX)
8492 		return -EINVAL;
8493 	if (prog->obj->loaded)
8494 		return -EBUSY;
8495 
8496 	prog->log_buf = log_buf;
8497 	prog->log_size = log_size;
8498 	return 0;
8499 }
8500 
8501 #define SEC_DEF(sec_pfx, ptype, atype, flags, ...) {			    \
8502 	.sec = (char *)sec_pfx,						    \
8503 	.prog_type = BPF_PROG_TYPE_##ptype,				    \
8504 	.expected_attach_type = atype,					    \
8505 	.cookie = (long)(flags),					    \
8506 	.prog_prepare_load_fn = libbpf_prepare_prog_load,		    \
8507 	__VA_ARGS__							    \
8508 }
8509 
8510 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8511 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8512 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8513 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8514 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8515 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8516 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8517 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8518 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8519 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8520 
8521 static const struct bpf_sec_def section_defs[] = {
8522 	SEC_DEF("socket",		SOCKET_FILTER, 0, SEC_NONE),
8523 	SEC_DEF("sk_reuseport/migrate",	SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE),
8524 	SEC_DEF("sk_reuseport",		SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE),
8525 	SEC_DEF("kprobe+",		KPROBE,	0, SEC_NONE, attach_kprobe),
8526 	SEC_DEF("uprobe+",		KPROBE,	0, SEC_NONE, attach_uprobe),
8527 	SEC_DEF("uprobe.s+",		KPROBE,	0, SEC_SLEEPABLE, attach_uprobe),
8528 	SEC_DEF("kretprobe+",		KPROBE, 0, SEC_NONE, attach_kprobe),
8529 	SEC_DEF("uretprobe+",		KPROBE, 0, SEC_NONE, attach_uprobe),
8530 	SEC_DEF("uretprobe.s+",		KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
8531 	SEC_DEF("kprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
8532 	SEC_DEF("kretprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
8533 	SEC_DEF("ksyscall+",		KPROBE,	0, SEC_NONE, attach_ksyscall),
8534 	SEC_DEF("kretsyscall+",		KPROBE, 0, SEC_NONE, attach_ksyscall),
8535 	SEC_DEF("usdt+",		KPROBE,	0, SEC_NONE, attach_usdt),
8536 	SEC_DEF("tc",			SCHED_CLS, 0, SEC_NONE),
8537 	SEC_DEF("classifier",		SCHED_CLS, 0, SEC_NONE),
8538 	SEC_DEF("action",		SCHED_ACT, 0, SEC_NONE),
8539 	SEC_DEF("tracepoint+",		TRACEPOINT, 0, SEC_NONE, attach_tp),
8540 	SEC_DEF("tp+",			TRACEPOINT, 0, SEC_NONE, attach_tp),
8541 	SEC_DEF("raw_tracepoint+",	RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
8542 	SEC_DEF("raw_tp+",		RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
8543 	SEC_DEF("raw_tracepoint.w+",	RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
8544 	SEC_DEF("raw_tp.w+",		RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
8545 	SEC_DEF("tp_btf+",		TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
8546 	SEC_DEF("fentry+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
8547 	SEC_DEF("fmod_ret+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
8548 	SEC_DEF("fexit+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
8549 	SEC_DEF("fentry.s+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8550 	SEC_DEF("fmod_ret.s+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8551 	SEC_DEF("fexit.s+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8552 	SEC_DEF("freplace+",		EXT, 0, SEC_ATTACH_BTF, attach_trace),
8553 	SEC_DEF("lsm+",			LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
8554 	SEC_DEF("lsm.s+",		LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
8555 	SEC_DEF("lsm_cgroup+",		LSM, BPF_LSM_CGROUP, SEC_ATTACH_BTF),
8556 	SEC_DEF("iter+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
8557 	SEC_DEF("iter.s+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_iter),
8558 	SEC_DEF("syscall",		SYSCALL, 0, SEC_SLEEPABLE),
8559 	SEC_DEF("xdp.frags/devmap",	XDP, BPF_XDP_DEVMAP, SEC_XDP_FRAGS),
8560 	SEC_DEF("xdp/devmap",		XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
8561 	SEC_DEF("xdp.frags/cpumap",	XDP, BPF_XDP_CPUMAP, SEC_XDP_FRAGS),
8562 	SEC_DEF("xdp/cpumap",		XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
8563 	SEC_DEF("xdp.frags",		XDP, BPF_XDP, SEC_XDP_FRAGS),
8564 	SEC_DEF("xdp",			XDP, BPF_XDP, SEC_ATTACHABLE_OPT),
8565 	SEC_DEF("perf_event",		PERF_EVENT, 0, SEC_NONE),
8566 	SEC_DEF("lwt_in",		LWT_IN, 0, SEC_NONE),
8567 	SEC_DEF("lwt_out",		LWT_OUT, 0, SEC_NONE),
8568 	SEC_DEF("lwt_xmit",		LWT_XMIT, 0, SEC_NONE),
8569 	SEC_DEF("lwt_seg6local",	LWT_SEG6LOCAL, 0, SEC_NONE),
8570 	SEC_DEF("sockops",		SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT),
8571 	SEC_DEF("sk_skb/stream_parser",	SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT),
8572 	SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT),
8573 	SEC_DEF("sk_skb",		SK_SKB, 0, SEC_NONE),
8574 	SEC_DEF("sk_msg",		SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT),
8575 	SEC_DEF("lirc_mode2",		LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT),
8576 	SEC_DEF("flow_dissector",	FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT),
8577 	SEC_DEF("cgroup_skb/ingress",	CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT),
8578 	SEC_DEF("cgroup_skb/egress",	CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT),
8579 	SEC_DEF("cgroup/skb",		CGROUP_SKB, 0, SEC_NONE),
8580 	SEC_DEF("cgroup/sock_create",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE),
8581 	SEC_DEF("cgroup/sock_release",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE),
8582 	SEC_DEF("cgroup/sock",		CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT),
8583 	SEC_DEF("cgroup/post_bind4",	CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE),
8584 	SEC_DEF("cgroup/post_bind6",	CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE),
8585 	SEC_DEF("cgroup/bind4",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE),
8586 	SEC_DEF("cgroup/bind6",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE),
8587 	SEC_DEF("cgroup/connect4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE),
8588 	SEC_DEF("cgroup/connect6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE),
8589 	SEC_DEF("cgroup/sendmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE),
8590 	SEC_DEF("cgroup/sendmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE),
8591 	SEC_DEF("cgroup/recvmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE),
8592 	SEC_DEF("cgroup/recvmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE),
8593 	SEC_DEF("cgroup/getpeername4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE),
8594 	SEC_DEF("cgroup/getpeername6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE),
8595 	SEC_DEF("cgroup/getsockname4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE),
8596 	SEC_DEF("cgroup/getsockname6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE),
8597 	SEC_DEF("cgroup/sysctl",	CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE),
8598 	SEC_DEF("cgroup/getsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE),
8599 	SEC_DEF("cgroup/setsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE),
8600 	SEC_DEF("cgroup/dev",		CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT),
8601 	SEC_DEF("struct_ops+",		STRUCT_OPS, 0, SEC_NONE),
8602 	SEC_DEF("sk_lookup",		SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE),
8603 };
8604 
8605 static size_t custom_sec_def_cnt;
8606 static struct bpf_sec_def *custom_sec_defs;
8607 static struct bpf_sec_def custom_fallback_def;
8608 static bool has_custom_fallback_def;
8609 
8610 static int last_custom_sec_def_handler_id;
8611 
8612 int libbpf_register_prog_handler(const char *sec,
8613 				 enum bpf_prog_type prog_type,
8614 				 enum bpf_attach_type exp_attach_type,
8615 				 const struct libbpf_prog_handler_opts *opts)
8616 {
8617 	struct bpf_sec_def *sec_def;
8618 
8619 	if (!OPTS_VALID(opts, libbpf_prog_handler_opts))
8620 		return libbpf_err(-EINVAL);
8621 
8622 	if (last_custom_sec_def_handler_id == INT_MAX) /* prevent overflow */
8623 		return libbpf_err(-E2BIG);
8624 
8625 	if (sec) {
8626 		sec_def = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt + 1,
8627 					      sizeof(*sec_def));
8628 		if (!sec_def)
8629 			return libbpf_err(-ENOMEM);
8630 
8631 		custom_sec_defs = sec_def;
8632 		sec_def = &custom_sec_defs[custom_sec_def_cnt];
8633 	} else {
8634 		if (has_custom_fallback_def)
8635 			return libbpf_err(-EBUSY);
8636 
8637 		sec_def = &custom_fallback_def;
8638 	}
8639 
8640 	sec_def->sec = sec ? strdup(sec) : NULL;
8641 	if (sec && !sec_def->sec)
8642 		return libbpf_err(-ENOMEM);
8643 
8644 	sec_def->prog_type = prog_type;
8645 	sec_def->expected_attach_type = exp_attach_type;
8646 	sec_def->cookie = OPTS_GET(opts, cookie, 0);
8647 
8648 	sec_def->prog_setup_fn = OPTS_GET(opts, prog_setup_fn, NULL);
8649 	sec_def->prog_prepare_load_fn = OPTS_GET(opts, prog_prepare_load_fn, NULL);
8650 	sec_def->prog_attach_fn = OPTS_GET(opts, prog_attach_fn, NULL);
8651 
8652 	sec_def->handler_id = ++last_custom_sec_def_handler_id;
8653 
8654 	if (sec)
8655 		custom_sec_def_cnt++;
8656 	else
8657 		has_custom_fallback_def = true;
8658 
8659 	return sec_def->handler_id;
8660 }
8661 
8662 int libbpf_unregister_prog_handler(int handler_id)
8663 {
8664 	struct bpf_sec_def *sec_defs;
8665 	int i;
8666 
8667 	if (handler_id <= 0)
8668 		return libbpf_err(-EINVAL);
8669 
8670 	if (has_custom_fallback_def && custom_fallback_def.handler_id == handler_id) {
8671 		memset(&custom_fallback_def, 0, sizeof(custom_fallback_def));
8672 		has_custom_fallback_def = false;
8673 		return 0;
8674 	}
8675 
8676 	for (i = 0; i < custom_sec_def_cnt; i++) {
8677 		if (custom_sec_defs[i].handler_id == handler_id)
8678 			break;
8679 	}
8680 
8681 	if (i == custom_sec_def_cnt)
8682 		return libbpf_err(-ENOENT);
8683 
8684 	free(custom_sec_defs[i].sec);
8685 	for (i = i + 1; i < custom_sec_def_cnt; i++)
8686 		custom_sec_defs[i - 1] = custom_sec_defs[i];
8687 	custom_sec_def_cnt--;
8688 
8689 	/* try to shrink the array, but it's ok if we couldn't */
8690 	sec_defs = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt, sizeof(*sec_defs));
8691 	if (sec_defs)
8692 		custom_sec_defs = sec_defs;
8693 
8694 	return 0;
8695 }
8696 
8697 static bool sec_def_matches(const struct bpf_sec_def *sec_def, const char *sec_name)
8698 {
8699 	size_t len = strlen(sec_def->sec);
8700 
8701 	/* "type/" always has to have proper SEC("type/extras") form */
8702 	if (sec_def->sec[len - 1] == '/') {
8703 		if (str_has_pfx(sec_name, sec_def->sec))
8704 			return true;
8705 		return false;
8706 	}
8707 
8708 	/* "type+" means it can be either exact SEC("type") or
8709 	 * well-formed SEC("type/extras") with proper '/' separator
8710 	 */
8711 	if (sec_def->sec[len - 1] == '+') {
8712 		len--;
8713 		/* not even a prefix */
8714 		if (strncmp(sec_name, sec_def->sec, len) != 0)
8715 			return false;
8716 		/* exact match or has '/' separator */
8717 		if (sec_name[len] == '\0' || sec_name[len] == '/')
8718 			return true;
8719 		return false;
8720 	}
8721 
8722 	return strcmp(sec_name, sec_def->sec) == 0;
8723 }
8724 
8725 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
8726 {
8727 	const struct bpf_sec_def *sec_def;
8728 	int i, n;
8729 
8730 	n = custom_sec_def_cnt;
8731 	for (i = 0; i < n; i++) {
8732 		sec_def = &custom_sec_defs[i];
8733 		if (sec_def_matches(sec_def, sec_name))
8734 			return sec_def;
8735 	}
8736 
8737 	n = ARRAY_SIZE(section_defs);
8738 	for (i = 0; i < n; i++) {
8739 		sec_def = &section_defs[i];
8740 		if (sec_def_matches(sec_def, sec_name))
8741 			return sec_def;
8742 	}
8743 
8744 	if (has_custom_fallback_def)
8745 		return &custom_fallback_def;
8746 
8747 	return NULL;
8748 }
8749 
8750 #define MAX_TYPE_NAME_SIZE 32
8751 
8752 static char *libbpf_get_type_names(bool attach_type)
8753 {
8754 	int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
8755 	char *buf;
8756 
8757 	buf = malloc(len);
8758 	if (!buf)
8759 		return NULL;
8760 
8761 	buf[0] = '\0';
8762 	/* Forge string buf with all available names */
8763 	for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
8764 		const struct bpf_sec_def *sec_def = &section_defs[i];
8765 
8766 		if (attach_type) {
8767 			if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
8768 				continue;
8769 
8770 			if (!(sec_def->cookie & SEC_ATTACHABLE))
8771 				continue;
8772 		}
8773 
8774 		if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
8775 			free(buf);
8776 			return NULL;
8777 		}
8778 		strcat(buf, " ");
8779 		strcat(buf, section_defs[i].sec);
8780 	}
8781 
8782 	return buf;
8783 }
8784 
8785 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
8786 			     enum bpf_attach_type *expected_attach_type)
8787 {
8788 	const struct bpf_sec_def *sec_def;
8789 	char *type_names;
8790 
8791 	if (!name)
8792 		return libbpf_err(-EINVAL);
8793 
8794 	sec_def = find_sec_def(name);
8795 	if (sec_def) {
8796 		*prog_type = sec_def->prog_type;
8797 		*expected_attach_type = sec_def->expected_attach_type;
8798 		return 0;
8799 	}
8800 
8801 	pr_debug("failed to guess program type from ELF section '%s'\n", name);
8802 	type_names = libbpf_get_type_names(false);
8803 	if (type_names != NULL) {
8804 		pr_debug("supported section(type) names are:%s\n", type_names);
8805 		free(type_names);
8806 	}
8807 
8808 	return libbpf_err(-ESRCH);
8809 }
8810 
8811 const char *libbpf_bpf_attach_type_str(enum bpf_attach_type t)
8812 {
8813 	if (t < 0 || t >= ARRAY_SIZE(attach_type_name))
8814 		return NULL;
8815 
8816 	return attach_type_name[t];
8817 }
8818 
8819 const char *libbpf_bpf_link_type_str(enum bpf_link_type t)
8820 {
8821 	if (t < 0 || t >= ARRAY_SIZE(link_type_name))
8822 		return NULL;
8823 
8824 	return link_type_name[t];
8825 }
8826 
8827 const char *libbpf_bpf_map_type_str(enum bpf_map_type t)
8828 {
8829 	if (t < 0 || t >= ARRAY_SIZE(map_type_name))
8830 		return NULL;
8831 
8832 	return map_type_name[t];
8833 }
8834 
8835 const char *libbpf_bpf_prog_type_str(enum bpf_prog_type t)
8836 {
8837 	if (t < 0 || t >= ARRAY_SIZE(prog_type_name))
8838 		return NULL;
8839 
8840 	return prog_type_name[t];
8841 }
8842 
8843 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
8844 						     size_t offset)
8845 {
8846 	struct bpf_map *map;
8847 	size_t i;
8848 
8849 	for (i = 0; i < obj->nr_maps; i++) {
8850 		map = &obj->maps[i];
8851 		if (!bpf_map__is_struct_ops(map))
8852 			continue;
8853 		if (map->sec_offset <= offset &&
8854 		    offset - map->sec_offset < map->def.value_size)
8855 			return map;
8856 	}
8857 
8858 	return NULL;
8859 }
8860 
8861 /* Collect the reloc from ELF and populate the st_ops->progs[] */
8862 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
8863 					    Elf64_Shdr *shdr, Elf_Data *data)
8864 {
8865 	const struct btf_member *member;
8866 	struct bpf_struct_ops *st_ops;
8867 	struct bpf_program *prog;
8868 	unsigned int shdr_idx;
8869 	const struct btf *btf;
8870 	struct bpf_map *map;
8871 	unsigned int moff, insn_idx;
8872 	const char *name;
8873 	__u32 member_idx;
8874 	Elf64_Sym *sym;
8875 	Elf64_Rel *rel;
8876 	int i, nrels;
8877 
8878 	btf = obj->btf;
8879 	nrels = shdr->sh_size / shdr->sh_entsize;
8880 	for (i = 0; i < nrels; i++) {
8881 		rel = elf_rel_by_idx(data, i);
8882 		if (!rel) {
8883 			pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
8884 			return -LIBBPF_ERRNO__FORMAT;
8885 		}
8886 
8887 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
8888 		if (!sym) {
8889 			pr_warn("struct_ops reloc: symbol %zx not found\n",
8890 				(size_t)ELF64_R_SYM(rel->r_info));
8891 			return -LIBBPF_ERRNO__FORMAT;
8892 		}
8893 
8894 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
8895 		map = find_struct_ops_map_by_offset(obj, rel->r_offset);
8896 		if (!map) {
8897 			pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
8898 				(size_t)rel->r_offset);
8899 			return -EINVAL;
8900 		}
8901 
8902 		moff = rel->r_offset - map->sec_offset;
8903 		shdr_idx = sym->st_shndx;
8904 		st_ops = map->st_ops;
8905 		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",
8906 			 map->name,
8907 			 (long long)(rel->r_info >> 32),
8908 			 (long long)sym->st_value,
8909 			 shdr_idx, (size_t)rel->r_offset,
8910 			 map->sec_offset, sym->st_name, name);
8911 
8912 		if (shdr_idx >= SHN_LORESERVE) {
8913 			pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
8914 				map->name, (size_t)rel->r_offset, shdr_idx);
8915 			return -LIBBPF_ERRNO__RELOC;
8916 		}
8917 		if (sym->st_value % BPF_INSN_SZ) {
8918 			pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
8919 				map->name, (unsigned long long)sym->st_value);
8920 			return -LIBBPF_ERRNO__FORMAT;
8921 		}
8922 		insn_idx = sym->st_value / BPF_INSN_SZ;
8923 
8924 		member = find_member_by_offset(st_ops->type, moff * 8);
8925 		if (!member) {
8926 			pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
8927 				map->name, moff);
8928 			return -EINVAL;
8929 		}
8930 		member_idx = member - btf_members(st_ops->type);
8931 		name = btf__name_by_offset(btf, member->name_off);
8932 
8933 		if (!resolve_func_ptr(btf, member->type, NULL)) {
8934 			pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
8935 				map->name, name);
8936 			return -EINVAL;
8937 		}
8938 
8939 		prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
8940 		if (!prog) {
8941 			pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
8942 				map->name, shdr_idx, name);
8943 			return -EINVAL;
8944 		}
8945 
8946 		/* prevent the use of BPF prog with invalid type */
8947 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
8948 			pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
8949 				map->name, prog->name);
8950 			return -EINVAL;
8951 		}
8952 
8953 		/* if we haven't yet processed this BPF program, record proper
8954 		 * attach_btf_id and member_idx
8955 		 */
8956 		if (!prog->attach_btf_id) {
8957 			prog->attach_btf_id = st_ops->type_id;
8958 			prog->expected_attach_type = member_idx;
8959 		}
8960 
8961 		/* struct_ops BPF prog can be re-used between multiple
8962 		 * .struct_ops as long as it's the same struct_ops struct
8963 		 * definition and the same function pointer field
8964 		 */
8965 		if (prog->attach_btf_id != st_ops->type_id ||
8966 		    prog->expected_attach_type != member_idx) {
8967 			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",
8968 				map->name, prog->name, prog->sec_name, prog->type,
8969 				prog->attach_btf_id, prog->expected_attach_type, name);
8970 			return -EINVAL;
8971 		}
8972 
8973 		st_ops->progs[member_idx] = prog;
8974 	}
8975 
8976 	return 0;
8977 }
8978 
8979 #define BTF_TRACE_PREFIX "btf_trace_"
8980 #define BTF_LSM_PREFIX "bpf_lsm_"
8981 #define BTF_ITER_PREFIX "bpf_iter_"
8982 #define BTF_MAX_NAME_SIZE 128
8983 
8984 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
8985 				const char **prefix, int *kind)
8986 {
8987 	switch (attach_type) {
8988 	case BPF_TRACE_RAW_TP:
8989 		*prefix = BTF_TRACE_PREFIX;
8990 		*kind = BTF_KIND_TYPEDEF;
8991 		break;
8992 	case BPF_LSM_MAC:
8993 	case BPF_LSM_CGROUP:
8994 		*prefix = BTF_LSM_PREFIX;
8995 		*kind = BTF_KIND_FUNC;
8996 		break;
8997 	case BPF_TRACE_ITER:
8998 		*prefix = BTF_ITER_PREFIX;
8999 		*kind = BTF_KIND_FUNC;
9000 		break;
9001 	default:
9002 		*prefix = "";
9003 		*kind = BTF_KIND_FUNC;
9004 	}
9005 }
9006 
9007 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
9008 				   const char *name, __u32 kind)
9009 {
9010 	char btf_type_name[BTF_MAX_NAME_SIZE];
9011 	int ret;
9012 
9013 	ret = snprintf(btf_type_name, sizeof(btf_type_name),
9014 		       "%s%s", prefix, name);
9015 	/* snprintf returns the number of characters written excluding the
9016 	 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
9017 	 * indicates truncation.
9018 	 */
9019 	if (ret < 0 || ret >= sizeof(btf_type_name))
9020 		return -ENAMETOOLONG;
9021 	return btf__find_by_name_kind(btf, btf_type_name, kind);
9022 }
9023 
9024 static inline int find_attach_btf_id(struct btf *btf, const char *name,
9025 				     enum bpf_attach_type attach_type)
9026 {
9027 	const char *prefix;
9028 	int kind;
9029 
9030 	btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
9031 	return find_btf_by_prefix_kind(btf, prefix, name, kind);
9032 }
9033 
9034 int libbpf_find_vmlinux_btf_id(const char *name,
9035 			       enum bpf_attach_type attach_type)
9036 {
9037 	struct btf *btf;
9038 	int err;
9039 
9040 	btf = btf__load_vmlinux_btf();
9041 	err = libbpf_get_error(btf);
9042 	if (err) {
9043 		pr_warn("vmlinux BTF is not found\n");
9044 		return libbpf_err(err);
9045 	}
9046 
9047 	err = find_attach_btf_id(btf, name, attach_type);
9048 	if (err <= 0)
9049 		pr_warn("%s is not found in vmlinux BTF\n", name);
9050 
9051 	btf__free(btf);
9052 	return libbpf_err(err);
9053 }
9054 
9055 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
9056 {
9057 	struct bpf_prog_info info;
9058 	__u32 info_len = sizeof(info);
9059 	struct btf *btf;
9060 	int err;
9061 
9062 	memset(&info, 0, info_len);
9063 	err = bpf_obj_get_info_by_fd(attach_prog_fd, &info, &info_len);
9064 	if (err) {
9065 		pr_warn("failed bpf_obj_get_info_by_fd for FD %d: %d\n",
9066 			attach_prog_fd, err);
9067 		return err;
9068 	}
9069 
9070 	err = -EINVAL;
9071 	if (!info.btf_id) {
9072 		pr_warn("The target program doesn't have BTF\n");
9073 		goto out;
9074 	}
9075 	btf = btf__load_from_kernel_by_id(info.btf_id);
9076 	err = libbpf_get_error(btf);
9077 	if (err) {
9078 		pr_warn("Failed to get BTF %d of the program: %d\n", info.btf_id, err);
9079 		goto out;
9080 	}
9081 	err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
9082 	btf__free(btf);
9083 	if (err <= 0) {
9084 		pr_warn("%s is not found in prog's BTF\n", name);
9085 		goto out;
9086 	}
9087 out:
9088 	return err;
9089 }
9090 
9091 static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
9092 			      enum bpf_attach_type attach_type,
9093 			      int *btf_obj_fd, int *btf_type_id)
9094 {
9095 	int ret, i;
9096 
9097 	ret = find_attach_btf_id(obj->btf_vmlinux, attach_name, attach_type);
9098 	if (ret > 0) {
9099 		*btf_obj_fd = 0; /* vmlinux BTF */
9100 		*btf_type_id = ret;
9101 		return 0;
9102 	}
9103 	if (ret != -ENOENT)
9104 		return ret;
9105 
9106 	ret = load_module_btfs(obj);
9107 	if (ret)
9108 		return ret;
9109 
9110 	for (i = 0; i < obj->btf_module_cnt; i++) {
9111 		const struct module_btf *mod = &obj->btf_modules[i];
9112 
9113 		ret = find_attach_btf_id(mod->btf, attach_name, attach_type);
9114 		if (ret > 0) {
9115 			*btf_obj_fd = mod->fd;
9116 			*btf_type_id = ret;
9117 			return 0;
9118 		}
9119 		if (ret == -ENOENT)
9120 			continue;
9121 
9122 		return ret;
9123 	}
9124 
9125 	return -ESRCH;
9126 }
9127 
9128 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
9129 				     int *btf_obj_fd, int *btf_type_id)
9130 {
9131 	enum bpf_attach_type attach_type = prog->expected_attach_type;
9132 	__u32 attach_prog_fd = prog->attach_prog_fd;
9133 	int err = 0;
9134 
9135 	/* BPF program's BTF ID */
9136 	if (prog->type == BPF_PROG_TYPE_EXT || attach_prog_fd) {
9137 		if (!attach_prog_fd) {
9138 			pr_warn("prog '%s': attach program FD is not set\n", prog->name);
9139 			return -EINVAL;
9140 		}
9141 		err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd);
9142 		if (err < 0) {
9143 			pr_warn("prog '%s': failed to find BPF program (FD %d) BTF ID for '%s': %d\n",
9144 				 prog->name, attach_prog_fd, attach_name, err);
9145 			return err;
9146 		}
9147 		*btf_obj_fd = 0;
9148 		*btf_type_id = err;
9149 		return 0;
9150 	}
9151 
9152 	/* kernel/module BTF ID */
9153 	if (prog->obj->gen_loader) {
9154 		bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
9155 		*btf_obj_fd = 0;
9156 		*btf_type_id = 1;
9157 	} else {
9158 		err = find_kernel_btf_id(prog->obj, attach_name, attach_type, btf_obj_fd, btf_type_id);
9159 	}
9160 	if (err) {
9161 		pr_warn("prog '%s': failed to find kernel BTF type ID of '%s': %d\n",
9162 			prog->name, attach_name, err);
9163 		return err;
9164 	}
9165 	return 0;
9166 }
9167 
9168 int libbpf_attach_type_by_name(const char *name,
9169 			       enum bpf_attach_type *attach_type)
9170 {
9171 	char *type_names;
9172 	const struct bpf_sec_def *sec_def;
9173 
9174 	if (!name)
9175 		return libbpf_err(-EINVAL);
9176 
9177 	sec_def = find_sec_def(name);
9178 	if (!sec_def) {
9179 		pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
9180 		type_names = libbpf_get_type_names(true);
9181 		if (type_names != NULL) {
9182 			pr_debug("attachable section(type) names are:%s\n", type_names);
9183 			free(type_names);
9184 		}
9185 
9186 		return libbpf_err(-EINVAL);
9187 	}
9188 
9189 	if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
9190 		return libbpf_err(-EINVAL);
9191 	if (!(sec_def->cookie & SEC_ATTACHABLE))
9192 		return libbpf_err(-EINVAL);
9193 
9194 	*attach_type = sec_def->expected_attach_type;
9195 	return 0;
9196 }
9197 
9198 int bpf_map__fd(const struct bpf_map *map)
9199 {
9200 	return map ? map->fd : libbpf_err(-EINVAL);
9201 }
9202 
9203 static bool map_uses_real_name(const struct bpf_map *map)
9204 {
9205 	/* Since libbpf started to support custom .data.* and .rodata.* maps,
9206 	 * their user-visible name differs from kernel-visible name. Users see
9207 	 * such map's corresponding ELF section name as a map name.
9208 	 * This check distinguishes .data/.rodata from .data.* and .rodata.*
9209 	 * maps to know which name has to be returned to the user.
9210 	 */
9211 	if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
9212 		return true;
9213 	if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
9214 		return true;
9215 	return false;
9216 }
9217 
9218 const char *bpf_map__name(const struct bpf_map *map)
9219 {
9220 	if (!map)
9221 		return NULL;
9222 
9223 	if (map_uses_real_name(map))
9224 		return map->real_name;
9225 
9226 	return map->name;
9227 }
9228 
9229 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
9230 {
9231 	return map->def.type;
9232 }
9233 
9234 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
9235 {
9236 	if (map->fd >= 0)
9237 		return libbpf_err(-EBUSY);
9238 	map->def.type = type;
9239 	return 0;
9240 }
9241 
9242 __u32 bpf_map__map_flags(const struct bpf_map *map)
9243 {
9244 	return map->def.map_flags;
9245 }
9246 
9247 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
9248 {
9249 	if (map->fd >= 0)
9250 		return libbpf_err(-EBUSY);
9251 	map->def.map_flags = flags;
9252 	return 0;
9253 }
9254 
9255 __u64 bpf_map__map_extra(const struct bpf_map *map)
9256 {
9257 	return map->map_extra;
9258 }
9259 
9260 int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
9261 {
9262 	if (map->fd >= 0)
9263 		return libbpf_err(-EBUSY);
9264 	map->map_extra = map_extra;
9265 	return 0;
9266 }
9267 
9268 __u32 bpf_map__numa_node(const struct bpf_map *map)
9269 {
9270 	return map->numa_node;
9271 }
9272 
9273 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
9274 {
9275 	if (map->fd >= 0)
9276 		return libbpf_err(-EBUSY);
9277 	map->numa_node = numa_node;
9278 	return 0;
9279 }
9280 
9281 __u32 bpf_map__key_size(const struct bpf_map *map)
9282 {
9283 	return map->def.key_size;
9284 }
9285 
9286 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
9287 {
9288 	if (map->fd >= 0)
9289 		return libbpf_err(-EBUSY);
9290 	map->def.key_size = size;
9291 	return 0;
9292 }
9293 
9294 __u32 bpf_map__value_size(const struct bpf_map *map)
9295 {
9296 	return map->def.value_size;
9297 }
9298 
9299 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
9300 {
9301 	if (map->fd >= 0)
9302 		return libbpf_err(-EBUSY);
9303 	map->def.value_size = size;
9304 	return 0;
9305 }
9306 
9307 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
9308 {
9309 	return map ? map->btf_key_type_id : 0;
9310 }
9311 
9312 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
9313 {
9314 	return map ? map->btf_value_type_id : 0;
9315 }
9316 
9317 int bpf_map__set_initial_value(struct bpf_map *map,
9318 			       const void *data, size_t size)
9319 {
9320 	if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG ||
9321 	    size != map->def.value_size || map->fd >= 0)
9322 		return libbpf_err(-EINVAL);
9323 
9324 	memcpy(map->mmaped, data, size);
9325 	return 0;
9326 }
9327 
9328 const void *bpf_map__initial_value(struct bpf_map *map, size_t *psize)
9329 {
9330 	if (!map->mmaped)
9331 		return NULL;
9332 	*psize = map->def.value_size;
9333 	return map->mmaped;
9334 }
9335 
9336 bool bpf_map__is_internal(const struct bpf_map *map)
9337 {
9338 	return map->libbpf_type != LIBBPF_MAP_UNSPEC;
9339 }
9340 
9341 __u32 bpf_map__ifindex(const struct bpf_map *map)
9342 {
9343 	return map->map_ifindex;
9344 }
9345 
9346 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
9347 {
9348 	if (map->fd >= 0)
9349 		return libbpf_err(-EBUSY);
9350 	map->map_ifindex = ifindex;
9351 	return 0;
9352 }
9353 
9354 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
9355 {
9356 	if (!bpf_map_type__is_map_in_map(map->def.type)) {
9357 		pr_warn("error: unsupported map type\n");
9358 		return libbpf_err(-EINVAL);
9359 	}
9360 	if (map->inner_map_fd != -1) {
9361 		pr_warn("error: inner_map_fd already specified\n");
9362 		return libbpf_err(-EINVAL);
9363 	}
9364 	if (map->inner_map) {
9365 		bpf_map__destroy(map->inner_map);
9366 		zfree(&map->inner_map);
9367 	}
9368 	map->inner_map_fd = fd;
9369 	return 0;
9370 }
9371 
9372 static struct bpf_map *
9373 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
9374 {
9375 	ssize_t idx;
9376 	struct bpf_map *s, *e;
9377 
9378 	if (!obj || !obj->maps)
9379 		return errno = EINVAL, NULL;
9380 
9381 	s = obj->maps;
9382 	e = obj->maps + obj->nr_maps;
9383 
9384 	if ((m < s) || (m >= e)) {
9385 		pr_warn("error in %s: map handler doesn't belong to object\n",
9386 			 __func__);
9387 		return errno = EINVAL, NULL;
9388 	}
9389 
9390 	idx = (m - obj->maps) + i;
9391 	if (idx >= obj->nr_maps || idx < 0)
9392 		return NULL;
9393 	return &obj->maps[idx];
9394 }
9395 
9396 struct bpf_map *
9397 bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
9398 {
9399 	if (prev == NULL)
9400 		return obj->maps;
9401 
9402 	return __bpf_map__iter(prev, obj, 1);
9403 }
9404 
9405 struct bpf_map *
9406 bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
9407 {
9408 	if (next == NULL) {
9409 		if (!obj->nr_maps)
9410 			return NULL;
9411 		return obj->maps + obj->nr_maps - 1;
9412 	}
9413 
9414 	return __bpf_map__iter(next, obj, -1);
9415 }
9416 
9417 struct bpf_map *
9418 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
9419 {
9420 	struct bpf_map *pos;
9421 
9422 	bpf_object__for_each_map(pos, obj) {
9423 		/* if it's a special internal map name (which always starts
9424 		 * with dot) then check if that special name matches the
9425 		 * real map name (ELF section name)
9426 		 */
9427 		if (name[0] == '.') {
9428 			if (pos->real_name && strcmp(pos->real_name, name) == 0)
9429 				return pos;
9430 			continue;
9431 		}
9432 		/* otherwise map name has to be an exact match */
9433 		if (map_uses_real_name(pos)) {
9434 			if (strcmp(pos->real_name, name) == 0)
9435 				return pos;
9436 			continue;
9437 		}
9438 		if (strcmp(pos->name, name) == 0)
9439 			return pos;
9440 	}
9441 	return errno = ENOENT, NULL;
9442 }
9443 
9444 int
9445 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
9446 {
9447 	return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
9448 }
9449 
9450 static int validate_map_op(const struct bpf_map *map, size_t key_sz,
9451 			   size_t value_sz, bool check_value_sz)
9452 {
9453 	if (map->fd <= 0)
9454 		return -ENOENT;
9455 
9456 	if (map->def.key_size != key_sz) {
9457 		pr_warn("map '%s': unexpected key size %zu provided, expected %u\n",
9458 			map->name, key_sz, map->def.key_size);
9459 		return -EINVAL;
9460 	}
9461 
9462 	if (!check_value_sz)
9463 		return 0;
9464 
9465 	switch (map->def.type) {
9466 	case BPF_MAP_TYPE_PERCPU_ARRAY:
9467 	case BPF_MAP_TYPE_PERCPU_HASH:
9468 	case BPF_MAP_TYPE_LRU_PERCPU_HASH:
9469 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: {
9470 		int num_cpu = libbpf_num_possible_cpus();
9471 		size_t elem_sz = roundup(map->def.value_size, 8);
9472 
9473 		if (value_sz != num_cpu * elem_sz) {
9474 			pr_warn("map '%s': unexpected value size %zu provided for per-CPU map, expected %d * %zu = %zd\n",
9475 				map->name, value_sz, num_cpu, elem_sz, num_cpu * elem_sz);
9476 			return -EINVAL;
9477 		}
9478 		break;
9479 	}
9480 	default:
9481 		if (map->def.value_size != value_sz) {
9482 			pr_warn("map '%s': unexpected value size %zu provided, expected %u\n",
9483 				map->name, value_sz, map->def.value_size);
9484 			return -EINVAL;
9485 		}
9486 		break;
9487 	}
9488 	return 0;
9489 }
9490 
9491 int bpf_map__lookup_elem(const struct bpf_map *map,
9492 			 const void *key, size_t key_sz,
9493 			 void *value, size_t value_sz, __u64 flags)
9494 {
9495 	int err;
9496 
9497 	err = validate_map_op(map, key_sz, value_sz, true);
9498 	if (err)
9499 		return libbpf_err(err);
9500 
9501 	return bpf_map_lookup_elem_flags(map->fd, key, value, flags);
9502 }
9503 
9504 int bpf_map__update_elem(const struct bpf_map *map,
9505 			 const void *key, size_t key_sz,
9506 			 const void *value, size_t value_sz, __u64 flags)
9507 {
9508 	int err;
9509 
9510 	err = validate_map_op(map, key_sz, value_sz, true);
9511 	if (err)
9512 		return libbpf_err(err);
9513 
9514 	return bpf_map_update_elem(map->fd, key, value, flags);
9515 }
9516 
9517 int bpf_map__delete_elem(const struct bpf_map *map,
9518 			 const void *key, size_t key_sz, __u64 flags)
9519 {
9520 	int err;
9521 
9522 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
9523 	if (err)
9524 		return libbpf_err(err);
9525 
9526 	return bpf_map_delete_elem_flags(map->fd, key, flags);
9527 }
9528 
9529 int bpf_map__lookup_and_delete_elem(const struct bpf_map *map,
9530 				    const void *key, size_t key_sz,
9531 				    void *value, size_t value_sz, __u64 flags)
9532 {
9533 	int err;
9534 
9535 	err = validate_map_op(map, key_sz, value_sz, true);
9536 	if (err)
9537 		return libbpf_err(err);
9538 
9539 	return bpf_map_lookup_and_delete_elem_flags(map->fd, key, value, flags);
9540 }
9541 
9542 int bpf_map__get_next_key(const struct bpf_map *map,
9543 			  const void *cur_key, void *next_key, size_t key_sz)
9544 {
9545 	int err;
9546 
9547 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
9548 	if (err)
9549 		return libbpf_err(err);
9550 
9551 	return bpf_map_get_next_key(map->fd, cur_key, next_key);
9552 }
9553 
9554 long libbpf_get_error(const void *ptr)
9555 {
9556 	if (!IS_ERR_OR_NULL(ptr))
9557 		return 0;
9558 
9559 	if (IS_ERR(ptr))
9560 		errno = -PTR_ERR(ptr);
9561 
9562 	/* If ptr == NULL, then errno should be already set by the failing
9563 	 * API, because libbpf never returns NULL on success and it now always
9564 	 * sets errno on error. So no extra errno handling for ptr == NULL
9565 	 * case.
9566 	 */
9567 	return -errno;
9568 }
9569 
9570 /* Replace link's underlying BPF program with the new one */
9571 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
9572 {
9573 	int ret;
9574 
9575 	ret = bpf_link_update(bpf_link__fd(link), bpf_program__fd(prog), NULL);
9576 	return libbpf_err_errno(ret);
9577 }
9578 
9579 /* Release "ownership" of underlying BPF resource (typically, BPF program
9580  * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
9581  * link, when destructed through bpf_link__destroy() call won't attempt to
9582  * detach/unregisted that BPF resource. This is useful in situations where,
9583  * say, attached BPF program has to outlive userspace program that attached it
9584  * in the system. Depending on type of BPF program, though, there might be
9585  * additional steps (like pinning BPF program in BPF FS) necessary to ensure
9586  * exit of userspace program doesn't trigger automatic detachment and clean up
9587  * inside the kernel.
9588  */
9589 void bpf_link__disconnect(struct bpf_link *link)
9590 {
9591 	link->disconnected = true;
9592 }
9593 
9594 int bpf_link__destroy(struct bpf_link *link)
9595 {
9596 	int err = 0;
9597 
9598 	if (IS_ERR_OR_NULL(link))
9599 		return 0;
9600 
9601 	if (!link->disconnected && link->detach)
9602 		err = link->detach(link);
9603 	if (link->pin_path)
9604 		free(link->pin_path);
9605 	if (link->dealloc)
9606 		link->dealloc(link);
9607 	else
9608 		free(link);
9609 
9610 	return libbpf_err(err);
9611 }
9612 
9613 int bpf_link__fd(const struct bpf_link *link)
9614 {
9615 	return link->fd;
9616 }
9617 
9618 const char *bpf_link__pin_path(const struct bpf_link *link)
9619 {
9620 	return link->pin_path;
9621 }
9622 
9623 static int bpf_link__detach_fd(struct bpf_link *link)
9624 {
9625 	return libbpf_err_errno(close(link->fd));
9626 }
9627 
9628 struct bpf_link *bpf_link__open(const char *path)
9629 {
9630 	struct bpf_link *link;
9631 	int fd;
9632 
9633 	fd = bpf_obj_get(path);
9634 	if (fd < 0) {
9635 		fd = -errno;
9636 		pr_warn("failed to open link at %s: %d\n", path, fd);
9637 		return libbpf_err_ptr(fd);
9638 	}
9639 
9640 	link = calloc(1, sizeof(*link));
9641 	if (!link) {
9642 		close(fd);
9643 		return libbpf_err_ptr(-ENOMEM);
9644 	}
9645 	link->detach = &bpf_link__detach_fd;
9646 	link->fd = fd;
9647 
9648 	link->pin_path = strdup(path);
9649 	if (!link->pin_path) {
9650 		bpf_link__destroy(link);
9651 		return libbpf_err_ptr(-ENOMEM);
9652 	}
9653 
9654 	return link;
9655 }
9656 
9657 int bpf_link__detach(struct bpf_link *link)
9658 {
9659 	return bpf_link_detach(link->fd) ? -errno : 0;
9660 }
9661 
9662 int bpf_link__pin(struct bpf_link *link, const char *path)
9663 {
9664 	int err;
9665 
9666 	if (link->pin_path)
9667 		return libbpf_err(-EBUSY);
9668 	err = make_parent_dir(path);
9669 	if (err)
9670 		return libbpf_err(err);
9671 	err = check_path(path);
9672 	if (err)
9673 		return libbpf_err(err);
9674 
9675 	link->pin_path = strdup(path);
9676 	if (!link->pin_path)
9677 		return libbpf_err(-ENOMEM);
9678 
9679 	if (bpf_obj_pin(link->fd, link->pin_path)) {
9680 		err = -errno;
9681 		zfree(&link->pin_path);
9682 		return libbpf_err(err);
9683 	}
9684 
9685 	pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
9686 	return 0;
9687 }
9688 
9689 int bpf_link__unpin(struct bpf_link *link)
9690 {
9691 	int err;
9692 
9693 	if (!link->pin_path)
9694 		return libbpf_err(-EINVAL);
9695 
9696 	err = unlink(link->pin_path);
9697 	if (err != 0)
9698 		return -errno;
9699 
9700 	pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
9701 	zfree(&link->pin_path);
9702 	return 0;
9703 }
9704 
9705 struct bpf_link_perf {
9706 	struct bpf_link link;
9707 	int perf_event_fd;
9708 	/* legacy kprobe support: keep track of probe identifier and type */
9709 	char *legacy_probe_name;
9710 	bool legacy_is_kprobe;
9711 	bool legacy_is_retprobe;
9712 };
9713 
9714 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
9715 static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
9716 
9717 static int bpf_link_perf_detach(struct bpf_link *link)
9718 {
9719 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
9720 	int err = 0;
9721 
9722 	if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
9723 		err = -errno;
9724 
9725 	if (perf_link->perf_event_fd != link->fd)
9726 		close(perf_link->perf_event_fd);
9727 	close(link->fd);
9728 
9729 	/* legacy uprobe/kprobe needs to be removed after perf event fd closure */
9730 	if (perf_link->legacy_probe_name) {
9731 		if (perf_link->legacy_is_kprobe) {
9732 			err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
9733 							 perf_link->legacy_is_retprobe);
9734 		} else {
9735 			err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
9736 							 perf_link->legacy_is_retprobe);
9737 		}
9738 	}
9739 
9740 	return err;
9741 }
9742 
9743 static void bpf_link_perf_dealloc(struct bpf_link *link)
9744 {
9745 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
9746 
9747 	free(perf_link->legacy_probe_name);
9748 	free(perf_link);
9749 }
9750 
9751 struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
9752 						     const struct bpf_perf_event_opts *opts)
9753 {
9754 	char errmsg[STRERR_BUFSIZE];
9755 	struct bpf_link_perf *link;
9756 	int prog_fd, link_fd = -1, err;
9757 
9758 	if (!OPTS_VALID(opts, bpf_perf_event_opts))
9759 		return libbpf_err_ptr(-EINVAL);
9760 
9761 	if (pfd < 0) {
9762 		pr_warn("prog '%s': invalid perf event FD %d\n",
9763 			prog->name, pfd);
9764 		return libbpf_err_ptr(-EINVAL);
9765 	}
9766 	prog_fd = bpf_program__fd(prog);
9767 	if (prog_fd < 0) {
9768 		pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
9769 			prog->name);
9770 		return libbpf_err_ptr(-EINVAL);
9771 	}
9772 
9773 	link = calloc(1, sizeof(*link));
9774 	if (!link)
9775 		return libbpf_err_ptr(-ENOMEM);
9776 	link->link.detach = &bpf_link_perf_detach;
9777 	link->link.dealloc = &bpf_link_perf_dealloc;
9778 	link->perf_event_fd = pfd;
9779 
9780 	if (kernel_supports(prog->obj, FEAT_PERF_LINK)) {
9781 		DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
9782 			.perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
9783 
9784 		link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
9785 		if (link_fd < 0) {
9786 			err = -errno;
9787 			pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %d (%s)\n",
9788 				prog->name, pfd,
9789 				err, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9790 			goto err_out;
9791 		}
9792 		link->link.fd = link_fd;
9793 	} else {
9794 		if (OPTS_GET(opts, bpf_cookie, 0)) {
9795 			pr_warn("prog '%s': user context value is not supported\n", prog->name);
9796 			err = -EOPNOTSUPP;
9797 			goto err_out;
9798 		}
9799 
9800 		if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
9801 			err = -errno;
9802 			pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
9803 				prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9804 			if (err == -EPROTO)
9805 				pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
9806 					prog->name, pfd);
9807 			goto err_out;
9808 		}
9809 		link->link.fd = pfd;
9810 	}
9811 	if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
9812 		err = -errno;
9813 		pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
9814 			prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9815 		goto err_out;
9816 	}
9817 
9818 	return &link->link;
9819 err_out:
9820 	if (link_fd >= 0)
9821 		close(link_fd);
9822 	free(link);
9823 	return libbpf_err_ptr(err);
9824 }
9825 
9826 struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
9827 {
9828 	return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
9829 }
9830 
9831 /*
9832  * this function is expected to parse integer in the range of [0, 2^31-1] from
9833  * given file using scanf format string fmt. If actual parsed value is
9834  * negative, the result might be indistinguishable from error
9835  */
9836 static int parse_uint_from_file(const char *file, const char *fmt)
9837 {
9838 	char buf[STRERR_BUFSIZE];
9839 	int err, ret;
9840 	FILE *f;
9841 
9842 	f = fopen(file, "r");
9843 	if (!f) {
9844 		err = -errno;
9845 		pr_debug("failed to open '%s': %s\n", file,
9846 			 libbpf_strerror_r(err, buf, sizeof(buf)));
9847 		return err;
9848 	}
9849 	err = fscanf(f, fmt, &ret);
9850 	if (err != 1) {
9851 		err = err == EOF ? -EIO : -errno;
9852 		pr_debug("failed to parse '%s': %s\n", file,
9853 			libbpf_strerror_r(err, buf, sizeof(buf)));
9854 		fclose(f);
9855 		return err;
9856 	}
9857 	fclose(f);
9858 	return ret;
9859 }
9860 
9861 static int determine_kprobe_perf_type(void)
9862 {
9863 	const char *file = "/sys/bus/event_source/devices/kprobe/type";
9864 
9865 	return parse_uint_from_file(file, "%d\n");
9866 }
9867 
9868 static int determine_uprobe_perf_type(void)
9869 {
9870 	const char *file = "/sys/bus/event_source/devices/uprobe/type";
9871 
9872 	return parse_uint_from_file(file, "%d\n");
9873 }
9874 
9875 static int determine_kprobe_retprobe_bit(void)
9876 {
9877 	const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
9878 
9879 	return parse_uint_from_file(file, "config:%d\n");
9880 }
9881 
9882 static int determine_uprobe_retprobe_bit(void)
9883 {
9884 	const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
9885 
9886 	return parse_uint_from_file(file, "config:%d\n");
9887 }
9888 
9889 #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
9890 #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
9891 
9892 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
9893 				 uint64_t offset, int pid, size_t ref_ctr_off)
9894 {
9895 	const size_t attr_sz = sizeof(struct perf_event_attr);
9896 	struct perf_event_attr attr;
9897 	char errmsg[STRERR_BUFSIZE];
9898 	int type, pfd;
9899 
9900 	if (ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
9901 		return -EINVAL;
9902 
9903 	memset(&attr, 0, attr_sz);
9904 
9905 	type = uprobe ? determine_uprobe_perf_type()
9906 		      : determine_kprobe_perf_type();
9907 	if (type < 0) {
9908 		pr_warn("failed to determine %s perf type: %s\n",
9909 			uprobe ? "uprobe" : "kprobe",
9910 			libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
9911 		return type;
9912 	}
9913 	if (retprobe) {
9914 		int bit = uprobe ? determine_uprobe_retprobe_bit()
9915 				 : determine_kprobe_retprobe_bit();
9916 
9917 		if (bit < 0) {
9918 			pr_warn("failed to determine %s retprobe bit: %s\n",
9919 				uprobe ? "uprobe" : "kprobe",
9920 				libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
9921 			return bit;
9922 		}
9923 		attr.config |= 1 << bit;
9924 	}
9925 	attr.size = attr_sz;
9926 	attr.type = type;
9927 	attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
9928 	attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
9929 	attr.config2 = offset;		 /* kprobe_addr or probe_offset */
9930 
9931 	/* pid filter is meaningful only for uprobes */
9932 	pfd = syscall(__NR_perf_event_open, &attr,
9933 		      pid < 0 ? -1 : pid /* pid */,
9934 		      pid == -1 ? 0 : -1 /* cpu */,
9935 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
9936 	return pfd >= 0 ? pfd : -errno;
9937 }
9938 
9939 static int append_to_file(const char *file, const char *fmt, ...)
9940 {
9941 	int fd, n, err = 0;
9942 	va_list ap;
9943 
9944 	fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
9945 	if (fd < 0)
9946 		return -errno;
9947 
9948 	va_start(ap, fmt);
9949 	n = vdprintf(fd, fmt, ap);
9950 	va_end(ap);
9951 
9952 	if (n < 0)
9953 		err = -errno;
9954 
9955 	close(fd);
9956 	return err;
9957 }
9958 
9959 #define DEBUGFS "/sys/kernel/debug/tracing"
9960 #define TRACEFS "/sys/kernel/tracing"
9961 
9962 static bool use_debugfs(void)
9963 {
9964 	static int has_debugfs = -1;
9965 
9966 	if (has_debugfs < 0)
9967 		has_debugfs = faccessat(AT_FDCWD, DEBUGFS, F_OK, AT_EACCESS) == 0;
9968 
9969 	return has_debugfs == 1;
9970 }
9971 
9972 static const char *tracefs_path(void)
9973 {
9974 	return use_debugfs() ? DEBUGFS : TRACEFS;
9975 }
9976 
9977 static const char *tracefs_kprobe_events(void)
9978 {
9979 	return use_debugfs() ? DEBUGFS"/kprobe_events" : TRACEFS"/kprobe_events";
9980 }
9981 
9982 static const char *tracefs_uprobe_events(void)
9983 {
9984 	return use_debugfs() ? DEBUGFS"/uprobe_events" : TRACEFS"/uprobe_events";
9985 }
9986 
9987 static void gen_kprobe_legacy_event_name(char *buf, size_t buf_sz,
9988 					 const char *kfunc_name, size_t offset)
9989 {
9990 	static int index = 0;
9991 
9992 	snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx_%d", getpid(), kfunc_name, offset,
9993 		 __sync_fetch_and_add(&index, 1));
9994 }
9995 
9996 static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
9997 				   const char *kfunc_name, size_t offset)
9998 {
9999 	return append_to_file(tracefs_kprobe_events(), "%c:%s/%s %s+0x%zx",
10000 			      retprobe ? 'r' : 'p',
10001 			      retprobe ? "kretprobes" : "kprobes",
10002 			      probe_name, kfunc_name, offset);
10003 }
10004 
10005 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
10006 {
10007 	return append_to_file(tracefs_kprobe_events(), "-:%s/%s",
10008 			      retprobe ? "kretprobes" : "kprobes", probe_name);
10009 }
10010 
10011 static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
10012 {
10013 	char file[256];
10014 
10015 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
10016 		 tracefs_path(), retprobe ? "kretprobes" : "kprobes", probe_name);
10017 
10018 	return parse_uint_from_file(file, "%d\n");
10019 }
10020 
10021 static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
10022 					 const char *kfunc_name, size_t offset, int pid)
10023 {
10024 	const size_t attr_sz = sizeof(struct perf_event_attr);
10025 	struct perf_event_attr attr;
10026 	char errmsg[STRERR_BUFSIZE];
10027 	int type, pfd, err;
10028 
10029 	err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
10030 	if (err < 0) {
10031 		pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
10032 			kfunc_name, offset,
10033 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10034 		return err;
10035 	}
10036 	type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
10037 	if (type < 0) {
10038 		err = type;
10039 		pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
10040 			kfunc_name, offset,
10041 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10042 		goto err_clean_legacy;
10043 	}
10044 
10045 	memset(&attr, 0, attr_sz);
10046 	attr.size = attr_sz;
10047 	attr.config = type;
10048 	attr.type = PERF_TYPE_TRACEPOINT;
10049 
10050 	pfd = syscall(__NR_perf_event_open, &attr,
10051 		      pid < 0 ? -1 : pid, /* pid */
10052 		      pid == -1 ? 0 : -1, /* cpu */
10053 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
10054 	if (pfd < 0) {
10055 		err = -errno;
10056 		pr_warn("legacy kprobe perf_event_open() failed: %s\n",
10057 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10058 		goto err_clean_legacy;
10059 	}
10060 	return pfd;
10061 
10062 err_clean_legacy:
10063 	/* Clear the newly added legacy kprobe_event */
10064 	remove_kprobe_event_legacy(probe_name, retprobe);
10065 	return err;
10066 }
10067 
10068 static const char *arch_specific_syscall_pfx(void)
10069 {
10070 #if defined(__x86_64__)
10071 	return "x64";
10072 #elif defined(__i386__)
10073 	return "ia32";
10074 #elif defined(__s390x__)
10075 	return "s390x";
10076 #elif defined(__s390__)
10077 	return "s390";
10078 #elif defined(__arm__)
10079 	return "arm";
10080 #elif defined(__aarch64__)
10081 	return "arm64";
10082 #elif defined(__mips__)
10083 	return "mips";
10084 #elif defined(__riscv)
10085 	return "riscv";
10086 #elif defined(__powerpc__)
10087 	return "powerpc";
10088 #elif defined(__powerpc64__)
10089 	return "powerpc64";
10090 #else
10091 	return NULL;
10092 #endif
10093 }
10094 
10095 static int probe_kern_syscall_wrapper(void)
10096 {
10097 	char syscall_name[64];
10098 	const char *ksys_pfx;
10099 
10100 	ksys_pfx = arch_specific_syscall_pfx();
10101 	if (!ksys_pfx)
10102 		return 0;
10103 
10104 	snprintf(syscall_name, sizeof(syscall_name), "__%s_sys_bpf", ksys_pfx);
10105 
10106 	if (determine_kprobe_perf_type() >= 0) {
10107 		int pfd;
10108 
10109 		pfd = perf_event_open_probe(false, false, syscall_name, 0, getpid(), 0);
10110 		if (pfd >= 0)
10111 			close(pfd);
10112 
10113 		return pfd >= 0 ? 1 : 0;
10114 	} else { /* legacy mode */
10115 		char probe_name[128];
10116 
10117 		gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name), syscall_name, 0);
10118 		if (add_kprobe_event_legacy(probe_name, false, syscall_name, 0) < 0)
10119 			return 0;
10120 
10121 		(void)remove_kprobe_event_legacy(probe_name, false);
10122 		return 1;
10123 	}
10124 }
10125 
10126 struct bpf_link *
10127 bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
10128 				const char *func_name,
10129 				const struct bpf_kprobe_opts *opts)
10130 {
10131 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
10132 	char errmsg[STRERR_BUFSIZE];
10133 	char *legacy_probe = NULL;
10134 	struct bpf_link *link;
10135 	size_t offset;
10136 	bool retprobe, legacy;
10137 	int pfd, err;
10138 
10139 	if (!OPTS_VALID(opts, bpf_kprobe_opts))
10140 		return libbpf_err_ptr(-EINVAL);
10141 
10142 	retprobe = OPTS_GET(opts, retprobe, false);
10143 	offset = OPTS_GET(opts, offset, 0);
10144 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10145 
10146 	legacy = determine_kprobe_perf_type() < 0;
10147 	if (!legacy) {
10148 		pfd = perf_event_open_probe(false /* uprobe */, retprobe,
10149 					    func_name, offset,
10150 					    -1 /* pid */, 0 /* ref_ctr_off */);
10151 	} else {
10152 		char probe_name[256];
10153 
10154 		gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name),
10155 					     func_name, offset);
10156 
10157 		legacy_probe = strdup(probe_name);
10158 		if (!legacy_probe)
10159 			return libbpf_err_ptr(-ENOMEM);
10160 
10161 		pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
10162 						    offset, -1 /* pid */);
10163 	}
10164 	if (pfd < 0) {
10165 		err = -errno;
10166 		pr_warn("prog '%s': failed to create %s '%s+0x%zx' perf event: %s\n",
10167 			prog->name, retprobe ? "kretprobe" : "kprobe",
10168 			func_name, offset,
10169 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10170 		goto err_out;
10171 	}
10172 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
10173 	err = libbpf_get_error(link);
10174 	if (err) {
10175 		close(pfd);
10176 		pr_warn("prog '%s': failed to attach to %s '%s+0x%zx': %s\n",
10177 			prog->name, retprobe ? "kretprobe" : "kprobe",
10178 			func_name, offset,
10179 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10180 		goto err_clean_legacy;
10181 	}
10182 	if (legacy) {
10183 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10184 
10185 		perf_link->legacy_probe_name = legacy_probe;
10186 		perf_link->legacy_is_kprobe = true;
10187 		perf_link->legacy_is_retprobe = retprobe;
10188 	}
10189 
10190 	return link;
10191 
10192 err_clean_legacy:
10193 	if (legacy)
10194 		remove_kprobe_event_legacy(legacy_probe, retprobe);
10195 err_out:
10196 	free(legacy_probe);
10197 	return libbpf_err_ptr(err);
10198 }
10199 
10200 struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
10201 					    bool retprobe,
10202 					    const char *func_name)
10203 {
10204 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
10205 		.retprobe = retprobe,
10206 	);
10207 
10208 	return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
10209 }
10210 
10211 struct bpf_link *bpf_program__attach_ksyscall(const struct bpf_program *prog,
10212 					      const char *syscall_name,
10213 					      const struct bpf_ksyscall_opts *opts)
10214 {
10215 	LIBBPF_OPTS(bpf_kprobe_opts, kprobe_opts);
10216 	char func_name[128];
10217 
10218 	if (!OPTS_VALID(opts, bpf_ksyscall_opts))
10219 		return libbpf_err_ptr(-EINVAL);
10220 
10221 	if (kernel_supports(prog->obj, FEAT_SYSCALL_WRAPPER)) {
10222 		/* arch_specific_syscall_pfx() should never return NULL here
10223 		 * because it is guarded by kernel_supports(). However, since
10224 		 * compiler does not know that we have an explicit conditional
10225 		 * as well.
10226 		 */
10227 		snprintf(func_name, sizeof(func_name), "__%s_sys_%s",
10228 			 arch_specific_syscall_pfx() ? : "", syscall_name);
10229 	} else {
10230 		snprintf(func_name, sizeof(func_name), "__se_sys_%s", syscall_name);
10231 	}
10232 
10233 	kprobe_opts.retprobe = OPTS_GET(opts, retprobe, false);
10234 	kprobe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10235 
10236 	return bpf_program__attach_kprobe_opts(prog, func_name, &kprobe_opts);
10237 }
10238 
10239 /* Adapted from perf/util/string.c */
10240 static bool glob_match(const char *str, const char *pat)
10241 {
10242 	while (*str && *pat && *pat != '*') {
10243 		if (*pat == '?') {      /* Matches any single character */
10244 			str++;
10245 			pat++;
10246 			continue;
10247 		}
10248 		if (*str != *pat)
10249 			return false;
10250 		str++;
10251 		pat++;
10252 	}
10253 	/* Check wild card */
10254 	if (*pat == '*') {
10255 		while (*pat == '*')
10256 			pat++;
10257 		if (!*pat) /* Tail wild card matches all */
10258 			return true;
10259 		while (*str)
10260 			if (glob_match(str++, pat))
10261 				return true;
10262 	}
10263 	return !*str && !*pat;
10264 }
10265 
10266 struct kprobe_multi_resolve {
10267 	const char *pattern;
10268 	unsigned long *addrs;
10269 	size_t cap;
10270 	size_t cnt;
10271 };
10272 
10273 static int
10274 resolve_kprobe_multi_cb(unsigned long long sym_addr, char sym_type,
10275 			const char *sym_name, void *ctx)
10276 {
10277 	struct kprobe_multi_resolve *res = ctx;
10278 	int err;
10279 
10280 	if (!glob_match(sym_name, res->pattern))
10281 		return 0;
10282 
10283 	err = libbpf_ensure_mem((void **) &res->addrs, &res->cap, sizeof(unsigned long),
10284 				res->cnt + 1);
10285 	if (err)
10286 		return err;
10287 
10288 	res->addrs[res->cnt++] = (unsigned long) sym_addr;
10289 	return 0;
10290 }
10291 
10292 struct bpf_link *
10293 bpf_program__attach_kprobe_multi_opts(const struct bpf_program *prog,
10294 				      const char *pattern,
10295 				      const struct bpf_kprobe_multi_opts *opts)
10296 {
10297 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
10298 	struct kprobe_multi_resolve res = {
10299 		.pattern = pattern,
10300 	};
10301 	struct bpf_link *link = NULL;
10302 	char errmsg[STRERR_BUFSIZE];
10303 	const unsigned long *addrs;
10304 	int err, link_fd, prog_fd;
10305 	const __u64 *cookies;
10306 	const char **syms;
10307 	bool retprobe;
10308 	size_t cnt;
10309 
10310 	if (!OPTS_VALID(opts, bpf_kprobe_multi_opts))
10311 		return libbpf_err_ptr(-EINVAL);
10312 
10313 	syms    = OPTS_GET(opts, syms, false);
10314 	addrs   = OPTS_GET(opts, addrs, false);
10315 	cnt     = OPTS_GET(opts, cnt, false);
10316 	cookies = OPTS_GET(opts, cookies, false);
10317 
10318 	if (!pattern && !addrs && !syms)
10319 		return libbpf_err_ptr(-EINVAL);
10320 	if (pattern && (addrs || syms || cookies || cnt))
10321 		return libbpf_err_ptr(-EINVAL);
10322 	if (!pattern && !cnt)
10323 		return libbpf_err_ptr(-EINVAL);
10324 	if (addrs && syms)
10325 		return libbpf_err_ptr(-EINVAL);
10326 
10327 	if (pattern) {
10328 		err = libbpf_kallsyms_parse(resolve_kprobe_multi_cb, &res);
10329 		if (err)
10330 			goto error;
10331 		if (!res.cnt) {
10332 			err = -ENOENT;
10333 			goto error;
10334 		}
10335 		addrs = res.addrs;
10336 		cnt = res.cnt;
10337 	}
10338 
10339 	retprobe = OPTS_GET(opts, retprobe, false);
10340 
10341 	lopts.kprobe_multi.syms = syms;
10342 	lopts.kprobe_multi.addrs = addrs;
10343 	lopts.kprobe_multi.cookies = cookies;
10344 	lopts.kprobe_multi.cnt = cnt;
10345 	lopts.kprobe_multi.flags = retprobe ? BPF_F_KPROBE_MULTI_RETURN : 0;
10346 
10347 	link = calloc(1, sizeof(*link));
10348 	if (!link) {
10349 		err = -ENOMEM;
10350 		goto error;
10351 	}
10352 	link->detach = &bpf_link__detach_fd;
10353 
10354 	prog_fd = bpf_program__fd(prog);
10355 	link_fd = bpf_link_create(prog_fd, 0, BPF_TRACE_KPROBE_MULTI, &lopts);
10356 	if (link_fd < 0) {
10357 		err = -errno;
10358 		pr_warn("prog '%s': failed to attach: %s\n",
10359 			prog->name, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10360 		goto error;
10361 	}
10362 	link->fd = link_fd;
10363 	free(res.addrs);
10364 	return link;
10365 
10366 error:
10367 	free(link);
10368 	free(res.addrs);
10369 	return libbpf_err_ptr(err);
10370 }
10371 
10372 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10373 {
10374 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
10375 	unsigned long offset = 0;
10376 	const char *func_name;
10377 	char *func;
10378 	int n;
10379 
10380 	*link = NULL;
10381 
10382 	/* no auto-attach for SEC("kprobe") and SEC("kretprobe") */
10383 	if (strcmp(prog->sec_name, "kprobe") == 0 || strcmp(prog->sec_name, "kretprobe") == 0)
10384 		return 0;
10385 
10386 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
10387 	if (opts.retprobe)
10388 		func_name = prog->sec_name + sizeof("kretprobe/") - 1;
10389 	else
10390 		func_name = prog->sec_name + sizeof("kprobe/") - 1;
10391 
10392 	n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
10393 	if (n < 1) {
10394 		pr_warn("kprobe name is invalid: %s\n", func_name);
10395 		return -EINVAL;
10396 	}
10397 	if (opts.retprobe && offset != 0) {
10398 		free(func);
10399 		pr_warn("kretprobes do not support offset specification\n");
10400 		return -EINVAL;
10401 	}
10402 
10403 	opts.offset = offset;
10404 	*link = bpf_program__attach_kprobe_opts(prog, func, &opts);
10405 	free(func);
10406 	return libbpf_get_error(*link);
10407 }
10408 
10409 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10410 {
10411 	LIBBPF_OPTS(bpf_ksyscall_opts, opts);
10412 	const char *syscall_name;
10413 
10414 	*link = NULL;
10415 
10416 	/* no auto-attach for SEC("ksyscall") and SEC("kretsyscall") */
10417 	if (strcmp(prog->sec_name, "ksyscall") == 0 || strcmp(prog->sec_name, "kretsyscall") == 0)
10418 		return 0;
10419 
10420 	opts.retprobe = str_has_pfx(prog->sec_name, "kretsyscall/");
10421 	if (opts.retprobe)
10422 		syscall_name = prog->sec_name + sizeof("kretsyscall/") - 1;
10423 	else
10424 		syscall_name = prog->sec_name + sizeof("ksyscall/") - 1;
10425 
10426 	*link = bpf_program__attach_ksyscall(prog, syscall_name, &opts);
10427 	return *link ? 0 : -errno;
10428 }
10429 
10430 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10431 {
10432 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts);
10433 	const char *spec;
10434 	char *pattern;
10435 	int n;
10436 
10437 	*link = NULL;
10438 
10439 	/* no auto-attach for SEC("kprobe.multi") and SEC("kretprobe.multi") */
10440 	if (strcmp(prog->sec_name, "kprobe.multi") == 0 ||
10441 	    strcmp(prog->sec_name, "kretprobe.multi") == 0)
10442 		return 0;
10443 
10444 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe.multi/");
10445 	if (opts.retprobe)
10446 		spec = prog->sec_name + sizeof("kretprobe.multi/") - 1;
10447 	else
10448 		spec = prog->sec_name + sizeof("kprobe.multi/") - 1;
10449 
10450 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
10451 	if (n < 1) {
10452 		pr_warn("kprobe multi pattern is invalid: %s\n", pattern);
10453 		return -EINVAL;
10454 	}
10455 
10456 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
10457 	free(pattern);
10458 	return libbpf_get_error(*link);
10459 }
10460 
10461 static void gen_uprobe_legacy_event_name(char *buf, size_t buf_sz,
10462 					 const char *binary_path, uint64_t offset)
10463 {
10464 	int i;
10465 
10466 	snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx", getpid(), binary_path, (size_t)offset);
10467 
10468 	/* sanitize binary_path in the probe name */
10469 	for (i = 0; buf[i]; i++) {
10470 		if (!isalnum(buf[i]))
10471 			buf[i] = '_';
10472 	}
10473 }
10474 
10475 static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
10476 					  const char *binary_path, size_t offset)
10477 {
10478 	return append_to_file(tracefs_uprobe_events(), "%c:%s/%s %s:0x%zx",
10479 			      retprobe ? 'r' : 'p',
10480 			      retprobe ? "uretprobes" : "uprobes",
10481 			      probe_name, binary_path, offset);
10482 }
10483 
10484 static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
10485 {
10486 	return append_to_file(tracefs_uprobe_events(), "-:%s/%s",
10487 			      retprobe ? "uretprobes" : "uprobes", probe_name);
10488 }
10489 
10490 static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
10491 {
10492 	char file[512];
10493 
10494 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
10495 		 tracefs_path(), retprobe ? "uretprobes" : "uprobes", probe_name);
10496 
10497 	return parse_uint_from_file(file, "%d\n");
10498 }
10499 
10500 static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
10501 					 const char *binary_path, size_t offset, int pid)
10502 {
10503 	const size_t attr_sz = sizeof(struct perf_event_attr);
10504 	struct perf_event_attr attr;
10505 	int type, pfd, err;
10506 
10507 	err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
10508 	if (err < 0) {
10509 		pr_warn("failed to add legacy uprobe event for %s:0x%zx: %d\n",
10510 			binary_path, (size_t)offset, err);
10511 		return err;
10512 	}
10513 	type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
10514 	if (type < 0) {
10515 		err = type;
10516 		pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %d\n",
10517 			binary_path, offset, err);
10518 		goto err_clean_legacy;
10519 	}
10520 
10521 	memset(&attr, 0, attr_sz);
10522 	attr.size = attr_sz;
10523 	attr.config = type;
10524 	attr.type = PERF_TYPE_TRACEPOINT;
10525 
10526 	pfd = syscall(__NR_perf_event_open, &attr,
10527 		      pid < 0 ? -1 : pid, /* pid */
10528 		      pid == -1 ? 0 : -1, /* cpu */
10529 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
10530 	if (pfd < 0) {
10531 		err = -errno;
10532 		pr_warn("legacy uprobe perf_event_open() failed: %d\n", err);
10533 		goto err_clean_legacy;
10534 	}
10535 	return pfd;
10536 
10537 err_clean_legacy:
10538 	/* Clear the newly added legacy uprobe_event */
10539 	remove_uprobe_event_legacy(probe_name, retprobe);
10540 	return err;
10541 }
10542 
10543 /* Return next ELF section of sh_type after scn, or first of that type if scn is NULL. */
10544 static Elf_Scn *elf_find_next_scn_by_type(Elf *elf, int sh_type, Elf_Scn *scn)
10545 {
10546 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
10547 		GElf_Shdr sh;
10548 
10549 		if (!gelf_getshdr(scn, &sh))
10550 			continue;
10551 		if (sh.sh_type == sh_type)
10552 			return scn;
10553 	}
10554 	return NULL;
10555 }
10556 
10557 /* Find offset of function name in object specified by path.  "name" matches
10558  * symbol name or name@@LIB for library functions.
10559  */
10560 static long elf_find_func_offset(const char *binary_path, const char *name)
10561 {
10562 	int fd, i, sh_types[2] = { SHT_DYNSYM, SHT_SYMTAB };
10563 	bool is_shared_lib, is_name_qualified;
10564 	char errmsg[STRERR_BUFSIZE];
10565 	long ret = -ENOENT;
10566 	size_t name_len;
10567 	GElf_Ehdr ehdr;
10568 	Elf *elf;
10569 
10570 	fd = open(binary_path, O_RDONLY | O_CLOEXEC);
10571 	if (fd < 0) {
10572 		ret = -errno;
10573 		pr_warn("failed to open %s: %s\n", binary_path,
10574 			libbpf_strerror_r(ret, errmsg, sizeof(errmsg)));
10575 		return ret;
10576 	}
10577 	elf = elf_begin(fd, ELF_C_READ_MMAP, NULL);
10578 	if (!elf) {
10579 		pr_warn("elf: could not read elf from %s: %s\n", binary_path, elf_errmsg(-1));
10580 		close(fd);
10581 		return -LIBBPF_ERRNO__FORMAT;
10582 	}
10583 	if (!gelf_getehdr(elf, &ehdr)) {
10584 		pr_warn("elf: failed to get ehdr from %s: %s\n", binary_path, elf_errmsg(-1));
10585 		ret = -LIBBPF_ERRNO__FORMAT;
10586 		goto out;
10587 	}
10588 	/* for shared lib case, we do not need to calculate relative offset */
10589 	is_shared_lib = ehdr.e_type == ET_DYN;
10590 
10591 	name_len = strlen(name);
10592 	/* Does name specify "@@LIB"? */
10593 	is_name_qualified = strstr(name, "@@") != NULL;
10594 
10595 	/* Search SHT_DYNSYM, SHT_SYMTAB for symbol.  This search order is used because if
10596 	 * a binary is stripped, it may only have SHT_DYNSYM, and a fully-statically
10597 	 * linked binary may not have SHT_DYMSYM, so absence of a section should not be
10598 	 * reported as a warning/error.
10599 	 */
10600 	for (i = 0; i < ARRAY_SIZE(sh_types); i++) {
10601 		size_t nr_syms, strtabidx, idx;
10602 		Elf_Data *symbols = NULL;
10603 		Elf_Scn *scn = NULL;
10604 		int last_bind = -1;
10605 		const char *sname;
10606 		GElf_Shdr sh;
10607 
10608 		scn = elf_find_next_scn_by_type(elf, sh_types[i], NULL);
10609 		if (!scn) {
10610 			pr_debug("elf: failed to find symbol table ELF sections in '%s'\n",
10611 				 binary_path);
10612 			continue;
10613 		}
10614 		if (!gelf_getshdr(scn, &sh))
10615 			continue;
10616 		strtabidx = sh.sh_link;
10617 		symbols = elf_getdata(scn, 0);
10618 		if (!symbols) {
10619 			pr_warn("elf: failed to get symbols for symtab section in '%s': %s\n",
10620 				binary_path, elf_errmsg(-1));
10621 			ret = -LIBBPF_ERRNO__FORMAT;
10622 			goto out;
10623 		}
10624 		nr_syms = symbols->d_size / sh.sh_entsize;
10625 
10626 		for (idx = 0; idx < nr_syms; idx++) {
10627 			int curr_bind;
10628 			GElf_Sym sym;
10629 			Elf_Scn *sym_scn;
10630 			GElf_Shdr sym_sh;
10631 
10632 			if (!gelf_getsym(symbols, idx, &sym))
10633 				continue;
10634 
10635 			if (GELF_ST_TYPE(sym.st_info) != STT_FUNC)
10636 				continue;
10637 
10638 			sname = elf_strptr(elf, strtabidx, sym.st_name);
10639 			if (!sname)
10640 				continue;
10641 
10642 			curr_bind = GELF_ST_BIND(sym.st_info);
10643 
10644 			/* User can specify func, func@@LIB or func@@LIB_VERSION. */
10645 			if (strncmp(sname, name, name_len) != 0)
10646 				continue;
10647 			/* ...but we don't want a search for "foo" to match 'foo2" also, so any
10648 			 * additional characters in sname should be of the form "@@LIB".
10649 			 */
10650 			if (!is_name_qualified && sname[name_len] != '\0' && sname[name_len] != '@')
10651 				continue;
10652 
10653 			if (ret >= 0) {
10654 				/* handle multiple matches */
10655 				if (last_bind != STB_WEAK && curr_bind != STB_WEAK) {
10656 					/* Only accept one non-weak bind. */
10657 					pr_warn("elf: ambiguous match for '%s', '%s' in '%s'\n",
10658 						sname, name, binary_path);
10659 					ret = -LIBBPF_ERRNO__FORMAT;
10660 					goto out;
10661 				} else if (curr_bind == STB_WEAK) {
10662 					/* already have a non-weak bind, and
10663 					 * this is a weak bind, so ignore.
10664 					 */
10665 					continue;
10666 				}
10667 			}
10668 
10669 			/* Transform symbol's virtual address (absolute for
10670 			 * binaries and relative for shared libs) into file
10671 			 * offset, which is what kernel is expecting for
10672 			 * uprobe/uretprobe attachment.
10673 			 * See Documentation/trace/uprobetracer.rst for more
10674 			 * details.
10675 			 * This is done by looking up symbol's containing
10676 			 * section's header and using it's virtual address
10677 			 * (sh_addr) and corresponding file offset (sh_offset)
10678 			 * to transform sym.st_value (virtual address) into
10679 			 * desired final file offset.
10680 			 */
10681 			sym_scn = elf_getscn(elf, sym.st_shndx);
10682 			if (!sym_scn)
10683 				continue;
10684 			if (!gelf_getshdr(sym_scn, &sym_sh))
10685 				continue;
10686 
10687 			ret = sym.st_value - sym_sh.sh_addr + sym_sh.sh_offset;
10688 			last_bind = curr_bind;
10689 		}
10690 		if (ret > 0)
10691 			break;
10692 	}
10693 
10694 	if (ret > 0) {
10695 		pr_debug("elf: symbol address match for '%s' in '%s': 0x%lx\n", name, binary_path,
10696 			 ret);
10697 	} else {
10698 		if (ret == 0) {
10699 			pr_warn("elf: '%s' is 0 in symtab for '%s': %s\n", name, binary_path,
10700 				is_shared_lib ? "should not be 0 in a shared library" :
10701 						"try using shared library path instead");
10702 			ret = -ENOENT;
10703 		} else {
10704 			pr_warn("elf: failed to find symbol '%s' in '%s'\n", name, binary_path);
10705 		}
10706 	}
10707 out:
10708 	elf_end(elf);
10709 	close(fd);
10710 	return ret;
10711 }
10712 
10713 static const char *arch_specific_lib_paths(void)
10714 {
10715 	/*
10716 	 * Based on https://packages.debian.org/sid/libc6.
10717 	 *
10718 	 * Assume that the traced program is built for the same architecture
10719 	 * as libbpf, which should cover the vast majority of cases.
10720 	 */
10721 #if defined(__x86_64__)
10722 	return "/lib/x86_64-linux-gnu";
10723 #elif defined(__i386__)
10724 	return "/lib/i386-linux-gnu";
10725 #elif defined(__s390x__)
10726 	return "/lib/s390x-linux-gnu";
10727 #elif defined(__s390__)
10728 	return "/lib/s390-linux-gnu";
10729 #elif defined(__arm__) && defined(__SOFTFP__)
10730 	return "/lib/arm-linux-gnueabi";
10731 #elif defined(__arm__) && !defined(__SOFTFP__)
10732 	return "/lib/arm-linux-gnueabihf";
10733 #elif defined(__aarch64__)
10734 	return "/lib/aarch64-linux-gnu";
10735 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 64
10736 	return "/lib/mips64el-linux-gnuabi64";
10737 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 32
10738 	return "/lib/mipsel-linux-gnu";
10739 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
10740 	return "/lib/powerpc64le-linux-gnu";
10741 #elif defined(__sparc__) && defined(__arch64__)
10742 	return "/lib/sparc64-linux-gnu";
10743 #elif defined(__riscv) && __riscv_xlen == 64
10744 	return "/lib/riscv64-linux-gnu";
10745 #else
10746 	return NULL;
10747 #endif
10748 }
10749 
10750 /* Get full path to program/shared library. */
10751 static int resolve_full_path(const char *file, char *result, size_t result_sz)
10752 {
10753 	const char *search_paths[3] = {};
10754 	int i, perm;
10755 
10756 	if (str_has_sfx(file, ".so") || strstr(file, ".so.")) {
10757 		search_paths[0] = getenv("LD_LIBRARY_PATH");
10758 		search_paths[1] = "/usr/lib64:/usr/lib";
10759 		search_paths[2] = arch_specific_lib_paths();
10760 		perm = R_OK;
10761 	} else {
10762 		search_paths[0] = getenv("PATH");
10763 		search_paths[1] = "/usr/bin:/usr/sbin";
10764 		perm = R_OK | X_OK;
10765 	}
10766 
10767 	for (i = 0; i < ARRAY_SIZE(search_paths); i++) {
10768 		const char *s;
10769 
10770 		if (!search_paths[i])
10771 			continue;
10772 		for (s = search_paths[i]; s != NULL; s = strchr(s, ':')) {
10773 			char *next_path;
10774 			int seg_len;
10775 
10776 			if (s[0] == ':')
10777 				s++;
10778 			next_path = strchr(s, ':');
10779 			seg_len = next_path ? next_path - s : strlen(s);
10780 			if (!seg_len)
10781 				continue;
10782 			snprintf(result, result_sz, "%.*s/%s", seg_len, s, file);
10783 			/* ensure it has required permissions */
10784 			if (faccessat(AT_FDCWD, result, perm, AT_EACCESS) < 0)
10785 				continue;
10786 			pr_debug("resolved '%s' to '%s'\n", file, result);
10787 			return 0;
10788 		}
10789 	}
10790 	return -ENOENT;
10791 }
10792 
10793 LIBBPF_API struct bpf_link *
10794 bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
10795 				const char *binary_path, size_t func_offset,
10796 				const struct bpf_uprobe_opts *opts)
10797 {
10798 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
10799 	char errmsg[STRERR_BUFSIZE], *legacy_probe = NULL;
10800 	char full_binary_path[PATH_MAX];
10801 	struct bpf_link *link;
10802 	size_t ref_ctr_off;
10803 	int pfd, err;
10804 	bool retprobe, legacy;
10805 	const char *func_name;
10806 
10807 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
10808 		return libbpf_err_ptr(-EINVAL);
10809 
10810 	retprobe = OPTS_GET(opts, retprobe, false);
10811 	ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
10812 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10813 
10814 	if (!binary_path)
10815 		return libbpf_err_ptr(-EINVAL);
10816 
10817 	if (!strchr(binary_path, '/')) {
10818 		err = resolve_full_path(binary_path, full_binary_path,
10819 					sizeof(full_binary_path));
10820 		if (err) {
10821 			pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
10822 				prog->name, binary_path, err);
10823 			return libbpf_err_ptr(err);
10824 		}
10825 		binary_path = full_binary_path;
10826 	}
10827 	func_name = OPTS_GET(opts, func_name, NULL);
10828 	if (func_name) {
10829 		long sym_off;
10830 
10831 		sym_off = elf_find_func_offset(binary_path, func_name);
10832 		if (sym_off < 0)
10833 			return libbpf_err_ptr(sym_off);
10834 		func_offset += sym_off;
10835 	}
10836 
10837 	legacy = determine_uprobe_perf_type() < 0;
10838 	if (!legacy) {
10839 		pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
10840 					    func_offset, pid, ref_ctr_off);
10841 	} else {
10842 		char probe_name[PATH_MAX + 64];
10843 
10844 		if (ref_ctr_off)
10845 			return libbpf_err_ptr(-EINVAL);
10846 
10847 		gen_uprobe_legacy_event_name(probe_name, sizeof(probe_name),
10848 					     binary_path, func_offset);
10849 
10850 		legacy_probe = strdup(probe_name);
10851 		if (!legacy_probe)
10852 			return libbpf_err_ptr(-ENOMEM);
10853 
10854 		pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
10855 						    binary_path, func_offset, pid);
10856 	}
10857 	if (pfd < 0) {
10858 		err = -errno;
10859 		pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
10860 			prog->name, retprobe ? "uretprobe" : "uprobe",
10861 			binary_path, func_offset,
10862 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10863 		goto err_out;
10864 	}
10865 
10866 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
10867 	err = libbpf_get_error(link);
10868 	if (err) {
10869 		close(pfd);
10870 		pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
10871 			prog->name, retprobe ? "uretprobe" : "uprobe",
10872 			binary_path, func_offset,
10873 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10874 		goto err_clean_legacy;
10875 	}
10876 	if (legacy) {
10877 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10878 
10879 		perf_link->legacy_probe_name = legacy_probe;
10880 		perf_link->legacy_is_kprobe = false;
10881 		perf_link->legacy_is_retprobe = retprobe;
10882 	}
10883 	return link;
10884 
10885 err_clean_legacy:
10886 	if (legacy)
10887 		remove_uprobe_event_legacy(legacy_probe, retprobe);
10888 err_out:
10889 	free(legacy_probe);
10890 	return libbpf_err_ptr(err);
10891 }
10892 
10893 /* Format of u[ret]probe section definition supporting auto-attach:
10894  * u[ret]probe/binary:function[+offset]
10895  *
10896  * binary can be an absolute/relative path or a filename; the latter is resolved to a
10897  * full binary path via bpf_program__attach_uprobe_opts.
10898  *
10899  * Specifying uprobe+ ensures we carry out strict matching; either "uprobe" must be
10900  * specified (and auto-attach is not possible) or the above format is specified for
10901  * auto-attach.
10902  */
10903 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10904 {
10905 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts);
10906 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
10907 	int n, ret = -EINVAL;
10908 	long offset = 0;
10909 
10910 	*link = NULL;
10911 
10912 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[a-zA-Z0-9_.]+%li",
10913 		   &probe_type, &binary_path, &func_name, &offset);
10914 	switch (n) {
10915 	case 1:
10916 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
10917 		ret = 0;
10918 		break;
10919 	case 2:
10920 		pr_warn("prog '%s': section '%s' missing ':function[+offset]' specification\n",
10921 			prog->name, prog->sec_name);
10922 		break;
10923 	case 3:
10924 	case 4:
10925 		opts.retprobe = strcmp(probe_type, "uretprobe") == 0 ||
10926 				strcmp(probe_type, "uretprobe.s") == 0;
10927 		if (opts.retprobe && offset != 0) {
10928 			pr_warn("prog '%s': uretprobes do not support offset specification\n",
10929 				prog->name);
10930 			break;
10931 		}
10932 		opts.func_name = func_name;
10933 		*link = bpf_program__attach_uprobe_opts(prog, -1, binary_path, offset, &opts);
10934 		ret = libbpf_get_error(*link);
10935 		break;
10936 	default:
10937 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
10938 			prog->sec_name);
10939 		break;
10940 	}
10941 	free(probe_type);
10942 	free(binary_path);
10943 	free(func_name);
10944 
10945 	return ret;
10946 }
10947 
10948 struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
10949 					    bool retprobe, pid_t pid,
10950 					    const char *binary_path,
10951 					    size_t func_offset)
10952 {
10953 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
10954 
10955 	return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
10956 }
10957 
10958 struct bpf_link *bpf_program__attach_usdt(const struct bpf_program *prog,
10959 					  pid_t pid, const char *binary_path,
10960 					  const char *usdt_provider, const char *usdt_name,
10961 					  const struct bpf_usdt_opts *opts)
10962 {
10963 	char resolved_path[512];
10964 	struct bpf_object *obj = prog->obj;
10965 	struct bpf_link *link;
10966 	__u64 usdt_cookie;
10967 	int err;
10968 
10969 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
10970 		return libbpf_err_ptr(-EINVAL);
10971 
10972 	if (bpf_program__fd(prog) < 0) {
10973 		pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
10974 			prog->name);
10975 		return libbpf_err_ptr(-EINVAL);
10976 	}
10977 
10978 	if (!binary_path)
10979 		return libbpf_err_ptr(-EINVAL);
10980 
10981 	if (!strchr(binary_path, '/')) {
10982 		err = resolve_full_path(binary_path, resolved_path, sizeof(resolved_path));
10983 		if (err) {
10984 			pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
10985 				prog->name, binary_path, err);
10986 			return libbpf_err_ptr(err);
10987 		}
10988 		binary_path = resolved_path;
10989 	}
10990 
10991 	/* USDT manager is instantiated lazily on first USDT attach. It will
10992 	 * be destroyed together with BPF object in bpf_object__close().
10993 	 */
10994 	if (IS_ERR(obj->usdt_man))
10995 		return libbpf_ptr(obj->usdt_man);
10996 	if (!obj->usdt_man) {
10997 		obj->usdt_man = usdt_manager_new(obj);
10998 		if (IS_ERR(obj->usdt_man))
10999 			return libbpf_ptr(obj->usdt_man);
11000 	}
11001 
11002 	usdt_cookie = OPTS_GET(opts, usdt_cookie, 0);
11003 	link = usdt_manager_attach_usdt(obj->usdt_man, prog, pid, binary_path,
11004 				        usdt_provider, usdt_name, usdt_cookie);
11005 	err = libbpf_get_error(link);
11006 	if (err)
11007 		return libbpf_err_ptr(err);
11008 	return link;
11009 }
11010 
11011 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11012 {
11013 	char *path = NULL, *provider = NULL, *name = NULL;
11014 	const char *sec_name;
11015 	int n, err;
11016 
11017 	sec_name = bpf_program__section_name(prog);
11018 	if (strcmp(sec_name, "usdt") == 0) {
11019 		/* no auto-attach for just SEC("usdt") */
11020 		*link = NULL;
11021 		return 0;
11022 	}
11023 
11024 	n = sscanf(sec_name, "usdt/%m[^:]:%m[^:]:%m[^:]", &path, &provider, &name);
11025 	if (n != 3) {
11026 		pr_warn("invalid section '%s', expected SEC(\"usdt/<path>:<provider>:<name>\")\n",
11027 			sec_name);
11028 		err = -EINVAL;
11029 	} else {
11030 		*link = bpf_program__attach_usdt(prog, -1 /* any process */, path,
11031 						 provider, name, NULL);
11032 		err = libbpf_get_error(*link);
11033 	}
11034 	free(path);
11035 	free(provider);
11036 	free(name);
11037 	return err;
11038 }
11039 
11040 static int determine_tracepoint_id(const char *tp_category,
11041 				   const char *tp_name)
11042 {
11043 	char file[PATH_MAX];
11044 	int ret;
11045 
11046 	ret = snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11047 		       tracefs_path(), tp_category, tp_name);
11048 	if (ret < 0)
11049 		return -errno;
11050 	if (ret >= sizeof(file)) {
11051 		pr_debug("tracepoint %s/%s path is too long\n",
11052 			 tp_category, tp_name);
11053 		return -E2BIG;
11054 	}
11055 	return parse_uint_from_file(file, "%d\n");
11056 }
11057 
11058 static int perf_event_open_tracepoint(const char *tp_category,
11059 				      const char *tp_name)
11060 {
11061 	const size_t attr_sz = sizeof(struct perf_event_attr);
11062 	struct perf_event_attr attr;
11063 	char errmsg[STRERR_BUFSIZE];
11064 	int tp_id, pfd, err;
11065 
11066 	tp_id = determine_tracepoint_id(tp_category, tp_name);
11067 	if (tp_id < 0) {
11068 		pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
11069 			tp_category, tp_name,
11070 			libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
11071 		return tp_id;
11072 	}
11073 
11074 	memset(&attr, 0, attr_sz);
11075 	attr.type = PERF_TYPE_TRACEPOINT;
11076 	attr.size = attr_sz;
11077 	attr.config = tp_id;
11078 
11079 	pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
11080 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
11081 	if (pfd < 0) {
11082 		err = -errno;
11083 		pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
11084 			tp_category, tp_name,
11085 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11086 		return err;
11087 	}
11088 	return pfd;
11089 }
11090 
11091 struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
11092 						     const char *tp_category,
11093 						     const char *tp_name,
11094 						     const struct bpf_tracepoint_opts *opts)
11095 {
11096 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11097 	char errmsg[STRERR_BUFSIZE];
11098 	struct bpf_link *link;
11099 	int pfd, err;
11100 
11101 	if (!OPTS_VALID(opts, bpf_tracepoint_opts))
11102 		return libbpf_err_ptr(-EINVAL);
11103 
11104 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11105 
11106 	pfd = perf_event_open_tracepoint(tp_category, tp_name);
11107 	if (pfd < 0) {
11108 		pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
11109 			prog->name, tp_category, tp_name,
11110 			libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11111 		return libbpf_err_ptr(pfd);
11112 	}
11113 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11114 	err = libbpf_get_error(link);
11115 	if (err) {
11116 		close(pfd);
11117 		pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
11118 			prog->name, tp_category, tp_name,
11119 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11120 		return libbpf_err_ptr(err);
11121 	}
11122 	return link;
11123 }
11124 
11125 struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
11126 						const char *tp_category,
11127 						const char *tp_name)
11128 {
11129 	return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
11130 }
11131 
11132 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11133 {
11134 	char *sec_name, *tp_cat, *tp_name;
11135 
11136 	*link = NULL;
11137 
11138 	/* no auto-attach for SEC("tp") or SEC("tracepoint") */
11139 	if (strcmp(prog->sec_name, "tp") == 0 || strcmp(prog->sec_name, "tracepoint") == 0)
11140 		return 0;
11141 
11142 	sec_name = strdup(prog->sec_name);
11143 	if (!sec_name)
11144 		return -ENOMEM;
11145 
11146 	/* extract "tp/<category>/<name>" or "tracepoint/<category>/<name>" */
11147 	if (str_has_pfx(prog->sec_name, "tp/"))
11148 		tp_cat = sec_name + sizeof("tp/") - 1;
11149 	else
11150 		tp_cat = sec_name + sizeof("tracepoint/") - 1;
11151 	tp_name = strchr(tp_cat, '/');
11152 	if (!tp_name) {
11153 		free(sec_name);
11154 		return -EINVAL;
11155 	}
11156 	*tp_name = '\0';
11157 	tp_name++;
11158 
11159 	*link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
11160 	free(sec_name);
11161 	return libbpf_get_error(*link);
11162 }
11163 
11164 struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
11165 						    const char *tp_name)
11166 {
11167 	char errmsg[STRERR_BUFSIZE];
11168 	struct bpf_link *link;
11169 	int prog_fd, pfd;
11170 
11171 	prog_fd = bpf_program__fd(prog);
11172 	if (prog_fd < 0) {
11173 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11174 		return libbpf_err_ptr(-EINVAL);
11175 	}
11176 
11177 	link = calloc(1, sizeof(*link));
11178 	if (!link)
11179 		return libbpf_err_ptr(-ENOMEM);
11180 	link->detach = &bpf_link__detach_fd;
11181 
11182 	pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
11183 	if (pfd < 0) {
11184 		pfd = -errno;
11185 		free(link);
11186 		pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
11187 			prog->name, tp_name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11188 		return libbpf_err_ptr(pfd);
11189 	}
11190 	link->fd = pfd;
11191 	return link;
11192 }
11193 
11194 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11195 {
11196 	static const char *const prefixes[] = {
11197 		"raw_tp",
11198 		"raw_tracepoint",
11199 		"raw_tp.w",
11200 		"raw_tracepoint.w",
11201 	};
11202 	size_t i;
11203 	const char *tp_name = NULL;
11204 
11205 	*link = NULL;
11206 
11207 	for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
11208 		size_t pfx_len;
11209 
11210 		if (!str_has_pfx(prog->sec_name, prefixes[i]))
11211 			continue;
11212 
11213 		pfx_len = strlen(prefixes[i]);
11214 		/* no auto-attach case of, e.g., SEC("raw_tp") */
11215 		if (prog->sec_name[pfx_len] == '\0')
11216 			return 0;
11217 
11218 		if (prog->sec_name[pfx_len] != '/')
11219 			continue;
11220 
11221 		tp_name = prog->sec_name + pfx_len + 1;
11222 		break;
11223 	}
11224 
11225 	if (!tp_name) {
11226 		pr_warn("prog '%s': invalid section name '%s'\n",
11227 			prog->name, prog->sec_name);
11228 		return -EINVAL;
11229 	}
11230 
11231 	*link = bpf_program__attach_raw_tracepoint(prog, tp_name);
11232 	return libbpf_get_error(link);
11233 }
11234 
11235 /* Common logic for all BPF program types that attach to a btf_id */
11236 static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog,
11237 						   const struct bpf_trace_opts *opts)
11238 {
11239 	LIBBPF_OPTS(bpf_link_create_opts, link_opts);
11240 	char errmsg[STRERR_BUFSIZE];
11241 	struct bpf_link *link;
11242 	int prog_fd, pfd;
11243 
11244 	if (!OPTS_VALID(opts, bpf_trace_opts))
11245 		return libbpf_err_ptr(-EINVAL);
11246 
11247 	prog_fd = bpf_program__fd(prog);
11248 	if (prog_fd < 0) {
11249 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11250 		return libbpf_err_ptr(-EINVAL);
11251 	}
11252 
11253 	link = calloc(1, sizeof(*link));
11254 	if (!link)
11255 		return libbpf_err_ptr(-ENOMEM);
11256 	link->detach = &bpf_link__detach_fd;
11257 
11258 	/* libbpf is smart enough to redirect to BPF_RAW_TRACEPOINT_OPEN on old kernels */
11259 	link_opts.tracing.cookie = OPTS_GET(opts, cookie, 0);
11260 	pfd = bpf_link_create(prog_fd, 0, bpf_program__expected_attach_type(prog), &link_opts);
11261 	if (pfd < 0) {
11262 		pfd = -errno;
11263 		free(link);
11264 		pr_warn("prog '%s': failed to attach: %s\n",
11265 			prog->name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11266 		return libbpf_err_ptr(pfd);
11267 	}
11268 	link->fd = pfd;
11269 	return link;
11270 }
11271 
11272 struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
11273 {
11274 	return bpf_program__attach_btf_id(prog, NULL);
11275 }
11276 
11277 struct bpf_link *bpf_program__attach_trace_opts(const struct bpf_program *prog,
11278 						const struct bpf_trace_opts *opts)
11279 {
11280 	return bpf_program__attach_btf_id(prog, opts);
11281 }
11282 
11283 struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
11284 {
11285 	return bpf_program__attach_btf_id(prog, NULL);
11286 }
11287 
11288 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11289 {
11290 	*link = bpf_program__attach_trace(prog);
11291 	return libbpf_get_error(*link);
11292 }
11293 
11294 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11295 {
11296 	*link = bpf_program__attach_lsm(prog);
11297 	return libbpf_get_error(*link);
11298 }
11299 
11300 static struct bpf_link *
11301 bpf_program__attach_fd(const struct bpf_program *prog, int target_fd, int btf_id,
11302 		       const char *target_name)
11303 {
11304 	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, opts,
11305 			    .target_btf_id = btf_id);
11306 	enum bpf_attach_type attach_type;
11307 	char errmsg[STRERR_BUFSIZE];
11308 	struct bpf_link *link;
11309 	int prog_fd, link_fd;
11310 
11311 	prog_fd = bpf_program__fd(prog);
11312 	if (prog_fd < 0) {
11313 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11314 		return libbpf_err_ptr(-EINVAL);
11315 	}
11316 
11317 	link = calloc(1, sizeof(*link));
11318 	if (!link)
11319 		return libbpf_err_ptr(-ENOMEM);
11320 	link->detach = &bpf_link__detach_fd;
11321 
11322 	attach_type = bpf_program__expected_attach_type(prog);
11323 	link_fd = bpf_link_create(prog_fd, target_fd, attach_type, &opts);
11324 	if (link_fd < 0) {
11325 		link_fd = -errno;
11326 		free(link);
11327 		pr_warn("prog '%s': failed to attach to %s: %s\n",
11328 			prog->name, target_name,
11329 			libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
11330 		return libbpf_err_ptr(link_fd);
11331 	}
11332 	link->fd = link_fd;
11333 	return link;
11334 }
11335 
11336 struct bpf_link *
11337 bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
11338 {
11339 	return bpf_program__attach_fd(prog, cgroup_fd, 0, "cgroup");
11340 }
11341 
11342 struct bpf_link *
11343 bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
11344 {
11345 	return bpf_program__attach_fd(prog, netns_fd, 0, "netns");
11346 }
11347 
11348 struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
11349 {
11350 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
11351 	return bpf_program__attach_fd(prog, ifindex, 0, "xdp");
11352 }
11353 
11354 struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
11355 					      int target_fd,
11356 					      const char *attach_func_name)
11357 {
11358 	int btf_id;
11359 
11360 	if (!!target_fd != !!attach_func_name) {
11361 		pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
11362 			prog->name);
11363 		return libbpf_err_ptr(-EINVAL);
11364 	}
11365 
11366 	if (prog->type != BPF_PROG_TYPE_EXT) {
11367 		pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace",
11368 			prog->name);
11369 		return libbpf_err_ptr(-EINVAL);
11370 	}
11371 
11372 	if (target_fd) {
11373 		btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd);
11374 		if (btf_id < 0)
11375 			return libbpf_err_ptr(btf_id);
11376 
11377 		return bpf_program__attach_fd(prog, target_fd, btf_id, "freplace");
11378 	} else {
11379 		/* no target, so use raw_tracepoint_open for compatibility
11380 		 * with old kernels
11381 		 */
11382 		return bpf_program__attach_trace(prog);
11383 	}
11384 }
11385 
11386 struct bpf_link *
11387 bpf_program__attach_iter(const struct bpf_program *prog,
11388 			 const struct bpf_iter_attach_opts *opts)
11389 {
11390 	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
11391 	char errmsg[STRERR_BUFSIZE];
11392 	struct bpf_link *link;
11393 	int prog_fd, link_fd;
11394 	__u32 target_fd = 0;
11395 
11396 	if (!OPTS_VALID(opts, bpf_iter_attach_opts))
11397 		return libbpf_err_ptr(-EINVAL);
11398 
11399 	link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
11400 	link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
11401 
11402 	prog_fd = bpf_program__fd(prog);
11403 	if (prog_fd < 0) {
11404 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11405 		return libbpf_err_ptr(-EINVAL);
11406 	}
11407 
11408 	link = calloc(1, sizeof(*link));
11409 	if (!link)
11410 		return libbpf_err_ptr(-ENOMEM);
11411 	link->detach = &bpf_link__detach_fd;
11412 
11413 	link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
11414 				  &link_create_opts);
11415 	if (link_fd < 0) {
11416 		link_fd = -errno;
11417 		free(link);
11418 		pr_warn("prog '%s': failed to attach to iterator: %s\n",
11419 			prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
11420 		return libbpf_err_ptr(link_fd);
11421 	}
11422 	link->fd = link_fd;
11423 	return link;
11424 }
11425 
11426 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11427 {
11428 	*link = bpf_program__attach_iter(prog, NULL);
11429 	return libbpf_get_error(*link);
11430 }
11431 
11432 struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
11433 {
11434 	struct bpf_link *link = NULL;
11435 	int err;
11436 
11437 	if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
11438 		return libbpf_err_ptr(-EOPNOTSUPP);
11439 
11440 	err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, &link);
11441 	if (err)
11442 		return libbpf_err_ptr(err);
11443 
11444 	/* When calling bpf_program__attach() explicitly, auto-attach support
11445 	 * is expected to work, so NULL returned link is considered an error.
11446 	 * This is different for skeleton's attach, see comment in
11447 	 * bpf_object__attach_skeleton().
11448 	 */
11449 	if (!link)
11450 		return libbpf_err_ptr(-EOPNOTSUPP);
11451 
11452 	return link;
11453 }
11454 
11455 static int bpf_link__detach_struct_ops(struct bpf_link *link)
11456 {
11457 	__u32 zero = 0;
11458 
11459 	if (bpf_map_delete_elem(link->fd, &zero))
11460 		return -errno;
11461 
11462 	return 0;
11463 }
11464 
11465 struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
11466 {
11467 	struct bpf_struct_ops *st_ops;
11468 	struct bpf_link *link;
11469 	__u32 i, zero = 0;
11470 	int err;
11471 
11472 	if (!bpf_map__is_struct_ops(map) || map->fd == -1)
11473 		return libbpf_err_ptr(-EINVAL);
11474 
11475 	link = calloc(1, sizeof(*link));
11476 	if (!link)
11477 		return libbpf_err_ptr(-EINVAL);
11478 
11479 	st_ops = map->st_ops;
11480 	for (i = 0; i < btf_vlen(st_ops->type); i++) {
11481 		struct bpf_program *prog = st_ops->progs[i];
11482 		void *kern_data;
11483 		int prog_fd;
11484 
11485 		if (!prog)
11486 			continue;
11487 
11488 		prog_fd = bpf_program__fd(prog);
11489 		kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
11490 		*(unsigned long *)kern_data = prog_fd;
11491 	}
11492 
11493 	err = bpf_map_update_elem(map->fd, &zero, st_ops->kern_vdata, 0);
11494 	if (err) {
11495 		err = -errno;
11496 		free(link);
11497 		return libbpf_err_ptr(err);
11498 	}
11499 
11500 	link->detach = bpf_link__detach_struct_ops;
11501 	link->fd = map->fd;
11502 
11503 	return link;
11504 }
11505 
11506 typedef enum bpf_perf_event_ret (*bpf_perf_event_print_t)(struct perf_event_header *hdr,
11507 							  void *private_data);
11508 
11509 static enum bpf_perf_event_ret
11510 perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
11511 		       void **copy_mem, size_t *copy_size,
11512 		       bpf_perf_event_print_t fn, void *private_data)
11513 {
11514 	struct perf_event_mmap_page *header = mmap_mem;
11515 	__u64 data_head = ring_buffer_read_head(header);
11516 	__u64 data_tail = header->data_tail;
11517 	void *base = ((__u8 *)header) + page_size;
11518 	int ret = LIBBPF_PERF_EVENT_CONT;
11519 	struct perf_event_header *ehdr;
11520 	size_t ehdr_size;
11521 
11522 	while (data_head != data_tail) {
11523 		ehdr = base + (data_tail & (mmap_size - 1));
11524 		ehdr_size = ehdr->size;
11525 
11526 		if (((void *)ehdr) + ehdr_size > base + mmap_size) {
11527 			void *copy_start = ehdr;
11528 			size_t len_first = base + mmap_size - copy_start;
11529 			size_t len_secnd = ehdr_size - len_first;
11530 
11531 			if (*copy_size < ehdr_size) {
11532 				free(*copy_mem);
11533 				*copy_mem = malloc(ehdr_size);
11534 				if (!*copy_mem) {
11535 					*copy_size = 0;
11536 					ret = LIBBPF_PERF_EVENT_ERROR;
11537 					break;
11538 				}
11539 				*copy_size = ehdr_size;
11540 			}
11541 
11542 			memcpy(*copy_mem, copy_start, len_first);
11543 			memcpy(*copy_mem + len_first, base, len_secnd);
11544 			ehdr = *copy_mem;
11545 		}
11546 
11547 		ret = fn(ehdr, private_data);
11548 		data_tail += ehdr_size;
11549 		if (ret != LIBBPF_PERF_EVENT_CONT)
11550 			break;
11551 	}
11552 
11553 	ring_buffer_write_tail(header, data_tail);
11554 	return libbpf_err(ret);
11555 }
11556 
11557 struct perf_buffer;
11558 
11559 struct perf_buffer_params {
11560 	struct perf_event_attr *attr;
11561 	/* if event_cb is specified, it takes precendence */
11562 	perf_buffer_event_fn event_cb;
11563 	/* sample_cb and lost_cb are higher-level common-case callbacks */
11564 	perf_buffer_sample_fn sample_cb;
11565 	perf_buffer_lost_fn lost_cb;
11566 	void *ctx;
11567 	int cpu_cnt;
11568 	int *cpus;
11569 	int *map_keys;
11570 };
11571 
11572 struct perf_cpu_buf {
11573 	struct perf_buffer *pb;
11574 	void *base; /* mmap()'ed memory */
11575 	void *buf; /* for reconstructing segmented data */
11576 	size_t buf_size;
11577 	int fd;
11578 	int cpu;
11579 	int map_key;
11580 };
11581 
11582 struct perf_buffer {
11583 	perf_buffer_event_fn event_cb;
11584 	perf_buffer_sample_fn sample_cb;
11585 	perf_buffer_lost_fn lost_cb;
11586 	void *ctx; /* passed into callbacks */
11587 
11588 	size_t page_size;
11589 	size_t mmap_size;
11590 	struct perf_cpu_buf **cpu_bufs;
11591 	struct epoll_event *events;
11592 	int cpu_cnt; /* number of allocated CPU buffers */
11593 	int epoll_fd; /* perf event FD */
11594 	int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
11595 };
11596 
11597 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
11598 				      struct perf_cpu_buf *cpu_buf)
11599 {
11600 	if (!cpu_buf)
11601 		return;
11602 	if (cpu_buf->base &&
11603 	    munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
11604 		pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
11605 	if (cpu_buf->fd >= 0) {
11606 		ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
11607 		close(cpu_buf->fd);
11608 	}
11609 	free(cpu_buf->buf);
11610 	free(cpu_buf);
11611 }
11612 
11613 void perf_buffer__free(struct perf_buffer *pb)
11614 {
11615 	int i;
11616 
11617 	if (IS_ERR_OR_NULL(pb))
11618 		return;
11619 	if (pb->cpu_bufs) {
11620 		for (i = 0; i < pb->cpu_cnt; i++) {
11621 			struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
11622 
11623 			if (!cpu_buf)
11624 				continue;
11625 
11626 			bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
11627 			perf_buffer__free_cpu_buf(pb, cpu_buf);
11628 		}
11629 		free(pb->cpu_bufs);
11630 	}
11631 	if (pb->epoll_fd >= 0)
11632 		close(pb->epoll_fd);
11633 	free(pb->events);
11634 	free(pb);
11635 }
11636 
11637 static struct perf_cpu_buf *
11638 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
11639 			  int cpu, int map_key)
11640 {
11641 	struct perf_cpu_buf *cpu_buf;
11642 	char msg[STRERR_BUFSIZE];
11643 	int err;
11644 
11645 	cpu_buf = calloc(1, sizeof(*cpu_buf));
11646 	if (!cpu_buf)
11647 		return ERR_PTR(-ENOMEM);
11648 
11649 	cpu_buf->pb = pb;
11650 	cpu_buf->cpu = cpu;
11651 	cpu_buf->map_key = map_key;
11652 
11653 	cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
11654 			      -1, PERF_FLAG_FD_CLOEXEC);
11655 	if (cpu_buf->fd < 0) {
11656 		err = -errno;
11657 		pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
11658 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
11659 		goto error;
11660 	}
11661 
11662 	cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
11663 			     PROT_READ | PROT_WRITE, MAP_SHARED,
11664 			     cpu_buf->fd, 0);
11665 	if (cpu_buf->base == MAP_FAILED) {
11666 		cpu_buf->base = NULL;
11667 		err = -errno;
11668 		pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
11669 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
11670 		goto error;
11671 	}
11672 
11673 	if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
11674 		err = -errno;
11675 		pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
11676 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
11677 		goto error;
11678 	}
11679 
11680 	return cpu_buf;
11681 
11682 error:
11683 	perf_buffer__free_cpu_buf(pb, cpu_buf);
11684 	return (struct perf_cpu_buf *)ERR_PTR(err);
11685 }
11686 
11687 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
11688 					      struct perf_buffer_params *p);
11689 
11690 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
11691 				     perf_buffer_sample_fn sample_cb,
11692 				     perf_buffer_lost_fn lost_cb,
11693 				     void *ctx,
11694 				     const struct perf_buffer_opts *opts)
11695 {
11696 	const size_t attr_sz = sizeof(struct perf_event_attr);
11697 	struct perf_buffer_params p = {};
11698 	struct perf_event_attr attr;
11699 
11700 	if (!OPTS_VALID(opts, perf_buffer_opts))
11701 		return libbpf_err_ptr(-EINVAL);
11702 
11703 	memset(&attr, 0, attr_sz);
11704 	attr.size = attr_sz;
11705 	attr.config = PERF_COUNT_SW_BPF_OUTPUT;
11706 	attr.type = PERF_TYPE_SOFTWARE;
11707 	attr.sample_type = PERF_SAMPLE_RAW;
11708 	attr.sample_period = 1;
11709 	attr.wakeup_events = 1;
11710 
11711 	p.attr = &attr;
11712 	p.sample_cb = sample_cb;
11713 	p.lost_cb = lost_cb;
11714 	p.ctx = ctx;
11715 
11716 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
11717 }
11718 
11719 struct perf_buffer *perf_buffer__new_raw(int map_fd, size_t page_cnt,
11720 					 struct perf_event_attr *attr,
11721 					 perf_buffer_event_fn event_cb, void *ctx,
11722 					 const struct perf_buffer_raw_opts *opts)
11723 {
11724 	struct perf_buffer_params p = {};
11725 
11726 	if (!attr)
11727 		return libbpf_err_ptr(-EINVAL);
11728 
11729 	if (!OPTS_VALID(opts, perf_buffer_raw_opts))
11730 		return libbpf_err_ptr(-EINVAL);
11731 
11732 	p.attr = attr;
11733 	p.event_cb = event_cb;
11734 	p.ctx = ctx;
11735 	p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
11736 	p.cpus = OPTS_GET(opts, cpus, NULL);
11737 	p.map_keys = OPTS_GET(opts, map_keys, NULL);
11738 
11739 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
11740 }
11741 
11742 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
11743 					      struct perf_buffer_params *p)
11744 {
11745 	const char *online_cpus_file = "/sys/devices/system/cpu/online";
11746 	struct bpf_map_info map;
11747 	char msg[STRERR_BUFSIZE];
11748 	struct perf_buffer *pb;
11749 	bool *online = NULL;
11750 	__u32 map_info_len;
11751 	int err, i, j, n;
11752 
11753 	if (page_cnt == 0 || (page_cnt & (page_cnt - 1))) {
11754 		pr_warn("page count should be power of two, but is %zu\n",
11755 			page_cnt);
11756 		return ERR_PTR(-EINVAL);
11757 	}
11758 
11759 	/* best-effort sanity checks */
11760 	memset(&map, 0, sizeof(map));
11761 	map_info_len = sizeof(map);
11762 	err = bpf_obj_get_info_by_fd(map_fd, &map, &map_info_len);
11763 	if (err) {
11764 		err = -errno;
11765 		/* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
11766 		 * -EBADFD, -EFAULT, or -E2BIG on real error
11767 		 */
11768 		if (err != -EINVAL) {
11769 			pr_warn("failed to get map info for map FD %d: %s\n",
11770 				map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
11771 			return ERR_PTR(err);
11772 		}
11773 		pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
11774 			 map_fd);
11775 	} else {
11776 		if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
11777 			pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
11778 				map.name);
11779 			return ERR_PTR(-EINVAL);
11780 		}
11781 	}
11782 
11783 	pb = calloc(1, sizeof(*pb));
11784 	if (!pb)
11785 		return ERR_PTR(-ENOMEM);
11786 
11787 	pb->event_cb = p->event_cb;
11788 	pb->sample_cb = p->sample_cb;
11789 	pb->lost_cb = p->lost_cb;
11790 	pb->ctx = p->ctx;
11791 
11792 	pb->page_size = getpagesize();
11793 	pb->mmap_size = pb->page_size * page_cnt;
11794 	pb->map_fd = map_fd;
11795 
11796 	pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
11797 	if (pb->epoll_fd < 0) {
11798 		err = -errno;
11799 		pr_warn("failed to create epoll instance: %s\n",
11800 			libbpf_strerror_r(err, msg, sizeof(msg)));
11801 		goto error;
11802 	}
11803 
11804 	if (p->cpu_cnt > 0) {
11805 		pb->cpu_cnt = p->cpu_cnt;
11806 	} else {
11807 		pb->cpu_cnt = libbpf_num_possible_cpus();
11808 		if (pb->cpu_cnt < 0) {
11809 			err = pb->cpu_cnt;
11810 			goto error;
11811 		}
11812 		if (map.max_entries && map.max_entries < pb->cpu_cnt)
11813 			pb->cpu_cnt = map.max_entries;
11814 	}
11815 
11816 	pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
11817 	if (!pb->events) {
11818 		err = -ENOMEM;
11819 		pr_warn("failed to allocate events: out of memory\n");
11820 		goto error;
11821 	}
11822 	pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
11823 	if (!pb->cpu_bufs) {
11824 		err = -ENOMEM;
11825 		pr_warn("failed to allocate buffers: out of memory\n");
11826 		goto error;
11827 	}
11828 
11829 	err = parse_cpu_mask_file(online_cpus_file, &online, &n);
11830 	if (err) {
11831 		pr_warn("failed to get online CPU mask: %d\n", err);
11832 		goto error;
11833 	}
11834 
11835 	for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
11836 		struct perf_cpu_buf *cpu_buf;
11837 		int cpu, map_key;
11838 
11839 		cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
11840 		map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
11841 
11842 		/* in case user didn't explicitly requested particular CPUs to
11843 		 * be attached to, skip offline/not present CPUs
11844 		 */
11845 		if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
11846 			continue;
11847 
11848 		cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
11849 		if (IS_ERR(cpu_buf)) {
11850 			err = PTR_ERR(cpu_buf);
11851 			goto error;
11852 		}
11853 
11854 		pb->cpu_bufs[j] = cpu_buf;
11855 
11856 		err = bpf_map_update_elem(pb->map_fd, &map_key,
11857 					  &cpu_buf->fd, 0);
11858 		if (err) {
11859 			err = -errno;
11860 			pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
11861 				cpu, map_key, cpu_buf->fd,
11862 				libbpf_strerror_r(err, msg, sizeof(msg)));
11863 			goto error;
11864 		}
11865 
11866 		pb->events[j].events = EPOLLIN;
11867 		pb->events[j].data.ptr = cpu_buf;
11868 		if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
11869 			      &pb->events[j]) < 0) {
11870 			err = -errno;
11871 			pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
11872 				cpu, cpu_buf->fd,
11873 				libbpf_strerror_r(err, msg, sizeof(msg)));
11874 			goto error;
11875 		}
11876 		j++;
11877 	}
11878 	pb->cpu_cnt = j;
11879 	free(online);
11880 
11881 	return pb;
11882 
11883 error:
11884 	free(online);
11885 	if (pb)
11886 		perf_buffer__free(pb);
11887 	return ERR_PTR(err);
11888 }
11889 
11890 struct perf_sample_raw {
11891 	struct perf_event_header header;
11892 	uint32_t size;
11893 	char data[];
11894 };
11895 
11896 struct perf_sample_lost {
11897 	struct perf_event_header header;
11898 	uint64_t id;
11899 	uint64_t lost;
11900 	uint64_t sample_id;
11901 };
11902 
11903 static enum bpf_perf_event_ret
11904 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
11905 {
11906 	struct perf_cpu_buf *cpu_buf = ctx;
11907 	struct perf_buffer *pb = cpu_buf->pb;
11908 	void *data = e;
11909 
11910 	/* user wants full control over parsing perf event */
11911 	if (pb->event_cb)
11912 		return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
11913 
11914 	switch (e->type) {
11915 	case PERF_RECORD_SAMPLE: {
11916 		struct perf_sample_raw *s = data;
11917 
11918 		if (pb->sample_cb)
11919 			pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
11920 		break;
11921 	}
11922 	case PERF_RECORD_LOST: {
11923 		struct perf_sample_lost *s = data;
11924 
11925 		if (pb->lost_cb)
11926 			pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
11927 		break;
11928 	}
11929 	default:
11930 		pr_warn("unknown perf sample type %d\n", e->type);
11931 		return LIBBPF_PERF_EVENT_ERROR;
11932 	}
11933 	return LIBBPF_PERF_EVENT_CONT;
11934 }
11935 
11936 static int perf_buffer__process_records(struct perf_buffer *pb,
11937 					struct perf_cpu_buf *cpu_buf)
11938 {
11939 	enum bpf_perf_event_ret ret;
11940 
11941 	ret = perf_event_read_simple(cpu_buf->base, pb->mmap_size,
11942 				     pb->page_size, &cpu_buf->buf,
11943 				     &cpu_buf->buf_size,
11944 				     perf_buffer__process_record, cpu_buf);
11945 	if (ret != LIBBPF_PERF_EVENT_CONT)
11946 		return ret;
11947 	return 0;
11948 }
11949 
11950 int perf_buffer__epoll_fd(const struct perf_buffer *pb)
11951 {
11952 	return pb->epoll_fd;
11953 }
11954 
11955 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
11956 {
11957 	int i, cnt, err;
11958 
11959 	cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
11960 	if (cnt < 0)
11961 		return -errno;
11962 
11963 	for (i = 0; i < cnt; i++) {
11964 		struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
11965 
11966 		err = perf_buffer__process_records(pb, cpu_buf);
11967 		if (err) {
11968 			pr_warn("error while processing records: %d\n", err);
11969 			return libbpf_err(err);
11970 		}
11971 	}
11972 	return cnt;
11973 }
11974 
11975 /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
11976  * manager.
11977  */
11978 size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
11979 {
11980 	return pb->cpu_cnt;
11981 }
11982 
11983 /*
11984  * Return perf_event FD of a ring buffer in *buf_idx* slot of
11985  * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
11986  * select()/poll()/epoll() Linux syscalls.
11987  */
11988 int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
11989 {
11990 	struct perf_cpu_buf *cpu_buf;
11991 
11992 	if (buf_idx >= pb->cpu_cnt)
11993 		return libbpf_err(-EINVAL);
11994 
11995 	cpu_buf = pb->cpu_bufs[buf_idx];
11996 	if (!cpu_buf)
11997 		return libbpf_err(-ENOENT);
11998 
11999 	return cpu_buf->fd;
12000 }
12001 
12002 int perf_buffer__buffer(struct perf_buffer *pb, int buf_idx, void **buf, size_t *buf_size)
12003 {
12004 	struct perf_cpu_buf *cpu_buf;
12005 
12006 	if (buf_idx >= pb->cpu_cnt)
12007 		return libbpf_err(-EINVAL);
12008 
12009 	cpu_buf = pb->cpu_bufs[buf_idx];
12010 	if (!cpu_buf)
12011 		return libbpf_err(-ENOENT);
12012 
12013 	*buf = cpu_buf->base;
12014 	*buf_size = pb->mmap_size;
12015 	return 0;
12016 }
12017 
12018 /*
12019  * Consume data from perf ring buffer corresponding to slot *buf_idx* in
12020  * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
12021  * consume, do nothing and return success.
12022  * Returns:
12023  *   - 0 on success;
12024  *   - <0 on failure.
12025  */
12026 int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
12027 {
12028 	struct perf_cpu_buf *cpu_buf;
12029 
12030 	if (buf_idx >= pb->cpu_cnt)
12031 		return libbpf_err(-EINVAL);
12032 
12033 	cpu_buf = pb->cpu_bufs[buf_idx];
12034 	if (!cpu_buf)
12035 		return libbpf_err(-ENOENT);
12036 
12037 	return perf_buffer__process_records(pb, cpu_buf);
12038 }
12039 
12040 int perf_buffer__consume(struct perf_buffer *pb)
12041 {
12042 	int i, err;
12043 
12044 	for (i = 0; i < pb->cpu_cnt; i++) {
12045 		struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
12046 
12047 		if (!cpu_buf)
12048 			continue;
12049 
12050 		err = perf_buffer__process_records(pb, cpu_buf);
12051 		if (err) {
12052 			pr_warn("perf_buffer: failed to process records in buffer #%d: %d\n", i, err);
12053 			return libbpf_err(err);
12054 		}
12055 	}
12056 	return 0;
12057 }
12058 
12059 int bpf_program__set_attach_target(struct bpf_program *prog,
12060 				   int attach_prog_fd,
12061 				   const char *attach_func_name)
12062 {
12063 	int btf_obj_fd = 0, btf_id = 0, err;
12064 
12065 	if (!prog || attach_prog_fd < 0)
12066 		return libbpf_err(-EINVAL);
12067 
12068 	if (prog->obj->loaded)
12069 		return libbpf_err(-EINVAL);
12070 
12071 	if (attach_prog_fd && !attach_func_name) {
12072 		/* remember attach_prog_fd and let bpf_program__load() find
12073 		 * BTF ID during the program load
12074 		 */
12075 		prog->attach_prog_fd = attach_prog_fd;
12076 		return 0;
12077 	}
12078 
12079 	if (attach_prog_fd) {
12080 		btf_id = libbpf_find_prog_btf_id(attach_func_name,
12081 						 attach_prog_fd);
12082 		if (btf_id < 0)
12083 			return libbpf_err(btf_id);
12084 	} else {
12085 		if (!attach_func_name)
12086 			return libbpf_err(-EINVAL);
12087 
12088 		/* load btf_vmlinux, if not yet */
12089 		err = bpf_object__load_vmlinux_btf(prog->obj, true);
12090 		if (err)
12091 			return libbpf_err(err);
12092 		err = find_kernel_btf_id(prog->obj, attach_func_name,
12093 					 prog->expected_attach_type,
12094 					 &btf_obj_fd, &btf_id);
12095 		if (err)
12096 			return libbpf_err(err);
12097 	}
12098 
12099 	prog->attach_btf_id = btf_id;
12100 	prog->attach_btf_obj_fd = btf_obj_fd;
12101 	prog->attach_prog_fd = attach_prog_fd;
12102 	return 0;
12103 }
12104 
12105 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
12106 {
12107 	int err = 0, n, len, start, end = -1;
12108 	bool *tmp;
12109 
12110 	*mask = NULL;
12111 	*mask_sz = 0;
12112 
12113 	/* Each sub string separated by ',' has format \d+-\d+ or \d+ */
12114 	while (*s) {
12115 		if (*s == ',' || *s == '\n') {
12116 			s++;
12117 			continue;
12118 		}
12119 		n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
12120 		if (n <= 0 || n > 2) {
12121 			pr_warn("Failed to get CPU range %s: %d\n", s, n);
12122 			err = -EINVAL;
12123 			goto cleanup;
12124 		} else if (n == 1) {
12125 			end = start;
12126 		}
12127 		if (start < 0 || start > end) {
12128 			pr_warn("Invalid CPU range [%d,%d] in %s\n",
12129 				start, end, s);
12130 			err = -EINVAL;
12131 			goto cleanup;
12132 		}
12133 		tmp = realloc(*mask, end + 1);
12134 		if (!tmp) {
12135 			err = -ENOMEM;
12136 			goto cleanup;
12137 		}
12138 		*mask = tmp;
12139 		memset(tmp + *mask_sz, 0, start - *mask_sz);
12140 		memset(tmp + start, 1, end - start + 1);
12141 		*mask_sz = end + 1;
12142 		s += len;
12143 	}
12144 	if (!*mask_sz) {
12145 		pr_warn("Empty CPU range\n");
12146 		return -EINVAL;
12147 	}
12148 	return 0;
12149 cleanup:
12150 	free(*mask);
12151 	*mask = NULL;
12152 	return err;
12153 }
12154 
12155 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
12156 {
12157 	int fd, err = 0, len;
12158 	char buf[128];
12159 
12160 	fd = open(fcpu, O_RDONLY | O_CLOEXEC);
12161 	if (fd < 0) {
12162 		err = -errno;
12163 		pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
12164 		return err;
12165 	}
12166 	len = read(fd, buf, sizeof(buf));
12167 	close(fd);
12168 	if (len <= 0) {
12169 		err = len ? -errno : -EINVAL;
12170 		pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
12171 		return err;
12172 	}
12173 	if (len >= sizeof(buf)) {
12174 		pr_warn("CPU mask is too big in file %s\n", fcpu);
12175 		return -E2BIG;
12176 	}
12177 	buf[len] = '\0';
12178 
12179 	return parse_cpu_mask_str(buf, mask, mask_sz);
12180 }
12181 
12182 int libbpf_num_possible_cpus(void)
12183 {
12184 	static const char *fcpu = "/sys/devices/system/cpu/possible";
12185 	static int cpus;
12186 	int err, n, i, tmp_cpus;
12187 	bool *mask;
12188 
12189 	tmp_cpus = READ_ONCE(cpus);
12190 	if (tmp_cpus > 0)
12191 		return tmp_cpus;
12192 
12193 	err = parse_cpu_mask_file(fcpu, &mask, &n);
12194 	if (err)
12195 		return libbpf_err(err);
12196 
12197 	tmp_cpus = 0;
12198 	for (i = 0; i < n; i++) {
12199 		if (mask[i])
12200 			tmp_cpus++;
12201 	}
12202 	free(mask);
12203 
12204 	WRITE_ONCE(cpus, tmp_cpus);
12205 	return tmp_cpus;
12206 }
12207 
12208 static int populate_skeleton_maps(const struct bpf_object *obj,
12209 				  struct bpf_map_skeleton *maps,
12210 				  size_t map_cnt)
12211 {
12212 	int i;
12213 
12214 	for (i = 0; i < map_cnt; i++) {
12215 		struct bpf_map **map = maps[i].map;
12216 		const char *name = maps[i].name;
12217 		void **mmaped = maps[i].mmaped;
12218 
12219 		*map = bpf_object__find_map_by_name(obj, name);
12220 		if (!*map) {
12221 			pr_warn("failed to find skeleton map '%s'\n", name);
12222 			return -ESRCH;
12223 		}
12224 
12225 		/* externs shouldn't be pre-setup from user code */
12226 		if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
12227 			*mmaped = (*map)->mmaped;
12228 	}
12229 	return 0;
12230 }
12231 
12232 static int populate_skeleton_progs(const struct bpf_object *obj,
12233 				   struct bpf_prog_skeleton *progs,
12234 				   size_t prog_cnt)
12235 {
12236 	int i;
12237 
12238 	for (i = 0; i < prog_cnt; i++) {
12239 		struct bpf_program **prog = progs[i].prog;
12240 		const char *name = progs[i].name;
12241 
12242 		*prog = bpf_object__find_program_by_name(obj, name);
12243 		if (!*prog) {
12244 			pr_warn("failed to find skeleton program '%s'\n", name);
12245 			return -ESRCH;
12246 		}
12247 	}
12248 	return 0;
12249 }
12250 
12251 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
12252 			      const struct bpf_object_open_opts *opts)
12253 {
12254 	DECLARE_LIBBPF_OPTS(bpf_object_open_opts, skel_opts,
12255 		.object_name = s->name,
12256 	);
12257 	struct bpf_object *obj;
12258 	int err;
12259 
12260 	/* Attempt to preserve opts->object_name, unless overriden by user
12261 	 * explicitly. Overwriting object name for skeletons is discouraged,
12262 	 * as it breaks global data maps, because they contain object name
12263 	 * prefix as their own map name prefix. When skeleton is generated,
12264 	 * bpftool is making an assumption that this name will stay the same.
12265 	 */
12266 	if (opts) {
12267 		memcpy(&skel_opts, opts, sizeof(*opts));
12268 		if (!opts->object_name)
12269 			skel_opts.object_name = s->name;
12270 	}
12271 
12272 	obj = bpf_object__open_mem(s->data, s->data_sz, &skel_opts);
12273 	err = libbpf_get_error(obj);
12274 	if (err) {
12275 		pr_warn("failed to initialize skeleton BPF object '%s': %d\n",
12276 			s->name, err);
12277 		return libbpf_err(err);
12278 	}
12279 
12280 	*s->obj = obj;
12281 	err = populate_skeleton_maps(obj, s->maps, s->map_cnt);
12282 	if (err) {
12283 		pr_warn("failed to populate skeleton maps for '%s': %d\n", s->name, err);
12284 		return libbpf_err(err);
12285 	}
12286 
12287 	err = populate_skeleton_progs(obj, s->progs, s->prog_cnt);
12288 	if (err) {
12289 		pr_warn("failed to populate skeleton progs for '%s': %d\n", s->name, err);
12290 		return libbpf_err(err);
12291 	}
12292 
12293 	return 0;
12294 }
12295 
12296 int bpf_object__open_subskeleton(struct bpf_object_subskeleton *s)
12297 {
12298 	int err, len, var_idx, i;
12299 	const char *var_name;
12300 	const struct bpf_map *map;
12301 	struct btf *btf;
12302 	__u32 map_type_id;
12303 	const struct btf_type *map_type, *var_type;
12304 	const struct bpf_var_skeleton *var_skel;
12305 	struct btf_var_secinfo *var;
12306 
12307 	if (!s->obj)
12308 		return libbpf_err(-EINVAL);
12309 
12310 	btf = bpf_object__btf(s->obj);
12311 	if (!btf) {
12312 		pr_warn("subskeletons require BTF at runtime (object %s)\n",
12313 		        bpf_object__name(s->obj));
12314 		return libbpf_err(-errno);
12315 	}
12316 
12317 	err = populate_skeleton_maps(s->obj, s->maps, s->map_cnt);
12318 	if (err) {
12319 		pr_warn("failed to populate subskeleton maps: %d\n", err);
12320 		return libbpf_err(err);
12321 	}
12322 
12323 	err = populate_skeleton_progs(s->obj, s->progs, s->prog_cnt);
12324 	if (err) {
12325 		pr_warn("failed to populate subskeleton maps: %d\n", err);
12326 		return libbpf_err(err);
12327 	}
12328 
12329 	for (var_idx = 0; var_idx < s->var_cnt; var_idx++) {
12330 		var_skel = &s->vars[var_idx];
12331 		map = *var_skel->map;
12332 		map_type_id = bpf_map__btf_value_type_id(map);
12333 		map_type = btf__type_by_id(btf, map_type_id);
12334 
12335 		if (!btf_is_datasec(map_type)) {
12336 			pr_warn("type for map '%1$s' is not a datasec: %2$s",
12337 				bpf_map__name(map),
12338 				__btf_kind_str(btf_kind(map_type)));
12339 			return libbpf_err(-EINVAL);
12340 		}
12341 
12342 		len = btf_vlen(map_type);
12343 		var = btf_var_secinfos(map_type);
12344 		for (i = 0; i < len; i++, var++) {
12345 			var_type = btf__type_by_id(btf, var->type);
12346 			var_name = btf__name_by_offset(btf, var_type->name_off);
12347 			if (strcmp(var_name, var_skel->name) == 0) {
12348 				*var_skel->addr = map->mmaped + var->offset;
12349 				break;
12350 			}
12351 		}
12352 	}
12353 	return 0;
12354 }
12355 
12356 void bpf_object__destroy_subskeleton(struct bpf_object_subskeleton *s)
12357 {
12358 	if (!s)
12359 		return;
12360 	free(s->maps);
12361 	free(s->progs);
12362 	free(s->vars);
12363 	free(s);
12364 }
12365 
12366 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
12367 {
12368 	int i, err;
12369 
12370 	err = bpf_object__load(*s->obj);
12371 	if (err) {
12372 		pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
12373 		return libbpf_err(err);
12374 	}
12375 
12376 	for (i = 0; i < s->map_cnt; i++) {
12377 		struct bpf_map *map = *s->maps[i].map;
12378 		size_t mmap_sz = bpf_map_mmap_sz(map);
12379 		int prot, map_fd = bpf_map__fd(map);
12380 		void **mmaped = s->maps[i].mmaped;
12381 
12382 		if (!mmaped)
12383 			continue;
12384 
12385 		if (!(map->def.map_flags & BPF_F_MMAPABLE)) {
12386 			*mmaped = NULL;
12387 			continue;
12388 		}
12389 
12390 		if (map->def.map_flags & BPF_F_RDONLY_PROG)
12391 			prot = PROT_READ;
12392 		else
12393 			prot = PROT_READ | PROT_WRITE;
12394 
12395 		/* Remap anonymous mmap()-ed "map initialization image" as
12396 		 * a BPF map-backed mmap()-ed memory, but preserving the same
12397 		 * memory address. This will cause kernel to change process'
12398 		 * page table to point to a different piece of kernel memory,
12399 		 * but from userspace point of view memory address (and its
12400 		 * contents, being identical at this point) will stay the
12401 		 * same. This mapping will be released by bpf_object__close()
12402 		 * as per normal clean up procedure, so we don't need to worry
12403 		 * about it from skeleton's clean up perspective.
12404 		 */
12405 		*mmaped = mmap(map->mmaped, mmap_sz, prot,
12406 				MAP_SHARED | MAP_FIXED, map_fd, 0);
12407 		if (*mmaped == MAP_FAILED) {
12408 			err = -errno;
12409 			*mmaped = NULL;
12410 			pr_warn("failed to re-mmap() map '%s': %d\n",
12411 				 bpf_map__name(map), err);
12412 			return libbpf_err(err);
12413 		}
12414 	}
12415 
12416 	return 0;
12417 }
12418 
12419 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
12420 {
12421 	int i, err;
12422 
12423 	for (i = 0; i < s->prog_cnt; i++) {
12424 		struct bpf_program *prog = *s->progs[i].prog;
12425 		struct bpf_link **link = s->progs[i].link;
12426 
12427 		if (!prog->autoload || !prog->autoattach)
12428 			continue;
12429 
12430 		/* auto-attaching not supported for this program */
12431 		if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
12432 			continue;
12433 
12434 		/* if user already set the link manually, don't attempt auto-attach */
12435 		if (*link)
12436 			continue;
12437 
12438 		err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, link);
12439 		if (err) {
12440 			pr_warn("prog '%s': failed to auto-attach: %d\n",
12441 				bpf_program__name(prog), err);
12442 			return libbpf_err(err);
12443 		}
12444 
12445 		/* It's possible that for some SEC() definitions auto-attach
12446 		 * is supported in some cases (e.g., if definition completely
12447 		 * specifies target information), but is not in other cases.
12448 		 * SEC("uprobe") is one such case. If user specified target
12449 		 * binary and function name, such BPF program can be
12450 		 * auto-attached. But if not, it shouldn't trigger skeleton's
12451 		 * attach to fail. It should just be skipped.
12452 		 * attach_fn signals such case with returning 0 (no error) and
12453 		 * setting link to NULL.
12454 		 */
12455 	}
12456 
12457 	return 0;
12458 }
12459 
12460 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
12461 {
12462 	int i;
12463 
12464 	for (i = 0; i < s->prog_cnt; i++) {
12465 		struct bpf_link **link = s->progs[i].link;
12466 
12467 		bpf_link__destroy(*link);
12468 		*link = NULL;
12469 	}
12470 }
12471 
12472 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
12473 {
12474 	if (!s)
12475 		return;
12476 
12477 	if (s->progs)
12478 		bpf_object__detach_skeleton(s);
12479 	if (s->obj)
12480 		bpf_object__close(*s->obj);
12481 	free(s->maps);
12482 	free(s->progs);
12483 	free(s);
12484 }
12485