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