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