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