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