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