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