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