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