xref: /linux/tools/lib/bpf/libbpf.c (revision 7bb377107c72a40ab7505341f8626c8eb79a0cb7)
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 <tools/libc_compat.h>
48 #include <libelf.h>
49 #include <gelf.h>
50 #include <zlib.h>
51 
52 #include "libbpf.h"
53 #include "bpf.h"
54 #include "btf.h"
55 #include "str_error.h"
56 #include "libbpf_internal.h"
57 #include "hashmap.h"
58 
59 /* make sure libbpf doesn't use kernel-only integer typedefs */
60 #pragma GCC poison u8 u16 u32 u64 s8 s16 s32 s64
61 
62 #ifndef EM_BPF
63 #define EM_BPF 247
64 #endif
65 
66 #ifndef BPF_FS_MAGIC
67 #define BPF_FS_MAGIC		0xcafe4a11
68 #endif
69 
70 /* vsprintf() in __base_pr() uses nonliteral format string. It may break
71  * compilation if user enables corresponding warning. Disable it explicitly.
72  */
73 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
74 
75 #define __printf(a, b)	__attribute__((format(printf, a, b)))
76 
77 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj);
78 static struct bpf_program *bpf_object__find_prog_by_idx(struct bpf_object *obj,
79 							int idx);
80 static const struct btf_type *
81 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id);
82 
83 static int __base_pr(enum libbpf_print_level level, const char *format,
84 		     va_list args)
85 {
86 	if (level == LIBBPF_DEBUG)
87 		return 0;
88 
89 	return vfprintf(stderr, format, args);
90 }
91 
92 static libbpf_print_fn_t __libbpf_pr = __base_pr;
93 
94 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
95 {
96 	libbpf_print_fn_t old_print_fn = __libbpf_pr;
97 
98 	__libbpf_pr = fn;
99 	return old_print_fn;
100 }
101 
102 __printf(2, 3)
103 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
104 {
105 	va_list args;
106 
107 	if (!__libbpf_pr)
108 		return;
109 
110 	va_start(args, format);
111 	__libbpf_pr(level, format, args);
112 	va_end(args);
113 }
114 
115 static void pr_perm_msg(int err)
116 {
117 	struct rlimit limit;
118 	char buf[100];
119 
120 	if (err != -EPERM || geteuid() != 0)
121 		return;
122 
123 	err = getrlimit(RLIMIT_MEMLOCK, &limit);
124 	if (err)
125 		return;
126 
127 	if (limit.rlim_cur == RLIM_INFINITY)
128 		return;
129 
130 	if (limit.rlim_cur < 1024)
131 		snprintf(buf, sizeof(buf), "%zu bytes", (size_t)limit.rlim_cur);
132 	else if (limit.rlim_cur < 1024*1024)
133 		snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
134 	else
135 		snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
136 
137 	pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
138 		buf);
139 }
140 
141 #define STRERR_BUFSIZE  128
142 
143 /* Copied from tools/perf/util/util.h */
144 #ifndef zfree
145 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
146 #endif
147 
148 #ifndef zclose
149 # define zclose(fd) ({			\
150 	int ___err = 0;			\
151 	if ((fd) >= 0)			\
152 		___err = close((fd));	\
153 	fd = -1;			\
154 	___err; })
155 #endif
156 
157 #ifdef HAVE_LIBELF_MMAP_SUPPORT
158 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ_MMAP
159 #else
160 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ
161 #endif
162 
163 static inline __u64 ptr_to_u64(const void *ptr)
164 {
165 	return (__u64) (unsigned long) ptr;
166 }
167 
168 struct bpf_capabilities {
169 	/* v4.14: kernel support for program & map names. */
170 	__u32 name:1;
171 	/* v5.2: kernel support for global data sections. */
172 	__u32 global_data:1;
173 	/* BTF_KIND_FUNC and BTF_KIND_FUNC_PROTO support */
174 	__u32 btf_func:1;
175 	/* BTF_KIND_VAR and BTF_KIND_DATASEC support */
176 	__u32 btf_datasec:1;
177 	/* BPF_F_MMAPABLE is supported for arrays */
178 	__u32 array_mmap:1;
179 	/* BTF_FUNC_GLOBAL is supported */
180 	__u32 btf_func_global:1;
181 	/* kernel support for expected_attach_type in BPF_PROG_LOAD */
182 	__u32 exp_attach_type:1;
183 };
184 
185 enum reloc_type {
186 	RELO_LD64,
187 	RELO_CALL,
188 	RELO_DATA,
189 	RELO_EXTERN,
190 };
191 
192 struct reloc_desc {
193 	enum reloc_type type;
194 	int insn_idx;
195 	int map_idx;
196 	int sym_off;
197 };
198 
199 struct bpf_sec_def;
200 
201 typedef struct bpf_link *(*attach_fn_t)(const struct bpf_sec_def *sec,
202 					struct bpf_program *prog);
203 
204 struct bpf_sec_def {
205 	const char *sec;
206 	size_t len;
207 	enum bpf_prog_type prog_type;
208 	enum bpf_attach_type expected_attach_type;
209 	bool is_exp_attach_type_optional;
210 	bool is_attachable;
211 	bool is_attach_btf;
212 	attach_fn_t attach_fn;
213 };
214 
215 /*
216  * bpf_prog should be a better name but it has been used in
217  * linux/filter.h.
218  */
219 struct bpf_program {
220 	/* Index in elf obj file, for relocation use. */
221 	int idx;
222 	char *name;
223 	int prog_ifindex;
224 	char *section_name;
225 	const struct bpf_sec_def *sec_def;
226 	/* section_name with / replaced by _; makes recursive pinning
227 	 * in bpf_object__pin_programs easier
228 	 */
229 	char *pin_name;
230 	struct bpf_insn *insns;
231 	size_t insns_cnt, main_prog_cnt;
232 	enum bpf_prog_type type;
233 
234 	struct reloc_desc *reloc_desc;
235 	int nr_reloc;
236 	int log_level;
237 
238 	struct {
239 		int nr;
240 		int *fds;
241 	} instances;
242 	bpf_program_prep_t preprocessor;
243 
244 	struct bpf_object *obj;
245 	void *priv;
246 	bpf_program_clear_priv_t clear_priv;
247 
248 	enum bpf_attach_type expected_attach_type;
249 	__u32 attach_btf_id;
250 	__u32 attach_prog_fd;
251 	void *func_info;
252 	__u32 func_info_rec_size;
253 	__u32 func_info_cnt;
254 
255 	struct bpf_capabilities *caps;
256 
257 	void *line_info;
258 	__u32 line_info_rec_size;
259 	__u32 line_info_cnt;
260 	__u32 prog_flags;
261 };
262 
263 struct bpf_struct_ops {
264 	const char *tname;
265 	const struct btf_type *type;
266 	struct bpf_program **progs;
267 	__u32 *kern_func_off;
268 	/* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
269 	void *data;
270 	/* e.g. struct bpf_struct_ops_tcp_congestion_ops in
271 	 *      btf_vmlinux's format.
272 	 * struct bpf_struct_ops_tcp_congestion_ops {
273 	 *	[... some other kernel fields ...]
274 	 *	struct tcp_congestion_ops data;
275 	 * }
276 	 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
277 	 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
278 	 * from "data".
279 	 */
280 	void *kern_vdata;
281 	__u32 type_id;
282 };
283 
284 #define DATA_SEC ".data"
285 #define BSS_SEC ".bss"
286 #define RODATA_SEC ".rodata"
287 #define KCONFIG_SEC ".kconfig"
288 #define STRUCT_OPS_SEC ".struct_ops"
289 
290 enum libbpf_map_type {
291 	LIBBPF_MAP_UNSPEC,
292 	LIBBPF_MAP_DATA,
293 	LIBBPF_MAP_BSS,
294 	LIBBPF_MAP_RODATA,
295 	LIBBPF_MAP_KCONFIG,
296 };
297 
298 static const char * const libbpf_type_to_btf_name[] = {
299 	[LIBBPF_MAP_DATA]	= DATA_SEC,
300 	[LIBBPF_MAP_BSS]	= BSS_SEC,
301 	[LIBBPF_MAP_RODATA]	= RODATA_SEC,
302 	[LIBBPF_MAP_KCONFIG]	= KCONFIG_SEC,
303 };
304 
305 struct bpf_map {
306 	char *name;
307 	int fd;
308 	int sec_idx;
309 	size_t sec_offset;
310 	int map_ifindex;
311 	int inner_map_fd;
312 	struct bpf_map_def def;
313 	__u32 btf_var_idx;
314 	__u32 btf_key_type_id;
315 	__u32 btf_value_type_id;
316 	__u32 btf_vmlinux_value_type_id;
317 	void *priv;
318 	bpf_map_clear_priv_t clear_priv;
319 	enum libbpf_map_type libbpf_type;
320 	void *mmaped;
321 	struct bpf_struct_ops *st_ops;
322 	struct bpf_map *inner_map;
323 	void **init_slots;
324 	int init_slots_sz;
325 	char *pin_path;
326 	bool pinned;
327 	bool reused;
328 };
329 
330 enum extern_type {
331 	EXT_UNKNOWN,
332 	EXT_CHAR,
333 	EXT_BOOL,
334 	EXT_INT,
335 	EXT_TRISTATE,
336 	EXT_CHAR_ARR,
337 };
338 
339 struct extern_desc {
340 	const char *name;
341 	int sym_idx;
342 	int btf_id;
343 	enum extern_type type;
344 	int sz;
345 	int align;
346 	int data_off;
347 	bool is_signed;
348 	bool is_weak;
349 	bool is_set;
350 };
351 
352 static LIST_HEAD(bpf_objects_list);
353 
354 struct bpf_object {
355 	char name[BPF_OBJ_NAME_LEN];
356 	char license[64];
357 	__u32 kern_version;
358 
359 	struct bpf_program *programs;
360 	size_t nr_programs;
361 	struct bpf_map *maps;
362 	size_t nr_maps;
363 	size_t maps_cap;
364 
365 	char *kconfig;
366 	struct extern_desc *externs;
367 	int nr_extern;
368 	int kconfig_map_idx;
369 
370 	bool loaded;
371 	bool has_pseudo_calls;
372 
373 	/*
374 	 * Information when doing elf related work. Only valid if fd
375 	 * is valid.
376 	 */
377 	struct {
378 		int fd;
379 		const void *obj_buf;
380 		size_t obj_buf_sz;
381 		Elf *elf;
382 		GElf_Ehdr ehdr;
383 		Elf_Data *symbols;
384 		Elf_Data *data;
385 		Elf_Data *rodata;
386 		Elf_Data *bss;
387 		Elf_Data *st_ops_data;
388 		size_t strtabidx;
389 		struct {
390 			GElf_Shdr shdr;
391 			Elf_Data *data;
392 		} *reloc_sects;
393 		int nr_reloc_sects;
394 		int maps_shndx;
395 		int btf_maps_shndx;
396 		__u32 btf_maps_sec_btf_id;
397 		int text_shndx;
398 		int symbols_shndx;
399 		int data_shndx;
400 		int rodata_shndx;
401 		int bss_shndx;
402 		int st_ops_shndx;
403 	} efile;
404 	/*
405 	 * All loaded bpf_object is linked in a list, which is
406 	 * hidden to caller. bpf_objects__<func> handlers deal with
407 	 * all objects.
408 	 */
409 	struct list_head list;
410 
411 	struct btf *btf;
412 	/* Parse and load BTF vmlinux if any of the programs in the object need
413 	 * it at load time.
414 	 */
415 	struct btf *btf_vmlinux;
416 	struct btf_ext *btf_ext;
417 
418 	void *priv;
419 	bpf_object_clear_priv_t clear_priv;
420 
421 	struct bpf_capabilities caps;
422 
423 	char path[];
424 };
425 #define obj_elf_valid(o)	((o)->efile.elf)
426 
427 void bpf_program__unload(struct bpf_program *prog)
428 {
429 	int i;
430 
431 	if (!prog)
432 		return;
433 
434 	/*
435 	 * If the object is opened but the program was never loaded,
436 	 * it is possible that prog->instances.nr == -1.
437 	 */
438 	if (prog->instances.nr > 0) {
439 		for (i = 0; i < prog->instances.nr; i++)
440 			zclose(prog->instances.fds[i]);
441 	} else if (prog->instances.nr != -1) {
442 		pr_warn("Internal error: instances.nr is %d\n",
443 			prog->instances.nr);
444 	}
445 
446 	prog->instances.nr = -1;
447 	zfree(&prog->instances.fds);
448 
449 	zfree(&prog->func_info);
450 	zfree(&prog->line_info);
451 }
452 
453 static void bpf_program__exit(struct bpf_program *prog)
454 {
455 	if (!prog)
456 		return;
457 
458 	if (prog->clear_priv)
459 		prog->clear_priv(prog, prog->priv);
460 
461 	prog->priv = NULL;
462 	prog->clear_priv = NULL;
463 
464 	bpf_program__unload(prog);
465 	zfree(&prog->name);
466 	zfree(&prog->section_name);
467 	zfree(&prog->pin_name);
468 	zfree(&prog->insns);
469 	zfree(&prog->reloc_desc);
470 
471 	prog->nr_reloc = 0;
472 	prog->insns_cnt = 0;
473 	prog->idx = -1;
474 }
475 
476 static char *__bpf_program__pin_name(struct bpf_program *prog)
477 {
478 	char *name, *p;
479 
480 	name = p = strdup(prog->section_name);
481 	while ((p = strchr(p, '/')))
482 		*p = '_';
483 
484 	return name;
485 }
486 
487 static int
488 bpf_program__init(void *data, size_t size, char *section_name, int idx,
489 		  struct bpf_program *prog)
490 {
491 	const size_t bpf_insn_sz = sizeof(struct bpf_insn);
492 
493 	if (size == 0 || size % bpf_insn_sz) {
494 		pr_warn("corrupted section '%s', size: %zu\n",
495 			section_name, size);
496 		return -EINVAL;
497 	}
498 
499 	memset(prog, 0, sizeof(*prog));
500 
501 	prog->section_name = strdup(section_name);
502 	if (!prog->section_name) {
503 		pr_warn("failed to alloc name for prog under section(%d) %s\n",
504 			idx, section_name);
505 		goto errout;
506 	}
507 
508 	prog->pin_name = __bpf_program__pin_name(prog);
509 	if (!prog->pin_name) {
510 		pr_warn("failed to alloc pin name for prog under section(%d) %s\n",
511 			idx, section_name);
512 		goto errout;
513 	}
514 
515 	prog->insns = malloc(size);
516 	if (!prog->insns) {
517 		pr_warn("failed to alloc insns for prog under section %s\n",
518 			section_name);
519 		goto errout;
520 	}
521 	prog->insns_cnt = size / bpf_insn_sz;
522 	memcpy(prog->insns, data, size);
523 	prog->idx = idx;
524 	prog->instances.fds = NULL;
525 	prog->instances.nr = -1;
526 	prog->type = BPF_PROG_TYPE_UNSPEC;
527 
528 	return 0;
529 errout:
530 	bpf_program__exit(prog);
531 	return -ENOMEM;
532 }
533 
534 static int
535 bpf_object__add_program(struct bpf_object *obj, void *data, size_t size,
536 			char *section_name, int idx)
537 {
538 	struct bpf_program prog, *progs;
539 	int nr_progs, err;
540 
541 	err = bpf_program__init(data, size, section_name, idx, &prog);
542 	if (err)
543 		return err;
544 
545 	prog.caps = &obj->caps;
546 	progs = obj->programs;
547 	nr_progs = obj->nr_programs;
548 
549 	progs = reallocarray(progs, nr_progs + 1, sizeof(progs[0]));
550 	if (!progs) {
551 		/*
552 		 * In this case the original obj->programs
553 		 * is still valid, so don't need special treat for
554 		 * bpf_close_object().
555 		 */
556 		pr_warn("failed to alloc a new program under section '%s'\n",
557 			section_name);
558 		bpf_program__exit(&prog);
559 		return -ENOMEM;
560 	}
561 
562 	pr_debug("found program %s\n", prog.section_name);
563 	obj->programs = progs;
564 	obj->nr_programs = nr_progs + 1;
565 	prog.obj = obj;
566 	progs[nr_progs] = prog;
567 	return 0;
568 }
569 
570 static int
571 bpf_object__init_prog_names(struct bpf_object *obj)
572 {
573 	Elf_Data *symbols = obj->efile.symbols;
574 	struct bpf_program *prog;
575 	size_t pi, si;
576 
577 	for (pi = 0; pi < obj->nr_programs; pi++) {
578 		const char *name = NULL;
579 
580 		prog = &obj->programs[pi];
581 
582 		for (si = 0; si < symbols->d_size / sizeof(GElf_Sym) && !name;
583 		     si++) {
584 			GElf_Sym sym;
585 
586 			if (!gelf_getsym(symbols, si, &sym))
587 				continue;
588 			if (sym.st_shndx != prog->idx)
589 				continue;
590 			if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL)
591 				continue;
592 
593 			name = elf_strptr(obj->efile.elf,
594 					  obj->efile.strtabidx,
595 					  sym.st_name);
596 			if (!name) {
597 				pr_warn("failed to get sym name string for prog %s\n",
598 					prog->section_name);
599 				return -LIBBPF_ERRNO__LIBELF;
600 			}
601 		}
602 
603 		if (!name && prog->idx == obj->efile.text_shndx)
604 			name = ".text";
605 
606 		if (!name) {
607 			pr_warn("failed to find sym for prog %s\n",
608 				prog->section_name);
609 			return -EINVAL;
610 		}
611 
612 		prog->name = strdup(name);
613 		if (!prog->name) {
614 			pr_warn("failed to allocate memory for prog sym %s\n",
615 				name);
616 			return -ENOMEM;
617 		}
618 	}
619 
620 	return 0;
621 }
622 
623 static __u32 get_kernel_version(void)
624 {
625 	__u32 major, minor, patch;
626 	struct utsname info;
627 
628 	uname(&info);
629 	if (sscanf(info.release, "%u.%u.%u", &major, &minor, &patch) != 3)
630 		return 0;
631 	return KERNEL_VERSION(major, minor, patch);
632 }
633 
634 static const struct btf_member *
635 find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
636 {
637 	struct btf_member *m;
638 	int i;
639 
640 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
641 		if (btf_member_bit_offset(t, i) == bit_offset)
642 			return m;
643 	}
644 
645 	return NULL;
646 }
647 
648 static const struct btf_member *
649 find_member_by_name(const struct btf *btf, const struct btf_type *t,
650 		    const char *name)
651 {
652 	struct btf_member *m;
653 	int i;
654 
655 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
656 		if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
657 			return m;
658 	}
659 
660 	return NULL;
661 }
662 
663 #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
664 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
665 				   const char *name, __u32 kind);
666 
667 static int
668 find_struct_ops_kern_types(const struct btf *btf, const char *tname,
669 			   const struct btf_type **type, __u32 *type_id,
670 			   const struct btf_type **vtype, __u32 *vtype_id,
671 			   const struct btf_member **data_member)
672 {
673 	const struct btf_type *kern_type, *kern_vtype;
674 	const struct btf_member *kern_data_member;
675 	__s32 kern_vtype_id, kern_type_id;
676 	__u32 i;
677 
678 	kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
679 	if (kern_type_id < 0) {
680 		pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n",
681 			tname);
682 		return kern_type_id;
683 	}
684 	kern_type = btf__type_by_id(btf, kern_type_id);
685 
686 	/* Find the corresponding "map_value" type that will be used
687 	 * in map_update(BPF_MAP_TYPE_STRUCT_OPS).  For example,
688 	 * find "struct bpf_struct_ops_tcp_congestion_ops" from the
689 	 * btf_vmlinux.
690 	 */
691 	kern_vtype_id = find_btf_by_prefix_kind(btf, STRUCT_OPS_VALUE_PREFIX,
692 						tname, BTF_KIND_STRUCT);
693 	if (kern_vtype_id < 0) {
694 		pr_warn("struct_ops init_kern: struct %s%s is not found in kernel BTF\n",
695 			STRUCT_OPS_VALUE_PREFIX, tname);
696 		return kern_vtype_id;
697 	}
698 	kern_vtype = btf__type_by_id(btf, kern_vtype_id);
699 
700 	/* Find "struct tcp_congestion_ops" from
701 	 * struct bpf_struct_ops_tcp_congestion_ops {
702 	 *	[ ... ]
703 	 *	struct tcp_congestion_ops data;
704 	 * }
705 	 */
706 	kern_data_member = btf_members(kern_vtype);
707 	for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
708 		if (kern_data_member->type == kern_type_id)
709 			break;
710 	}
711 	if (i == btf_vlen(kern_vtype)) {
712 		pr_warn("struct_ops init_kern: struct %s data is not found in struct %s%s\n",
713 			tname, STRUCT_OPS_VALUE_PREFIX, tname);
714 		return -EINVAL;
715 	}
716 
717 	*type = kern_type;
718 	*type_id = kern_type_id;
719 	*vtype = kern_vtype;
720 	*vtype_id = kern_vtype_id;
721 	*data_member = kern_data_member;
722 
723 	return 0;
724 }
725 
726 static bool bpf_map__is_struct_ops(const struct bpf_map *map)
727 {
728 	return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
729 }
730 
731 /* Init the map's fields that depend on kern_btf */
732 static int bpf_map__init_kern_struct_ops(struct bpf_map *map,
733 					 const struct btf *btf,
734 					 const struct btf *kern_btf)
735 {
736 	const struct btf_member *member, *kern_member, *kern_data_member;
737 	const struct btf_type *type, *kern_type, *kern_vtype;
738 	__u32 i, kern_type_id, kern_vtype_id, kern_data_off;
739 	struct bpf_struct_ops *st_ops;
740 	void *data, *kern_data;
741 	const char *tname;
742 	int err;
743 
744 	st_ops = map->st_ops;
745 	type = st_ops->type;
746 	tname = st_ops->tname;
747 	err = find_struct_ops_kern_types(kern_btf, tname,
748 					 &kern_type, &kern_type_id,
749 					 &kern_vtype, &kern_vtype_id,
750 					 &kern_data_member);
751 	if (err)
752 		return err;
753 
754 	pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
755 		 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
756 
757 	map->def.value_size = kern_vtype->size;
758 	map->btf_vmlinux_value_type_id = kern_vtype_id;
759 
760 	st_ops->kern_vdata = calloc(1, kern_vtype->size);
761 	if (!st_ops->kern_vdata)
762 		return -ENOMEM;
763 
764 	data = st_ops->data;
765 	kern_data_off = kern_data_member->offset / 8;
766 	kern_data = st_ops->kern_vdata + kern_data_off;
767 
768 	member = btf_members(type);
769 	for (i = 0; i < btf_vlen(type); i++, member++) {
770 		const struct btf_type *mtype, *kern_mtype;
771 		__u32 mtype_id, kern_mtype_id;
772 		void *mdata, *kern_mdata;
773 		__s64 msize, kern_msize;
774 		__u32 moff, kern_moff;
775 		__u32 kern_member_idx;
776 		const char *mname;
777 
778 		mname = btf__name_by_offset(btf, member->name_off);
779 		kern_member = find_member_by_name(kern_btf, kern_type, mname);
780 		if (!kern_member) {
781 			pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
782 				map->name, mname);
783 			return -ENOTSUP;
784 		}
785 
786 		kern_member_idx = kern_member - btf_members(kern_type);
787 		if (btf_member_bitfield_size(type, i) ||
788 		    btf_member_bitfield_size(kern_type, kern_member_idx)) {
789 			pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
790 				map->name, mname);
791 			return -ENOTSUP;
792 		}
793 
794 		moff = member->offset / 8;
795 		kern_moff = kern_member->offset / 8;
796 
797 		mdata = data + moff;
798 		kern_mdata = kern_data + kern_moff;
799 
800 		mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
801 		kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
802 						    &kern_mtype_id);
803 		if (BTF_INFO_KIND(mtype->info) !=
804 		    BTF_INFO_KIND(kern_mtype->info)) {
805 			pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
806 				map->name, mname, BTF_INFO_KIND(mtype->info),
807 				BTF_INFO_KIND(kern_mtype->info));
808 			return -ENOTSUP;
809 		}
810 
811 		if (btf_is_ptr(mtype)) {
812 			struct bpf_program *prog;
813 
814 			mtype = skip_mods_and_typedefs(btf, mtype->type, &mtype_id);
815 			kern_mtype = skip_mods_and_typedefs(kern_btf,
816 							    kern_mtype->type,
817 							    &kern_mtype_id);
818 			if (!btf_is_func_proto(mtype) ||
819 			    !btf_is_func_proto(kern_mtype)) {
820 				pr_warn("struct_ops init_kern %s: non func ptr %s is not supported\n",
821 					map->name, mname);
822 				return -ENOTSUP;
823 			}
824 
825 			prog = st_ops->progs[i];
826 			if (!prog) {
827 				pr_debug("struct_ops init_kern %s: func ptr %s is not set\n",
828 					 map->name, mname);
829 				continue;
830 			}
831 
832 			prog->attach_btf_id = kern_type_id;
833 			prog->expected_attach_type = kern_member_idx;
834 
835 			st_ops->kern_func_off[i] = kern_data_off + kern_moff;
836 
837 			pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
838 				 map->name, mname, prog->name, moff,
839 				 kern_moff);
840 
841 			continue;
842 		}
843 
844 		msize = btf__resolve_size(btf, mtype_id);
845 		kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
846 		if (msize < 0 || kern_msize < 0 || msize != kern_msize) {
847 			pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
848 				map->name, mname, (ssize_t)msize,
849 				(ssize_t)kern_msize);
850 			return -ENOTSUP;
851 		}
852 
853 		pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
854 			 map->name, mname, (unsigned int)msize,
855 			 moff, kern_moff);
856 		memcpy(kern_mdata, mdata, msize);
857 	}
858 
859 	return 0;
860 }
861 
862 static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
863 {
864 	struct bpf_map *map;
865 	size_t i;
866 	int err;
867 
868 	for (i = 0; i < obj->nr_maps; i++) {
869 		map = &obj->maps[i];
870 
871 		if (!bpf_map__is_struct_ops(map))
872 			continue;
873 
874 		err = bpf_map__init_kern_struct_ops(map, obj->btf,
875 						    obj->btf_vmlinux);
876 		if (err)
877 			return err;
878 	}
879 
880 	return 0;
881 }
882 
883 static int bpf_object__init_struct_ops_maps(struct bpf_object *obj)
884 {
885 	const struct btf_type *type, *datasec;
886 	const struct btf_var_secinfo *vsi;
887 	struct bpf_struct_ops *st_ops;
888 	const char *tname, *var_name;
889 	__s32 type_id, datasec_id;
890 	const struct btf *btf;
891 	struct bpf_map *map;
892 	__u32 i;
893 
894 	if (obj->efile.st_ops_shndx == -1)
895 		return 0;
896 
897 	btf = obj->btf;
898 	datasec_id = btf__find_by_name_kind(btf, STRUCT_OPS_SEC,
899 					    BTF_KIND_DATASEC);
900 	if (datasec_id < 0) {
901 		pr_warn("struct_ops init: DATASEC %s not found\n",
902 			STRUCT_OPS_SEC);
903 		return -EINVAL;
904 	}
905 
906 	datasec = btf__type_by_id(btf, datasec_id);
907 	vsi = btf_var_secinfos(datasec);
908 	for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
909 		type = btf__type_by_id(obj->btf, vsi->type);
910 		var_name = btf__name_by_offset(obj->btf, type->name_off);
911 
912 		type_id = btf__resolve_type(obj->btf, vsi->type);
913 		if (type_id < 0) {
914 			pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
915 				vsi->type, STRUCT_OPS_SEC);
916 			return -EINVAL;
917 		}
918 
919 		type = btf__type_by_id(obj->btf, type_id);
920 		tname = btf__name_by_offset(obj->btf, type->name_off);
921 		if (!tname[0]) {
922 			pr_warn("struct_ops init: anonymous type is not supported\n");
923 			return -ENOTSUP;
924 		}
925 		if (!btf_is_struct(type)) {
926 			pr_warn("struct_ops init: %s is not a struct\n", tname);
927 			return -EINVAL;
928 		}
929 
930 		map = bpf_object__add_map(obj);
931 		if (IS_ERR(map))
932 			return PTR_ERR(map);
933 
934 		map->sec_idx = obj->efile.st_ops_shndx;
935 		map->sec_offset = vsi->offset;
936 		map->name = strdup(var_name);
937 		if (!map->name)
938 			return -ENOMEM;
939 
940 		map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
941 		map->def.key_size = sizeof(int);
942 		map->def.value_size = type->size;
943 		map->def.max_entries = 1;
944 
945 		map->st_ops = calloc(1, sizeof(*map->st_ops));
946 		if (!map->st_ops)
947 			return -ENOMEM;
948 		st_ops = map->st_ops;
949 		st_ops->data = malloc(type->size);
950 		st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
951 		st_ops->kern_func_off = malloc(btf_vlen(type) *
952 					       sizeof(*st_ops->kern_func_off));
953 		if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
954 			return -ENOMEM;
955 
956 		if (vsi->offset + type->size > obj->efile.st_ops_data->d_size) {
957 			pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
958 				var_name, STRUCT_OPS_SEC);
959 			return -EINVAL;
960 		}
961 
962 		memcpy(st_ops->data,
963 		       obj->efile.st_ops_data->d_buf + vsi->offset,
964 		       type->size);
965 		st_ops->tname = tname;
966 		st_ops->type = type;
967 		st_ops->type_id = type_id;
968 
969 		pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
970 			 tname, type_id, var_name, vsi->offset);
971 	}
972 
973 	return 0;
974 }
975 
976 static struct bpf_object *bpf_object__new(const char *path,
977 					  const void *obj_buf,
978 					  size_t obj_buf_sz,
979 					  const char *obj_name)
980 {
981 	struct bpf_object *obj;
982 	char *end;
983 
984 	obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
985 	if (!obj) {
986 		pr_warn("alloc memory failed for %s\n", path);
987 		return ERR_PTR(-ENOMEM);
988 	}
989 
990 	strcpy(obj->path, path);
991 	if (obj_name) {
992 		strncpy(obj->name, obj_name, sizeof(obj->name) - 1);
993 		obj->name[sizeof(obj->name) - 1] = 0;
994 	} else {
995 		/* Using basename() GNU version which doesn't modify arg. */
996 		strncpy(obj->name, basename((void *)path),
997 			sizeof(obj->name) - 1);
998 		end = strchr(obj->name, '.');
999 		if (end)
1000 			*end = 0;
1001 	}
1002 
1003 	obj->efile.fd = -1;
1004 	/*
1005 	 * Caller of this function should also call
1006 	 * bpf_object__elf_finish() after data collection to return
1007 	 * obj_buf to user. If not, we should duplicate the buffer to
1008 	 * avoid user freeing them before elf finish.
1009 	 */
1010 	obj->efile.obj_buf = obj_buf;
1011 	obj->efile.obj_buf_sz = obj_buf_sz;
1012 	obj->efile.maps_shndx = -1;
1013 	obj->efile.btf_maps_shndx = -1;
1014 	obj->efile.data_shndx = -1;
1015 	obj->efile.rodata_shndx = -1;
1016 	obj->efile.bss_shndx = -1;
1017 	obj->efile.st_ops_shndx = -1;
1018 	obj->kconfig_map_idx = -1;
1019 
1020 	obj->kern_version = get_kernel_version();
1021 	obj->loaded = false;
1022 
1023 	INIT_LIST_HEAD(&obj->list);
1024 	list_add(&obj->list, &bpf_objects_list);
1025 	return obj;
1026 }
1027 
1028 static void bpf_object__elf_finish(struct bpf_object *obj)
1029 {
1030 	if (!obj_elf_valid(obj))
1031 		return;
1032 
1033 	if (obj->efile.elf) {
1034 		elf_end(obj->efile.elf);
1035 		obj->efile.elf = NULL;
1036 	}
1037 	obj->efile.symbols = NULL;
1038 	obj->efile.data = NULL;
1039 	obj->efile.rodata = NULL;
1040 	obj->efile.bss = NULL;
1041 	obj->efile.st_ops_data = NULL;
1042 
1043 	zfree(&obj->efile.reloc_sects);
1044 	obj->efile.nr_reloc_sects = 0;
1045 	zclose(obj->efile.fd);
1046 	obj->efile.obj_buf = NULL;
1047 	obj->efile.obj_buf_sz = 0;
1048 }
1049 
1050 static int bpf_object__elf_init(struct bpf_object *obj)
1051 {
1052 	int err = 0;
1053 	GElf_Ehdr *ep;
1054 
1055 	if (obj_elf_valid(obj)) {
1056 		pr_warn("elf init: internal error\n");
1057 		return -LIBBPF_ERRNO__LIBELF;
1058 	}
1059 
1060 	if (obj->efile.obj_buf_sz > 0) {
1061 		/*
1062 		 * obj_buf should have been validated by
1063 		 * bpf_object__open_buffer().
1064 		 */
1065 		obj->efile.elf = elf_memory((char *)obj->efile.obj_buf,
1066 					    obj->efile.obj_buf_sz);
1067 	} else {
1068 		obj->efile.fd = open(obj->path, O_RDONLY);
1069 		if (obj->efile.fd < 0) {
1070 			char errmsg[STRERR_BUFSIZE], *cp;
1071 
1072 			err = -errno;
1073 			cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
1074 			pr_warn("failed to open %s: %s\n", obj->path, cp);
1075 			return err;
1076 		}
1077 
1078 		obj->efile.elf = elf_begin(obj->efile.fd,
1079 					   LIBBPF_ELF_C_READ_MMAP, NULL);
1080 	}
1081 
1082 	if (!obj->efile.elf) {
1083 		pr_warn("failed to open %s as ELF file\n", obj->path);
1084 		err = -LIBBPF_ERRNO__LIBELF;
1085 		goto errout;
1086 	}
1087 
1088 	if (!gelf_getehdr(obj->efile.elf, &obj->efile.ehdr)) {
1089 		pr_warn("failed to get EHDR from %s\n", obj->path);
1090 		err = -LIBBPF_ERRNO__FORMAT;
1091 		goto errout;
1092 	}
1093 	ep = &obj->efile.ehdr;
1094 
1095 	/* Old LLVM set e_machine to EM_NONE */
1096 	if (ep->e_type != ET_REL ||
1097 	    (ep->e_machine && ep->e_machine != EM_BPF)) {
1098 		pr_warn("%s is not an eBPF object file\n", obj->path);
1099 		err = -LIBBPF_ERRNO__FORMAT;
1100 		goto errout;
1101 	}
1102 
1103 	return 0;
1104 errout:
1105 	bpf_object__elf_finish(obj);
1106 	return err;
1107 }
1108 
1109 static int bpf_object__check_endianness(struct bpf_object *obj)
1110 {
1111 #if __BYTE_ORDER == __LITTLE_ENDIAN
1112 	if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2LSB)
1113 		return 0;
1114 #elif __BYTE_ORDER == __BIG_ENDIAN
1115 	if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2MSB)
1116 		return 0;
1117 #else
1118 # error "Unrecognized __BYTE_ORDER__"
1119 #endif
1120 	pr_warn("endianness mismatch.\n");
1121 	return -LIBBPF_ERRNO__ENDIAN;
1122 }
1123 
1124 static int
1125 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1126 {
1127 	memcpy(obj->license, data, min(size, sizeof(obj->license) - 1));
1128 	pr_debug("license of %s is %s\n", obj->path, obj->license);
1129 	return 0;
1130 }
1131 
1132 static int
1133 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1134 {
1135 	__u32 kver;
1136 
1137 	if (size != sizeof(kver)) {
1138 		pr_warn("invalid kver section in %s\n", obj->path);
1139 		return -LIBBPF_ERRNO__FORMAT;
1140 	}
1141 	memcpy(&kver, data, sizeof(kver));
1142 	obj->kern_version = kver;
1143 	pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1144 	return 0;
1145 }
1146 
1147 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1148 {
1149 	if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1150 	    type == BPF_MAP_TYPE_HASH_OF_MAPS)
1151 		return true;
1152 	return false;
1153 }
1154 
1155 static int bpf_object_search_section_size(const struct bpf_object *obj,
1156 					  const char *name, size_t *d_size)
1157 {
1158 	const GElf_Ehdr *ep = &obj->efile.ehdr;
1159 	Elf *elf = obj->efile.elf;
1160 	Elf_Scn *scn = NULL;
1161 	int idx = 0;
1162 
1163 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
1164 		const char *sec_name;
1165 		Elf_Data *data;
1166 		GElf_Shdr sh;
1167 
1168 		idx++;
1169 		if (gelf_getshdr(scn, &sh) != &sh) {
1170 			pr_warn("failed to get section(%d) header from %s\n",
1171 				idx, obj->path);
1172 			return -EIO;
1173 		}
1174 
1175 		sec_name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
1176 		if (!sec_name) {
1177 			pr_warn("failed to get section(%d) name from %s\n",
1178 				idx, obj->path);
1179 			return -EIO;
1180 		}
1181 
1182 		if (strcmp(name, sec_name))
1183 			continue;
1184 
1185 		data = elf_getdata(scn, 0);
1186 		if (!data) {
1187 			pr_warn("failed to get section(%d) data from %s(%s)\n",
1188 				idx, name, obj->path);
1189 			return -EIO;
1190 		}
1191 
1192 		*d_size = data->d_size;
1193 		return 0;
1194 	}
1195 
1196 	return -ENOENT;
1197 }
1198 
1199 int bpf_object__section_size(const struct bpf_object *obj, const char *name,
1200 			     __u32 *size)
1201 {
1202 	int ret = -ENOENT;
1203 	size_t d_size;
1204 
1205 	*size = 0;
1206 	if (!name) {
1207 		return -EINVAL;
1208 	} else if (!strcmp(name, DATA_SEC)) {
1209 		if (obj->efile.data)
1210 			*size = obj->efile.data->d_size;
1211 	} else if (!strcmp(name, BSS_SEC)) {
1212 		if (obj->efile.bss)
1213 			*size = obj->efile.bss->d_size;
1214 	} else if (!strcmp(name, RODATA_SEC)) {
1215 		if (obj->efile.rodata)
1216 			*size = obj->efile.rodata->d_size;
1217 	} else if (!strcmp(name, STRUCT_OPS_SEC)) {
1218 		if (obj->efile.st_ops_data)
1219 			*size = obj->efile.st_ops_data->d_size;
1220 	} else {
1221 		ret = bpf_object_search_section_size(obj, name, &d_size);
1222 		if (!ret)
1223 			*size = d_size;
1224 	}
1225 
1226 	return *size ? 0 : ret;
1227 }
1228 
1229 int bpf_object__variable_offset(const struct bpf_object *obj, const char *name,
1230 				__u32 *off)
1231 {
1232 	Elf_Data *symbols = obj->efile.symbols;
1233 	const char *sname;
1234 	size_t si;
1235 
1236 	if (!name || !off)
1237 		return -EINVAL;
1238 
1239 	for (si = 0; si < symbols->d_size / sizeof(GElf_Sym); si++) {
1240 		GElf_Sym sym;
1241 
1242 		if (!gelf_getsym(symbols, si, &sym))
1243 			continue;
1244 		if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL ||
1245 		    GELF_ST_TYPE(sym.st_info) != STT_OBJECT)
1246 			continue;
1247 
1248 		sname = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
1249 				   sym.st_name);
1250 		if (!sname) {
1251 			pr_warn("failed to get sym name string for var %s\n",
1252 				name);
1253 			return -EIO;
1254 		}
1255 		if (strcmp(name, sname) == 0) {
1256 			*off = sym.st_value;
1257 			return 0;
1258 		}
1259 	}
1260 
1261 	return -ENOENT;
1262 }
1263 
1264 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1265 {
1266 	struct bpf_map *new_maps;
1267 	size_t new_cap;
1268 	int i;
1269 
1270 	if (obj->nr_maps < obj->maps_cap)
1271 		return &obj->maps[obj->nr_maps++];
1272 
1273 	new_cap = max((size_t)4, obj->maps_cap * 3 / 2);
1274 	new_maps = realloc(obj->maps, new_cap * sizeof(*obj->maps));
1275 	if (!new_maps) {
1276 		pr_warn("alloc maps for object failed\n");
1277 		return ERR_PTR(-ENOMEM);
1278 	}
1279 
1280 	obj->maps_cap = new_cap;
1281 	obj->maps = new_maps;
1282 
1283 	/* zero out new maps */
1284 	memset(obj->maps + obj->nr_maps, 0,
1285 	       (obj->maps_cap - obj->nr_maps) * sizeof(*obj->maps));
1286 	/*
1287 	 * fill all fd with -1 so won't close incorrect fd (fd=0 is stdin)
1288 	 * when failure (zclose won't close negative fd)).
1289 	 */
1290 	for (i = obj->nr_maps; i < obj->maps_cap; i++) {
1291 		obj->maps[i].fd = -1;
1292 		obj->maps[i].inner_map_fd = -1;
1293 	}
1294 
1295 	return &obj->maps[obj->nr_maps++];
1296 }
1297 
1298 static size_t bpf_map_mmap_sz(const struct bpf_map *map)
1299 {
1300 	long page_sz = sysconf(_SC_PAGE_SIZE);
1301 	size_t map_sz;
1302 
1303 	map_sz = (size_t)roundup(map->def.value_size, 8) * map->def.max_entries;
1304 	map_sz = roundup(map_sz, page_sz);
1305 	return map_sz;
1306 }
1307 
1308 static char *internal_map_name(struct bpf_object *obj,
1309 			       enum libbpf_map_type type)
1310 {
1311 	char map_name[BPF_OBJ_NAME_LEN], *p;
1312 	const char *sfx = libbpf_type_to_btf_name[type];
1313 	int sfx_len = max((size_t)7, strlen(sfx));
1314 	int pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1,
1315 			  strlen(obj->name));
1316 
1317 	snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1318 		 sfx_len, libbpf_type_to_btf_name[type]);
1319 
1320 	/* sanitise map name to characters allowed by kernel */
1321 	for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1322 		if (!isalnum(*p) && *p != '_' && *p != '.')
1323 			*p = '_';
1324 
1325 	return strdup(map_name);
1326 }
1327 
1328 static int
1329 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
1330 			      int sec_idx, void *data, size_t data_sz)
1331 {
1332 	struct bpf_map_def *def;
1333 	struct bpf_map *map;
1334 	int err;
1335 
1336 	map = bpf_object__add_map(obj);
1337 	if (IS_ERR(map))
1338 		return PTR_ERR(map);
1339 
1340 	map->libbpf_type = type;
1341 	map->sec_idx = sec_idx;
1342 	map->sec_offset = 0;
1343 	map->name = internal_map_name(obj, type);
1344 	if (!map->name) {
1345 		pr_warn("failed to alloc map name\n");
1346 		return -ENOMEM;
1347 	}
1348 
1349 	def = &map->def;
1350 	def->type = BPF_MAP_TYPE_ARRAY;
1351 	def->key_size = sizeof(int);
1352 	def->value_size = data_sz;
1353 	def->max_entries = 1;
1354 	def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
1355 			 ? BPF_F_RDONLY_PROG : 0;
1356 	def->map_flags |= BPF_F_MMAPABLE;
1357 
1358 	pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
1359 		 map->name, map->sec_idx, map->sec_offset, def->map_flags);
1360 
1361 	map->mmaped = mmap(NULL, bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
1362 			   MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1363 	if (map->mmaped == MAP_FAILED) {
1364 		err = -errno;
1365 		map->mmaped = NULL;
1366 		pr_warn("failed to alloc map '%s' content buffer: %d\n",
1367 			map->name, err);
1368 		zfree(&map->name);
1369 		return err;
1370 	}
1371 
1372 	if (data)
1373 		memcpy(map->mmaped, data, data_sz);
1374 
1375 	pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
1376 	return 0;
1377 }
1378 
1379 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
1380 {
1381 	int err;
1382 
1383 	/*
1384 	 * Populate obj->maps with libbpf internal maps.
1385 	 */
1386 	if (obj->efile.data_shndx >= 0) {
1387 		err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
1388 						    obj->efile.data_shndx,
1389 						    obj->efile.data->d_buf,
1390 						    obj->efile.data->d_size);
1391 		if (err)
1392 			return err;
1393 	}
1394 	if (obj->efile.rodata_shndx >= 0) {
1395 		err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
1396 						    obj->efile.rodata_shndx,
1397 						    obj->efile.rodata->d_buf,
1398 						    obj->efile.rodata->d_size);
1399 		if (err)
1400 			return err;
1401 	}
1402 	if (obj->efile.bss_shndx >= 0) {
1403 		err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
1404 						    obj->efile.bss_shndx,
1405 						    NULL,
1406 						    obj->efile.bss->d_size);
1407 		if (err)
1408 			return err;
1409 	}
1410 	return 0;
1411 }
1412 
1413 
1414 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
1415 					       const void *name)
1416 {
1417 	int i;
1418 
1419 	for (i = 0; i < obj->nr_extern; i++) {
1420 		if (strcmp(obj->externs[i].name, name) == 0)
1421 			return &obj->externs[i];
1422 	}
1423 	return NULL;
1424 }
1425 
1426 static int set_ext_value_tri(struct extern_desc *ext, void *ext_val,
1427 			     char value)
1428 {
1429 	switch (ext->type) {
1430 	case EXT_BOOL:
1431 		if (value == 'm') {
1432 			pr_warn("extern %s=%c should be tristate or char\n",
1433 				ext->name, value);
1434 			return -EINVAL;
1435 		}
1436 		*(bool *)ext_val = value == 'y' ? true : false;
1437 		break;
1438 	case EXT_TRISTATE:
1439 		if (value == 'y')
1440 			*(enum libbpf_tristate *)ext_val = TRI_YES;
1441 		else if (value == 'm')
1442 			*(enum libbpf_tristate *)ext_val = TRI_MODULE;
1443 		else /* value == 'n' */
1444 			*(enum libbpf_tristate *)ext_val = TRI_NO;
1445 		break;
1446 	case EXT_CHAR:
1447 		*(char *)ext_val = value;
1448 		break;
1449 	case EXT_UNKNOWN:
1450 	case EXT_INT:
1451 	case EXT_CHAR_ARR:
1452 	default:
1453 		pr_warn("extern %s=%c should be bool, tristate, or char\n",
1454 			ext->name, value);
1455 		return -EINVAL;
1456 	}
1457 	ext->is_set = true;
1458 	return 0;
1459 }
1460 
1461 static int set_ext_value_str(struct extern_desc *ext, char *ext_val,
1462 			     const char *value)
1463 {
1464 	size_t len;
1465 
1466 	if (ext->type != EXT_CHAR_ARR) {
1467 		pr_warn("extern %s=%s should char array\n", ext->name, value);
1468 		return -EINVAL;
1469 	}
1470 
1471 	len = strlen(value);
1472 	if (value[len - 1] != '"') {
1473 		pr_warn("extern '%s': invalid string config '%s'\n",
1474 			ext->name, value);
1475 		return -EINVAL;
1476 	}
1477 
1478 	/* strip quotes */
1479 	len -= 2;
1480 	if (len >= ext->sz) {
1481 		pr_warn("extern '%s': long string config %s of (%zu bytes) truncated to %d bytes\n",
1482 			ext->name, value, len, ext->sz - 1);
1483 		len = ext->sz - 1;
1484 	}
1485 	memcpy(ext_val, value + 1, len);
1486 	ext_val[len] = '\0';
1487 	ext->is_set = true;
1488 	return 0;
1489 }
1490 
1491 static int parse_u64(const char *value, __u64 *res)
1492 {
1493 	char *value_end;
1494 	int err;
1495 
1496 	errno = 0;
1497 	*res = strtoull(value, &value_end, 0);
1498 	if (errno) {
1499 		err = -errno;
1500 		pr_warn("failed to parse '%s' as integer: %d\n", value, err);
1501 		return err;
1502 	}
1503 	if (*value_end) {
1504 		pr_warn("failed to parse '%s' as integer completely\n", value);
1505 		return -EINVAL;
1506 	}
1507 	return 0;
1508 }
1509 
1510 static bool is_ext_value_in_range(const struct extern_desc *ext, __u64 v)
1511 {
1512 	int bit_sz = ext->sz * 8;
1513 
1514 	if (ext->sz == 8)
1515 		return true;
1516 
1517 	/* Validate that value stored in u64 fits in integer of `ext->sz`
1518 	 * bytes size without any loss of information. If the target integer
1519 	 * is signed, we rely on the following limits of integer type of
1520 	 * Y bits and subsequent transformation:
1521 	 *
1522 	 *     -2^(Y-1) <= X           <= 2^(Y-1) - 1
1523 	 *            0 <= X + 2^(Y-1) <= 2^Y - 1
1524 	 *            0 <= X + 2^(Y-1) <  2^Y
1525 	 *
1526 	 *  For unsigned target integer, check that all the (64 - Y) bits are
1527 	 *  zero.
1528 	 */
1529 	if (ext->is_signed)
1530 		return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
1531 	else
1532 		return (v >> bit_sz) == 0;
1533 }
1534 
1535 static int set_ext_value_num(struct extern_desc *ext, void *ext_val,
1536 			     __u64 value)
1537 {
1538 	if (ext->type != EXT_INT && ext->type != EXT_CHAR) {
1539 		pr_warn("extern %s=%llu should be integer\n",
1540 			ext->name, (unsigned long long)value);
1541 		return -EINVAL;
1542 	}
1543 	if (!is_ext_value_in_range(ext, value)) {
1544 		pr_warn("extern %s=%llu value doesn't fit in %d bytes\n",
1545 			ext->name, (unsigned long long)value, ext->sz);
1546 		return -ERANGE;
1547 	}
1548 	switch (ext->sz) {
1549 		case 1: *(__u8 *)ext_val = value; break;
1550 		case 2: *(__u16 *)ext_val = value; break;
1551 		case 4: *(__u32 *)ext_val = value; break;
1552 		case 8: *(__u64 *)ext_val = value; break;
1553 		default:
1554 			return -EINVAL;
1555 	}
1556 	ext->is_set = true;
1557 	return 0;
1558 }
1559 
1560 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
1561 					    char *buf, void *data)
1562 {
1563 	struct extern_desc *ext;
1564 	char *sep, *value;
1565 	int len, err = 0;
1566 	void *ext_val;
1567 	__u64 num;
1568 
1569 	if (strncmp(buf, "CONFIG_", 7))
1570 		return 0;
1571 
1572 	sep = strchr(buf, '=');
1573 	if (!sep) {
1574 		pr_warn("failed to parse '%s': no separator\n", buf);
1575 		return -EINVAL;
1576 	}
1577 
1578 	/* Trim ending '\n' */
1579 	len = strlen(buf);
1580 	if (buf[len - 1] == '\n')
1581 		buf[len - 1] = '\0';
1582 	/* Split on '=' and ensure that a value is present. */
1583 	*sep = '\0';
1584 	if (!sep[1]) {
1585 		*sep = '=';
1586 		pr_warn("failed to parse '%s': no value\n", buf);
1587 		return -EINVAL;
1588 	}
1589 
1590 	ext = find_extern_by_name(obj, buf);
1591 	if (!ext || ext->is_set)
1592 		return 0;
1593 
1594 	ext_val = data + ext->data_off;
1595 	value = sep + 1;
1596 
1597 	switch (*value) {
1598 	case 'y': case 'n': case 'm':
1599 		err = set_ext_value_tri(ext, ext_val, *value);
1600 		break;
1601 	case '"':
1602 		err = set_ext_value_str(ext, ext_val, value);
1603 		break;
1604 	default:
1605 		/* assume integer */
1606 		err = parse_u64(value, &num);
1607 		if (err) {
1608 			pr_warn("extern %s=%s should be integer\n",
1609 				ext->name, value);
1610 			return err;
1611 		}
1612 		err = set_ext_value_num(ext, ext_val, num);
1613 		break;
1614 	}
1615 	if (err)
1616 		return err;
1617 	pr_debug("extern %s=%s\n", ext->name, value);
1618 	return 0;
1619 }
1620 
1621 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
1622 {
1623 	char buf[PATH_MAX];
1624 	struct utsname uts;
1625 	int len, err = 0;
1626 	gzFile file;
1627 
1628 	uname(&uts);
1629 	len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
1630 	if (len < 0)
1631 		return -EINVAL;
1632 	else if (len >= PATH_MAX)
1633 		return -ENAMETOOLONG;
1634 
1635 	/* gzopen also accepts uncompressed files. */
1636 	file = gzopen(buf, "r");
1637 	if (!file)
1638 		file = gzopen("/proc/config.gz", "r");
1639 
1640 	if (!file) {
1641 		pr_warn("failed to open system Kconfig\n");
1642 		return -ENOENT;
1643 	}
1644 
1645 	while (gzgets(file, buf, sizeof(buf))) {
1646 		err = bpf_object__process_kconfig_line(obj, buf, data);
1647 		if (err) {
1648 			pr_warn("error parsing system Kconfig line '%s': %d\n",
1649 				buf, err);
1650 			goto out;
1651 		}
1652 	}
1653 
1654 out:
1655 	gzclose(file);
1656 	return err;
1657 }
1658 
1659 static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
1660 					const char *config, void *data)
1661 {
1662 	char buf[PATH_MAX];
1663 	int err = 0;
1664 	FILE *file;
1665 
1666 	file = fmemopen((void *)config, strlen(config), "r");
1667 	if (!file) {
1668 		err = -errno;
1669 		pr_warn("failed to open in-memory Kconfig: %d\n", err);
1670 		return err;
1671 	}
1672 
1673 	while (fgets(buf, sizeof(buf), file)) {
1674 		err = bpf_object__process_kconfig_line(obj, buf, data);
1675 		if (err) {
1676 			pr_warn("error parsing in-memory Kconfig line '%s': %d\n",
1677 				buf, err);
1678 			break;
1679 		}
1680 	}
1681 
1682 	fclose(file);
1683 	return err;
1684 }
1685 
1686 static int bpf_object__init_kconfig_map(struct bpf_object *obj)
1687 {
1688 	struct extern_desc *last_ext;
1689 	size_t map_sz;
1690 	int err;
1691 
1692 	if (obj->nr_extern == 0)
1693 		return 0;
1694 
1695 	last_ext = &obj->externs[obj->nr_extern - 1];
1696 	map_sz = last_ext->data_off + last_ext->sz;
1697 
1698 	err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
1699 					    obj->efile.symbols_shndx,
1700 					    NULL, map_sz);
1701 	if (err)
1702 		return err;
1703 
1704 	obj->kconfig_map_idx = obj->nr_maps - 1;
1705 
1706 	return 0;
1707 }
1708 
1709 static int bpf_object__init_user_maps(struct bpf_object *obj, bool strict)
1710 {
1711 	Elf_Data *symbols = obj->efile.symbols;
1712 	int i, map_def_sz = 0, nr_maps = 0, nr_syms;
1713 	Elf_Data *data = NULL;
1714 	Elf_Scn *scn;
1715 
1716 	if (obj->efile.maps_shndx < 0)
1717 		return 0;
1718 
1719 	if (!symbols)
1720 		return -EINVAL;
1721 
1722 	scn = elf_getscn(obj->efile.elf, obj->efile.maps_shndx);
1723 	if (scn)
1724 		data = elf_getdata(scn, NULL);
1725 	if (!scn || !data) {
1726 		pr_warn("failed to get Elf_Data from map section %d\n",
1727 			obj->efile.maps_shndx);
1728 		return -EINVAL;
1729 	}
1730 
1731 	/*
1732 	 * Count number of maps. Each map has a name.
1733 	 * Array of maps is not supported: only the first element is
1734 	 * considered.
1735 	 *
1736 	 * TODO: Detect array of map and report error.
1737 	 */
1738 	nr_syms = symbols->d_size / sizeof(GElf_Sym);
1739 	for (i = 0; i < nr_syms; i++) {
1740 		GElf_Sym sym;
1741 
1742 		if (!gelf_getsym(symbols, i, &sym))
1743 			continue;
1744 		if (sym.st_shndx != obj->efile.maps_shndx)
1745 			continue;
1746 		nr_maps++;
1747 	}
1748 	/* Assume equally sized map definitions */
1749 	pr_debug("maps in %s: %d maps in %zd bytes\n",
1750 		 obj->path, nr_maps, data->d_size);
1751 
1752 	if (!data->d_size || nr_maps == 0 || (data->d_size % nr_maps) != 0) {
1753 		pr_warn("unable to determine map definition size section %s, %d maps in %zd bytes\n",
1754 			obj->path, nr_maps, data->d_size);
1755 		return -EINVAL;
1756 	}
1757 	map_def_sz = data->d_size / nr_maps;
1758 
1759 	/* Fill obj->maps using data in "maps" section.  */
1760 	for (i = 0; i < nr_syms; i++) {
1761 		GElf_Sym sym;
1762 		const char *map_name;
1763 		struct bpf_map_def *def;
1764 		struct bpf_map *map;
1765 
1766 		if (!gelf_getsym(symbols, i, &sym))
1767 			continue;
1768 		if (sym.st_shndx != obj->efile.maps_shndx)
1769 			continue;
1770 
1771 		map = bpf_object__add_map(obj);
1772 		if (IS_ERR(map))
1773 			return PTR_ERR(map);
1774 
1775 		map_name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
1776 				      sym.st_name);
1777 		if (!map_name) {
1778 			pr_warn("failed to get map #%d name sym string for obj %s\n",
1779 				i, obj->path);
1780 			return -LIBBPF_ERRNO__FORMAT;
1781 		}
1782 
1783 		map->libbpf_type = LIBBPF_MAP_UNSPEC;
1784 		map->sec_idx = sym.st_shndx;
1785 		map->sec_offset = sym.st_value;
1786 		pr_debug("map '%s' (legacy): at sec_idx %d, offset %zu.\n",
1787 			 map_name, map->sec_idx, map->sec_offset);
1788 		if (sym.st_value + map_def_sz > data->d_size) {
1789 			pr_warn("corrupted maps section in %s: last map \"%s\" too small\n",
1790 				obj->path, map_name);
1791 			return -EINVAL;
1792 		}
1793 
1794 		map->name = strdup(map_name);
1795 		if (!map->name) {
1796 			pr_warn("failed to alloc map name\n");
1797 			return -ENOMEM;
1798 		}
1799 		pr_debug("map %d is \"%s\"\n", i, map->name);
1800 		def = (struct bpf_map_def *)(data->d_buf + sym.st_value);
1801 		/*
1802 		 * If the definition of the map in the object file fits in
1803 		 * bpf_map_def, copy it.  Any extra fields in our version
1804 		 * of bpf_map_def will default to zero as a result of the
1805 		 * calloc above.
1806 		 */
1807 		if (map_def_sz <= sizeof(struct bpf_map_def)) {
1808 			memcpy(&map->def, def, map_def_sz);
1809 		} else {
1810 			/*
1811 			 * Here the map structure being read is bigger than what
1812 			 * we expect, truncate if the excess bits are all zero.
1813 			 * If they are not zero, reject this map as
1814 			 * incompatible.
1815 			 */
1816 			char *b;
1817 
1818 			for (b = ((char *)def) + sizeof(struct bpf_map_def);
1819 			     b < ((char *)def) + map_def_sz; b++) {
1820 				if (*b != 0) {
1821 					pr_warn("maps section in %s: \"%s\" has unrecognized, non-zero options\n",
1822 						obj->path, map_name);
1823 					if (strict)
1824 						return -EINVAL;
1825 				}
1826 			}
1827 			memcpy(&map->def, def, sizeof(struct bpf_map_def));
1828 		}
1829 	}
1830 	return 0;
1831 }
1832 
1833 static const struct btf_type *
1834 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
1835 {
1836 	const struct btf_type *t = btf__type_by_id(btf, id);
1837 
1838 	if (res_id)
1839 		*res_id = id;
1840 
1841 	while (btf_is_mod(t) || btf_is_typedef(t)) {
1842 		if (res_id)
1843 			*res_id = t->type;
1844 		t = btf__type_by_id(btf, t->type);
1845 	}
1846 
1847 	return t;
1848 }
1849 
1850 static const struct btf_type *
1851 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
1852 {
1853 	const struct btf_type *t;
1854 
1855 	t = skip_mods_and_typedefs(btf, id, NULL);
1856 	if (!btf_is_ptr(t))
1857 		return NULL;
1858 
1859 	t = skip_mods_and_typedefs(btf, t->type, res_id);
1860 
1861 	return btf_is_func_proto(t) ? t : NULL;
1862 }
1863 
1864 /*
1865  * Fetch integer attribute of BTF map definition. Such attributes are
1866  * represented using a pointer to an array, in which dimensionality of array
1867  * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
1868  * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
1869  * type definition, while using only sizeof(void *) space in ELF data section.
1870  */
1871 static bool get_map_field_int(const char *map_name, const struct btf *btf,
1872 			      const struct btf_member *m, __u32 *res)
1873 {
1874 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
1875 	const char *name = btf__name_by_offset(btf, m->name_off);
1876 	const struct btf_array *arr_info;
1877 	const struct btf_type *arr_t;
1878 
1879 	if (!btf_is_ptr(t)) {
1880 		pr_warn("map '%s': attr '%s': expected PTR, got %u.\n",
1881 			map_name, name, btf_kind(t));
1882 		return false;
1883 	}
1884 
1885 	arr_t = btf__type_by_id(btf, t->type);
1886 	if (!arr_t) {
1887 		pr_warn("map '%s': attr '%s': type [%u] not found.\n",
1888 			map_name, name, t->type);
1889 		return false;
1890 	}
1891 	if (!btf_is_array(arr_t)) {
1892 		pr_warn("map '%s': attr '%s': expected ARRAY, got %u.\n",
1893 			map_name, name, btf_kind(arr_t));
1894 		return false;
1895 	}
1896 	arr_info = btf_array(arr_t);
1897 	*res = arr_info->nelems;
1898 	return true;
1899 }
1900 
1901 static int build_map_pin_path(struct bpf_map *map, const char *path)
1902 {
1903 	char buf[PATH_MAX];
1904 	int err, len;
1905 
1906 	if (!path)
1907 		path = "/sys/fs/bpf";
1908 
1909 	len = snprintf(buf, PATH_MAX, "%s/%s", path, bpf_map__name(map));
1910 	if (len < 0)
1911 		return -EINVAL;
1912 	else if (len >= PATH_MAX)
1913 		return -ENAMETOOLONG;
1914 
1915 	err = bpf_map__set_pin_path(map, buf);
1916 	if (err)
1917 		return err;
1918 
1919 	return 0;
1920 }
1921 
1922 
1923 static int parse_btf_map_def(struct bpf_object *obj,
1924 			     struct bpf_map *map,
1925 			     const struct btf_type *def,
1926 			     bool strict, bool is_inner,
1927 			     const char *pin_root_path)
1928 {
1929 	const struct btf_type *t;
1930 	const struct btf_member *m;
1931 	int vlen, i;
1932 
1933 	vlen = btf_vlen(def);
1934 	m = btf_members(def);
1935 	for (i = 0; i < vlen; i++, m++) {
1936 		const char *name = btf__name_by_offset(obj->btf, m->name_off);
1937 
1938 		if (!name) {
1939 			pr_warn("map '%s': invalid field #%d.\n", map->name, i);
1940 			return -EINVAL;
1941 		}
1942 		if (strcmp(name, "type") == 0) {
1943 			if (!get_map_field_int(map->name, obj->btf, m,
1944 					       &map->def.type))
1945 				return -EINVAL;
1946 			pr_debug("map '%s': found type = %u.\n",
1947 				 map->name, map->def.type);
1948 		} else if (strcmp(name, "max_entries") == 0) {
1949 			if (!get_map_field_int(map->name, obj->btf, m,
1950 					       &map->def.max_entries))
1951 				return -EINVAL;
1952 			pr_debug("map '%s': found max_entries = %u.\n",
1953 				 map->name, map->def.max_entries);
1954 		} else if (strcmp(name, "map_flags") == 0) {
1955 			if (!get_map_field_int(map->name, obj->btf, m,
1956 					       &map->def.map_flags))
1957 				return -EINVAL;
1958 			pr_debug("map '%s': found map_flags = %u.\n",
1959 				 map->name, map->def.map_flags);
1960 		} else if (strcmp(name, "key_size") == 0) {
1961 			__u32 sz;
1962 
1963 			if (!get_map_field_int(map->name, obj->btf, m, &sz))
1964 				return -EINVAL;
1965 			pr_debug("map '%s': found key_size = %u.\n",
1966 				 map->name, sz);
1967 			if (map->def.key_size && map->def.key_size != sz) {
1968 				pr_warn("map '%s': conflicting key size %u != %u.\n",
1969 					map->name, map->def.key_size, sz);
1970 				return -EINVAL;
1971 			}
1972 			map->def.key_size = sz;
1973 		} else if (strcmp(name, "key") == 0) {
1974 			__s64 sz;
1975 
1976 			t = btf__type_by_id(obj->btf, m->type);
1977 			if (!t) {
1978 				pr_warn("map '%s': key type [%d] not found.\n",
1979 					map->name, m->type);
1980 				return -EINVAL;
1981 			}
1982 			if (!btf_is_ptr(t)) {
1983 				pr_warn("map '%s': key spec is not PTR: %u.\n",
1984 					map->name, btf_kind(t));
1985 				return -EINVAL;
1986 			}
1987 			sz = btf__resolve_size(obj->btf, t->type);
1988 			if (sz < 0) {
1989 				pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
1990 					map->name, t->type, (ssize_t)sz);
1991 				return sz;
1992 			}
1993 			pr_debug("map '%s': found key [%u], sz = %zd.\n",
1994 				 map->name, t->type, (ssize_t)sz);
1995 			if (map->def.key_size && map->def.key_size != sz) {
1996 				pr_warn("map '%s': conflicting key size %u != %zd.\n",
1997 					map->name, map->def.key_size, (ssize_t)sz);
1998 				return -EINVAL;
1999 			}
2000 			map->def.key_size = sz;
2001 			map->btf_key_type_id = t->type;
2002 		} else if (strcmp(name, "value_size") == 0) {
2003 			__u32 sz;
2004 
2005 			if (!get_map_field_int(map->name, obj->btf, m, &sz))
2006 				return -EINVAL;
2007 			pr_debug("map '%s': found value_size = %u.\n",
2008 				 map->name, sz);
2009 			if (map->def.value_size && map->def.value_size != sz) {
2010 				pr_warn("map '%s': conflicting value size %u != %u.\n",
2011 					map->name, map->def.value_size, sz);
2012 				return -EINVAL;
2013 			}
2014 			map->def.value_size = sz;
2015 		} else if (strcmp(name, "value") == 0) {
2016 			__s64 sz;
2017 
2018 			t = btf__type_by_id(obj->btf, m->type);
2019 			if (!t) {
2020 				pr_warn("map '%s': value type [%d] not found.\n",
2021 					map->name, m->type);
2022 				return -EINVAL;
2023 			}
2024 			if (!btf_is_ptr(t)) {
2025 				pr_warn("map '%s': value spec is not PTR: %u.\n",
2026 					map->name, btf_kind(t));
2027 				return -EINVAL;
2028 			}
2029 			sz = btf__resolve_size(obj->btf, t->type);
2030 			if (sz < 0) {
2031 				pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2032 					map->name, t->type, (ssize_t)sz);
2033 				return sz;
2034 			}
2035 			pr_debug("map '%s': found value [%u], sz = %zd.\n",
2036 				 map->name, t->type, (ssize_t)sz);
2037 			if (map->def.value_size && map->def.value_size != sz) {
2038 				pr_warn("map '%s': conflicting value size %u != %zd.\n",
2039 					map->name, map->def.value_size, (ssize_t)sz);
2040 				return -EINVAL;
2041 			}
2042 			map->def.value_size = sz;
2043 			map->btf_value_type_id = t->type;
2044 		}
2045 		else if (strcmp(name, "values") == 0) {
2046 			int err;
2047 
2048 			if (is_inner) {
2049 				pr_warn("map '%s': multi-level inner maps not supported.\n",
2050 					map->name);
2051 				return -ENOTSUP;
2052 			}
2053 			if (i != vlen - 1) {
2054 				pr_warn("map '%s': '%s' member should be last.\n",
2055 					map->name, name);
2056 				return -EINVAL;
2057 			}
2058 			if (!bpf_map_type__is_map_in_map(map->def.type)) {
2059 				pr_warn("map '%s': should be map-in-map.\n",
2060 					map->name);
2061 				return -ENOTSUP;
2062 			}
2063 			if (map->def.value_size && map->def.value_size != 4) {
2064 				pr_warn("map '%s': conflicting value size %u != 4.\n",
2065 					map->name, map->def.value_size);
2066 				return -EINVAL;
2067 			}
2068 			map->def.value_size = 4;
2069 			t = btf__type_by_id(obj->btf, m->type);
2070 			if (!t) {
2071 				pr_warn("map '%s': map-in-map inner type [%d] not found.\n",
2072 					map->name, m->type);
2073 				return -EINVAL;
2074 			}
2075 			if (!btf_is_array(t) || btf_array(t)->nelems) {
2076 				pr_warn("map '%s': map-in-map inner spec is not a zero-sized array.\n",
2077 					map->name);
2078 				return -EINVAL;
2079 			}
2080 			t = skip_mods_and_typedefs(obj->btf, btf_array(t)->type,
2081 						   NULL);
2082 			if (!btf_is_ptr(t)) {
2083 				pr_warn("map '%s': map-in-map inner def is of unexpected kind %u.\n",
2084 					map->name, btf_kind(t));
2085 				return -EINVAL;
2086 			}
2087 			t = skip_mods_and_typedefs(obj->btf, t->type, NULL);
2088 			if (!btf_is_struct(t)) {
2089 				pr_warn("map '%s': map-in-map inner def is of unexpected kind %u.\n",
2090 					map->name, btf_kind(t));
2091 				return -EINVAL;
2092 			}
2093 
2094 			map->inner_map = calloc(1, sizeof(*map->inner_map));
2095 			if (!map->inner_map)
2096 				return -ENOMEM;
2097 			map->inner_map->sec_idx = obj->efile.btf_maps_shndx;
2098 			map->inner_map->name = malloc(strlen(map->name) +
2099 						      sizeof(".inner") + 1);
2100 			if (!map->inner_map->name)
2101 				return -ENOMEM;
2102 			sprintf(map->inner_map->name, "%s.inner", map->name);
2103 
2104 			err = parse_btf_map_def(obj, map->inner_map, t, strict,
2105 						true /* is_inner */, NULL);
2106 			if (err)
2107 				return err;
2108 		} else if (strcmp(name, "pinning") == 0) {
2109 			__u32 val;
2110 			int err;
2111 
2112 			if (is_inner) {
2113 				pr_debug("map '%s': inner def can't be pinned.\n",
2114 					 map->name);
2115 				return -EINVAL;
2116 			}
2117 			if (!get_map_field_int(map->name, obj->btf, m, &val))
2118 				return -EINVAL;
2119 			pr_debug("map '%s': found pinning = %u.\n",
2120 				 map->name, val);
2121 
2122 			if (val != LIBBPF_PIN_NONE &&
2123 			    val != LIBBPF_PIN_BY_NAME) {
2124 				pr_warn("map '%s': invalid pinning value %u.\n",
2125 					map->name, val);
2126 				return -EINVAL;
2127 			}
2128 			if (val == LIBBPF_PIN_BY_NAME) {
2129 				err = build_map_pin_path(map, pin_root_path);
2130 				if (err) {
2131 					pr_warn("map '%s': couldn't build pin path.\n",
2132 						map->name);
2133 					return err;
2134 				}
2135 			}
2136 		} else {
2137 			if (strict) {
2138 				pr_warn("map '%s': unknown field '%s'.\n",
2139 					map->name, name);
2140 				return -ENOTSUP;
2141 			}
2142 			pr_debug("map '%s': ignoring unknown field '%s'.\n",
2143 				 map->name, name);
2144 		}
2145 	}
2146 
2147 	if (map->def.type == BPF_MAP_TYPE_UNSPEC) {
2148 		pr_warn("map '%s': map type isn't specified.\n", map->name);
2149 		return -EINVAL;
2150 	}
2151 
2152 	return 0;
2153 }
2154 
2155 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2156 					 const struct btf_type *sec,
2157 					 int var_idx, int sec_idx,
2158 					 const Elf_Data *data, bool strict,
2159 					 const char *pin_root_path)
2160 {
2161 	const struct btf_type *var, *def;
2162 	const struct btf_var_secinfo *vi;
2163 	const struct btf_var *var_extra;
2164 	const char *map_name;
2165 	struct bpf_map *map;
2166 
2167 	vi = btf_var_secinfos(sec) + var_idx;
2168 	var = btf__type_by_id(obj->btf, vi->type);
2169 	var_extra = btf_var(var);
2170 	map_name = btf__name_by_offset(obj->btf, var->name_off);
2171 
2172 	if (map_name == NULL || map_name[0] == '\0') {
2173 		pr_warn("map #%d: empty name.\n", var_idx);
2174 		return -EINVAL;
2175 	}
2176 	if ((__u64)vi->offset + vi->size > data->d_size) {
2177 		pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2178 		return -EINVAL;
2179 	}
2180 	if (!btf_is_var(var)) {
2181 		pr_warn("map '%s': unexpected var kind %u.\n",
2182 			map_name, btf_kind(var));
2183 		return -EINVAL;
2184 	}
2185 	if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED &&
2186 	    var_extra->linkage != BTF_VAR_STATIC) {
2187 		pr_warn("map '%s': unsupported var linkage %u.\n",
2188 			map_name, var_extra->linkage);
2189 		return -EOPNOTSUPP;
2190 	}
2191 
2192 	def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2193 	if (!btf_is_struct(def)) {
2194 		pr_warn("map '%s': unexpected def kind %u.\n",
2195 			map_name, btf_kind(var));
2196 		return -EINVAL;
2197 	}
2198 	if (def->size > vi->size) {
2199 		pr_warn("map '%s': invalid def size.\n", map_name);
2200 		return -EINVAL;
2201 	}
2202 
2203 	map = bpf_object__add_map(obj);
2204 	if (IS_ERR(map))
2205 		return PTR_ERR(map);
2206 	map->name = strdup(map_name);
2207 	if (!map->name) {
2208 		pr_warn("map '%s': failed to alloc map name.\n", map_name);
2209 		return -ENOMEM;
2210 	}
2211 	map->libbpf_type = LIBBPF_MAP_UNSPEC;
2212 	map->def.type = BPF_MAP_TYPE_UNSPEC;
2213 	map->sec_idx = sec_idx;
2214 	map->sec_offset = vi->offset;
2215 	map->btf_var_idx = var_idx;
2216 	pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2217 		 map_name, map->sec_idx, map->sec_offset);
2218 
2219 	return parse_btf_map_def(obj, map, def, strict, false, pin_root_path);
2220 }
2221 
2222 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
2223 					  const char *pin_root_path)
2224 {
2225 	const struct btf_type *sec = NULL;
2226 	int nr_types, i, vlen, err;
2227 	const struct btf_type *t;
2228 	const char *name;
2229 	Elf_Data *data;
2230 	Elf_Scn *scn;
2231 
2232 	if (obj->efile.btf_maps_shndx < 0)
2233 		return 0;
2234 
2235 	scn = elf_getscn(obj->efile.elf, obj->efile.btf_maps_shndx);
2236 	if (scn)
2237 		data = elf_getdata(scn, NULL);
2238 	if (!scn || !data) {
2239 		pr_warn("failed to get Elf_Data from map section %d (%s)\n",
2240 			obj->efile.maps_shndx, MAPS_ELF_SEC);
2241 		return -EINVAL;
2242 	}
2243 
2244 	nr_types = btf__get_nr_types(obj->btf);
2245 	for (i = 1; i <= nr_types; i++) {
2246 		t = btf__type_by_id(obj->btf, i);
2247 		if (!btf_is_datasec(t))
2248 			continue;
2249 		name = btf__name_by_offset(obj->btf, t->name_off);
2250 		if (strcmp(name, MAPS_ELF_SEC) == 0) {
2251 			sec = t;
2252 			obj->efile.btf_maps_sec_btf_id = i;
2253 			break;
2254 		}
2255 	}
2256 
2257 	if (!sec) {
2258 		pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
2259 		return -ENOENT;
2260 	}
2261 
2262 	vlen = btf_vlen(sec);
2263 	for (i = 0; i < vlen; i++) {
2264 		err = bpf_object__init_user_btf_map(obj, sec, i,
2265 						    obj->efile.btf_maps_shndx,
2266 						    data, strict,
2267 						    pin_root_path);
2268 		if (err)
2269 			return err;
2270 	}
2271 
2272 	return 0;
2273 }
2274 
2275 static int bpf_object__init_maps(struct bpf_object *obj,
2276 				 const struct bpf_object_open_opts *opts)
2277 {
2278 	const char *pin_root_path;
2279 	bool strict;
2280 	int err;
2281 
2282 	strict = !OPTS_GET(opts, relaxed_maps, false);
2283 	pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
2284 
2285 	err = bpf_object__init_user_maps(obj, strict);
2286 	err = err ?: bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
2287 	err = err ?: bpf_object__init_global_data_maps(obj);
2288 	err = err ?: bpf_object__init_kconfig_map(obj);
2289 	err = err ?: bpf_object__init_struct_ops_maps(obj);
2290 	if (err)
2291 		return err;
2292 
2293 	return 0;
2294 }
2295 
2296 static bool section_have_execinstr(struct bpf_object *obj, int idx)
2297 {
2298 	Elf_Scn *scn;
2299 	GElf_Shdr sh;
2300 
2301 	scn = elf_getscn(obj->efile.elf, idx);
2302 	if (!scn)
2303 		return false;
2304 
2305 	if (gelf_getshdr(scn, &sh) != &sh)
2306 		return false;
2307 
2308 	if (sh.sh_flags & SHF_EXECINSTR)
2309 		return true;
2310 
2311 	return false;
2312 }
2313 
2314 static void bpf_object__sanitize_btf(struct bpf_object *obj)
2315 {
2316 	bool has_func_global = obj->caps.btf_func_global;
2317 	bool has_datasec = obj->caps.btf_datasec;
2318 	bool has_func = obj->caps.btf_func;
2319 	struct btf *btf = obj->btf;
2320 	struct btf_type *t;
2321 	int i, j, vlen;
2322 
2323 	if (!obj->btf || (has_func && has_datasec && has_func_global))
2324 		return;
2325 
2326 	for (i = 1; i <= btf__get_nr_types(btf); i++) {
2327 		t = (struct btf_type *)btf__type_by_id(btf, i);
2328 
2329 		if (!has_datasec && btf_is_var(t)) {
2330 			/* replace VAR with INT */
2331 			t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
2332 			/*
2333 			 * using size = 1 is the safest choice, 4 will be too
2334 			 * big and cause kernel BTF validation failure if
2335 			 * original variable took less than 4 bytes
2336 			 */
2337 			t->size = 1;
2338 			*(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
2339 		} else if (!has_datasec && btf_is_datasec(t)) {
2340 			/* replace DATASEC with STRUCT */
2341 			const struct btf_var_secinfo *v = btf_var_secinfos(t);
2342 			struct btf_member *m = btf_members(t);
2343 			struct btf_type *vt;
2344 			char *name;
2345 
2346 			name = (char *)btf__name_by_offset(btf, t->name_off);
2347 			while (*name) {
2348 				if (*name == '.')
2349 					*name = '_';
2350 				name++;
2351 			}
2352 
2353 			vlen = btf_vlen(t);
2354 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
2355 			for (j = 0; j < vlen; j++, v++, m++) {
2356 				/* order of field assignments is important */
2357 				m->offset = v->offset * 8;
2358 				m->type = v->type;
2359 				/* preserve variable name as member name */
2360 				vt = (void *)btf__type_by_id(btf, v->type);
2361 				m->name_off = vt->name_off;
2362 			}
2363 		} else if (!has_func && btf_is_func_proto(t)) {
2364 			/* replace FUNC_PROTO with ENUM */
2365 			vlen = btf_vlen(t);
2366 			t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
2367 			t->size = sizeof(__u32); /* kernel enforced */
2368 		} else if (!has_func && btf_is_func(t)) {
2369 			/* replace FUNC with TYPEDEF */
2370 			t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
2371 		} else if (!has_func_global && btf_is_func(t)) {
2372 			/* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
2373 			t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
2374 		}
2375 	}
2376 }
2377 
2378 static void bpf_object__sanitize_btf_ext(struct bpf_object *obj)
2379 {
2380 	if (!obj->btf_ext)
2381 		return;
2382 
2383 	if (!obj->caps.btf_func) {
2384 		btf_ext__free(obj->btf_ext);
2385 		obj->btf_ext = NULL;
2386 	}
2387 }
2388 
2389 static bool libbpf_needs_btf(const struct bpf_object *obj)
2390 {
2391 	return obj->efile.btf_maps_shndx >= 0 ||
2392 	       obj->efile.st_ops_shndx >= 0 ||
2393 	       obj->nr_extern > 0;
2394 }
2395 
2396 static bool kernel_needs_btf(const struct bpf_object *obj)
2397 {
2398 	return obj->efile.st_ops_shndx >= 0;
2399 }
2400 
2401 static int bpf_object__init_btf(struct bpf_object *obj,
2402 				Elf_Data *btf_data,
2403 				Elf_Data *btf_ext_data)
2404 {
2405 	int err = -ENOENT;
2406 
2407 	if (btf_data) {
2408 		obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
2409 		if (IS_ERR(obj->btf)) {
2410 			err = PTR_ERR(obj->btf);
2411 			obj->btf = NULL;
2412 			pr_warn("Error loading ELF section %s: %d.\n",
2413 				BTF_ELF_SEC, err);
2414 			goto out;
2415 		}
2416 		err = 0;
2417 	}
2418 	if (btf_ext_data) {
2419 		if (!obj->btf) {
2420 			pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
2421 				 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
2422 			goto out;
2423 		}
2424 		obj->btf_ext = btf_ext__new(btf_ext_data->d_buf,
2425 					    btf_ext_data->d_size);
2426 		if (IS_ERR(obj->btf_ext)) {
2427 			pr_warn("Error loading ELF section %s: %ld. Ignored and continue.\n",
2428 				BTF_EXT_ELF_SEC, PTR_ERR(obj->btf_ext));
2429 			obj->btf_ext = NULL;
2430 			goto out;
2431 		}
2432 	}
2433 out:
2434 	if (err && libbpf_needs_btf(obj)) {
2435 		pr_warn("BTF is required, but is missing or corrupted.\n");
2436 		return err;
2437 	}
2438 	return 0;
2439 }
2440 
2441 static int bpf_object__finalize_btf(struct bpf_object *obj)
2442 {
2443 	int err;
2444 
2445 	if (!obj->btf)
2446 		return 0;
2447 
2448 	err = btf__finalize_data(obj, obj->btf);
2449 	if (!err)
2450 		return 0;
2451 
2452 	pr_warn("Error finalizing %s: %d.\n", BTF_ELF_SEC, err);
2453 	btf__free(obj->btf);
2454 	obj->btf = NULL;
2455 	btf_ext__free(obj->btf_ext);
2456 	obj->btf_ext = NULL;
2457 
2458 	if (libbpf_needs_btf(obj)) {
2459 		pr_warn("BTF is required, but is missing or corrupted.\n");
2460 		return -ENOENT;
2461 	}
2462 	return 0;
2463 }
2464 
2465 static inline bool libbpf_prog_needs_vmlinux_btf(struct bpf_program *prog)
2466 {
2467 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
2468 	    prog->type == BPF_PROG_TYPE_LSM)
2469 		return true;
2470 
2471 	/* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
2472 	 * also need vmlinux BTF
2473 	 */
2474 	if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
2475 		return true;
2476 
2477 	return false;
2478 }
2479 
2480 static int bpf_object__load_vmlinux_btf(struct bpf_object *obj)
2481 {
2482 	struct bpf_program *prog;
2483 	int err;
2484 
2485 	bpf_object__for_each_program(prog, obj) {
2486 		if (libbpf_prog_needs_vmlinux_btf(prog)) {
2487 			obj->btf_vmlinux = libbpf_find_kernel_btf();
2488 			if (IS_ERR(obj->btf_vmlinux)) {
2489 				err = PTR_ERR(obj->btf_vmlinux);
2490 				pr_warn("Error loading vmlinux BTF: %d\n", err);
2491 				obj->btf_vmlinux = NULL;
2492 				return err;
2493 			}
2494 			return 0;
2495 		}
2496 	}
2497 
2498 	return 0;
2499 }
2500 
2501 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
2502 {
2503 	int err = 0;
2504 
2505 	if (!obj->btf)
2506 		return 0;
2507 
2508 	bpf_object__sanitize_btf(obj);
2509 	bpf_object__sanitize_btf_ext(obj);
2510 
2511 	err = btf__load(obj->btf);
2512 	if (err) {
2513 		pr_warn("Error loading %s into kernel: %d.\n",
2514 			BTF_ELF_SEC, err);
2515 		btf__free(obj->btf);
2516 		obj->btf = NULL;
2517 		/* btf_ext can't exist without btf, so free it as well */
2518 		if (obj->btf_ext) {
2519 			btf_ext__free(obj->btf_ext);
2520 			obj->btf_ext = NULL;
2521 		}
2522 
2523 		if (kernel_needs_btf(obj))
2524 			return err;
2525 	}
2526 	return 0;
2527 }
2528 
2529 static int bpf_object__elf_collect(struct bpf_object *obj)
2530 {
2531 	Elf *elf = obj->efile.elf;
2532 	GElf_Ehdr *ep = &obj->efile.ehdr;
2533 	Elf_Data *btf_ext_data = NULL;
2534 	Elf_Data *btf_data = NULL;
2535 	Elf_Scn *scn = NULL;
2536 	int idx = 0, err = 0;
2537 
2538 	/* Elf is corrupted/truncated, avoid calling elf_strptr. */
2539 	if (!elf_rawdata(elf_getscn(elf, ep->e_shstrndx), NULL)) {
2540 		pr_warn("failed to get e_shstrndx from %s\n", obj->path);
2541 		return -LIBBPF_ERRNO__FORMAT;
2542 	}
2543 
2544 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
2545 		char *name;
2546 		GElf_Shdr sh;
2547 		Elf_Data *data;
2548 
2549 		idx++;
2550 		if (gelf_getshdr(scn, &sh) != &sh) {
2551 			pr_warn("failed to get section(%d) header from %s\n",
2552 				idx, obj->path);
2553 			return -LIBBPF_ERRNO__FORMAT;
2554 		}
2555 
2556 		name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
2557 		if (!name) {
2558 			pr_warn("failed to get section(%d) name from %s\n",
2559 				idx, obj->path);
2560 			return -LIBBPF_ERRNO__FORMAT;
2561 		}
2562 
2563 		data = elf_getdata(scn, 0);
2564 		if (!data) {
2565 			pr_warn("failed to get section(%d) data from %s(%s)\n",
2566 				idx, name, obj->path);
2567 			return -LIBBPF_ERRNO__FORMAT;
2568 		}
2569 		pr_debug("section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
2570 			 idx, name, (unsigned long)data->d_size,
2571 			 (int)sh.sh_link, (unsigned long)sh.sh_flags,
2572 			 (int)sh.sh_type);
2573 
2574 		if (strcmp(name, "license") == 0) {
2575 			err = bpf_object__init_license(obj,
2576 						       data->d_buf,
2577 						       data->d_size);
2578 			if (err)
2579 				return err;
2580 		} else if (strcmp(name, "version") == 0) {
2581 			err = bpf_object__init_kversion(obj,
2582 							data->d_buf,
2583 							data->d_size);
2584 			if (err)
2585 				return err;
2586 		} else if (strcmp(name, "maps") == 0) {
2587 			obj->efile.maps_shndx = idx;
2588 		} else if (strcmp(name, MAPS_ELF_SEC) == 0) {
2589 			obj->efile.btf_maps_shndx = idx;
2590 		} else if (strcmp(name, BTF_ELF_SEC) == 0) {
2591 			btf_data = data;
2592 		} else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
2593 			btf_ext_data = data;
2594 		} else if (sh.sh_type == SHT_SYMTAB) {
2595 			if (obj->efile.symbols) {
2596 				pr_warn("bpf: multiple SYMTAB in %s\n",
2597 					obj->path);
2598 				return -LIBBPF_ERRNO__FORMAT;
2599 			}
2600 			obj->efile.symbols = data;
2601 			obj->efile.symbols_shndx = idx;
2602 			obj->efile.strtabidx = sh.sh_link;
2603 		} else if (sh.sh_type == SHT_PROGBITS && data->d_size > 0) {
2604 			if (sh.sh_flags & SHF_EXECINSTR) {
2605 				if (strcmp(name, ".text") == 0)
2606 					obj->efile.text_shndx = idx;
2607 				err = bpf_object__add_program(obj, data->d_buf,
2608 							      data->d_size,
2609 							      name, idx);
2610 				if (err) {
2611 					char errmsg[STRERR_BUFSIZE];
2612 					char *cp;
2613 
2614 					cp = libbpf_strerror_r(-err, errmsg,
2615 							       sizeof(errmsg));
2616 					pr_warn("failed to alloc program %s (%s): %s",
2617 						name, obj->path, cp);
2618 					return err;
2619 				}
2620 			} else if (strcmp(name, DATA_SEC) == 0) {
2621 				obj->efile.data = data;
2622 				obj->efile.data_shndx = idx;
2623 			} else if (strcmp(name, RODATA_SEC) == 0) {
2624 				obj->efile.rodata = data;
2625 				obj->efile.rodata_shndx = idx;
2626 			} else if (strcmp(name, STRUCT_OPS_SEC) == 0) {
2627 				obj->efile.st_ops_data = data;
2628 				obj->efile.st_ops_shndx = idx;
2629 			} else {
2630 				pr_debug("skip section(%d) %s\n", idx, name);
2631 			}
2632 		} else if (sh.sh_type == SHT_REL) {
2633 			int nr_sects = obj->efile.nr_reloc_sects;
2634 			void *sects = obj->efile.reloc_sects;
2635 			int sec = sh.sh_info; /* points to other section */
2636 
2637 			/* Only do relo for section with exec instructions */
2638 			if (!section_have_execinstr(obj, sec) &&
2639 			    strcmp(name, ".rel" STRUCT_OPS_SEC) &&
2640 			    strcmp(name, ".rel" MAPS_ELF_SEC)) {
2641 				pr_debug("skip relo %s(%d) for section(%d)\n",
2642 					 name, idx, sec);
2643 				continue;
2644 			}
2645 
2646 			sects = reallocarray(sects, nr_sects + 1,
2647 					     sizeof(*obj->efile.reloc_sects));
2648 			if (!sects) {
2649 				pr_warn("reloc_sects realloc failed\n");
2650 				return -ENOMEM;
2651 			}
2652 
2653 			obj->efile.reloc_sects = sects;
2654 			obj->efile.nr_reloc_sects++;
2655 
2656 			obj->efile.reloc_sects[nr_sects].shdr = sh;
2657 			obj->efile.reloc_sects[nr_sects].data = data;
2658 		} else if (sh.sh_type == SHT_NOBITS &&
2659 			   strcmp(name, BSS_SEC) == 0) {
2660 			obj->efile.bss = data;
2661 			obj->efile.bss_shndx = idx;
2662 		} else {
2663 			pr_debug("skip section(%d) %s\n", idx, name);
2664 		}
2665 	}
2666 
2667 	if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
2668 		pr_warn("Corrupted ELF file: index of strtab invalid\n");
2669 		return -LIBBPF_ERRNO__FORMAT;
2670 	}
2671 	return bpf_object__init_btf(obj, btf_data, btf_ext_data);
2672 }
2673 
2674 static bool sym_is_extern(const GElf_Sym *sym)
2675 {
2676 	int bind = GELF_ST_BIND(sym->st_info);
2677 	/* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
2678 	return sym->st_shndx == SHN_UNDEF &&
2679 	       (bind == STB_GLOBAL || bind == STB_WEAK) &&
2680 	       GELF_ST_TYPE(sym->st_info) == STT_NOTYPE;
2681 }
2682 
2683 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
2684 {
2685 	const struct btf_type *t;
2686 	const char *var_name;
2687 	int i, n;
2688 
2689 	if (!btf)
2690 		return -ESRCH;
2691 
2692 	n = btf__get_nr_types(btf);
2693 	for (i = 1; i <= n; i++) {
2694 		t = btf__type_by_id(btf, i);
2695 
2696 		if (!btf_is_var(t))
2697 			continue;
2698 
2699 		var_name = btf__name_by_offset(btf, t->name_off);
2700 		if (strcmp(var_name, ext_name))
2701 			continue;
2702 
2703 		if (btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
2704 			return -EINVAL;
2705 
2706 		return i;
2707 	}
2708 
2709 	return -ENOENT;
2710 }
2711 
2712 static enum extern_type find_extern_type(const struct btf *btf, int id,
2713 					 bool *is_signed)
2714 {
2715 	const struct btf_type *t;
2716 	const char *name;
2717 
2718 	t = skip_mods_and_typedefs(btf, id, NULL);
2719 	name = btf__name_by_offset(btf, t->name_off);
2720 
2721 	if (is_signed)
2722 		*is_signed = false;
2723 	switch (btf_kind(t)) {
2724 	case BTF_KIND_INT: {
2725 		int enc = btf_int_encoding(t);
2726 
2727 		if (enc & BTF_INT_BOOL)
2728 			return t->size == 1 ? EXT_BOOL : EXT_UNKNOWN;
2729 		if (is_signed)
2730 			*is_signed = enc & BTF_INT_SIGNED;
2731 		if (t->size == 1)
2732 			return EXT_CHAR;
2733 		if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
2734 			return EXT_UNKNOWN;
2735 		return EXT_INT;
2736 	}
2737 	case BTF_KIND_ENUM:
2738 		if (t->size != 4)
2739 			return EXT_UNKNOWN;
2740 		if (strcmp(name, "libbpf_tristate"))
2741 			return EXT_UNKNOWN;
2742 		return EXT_TRISTATE;
2743 	case BTF_KIND_ARRAY:
2744 		if (btf_array(t)->nelems == 0)
2745 			return EXT_UNKNOWN;
2746 		if (find_extern_type(btf, btf_array(t)->type, NULL) != EXT_CHAR)
2747 			return EXT_UNKNOWN;
2748 		return EXT_CHAR_ARR;
2749 	default:
2750 		return EXT_UNKNOWN;
2751 	}
2752 }
2753 
2754 static int cmp_externs(const void *_a, const void *_b)
2755 {
2756 	const struct extern_desc *a = _a;
2757 	const struct extern_desc *b = _b;
2758 
2759 	/* descending order by alignment requirements */
2760 	if (a->align != b->align)
2761 		return a->align > b->align ? -1 : 1;
2762 	/* ascending order by size, within same alignment class */
2763 	if (a->sz != b->sz)
2764 		return a->sz < b->sz ? -1 : 1;
2765 	/* resolve ties by name */
2766 	return strcmp(a->name, b->name);
2767 }
2768 
2769 static int bpf_object__collect_externs(struct bpf_object *obj)
2770 {
2771 	const struct btf_type *t;
2772 	struct extern_desc *ext;
2773 	int i, n, off, btf_id;
2774 	struct btf_type *sec;
2775 	const char *ext_name;
2776 	Elf_Scn *scn;
2777 	GElf_Shdr sh;
2778 
2779 	if (!obj->efile.symbols)
2780 		return 0;
2781 
2782 	scn = elf_getscn(obj->efile.elf, obj->efile.symbols_shndx);
2783 	if (!scn)
2784 		return -LIBBPF_ERRNO__FORMAT;
2785 	if (gelf_getshdr(scn, &sh) != &sh)
2786 		return -LIBBPF_ERRNO__FORMAT;
2787 	n = sh.sh_size / sh.sh_entsize;
2788 
2789 	pr_debug("looking for externs among %d symbols...\n", n);
2790 	for (i = 0; i < n; i++) {
2791 		GElf_Sym sym;
2792 
2793 		if (!gelf_getsym(obj->efile.symbols, i, &sym))
2794 			return -LIBBPF_ERRNO__FORMAT;
2795 		if (!sym_is_extern(&sym))
2796 			continue;
2797 		ext_name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
2798 				      sym.st_name);
2799 		if (!ext_name || !ext_name[0])
2800 			continue;
2801 
2802 		ext = obj->externs;
2803 		ext = reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
2804 		if (!ext)
2805 			return -ENOMEM;
2806 		obj->externs = ext;
2807 		ext = &ext[obj->nr_extern];
2808 		memset(ext, 0, sizeof(*ext));
2809 		obj->nr_extern++;
2810 
2811 		ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
2812 		if (ext->btf_id <= 0) {
2813 			pr_warn("failed to find BTF for extern '%s': %d\n",
2814 				ext_name, ext->btf_id);
2815 			return ext->btf_id;
2816 		}
2817 		t = btf__type_by_id(obj->btf, ext->btf_id);
2818 		ext->name = btf__name_by_offset(obj->btf, t->name_off);
2819 		ext->sym_idx = i;
2820 		ext->is_weak = GELF_ST_BIND(sym.st_info) == STB_WEAK;
2821 		ext->sz = btf__resolve_size(obj->btf, t->type);
2822 		if (ext->sz <= 0) {
2823 			pr_warn("failed to resolve size of extern '%s': %d\n",
2824 				ext_name, ext->sz);
2825 			return ext->sz;
2826 		}
2827 		ext->align = btf__align_of(obj->btf, t->type);
2828 		if (ext->align <= 0) {
2829 			pr_warn("failed to determine alignment of extern '%s': %d\n",
2830 				ext_name, ext->align);
2831 			return -EINVAL;
2832 		}
2833 		ext->type = find_extern_type(obj->btf, t->type,
2834 					     &ext->is_signed);
2835 		if (ext->type == EXT_UNKNOWN) {
2836 			pr_warn("extern '%s' type is unsupported\n", ext_name);
2837 			return -ENOTSUP;
2838 		}
2839 	}
2840 	pr_debug("collected %d externs total\n", obj->nr_extern);
2841 
2842 	if (!obj->nr_extern)
2843 		return 0;
2844 
2845 	/* sort externs by (alignment, size, name) and calculate their offsets
2846 	 * within a map */
2847 	qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
2848 	off = 0;
2849 	for (i = 0; i < obj->nr_extern; i++) {
2850 		ext = &obj->externs[i];
2851 		ext->data_off = roundup(off, ext->align);
2852 		off = ext->data_off + ext->sz;
2853 		pr_debug("extern #%d: symbol %d, off %u, name %s\n",
2854 			 i, ext->sym_idx, ext->data_off, ext->name);
2855 	}
2856 
2857 	btf_id = btf__find_by_name(obj->btf, KCONFIG_SEC);
2858 	if (btf_id <= 0) {
2859 		pr_warn("no BTF info found for '%s' datasec\n", KCONFIG_SEC);
2860 		return -ESRCH;
2861 	}
2862 
2863 	sec = (struct btf_type *)btf__type_by_id(obj->btf, btf_id);
2864 	sec->size = off;
2865 	n = btf_vlen(sec);
2866 	for (i = 0; i < n; i++) {
2867 		struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
2868 
2869 		t = btf__type_by_id(obj->btf, vs->type);
2870 		ext_name = btf__name_by_offset(obj->btf, t->name_off);
2871 		ext = find_extern_by_name(obj, ext_name);
2872 		if (!ext) {
2873 			pr_warn("failed to find extern definition for BTF var '%s'\n",
2874 				ext_name);
2875 			return -ESRCH;
2876 		}
2877 		vs->offset = ext->data_off;
2878 		btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
2879 	}
2880 
2881 	return 0;
2882 }
2883 
2884 static struct bpf_program *
2885 bpf_object__find_prog_by_idx(struct bpf_object *obj, int idx)
2886 {
2887 	struct bpf_program *prog;
2888 	size_t i;
2889 
2890 	for (i = 0; i < obj->nr_programs; i++) {
2891 		prog = &obj->programs[i];
2892 		if (prog->idx == idx)
2893 			return prog;
2894 	}
2895 	return NULL;
2896 }
2897 
2898 struct bpf_program *
2899 bpf_object__find_program_by_title(const struct bpf_object *obj,
2900 				  const char *title)
2901 {
2902 	struct bpf_program *pos;
2903 
2904 	bpf_object__for_each_program(pos, obj) {
2905 		if (pos->section_name && !strcmp(pos->section_name, title))
2906 			return pos;
2907 	}
2908 	return NULL;
2909 }
2910 
2911 struct bpf_program *
2912 bpf_object__find_program_by_name(const struct bpf_object *obj,
2913 				 const char *name)
2914 {
2915 	struct bpf_program *prog;
2916 
2917 	bpf_object__for_each_program(prog, obj) {
2918 		if (!strcmp(prog->name, name))
2919 			return prog;
2920 	}
2921 	return NULL;
2922 }
2923 
2924 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
2925 				      int shndx)
2926 {
2927 	return shndx == obj->efile.data_shndx ||
2928 	       shndx == obj->efile.bss_shndx ||
2929 	       shndx == obj->efile.rodata_shndx;
2930 }
2931 
2932 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
2933 				      int shndx)
2934 {
2935 	return shndx == obj->efile.maps_shndx ||
2936 	       shndx == obj->efile.btf_maps_shndx;
2937 }
2938 
2939 static enum libbpf_map_type
2940 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
2941 {
2942 	if (shndx == obj->efile.data_shndx)
2943 		return LIBBPF_MAP_DATA;
2944 	else if (shndx == obj->efile.bss_shndx)
2945 		return LIBBPF_MAP_BSS;
2946 	else if (shndx == obj->efile.rodata_shndx)
2947 		return LIBBPF_MAP_RODATA;
2948 	else if (shndx == obj->efile.symbols_shndx)
2949 		return LIBBPF_MAP_KCONFIG;
2950 	else
2951 		return LIBBPF_MAP_UNSPEC;
2952 }
2953 
2954 static int bpf_program__record_reloc(struct bpf_program *prog,
2955 				     struct reloc_desc *reloc_desc,
2956 				     __u32 insn_idx, const char *name,
2957 				     const GElf_Sym *sym, const GElf_Rel *rel)
2958 {
2959 	struct bpf_insn *insn = &prog->insns[insn_idx];
2960 	size_t map_idx, nr_maps = prog->obj->nr_maps;
2961 	struct bpf_object *obj = prog->obj;
2962 	__u32 shdr_idx = sym->st_shndx;
2963 	enum libbpf_map_type type;
2964 	struct bpf_map *map;
2965 
2966 	/* sub-program call relocation */
2967 	if (insn->code == (BPF_JMP | BPF_CALL)) {
2968 		if (insn->src_reg != BPF_PSEUDO_CALL) {
2969 			pr_warn("incorrect bpf_call opcode\n");
2970 			return -LIBBPF_ERRNO__RELOC;
2971 		}
2972 		/* text_shndx can be 0, if no default "main" program exists */
2973 		if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
2974 			pr_warn("bad call relo against section %u\n", shdr_idx);
2975 			return -LIBBPF_ERRNO__RELOC;
2976 		}
2977 		if (sym->st_value % 8) {
2978 			pr_warn("bad call relo offset: %zu\n",
2979 				(size_t)sym->st_value);
2980 			return -LIBBPF_ERRNO__RELOC;
2981 		}
2982 		reloc_desc->type = RELO_CALL;
2983 		reloc_desc->insn_idx = insn_idx;
2984 		reloc_desc->sym_off = sym->st_value;
2985 		obj->has_pseudo_calls = true;
2986 		return 0;
2987 	}
2988 
2989 	if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
2990 		pr_warn("invalid relo for insns[%d].code 0x%x\n",
2991 			insn_idx, insn->code);
2992 		return -LIBBPF_ERRNO__RELOC;
2993 	}
2994 
2995 	if (sym_is_extern(sym)) {
2996 		int sym_idx = GELF_R_SYM(rel->r_info);
2997 		int i, n = obj->nr_extern;
2998 		struct extern_desc *ext;
2999 
3000 		for (i = 0; i < n; i++) {
3001 			ext = &obj->externs[i];
3002 			if (ext->sym_idx == sym_idx)
3003 				break;
3004 		}
3005 		if (i >= n) {
3006 			pr_warn("extern relo failed to find extern for sym %d\n",
3007 				sym_idx);
3008 			return -LIBBPF_ERRNO__RELOC;
3009 		}
3010 		pr_debug("found extern #%d '%s' (sym %d, off %u) for insn %u\n",
3011 			 i, ext->name, ext->sym_idx, ext->data_off, insn_idx);
3012 		reloc_desc->type = RELO_EXTERN;
3013 		reloc_desc->insn_idx = insn_idx;
3014 		reloc_desc->sym_off = ext->data_off;
3015 		return 0;
3016 	}
3017 
3018 	if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
3019 		pr_warn("invalid relo for \'%s\' in special section 0x%x; forgot to initialize global var?..\n",
3020 			name, shdr_idx);
3021 		return -LIBBPF_ERRNO__RELOC;
3022 	}
3023 
3024 	type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
3025 
3026 	/* generic map reference relocation */
3027 	if (type == LIBBPF_MAP_UNSPEC) {
3028 		if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
3029 			pr_warn("bad map relo against section %u\n",
3030 				shdr_idx);
3031 			return -LIBBPF_ERRNO__RELOC;
3032 		}
3033 		for (map_idx = 0; map_idx < nr_maps; map_idx++) {
3034 			map = &obj->maps[map_idx];
3035 			if (map->libbpf_type != type ||
3036 			    map->sec_idx != sym->st_shndx ||
3037 			    map->sec_offset != sym->st_value)
3038 				continue;
3039 			pr_debug("found map %zd (%s, sec %d, off %zu) for insn %u\n",
3040 				 map_idx, map->name, map->sec_idx,
3041 				 map->sec_offset, insn_idx);
3042 			break;
3043 		}
3044 		if (map_idx >= nr_maps) {
3045 			pr_warn("map relo failed to find map for sec %u, off %zu\n",
3046 				shdr_idx, (size_t)sym->st_value);
3047 			return -LIBBPF_ERRNO__RELOC;
3048 		}
3049 		reloc_desc->type = RELO_LD64;
3050 		reloc_desc->insn_idx = insn_idx;
3051 		reloc_desc->map_idx = map_idx;
3052 		reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
3053 		return 0;
3054 	}
3055 
3056 	/* global data map relocation */
3057 	if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
3058 		pr_warn("bad data relo against section %u\n", shdr_idx);
3059 		return -LIBBPF_ERRNO__RELOC;
3060 	}
3061 	for (map_idx = 0; map_idx < nr_maps; map_idx++) {
3062 		map = &obj->maps[map_idx];
3063 		if (map->libbpf_type != type)
3064 			continue;
3065 		pr_debug("found data map %zd (%s, sec %d, off %zu) for insn %u\n",
3066 			 map_idx, map->name, map->sec_idx, map->sec_offset,
3067 			 insn_idx);
3068 		break;
3069 	}
3070 	if (map_idx >= nr_maps) {
3071 		pr_warn("data relo failed to find map for sec %u\n",
3072 			shdr_idx);
3073 		return -LIBBPF_ERRNO__RELOC;
3074 	}
3075 
3076 	reloc_desc->type = RELO_DATA;
3077 	reloc_desc->insn_idx = insn_idx;
3078 	reloc_desc->map_idx = map_idx;
3079 	reloc_desc->sym_off = sym->st_value;
3080 	return 0;
3081 }
3082 
3083 static int
3084 bpf_program__collect_reloc(struct bpf_program *prog, GElf_Shdr *shdr,
3085 			   Elf_Data *data, struct bpf_object *obj)
3086 {
3087 	Elf_Data *symbols = obj->efile.symbols;
3088 	int err, i, nrels;
3089 
3090 	pr_debug("collecting relocating info for: '%s'\n", prog->section_name);
3091 	nrels = shdr->sh_size / shdr->sh_entsize;
3092 
3093 	prog->reloc_desc = malloc(sizeof(*prog->reloc_desc) * nrels);
3094 	if (!prog->reloc_desc) {
3095 		pr_warn("failed to alloc memory in relocation\n");
3096 		return -ENOMEM;
3097 	}
3098 	prog->nr_reloc = nrels;
3099 
3100 	for (i = 0; i < nrels; i++) {
3101 		const char *name;
3102 		__u32 insn_idx;
3103 		GElf_Sym sym;
3104 		GElf_Rel rel;
3105 
3106 		if (!gelf_getrel(data, i, &rel)) {
3107 			pr_warn("relocation: failed to get %d reloc\n", i);
3108 			return -LIBBPF_ERRNO__FORMAT;
3109 		}
3110 		if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) {
3111 			pr_warn("relocation: symbol %"PRIx64" not found\n",
3112 				GELF_R_SYM(rel.r_info));
3113 			return -LIBBPF_ERRNO__FORMAT;
3114 		}
3115 		if (rel.r_offset % sizeof(struct bpf_insn))
3116 			return -LIBBPF_ERRNO__FORMAT;
3117 
3118 		insn_idx = rel.r_offset / sizeof(struct bpf_insn);
3119 		name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
3120 				  sym.st_name) ? : "<?>";
3121 
3122 		pr_debug("relo for shdr %u, symb %zu, value %zu, type %d, bind %d, name %d (\'%s\'), insn %u\n",
3123 			 (__u32)sym.st_shndx, (size_t)GELF_R_SYM(rel.r_info),
3124 			 (size_t)sym.st_value, GELF_ST_TYPE(sym.st_info),
3125 			 GELF_ST_BIND(sym.st_info), sym.st_name, name,
3126 			 insn_idx);
3127 
3128 		err = bpf_program__record_reloc(prog, &prog->reloc_desc[i],
3129 						insn_idx, name, &sym, &rel);
3130 		if (err)
3131 			return err;
3132 	}
3133 	return 0;
3134 }
3135 
3136 static int bpf_map_find_btf_info(struct bpf_object *obj, struct bpf_map *map)
3137 {
3138 	struct bpf_map_def *def = &map->def;
3139 	__u32 key_type_id = 0, value_type_id = 0;
3140 	int ret;
3141 
3142 	/* if it's BTF-defined map, we don't need to search for type IDs.
3143 	 * For struct_ops map, it does not need btf_key_type_id and
3144 	 * btf_value_type_id.
3145 	 */
3146 	if (map->sec_idx == obj->efile.btf_maps_shndx ||
3147 	    bpf_map__is_struct_ops(map))
3148 		return 0;
3149 
3150 	if (!bpf_map__is_internal(map)) {
3151 		ret = btf__get_map_kv_tids(obj->btf, map->name, def->key_size,
3152 					   def->value_size, &key_type_id,
3153 					   &value_type_id);
3154 	} else {
3155 		/*
3156 		 * LLVM annotates global data differently in BTF, that is,
3157 		 * only as '.data', '.bss' or '.rodata'.
3158 		 */
3159 		ret = btf__find_by_name(obj->btf,
3160 				libbpf_type_to_btf_name[map->libbpf_type]);
3161 	}
3162 	if (ret < 0)
3163 		return ret;
3164 
3165 	map->btf_key_type_id = key_type_id;
3166 	map->btf_value_type_id = bpf_map__is_internal(map) ?
3167 				 ret : value_type_id;
3168 	return 0;
3169 }
3170 
3171 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
3172 {
3173 	struct bpf_map_info info = {};
3174 	__u32 len = sizeof(info);
3175 	int new_fd, err;
3176 	char *new_name;
3177 
3178 	err = bpf_obj_get_info_by_fd(fd, &info, &len);
3179 	if (err)
3180 		return err;
3181 
3182 	new_name = strdup(info.name);
3183 	if (!new_name)
3184 		return -errno;
3185 
3186 	new_fd = open("/", O_RDONLY | O_CLOEXEC);
3187 	if (new_fd < 0) {
3188 		err = -errno;
3189 		goto err_free_new_name;
3190 	}
3191 
3192 	new_fd = dup3(fd, new_fd, O_CLOEXEC);
3193 	if (new_fd < 0) {
3194 		err = -errno;
3195 		goto err_close_new_fd;
3196 	}
3197 
3198 	err = zclose(map->fd);
3199 	if (err) {
3200 		err = -errno;
3201 		goto err_close_new_fd;
3202 	}
3203 	free(map->name);
3204 
3205 	map->fd = new_fd;
3206 	map->name = new_name;
3207 	map->def.type = info.type;
3208 	map->def.key_size = info.key_size;
3209 	map->def.value_size = info.value_size;
3210 	map->def.max_entries = info.max_entries;
3211 	map->def.map_flags = info.map_flags;
3212 	map->btf_key_type_id = info.btf_key_type_id;
3213 	map->btf_value_type_id = info.btf_value_type_id;
3214 	map->reused = true;
3215 
3216 	return 0;
3217 
3218 err_close_new_fd:
3219 	close(new_fd);
3220 err_free_new_name:
3221 	free(new_name);
3222 	return err;
3223 }
3224 
3225 int bpf_map__resize(struct bpf_map *map, __u32 max_entries)
3226 {
3227 	if (!map || !max_entries)
3228 		return -EINVAL;
3229 
3230 	/* If map already created, its attributes can't be changed. */
3231 	if (map->fd >= 0)
3232 		return -EBUSY;
3233 
3234 	map->def.max_entries = max_entries;
3235 
3236 	return 0;
3237 }
3238 
3239 static int
3240 bpf_object__probe_name(struct bpf_object *obj)
3241 {
3242 	struct bpf_load_program_attr attr;
3243 	char *cp, errmsg[STRERR_BUFSIZE];
3244 	struct bpf_insn insns[] = {
3245 		BPF_MOV64_IMM(BPF_REG_0, 0),
3246 		BPF_EXIT_INSN(),
3247 	};
3248 	int ret;
3249 
3250 	/* make sure basic loading works */
3251 
3252 	memset(&attr, 0, sizeof(attr));
3253 	attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
3254 	attr.insns = insns;
3255 	attr.insns_cnt = ARRAY_SIZE(insns);
3256 	attr.license = "GPL";
3257 
3258 	ret = bpf_load_program_xattr(&attr, NULL, 0);
3259 	if (ret < 0) {
3260 		cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
3261 		pr_warn("Error in %s():%s(%d). Couldn't load basic 'r0 = 0' BPF program.\n",
3262 			__func__, cp, errno);
3263 		return -errno;
3264 	}
3265 	close(ret);
3266 
3267 	/* now try the same program, but with the name */
3268 
3269 	attr.name = "test";
3270 	ret = bpf_load_program_xattr(&attr, NULL, 0);
3271 	if (ret >= 0) {
3272 		obj->caps.name = 1;
3273 		close(ret);
3274 	}
3275 
3276 	return 0;
3277 }
3278 
3279 static int
3280 bpf_object__probe_global_data(struct bpf_object *obj)
3281 {
3282 	struct bpf_load_program_attr prg_attr;
3283 	struct bpf_create_map_attr map_attr;
3284 	char *cp, errmsg[STRERR_BUFSIZE];
3285 	struct bpf_insn insns[] = {
3286 		BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
3287 		BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
3288 		BPF_MOV64_IMM(BPF_REG_0, 0),
3289 		BPF_EXIT_INSN(),
3290 	};
3291 	int ret, map;
3292 
3293 	memset(&map_attr, 0, sizeof(map_attr));
3294 	map_attr.map_type = BPF_MAP_TYPE_ARRAY;
3295 	map_attr.key_size = sizeof(int);
3296 	map_attr.value_size = 32;
3297 	map_attr.max_entries = 1;
3298 
3299 	map = bpf_create_map_xattr(&map_attr);
3300 	if (map < 0) {
3301 		cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
3302 		pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
3303 			__func__, cp, errno);
3304 		return -errno;
3305 	}
3306 
3307 	insns[0].imm = map;
3308 
3309 	memset(&prg_attr, 0, sizeof(prg_attr));
3310 	prg_attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
3311 	prg_attr.insns = insns;
3312 	prg_attr.insns_cnt = ARRAY_SIZE(insns);
3313 	prg_attr.license = "GPL";
3314 
3315 	ret = bpf_load_program_xattr(&prg_attr, NULL, 0);
3316 	if (ret >= 0) {
3317 		obj->caps.global_data = 1;
3318 		close(ret);
3319 	}
3320 
3321 	close(map);
3322 	return 0;
3323 }
3324 
3325 static int bpf_object__probe_btf_func(struct bpf_object *obj)
3326 {
3327 	static const char strs[] = "\0int\0x\0a";
3328 	/* void x(int a) {} */
3329 	__u32 types[] = {
3330 		/* int */
3331 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
3332 		/* FUNC_PROTO */                                /* [2] */
3333 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
3334 		BTF_PARAM_ENC(7, 1),
3335 		/* FUNC x */                                    /* [3] */
3336 		BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
3337 	};
3338 	int btf_fd;
3339 
3340 	btf_fd = libbpf__load_raw_btf((char *)types, sizeof(types),
3341 				      strs, sizeof(strs));
3342 	if (btf_fd >= 0) {
3343 		obj->caps.btf_func = 1;
3344 		close(btf_fd);
3345 		return 1;
3346 	}
3347 
3348 	return 0;
3349 }
3350 
3351 static int bpf_object__probe_btf_func_global(struct bpf_object *obj)
3352 {
3353 	static const char strs[] = "\0int\0x\0a";
3354 	/* static void x(int a) {} */
3355 	__u32 types[] = {
3356 		/* int */
3357 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
3358 		/* FUNC_PROTO */                                /* [2] */
3359 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
3360 		BTF_PARAM_ENC(7, 1),
3361 		/* FUNC x BTF_FUNC_GLOBAL */                    /* [3] */
3362 		BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, BTF_FUNC_GLOBAL), 2),
3363 	};
3364 	int btf_fd;
3365 
3366 	btf_fd = libbpf__load_raw_btf((char *)types, sizeof(types),
3367 				      strs, sizeof(strs));
3368 	if (btf_fd >= 0) {
3369 		obj->caps.btf_func_global = 1;
3370 		close(btf_fd);
3371 		return 1;
3372 	}
3373 
3374 	return 0;
3375 }
3376 
3377 static int bpf_object__probe_btf_datasec(struct bpf_object *obj)
3378 {
3379 	static const char strs[] = "\0x\0.data";
3380 	/* static int a; */
3381 	__u32 types[] = {
3382 		/* int */
3383 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
3384 		/* VAR x */                                     /* [2] */
3385 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
3386 		BTF_VAR_STATIC,
3387 		/* DATASEC val */                               /* [3] */
3388 		BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
3389 		BTF_VAR_SECINFO_ENC(2, 0, 4),
3390 	};
3391 	int btf_fd;
3392 
3393 	btf_fd = libbpf__load_raw_btf((char *)types, sizeof(types),
3394 				      strs, sizeof(strs));
3395 	if (btf_fd >= 0) {
3396 		obj->caps.btf_datasec = 1;
3397 		close(btf_fd);
3398 		return 1;
3399 	}
3400 
3401 	return 0;
3402 }
3403 
3404 static int bpf_object__probe_array_mmap(struct bpf_object *obj)
3405 {
3406 	struct bpf_create_map_attr attr = {
3407 		.map_type = BPF_MAP_TYPE_ARRAY,
3408 		.map_flags = BPF_F_MMAPABLE,
3409 		.key_size = sizeof(int),
3410 		.value_size = sizeof(int),
3411 		.max_entries = 1,
3412 	};
3413 	int fd;
3414 
3415 	fd = bpf_create_map_xattr(&attr);
3416 	if (fd >= 0) {
3417 		obj->caps.array_mmap = 1;
3418 		close(fd);
3419 		return 1;
3420 	}
3421 
3422 	return 0;
3423 }
3424 
3425 static int
3426 bpf_object__probe_exp_attach_type(struct bpf_object *obj)
3427 {
3428 	struct bpf_load_program_attr attr;
3429 	struct bpf_insn insns[] = {
3430 		BPF_MOV64_IMM(BPF_REG_0, 0),
3431 		BPF_EXIT_INSN(),
3432 	};
3433 	int fd;
3434 
3435 	memset(&attr, 0, sizeof(attr));
3436 	/* use any valid combination of program type and (optional)
3437 	 * non-zero expected attach type (i.e., not a BPF_CGROUP_INET_INGRESS)
3438 	 * to see if kernel supports expected_attach_type field for
3439 	 * BPF_PROG_LOAD command
3440 	 */
3441 	attr.prog_type = BPF_PROG_TYPE_CGROUP_SOCK;
3442 	attr.expected_attach_type = BPF_CGROUP_INET_SOCK_CREATE;
3443 	attr.insns = insns;
3444 	attr.insns_cnt = ARRAY_SIZE(insns);
3445 	attr.license = "GPL";
3446 
3447 	fd = bpf_load_program_xattr(&attr, NULL, 0);
3448 	if (fd >= 0) {
3449 		obj->caps.exp_attach_type = 1;
3450 		close(fd);
3451 		return 1;
3452 	}
3453 	return 0;
3454 }
3455 
3456 static int
3457 bpf_object__probe_caps(struct bpf_object *obj)
3458 {
3459 	int (*probe_fn[])(struct bpf_object *obj) = {
3460 		bpf_object__probe_name,
3461 		bpf_object__probe_global_data,
3462 		bpf_object__probe_btf_func,
3463 		bpf_object__probe_btf_func_global,
3464 		bpf_object__probe_btf_datasec,
3465 		bpf_object__probe_array_mmap,
3466 		bpf_object__probe_exp_attach_type,
3467 	};
3468 	int i, ret;
3469 
3470 	for (i = 0; i < ARRAY_SIZE(probe_fn); i++) {
3471 		ret = probe_fn[i](obj);
3472 		if (ret < 0)
3473 			pr_debug("Probe #%d failed with %d.\n", i, ret);
3474 	}
3475 
3476 	return 0;
3477 }
3478 
3479 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
3480 {
3481 	struct bpf_map_info map_info = {};
3482 	char msg[STRERR_BUFSIZE];
3483 	__u32 map_info_len;
3484 
3485 	map_info_len = sizeof(map_info);
3486 
3487 	if (bpf_obj_get_info_by_fd(map_fd, &map_info, &map_info_len)) {
3488 		pr_warn("failed to get map info for map FD %d: %s\n",
3489 			map_fd, libbpf_strerror_r(errno, msg, sizeof(msg)));
3490 		return false;
3491 	}
3492 
3493 	return (map_info.type == map->def.type &&
3494 		map_info.key_size == map->def.key_size &&
3495 		map_info.value_size == map->def.value_size &&
3496 		map_info.max_entries == map->def.max_entries &&
3497 		map_info.map_flags == map->def.map_flags);
3498 }
3499 
3500 static int
3501 bpf_object__reuse_map(struct bpf_map *map)
3502 {
3503 	char *cp, errmsg[STRERR_BUFSIZE];
3504 	int err, pin_fd;
3505 
3506 	pin_fd = bpf_obj_get(map->pin_path);
3507 	if (pin_fd < 0) {
3508 		err = -errno;
3509 		if (err == -ENOENT) {
3510 			pr_debug("found no pinned map to reuse at '%s'\n",
3511 				 map->pin_path);
3512 			return 0;
3513 		}
3514 
3515 		cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
3516 		pr_warn("couldn't retrieve pinned map '%s': %s\n",
3517 			map->pin_path, cp);
3518 		return err;
3519 	}
3520 
3521 	if (!map_is_reuse_compat(map, pin_fd)) {
3522 		pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
3523 			map->pin_path);
3524 		close(pin_fd);
3525 		return -EINVAL;
3526 	}
3527 
3528 	err = bpf_map__reuse_fd(map, pin_fd);
3529 	if (err) {
3530 		close(pin_fd);
3531 		return err;
3532 	}
3533 	map->pinned = true;
3534 	pr_debug("reused pinned map at '%s'\n", map->pin_path);
3535 
3536 	return 0;
3537 }
3538 
3539 static int
3540 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
3541 {
3542 	enum libbpf_map_type map_type = map->libbpf_type;
3543 	char *cp, errmsg[STRERR_BUFSIZE];
3544 	int err, zero = 0;
3545 
3546 	/* kernel already zero-initializes .bss map. */
3547 	if (map_type == LIBBPF_MAP_BSS)
3548 		return 0;
3549 
3550 	err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
3551 	if (err) {
3552 		err = -errno;
3553 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
3554 		pr_warn("Error setting initial map(%s) contents: %s\n",
3555 			map->name, cp);
3556 		return err;
3557 	}
3558 
3559 	/* Freeze .rodata and .kconfig map as read-only from syscall side. */
3560 	if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
3561 		err = bpf_map_freeze(map->fd);
3562 		if (err) {
3563 			err = -errno;
3564 			cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
3565 			pr_warn("Error freezing map(%s) as read-only: %s\n",
3566 				map->name, cp);
3567 			return err;
3568 		}
3569 	}
3570 	return 0;
3571 }
3572 
3573 static void bpf_map__destroy(struct bpf_map *map);
3574 
3575 static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map)
3576 {
3577 	struct bpf_create_map_attr create_attr;
3578 	struct bpf_map_def *def = &map->def;
3579 
3580 	memset(&create_attr, 0, sizeof(create_attr));
3581 
3582 	if (obj->caps.name)
3583 		create_attr.name = map->name;
3584 	create_attr.map_ifindex = map->map_ifindex;
3585 	create_attr.map_type = def->type;
3586 	create_attr.map_flags = def->map_flags;
3587 	create_attr.key_size = def->key_size;
3588 	create_attr.value_size = def->value_size;
3589 
3590 	if (def->type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !def->max_entries) {
3591 		int nr_cpus;
3592 
3593 		nr_cpus = libbpf_num_possible_cpus();
3594 		if (nr_cpus < 0) {
3595 			pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
3596 				map->name, nr_cpus);
3597 			return nr_cpus;
3598 		}
3599 		pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
3600 		create_attr.max_entries = nr_cpus;
3601 	} else {
3602 		create_attr.max_entries = def->max_entries;
3603 	}
3604 
3605 	if (bpf_map__is_struct_ops(map))
3606 		create_attr.btf_vmlinux_value_type_id =
3607 			map->btf_vmlinux_value_type_id;
3608 
3609 	create_attr.btf_fd = 0;
3610 	create_attr.btf_key_type_id = 0;
3611 	create_attr.btf_value_type_id = 0;
3612 	if (obj->btf && !bpf_map_find_btf_info(obj, map)) {
3613 		create_attr.btf_fd = btf__fd(obj->btf);
3614 		create_attr.btf_key_type_id = map->btf_key_type_id;
3615 		create_attr.btf_value_type_id = map->btf_value_type_id;
3616 	}
3617 
3618 	if (bpf_map_type__is_map_in_map(def->type)) {
3619 		if (map->inner_map) {
3620 			int err;
3621 
3622 			err = bpf_object__create_map(obj, map->inner_map);
3623 			if (err) {
3624 				pr_warn("map '%s': failed to create inner map: %d\n",
3625 					map->name, err);
3626 				return err;
3627 			}
3628 			map->inner_map_fd = bpf_map__fd(map->inner_map);
3629 		}
3630 		if (map->inner_map_fd >= 0)
3631 			create_attr.inner_map_fd = map->inner_map_fd;
3632 	}
3633 
3634 	map->fd = bpf_create_map_xattr(&create_attr);
3635 	if (map->fd < 0 && (create_attr.btf_key_type_id ||
3636 			    create_attr.btf_value_type_id)) {
3637 		char *cp, errmsg[STRERR_BUFSIZE];
3638 		int err = -errno;
3639 
3640 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
3641 		pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
3642 			map->name, cp, err);
3643 		create_attr.btf_fd = 0;
3644 		create_attr.btf_key_type_id = 0;
3645 		create_attr.btf_value_type_id = 0;
3646 		map->btf_key_type_id = 0;
3647 		map->btf_value_type_id = 0;
3648 		map->fd = bpf_create_map_xattr(&create_attr);
3649 	}
3650 
3651 	if (map->fd < 0)
3652 		return -errno;
3653 
3654 	if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
3655 		bpf_map__destroy(map->inner_map);
3656 		zfree(&map->inner_map);
3657 	}
3658 
3659 	return 0;
3660 }
3661 
3662 static int
3663 bpf_object__create_maps(struct bpf_object *obj)
3664 {
3665 	struct bpf_map *map;
3666 	char *cp, errmsg[STRERR_BUFSIZE];
3667 	unsigned int i, j;
3668 	int err;
3669 
3670 	for (i = 0; i < obj->nr_maps; i++) {
3671 		map = &obj->maps[i];
3672 
3673 		if (map->pin_path) {
3674 			err = bpf_object__reuse_map(map);
3675 			if (err) {
3676 				pr_warn("map '%s': error reusing pinned map\n",
3677 					map->name);
3678 				goto err_out;
3679 			}
3680 		}
3681 
3682 		if (map->fd >= 0) {
3683 			pr_debug("map '%s': skipping creation (preset fd=%d)\n",
3684 				 map->name, map->fd);
3685 			continue;
3686 		}
3687 
3688 		err = bpf_object__create_map(obj, map);
3689 		if (err)
3690 			goto err_out;
3691 
3692 		pr_debug("map '%s': created successfully, fd=%d\n", map->name,
3693 			 map->fd);
3694 
3695 		if (bpf_map__is_internal(map)) {
3696 			err = bpf_object__populate_internal_map(obj, map);
3697 			if (err < 0) {
3698 				zclose(map->fd);
3699 				goto err_out;
3700 			}
3701 		}
3702 
3703 		if (map->init_slots_sz) {
3704 			for (j = 0; j < map->init_slots_sz; j++) {
3705 				const struct bpf_map *targ_map;
3706 				int fd;
3707 
3708 				if (!map->init_slots[j])
3709 					continue;
3710 
3711 				targ_map = map->init_slots[j];
3712 				fd = bpf_map__fd(targ_map);
3713 				err = bpf_map_update_elem(map->fd, &j, &fd, 0);
3714 				if (err) {
3715 					err = -errno;
3716 					pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %d\n",
3717 						map->name, j, targ_map->name,
3718 						fd, err);
3719 					goto err_out;
3720 				}
3721 				pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
3722 					 map->name, j, targ_map->name, fd);
3723 			}
3724 			zfree(&map->init_slots);
3725 			map->init_slots_sz = 0;
3726 		}
3727 
3728 		if (map->pin_path && !map->pinned) {
3729 			err = bpf_map__pin(map, NULL);
3730 			if (err) {
3731 				pr_warn("map '%s': failed to auto-pin at '%s': %d\n",
3732 					map->name, map->pin_path, err);
3733 				zclose(map->fd);
3734 				goto err_out;
3735 			}
3736 		}
3737 	}
3738 
3739 	return 0;
3740 
3741 err_out:
3742 	cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
3743 	pr_warn("map '%s': failed to create: %s(%d)\n", map->name, cp, err);
3744 	pr_perm_msg(err);
3745 	for (j = 0; j < i; j++)
3746 		zclose(obj->maps[j].fd);
3747 	return err;
3748 }
3749 
3750 static int
3751 check_btf_ext_reloc_err(struct bpf_program *prog, int err,
3752 			void *btf_prog_info, const char *info_name)
3753 {
3754 	if (err != -ENOENT) {
3755 		pr_warn("Error in loading %s for sec %s.\n",
3756 			info_name, prog->section_name);
3757 		return err;
3758 	}
3759 
3760 	/* err == -ENOENT (i.e. prog->section_name not found in btf_ext) */
3761 
3762 	if (btf_prog_info) {
3763 		/*
3764 		 * Some info has already been found but has problem
3765 		 * in the last btf_ext reloc. Must have to error out.
3766 		 */
3767 		pr_warn("Error in relocating %s for sec %s.\n",
3768 			info_name, prog->section_name);
3769 		return err;
3770 	}
3771 
3772 	/* Have problem loading the very first info. Ignore the rest. */
3773 	pr_warn("Cannot find %s for main program sec %s. Ignore all %s.\n",
3774 		info_name, prog->section_name, info_name);
3775 	return 0;
3776 }
3777 
3778 static int
3779 bpf_program_reloc_btf_ext(struct bpf_program *prog, struct bpf_object *obj,
3780 			  const char *section_name,  __u32 insn_offset)
3781 {
3782 	int err;
3783 
3784 	if (!insn_offset || prog->func_info) {
3785 		/*
3786 		 * !insn_offset => main program
3787 		 *
3788 		 * For sub prog, the main program's func_info has to
3789 		 * be loaded first (i.e. prog->func_info != NULL)
3790 		 */
3791 		err = btf_ext__reloc_func_info(obj->btf, obj->btf_ext,
3792 					       section_name, insn_offset,
3793 					       &prog->func_info,
3794 					       &prog->func_info_cnt);
3795 		if (err)
3796 			return check_btf_ext_reloc_err(prog, err,
3797 						       prog->func_info,
3798 						       "bpf_func_info");
3799 
3800 		prog->func_info_rec_size = btf_ext__func_info_rec_size(obj->btf_ext);
3801 	}
3802 
3803 	if (!insn_offset || prog->line_info) {
3804 		err = btf_ext__reloc_line_info(obj->btf, obj->btf_ext,
3805 					       section_name, insn_offset,
3806 					       &prog->line_info,
3807 					       &prog->line_info_cnt);
3808 		if (err)
3809 			return check_btf_ext_reloc_err(prog, err,
3810 						       prog->line_info,
3811 						       "bpf_line_info");
3812 
3813 		prog->line_info_rec_size = btf_ext__line_info_rec_size(obj->btf_ext);
3814 	}
3815 
3816 	return 0;
3817 }
3818 
3819 #define BPF_CORE_SPEC_MAX_LEN 64
3820 
3821 /* represents BPF CO-RE field or array element accessor */
3822 struct bpf_core_accessor {
3823 	__u32 type_id;		/* struct/union type or array element type */
3824 	__u32 idx;		/* field index or array index */
3825 	const char *name;	/* field name or NULL for array accessor */
3826 };
3827 
3828 struct bpf_core_spec {
3829 	const struct btf *btf;
3830 	/* high-level spec: named fields and array indices only */
3831 	struct bpf_core_accessor spec[BPF_CORE_SPEC_MAX_LEN];
3832 	/* high-level spec length */
3833 	int len;
3834 	/* raw, low-level spec: 1-to-1 with accessor spec string */
3835 	int raw_spec[BPF_CORE_SPEC_MAX_LEN];
3836 	/* raw spec length */
3837 	int raw_len;
3838 	/* field bit offset represented by spec */
3839 	__u32 bit_offset;
3840 };
3841 
3842 static bool str_is_empty(const char *s)
3843 {
3844 	return !s || !s[0];
3845 }
3846 
3847 static bool is_flex_arr(const struct btf *btf,
3848 			const struct bpf_core_accessor *acc,
3849 			const struct btf_array *arr)
3850 {
3851 	const struct btf_type *t;
3852 
3853 	/* not a flexible array, if not inside a struct or has non-zero size */
3854 	if (!acc->name || arr->nelems > 0)
3855 		return false;
3856 
3857 	/* has to be the last member of enclosing struct */
3858 	t = btf__type_by_id(btf, acc->type_id);
3859 	return acc->idx == btf_vlen(t) - 1;
3860 }
3861 
3862 /*
3863  * Turn bpf_field_reloc into a low- and high-level spec representation,
3864  * validating correctness along the way, as well as calculating resulting
3865  * field bit offset, specified by accessor string. Low-level spec captures
3866  * every single level of nestedness, including traversing anonymous
3867  * struct/union members. High-level one only captures semantically meaningful
3868  * "turning points": named fields and array indicies.
3869  * E.g., for this case:
3870  *
3871  *   struct sample {
3872  *       int __unimportant;
3873  *       struct {
3874  *           int __1;
3875  *           int __2;
3876  *           int a[7];
3877  *       };
3878  *   };
3879  *
3880  *   struct sample *s = ...;
3881  *
3882  *   int x = &s->a[3]; // access string = '0:1:2:3'
3883  *
3884  * Low-level spec has 1:1 mapping with each element of access string (it's
3885  * just a parsed access string representation): [0, 1, 2, 3].
3886  *
3887  * High-level spec will capture only 3 points:
3888  *   - intial zero-index access by pointer (&s->... is the same as &s[0]...);
3889  *   - field 'a' access (corresponds to '2' in low-level spec);
3890  *   - array element #3 access (corresponds to '3' in low-level spec).
3891  *
3892  */
3893 static int bpf_core_spec_parse(const struct btf *btf,
3894 			       __u32 type_id,
3895 			       const char *spec_str,
3896 			       struct bpf_core_spec *spec)
3897 {
3898 	int access_idx, parsed_len, i;
3899 	struct bpf_core_accessor *acc;
3900 	const struct btf_type *t;
3901 	const char *name;
3902 	__u32 id;
3903 	__s64 sz;
3904 
3905 	if (str_is_empty(spec_str) || *spec_str == ':')
3906 		return -EINVAL;
3907 
3908 	memset(spec, 0, sizeof(*spec));
3909 	spec->btf = btf;
3910 
3911 	/* parse spec_str="0:1:2:3:4" into array raw_spec=[0, 1, 2, 3, 4] */
3912 	while (*spec_str) {
3913 		if (*spec_str == ':')
3914 			++spec_str;
3915 		if (sscanf(spec_str, "%d%n", &access_idx, &parsed_len) != 1)
3916 			return -EINVAL;
3917 		if (spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
3918 			return -E2BIG;
3919 		spec_str += parsed_len;
3920 		spec->raw_spec[spec->raw_len++] = access_idx;
3921 	}
3922 
3923 	if (spec->raw_len == 0)
3924 		return -EINVAL;
3925 
3926 	/* first spec value is always reloc type array index */
3927 	t = skip_mods_and_typedefs(btf, type_id, &id);
3928 	if (!t)
3929 		return -EINVAL;
3930 
3931 	access_idx = spec->raw_spec[0];
3932 	spec->spec[0].type_id = id;
3933 	spec->spec[0].idx = access_idx;
3934 	spec->len++;
3935 
3936 	sz = btf__resolve_size(btf, id);
3937 	if (sz < 0)
3938 		return sz;
3939 	spec->bit_offset = access_idx * sz * 8;
3940 
3941 	for (i = 1; i < spec->raw_len; i++) {
3942 		t = skip_mods_and_typedefs(btf, id, &id);
3943 		if (!t)
3944 			return -EINVAL;
3945 
3946 		access_idx = spec->raw_spec[i];
3947 		acc = &spec->spec[spec->len];
3948 
3949 		if (btf_is_composite(t)) {
3950 			const struct btf_member *m;
3951 			__u32 bit_offset;
3952 
3953 			if (access_idx >= btf_vlen(t))
3954 				return -EINVAL;
3955 
3956 			bit_offset = btf_member_bit_offset(t, access_idx);
3957 			spec->bit_offset += bit_offset;
3958 
3959 			m = btf_members(t) + access_idx;
3960 			if (m->name_off) {
3961 				name = btf__name_by_offset(btf, m->name_off);
3962 				if (str_is_empty(name))
3963 					return -EINVAL;
3964 
3965 				acc->type_id = id;
3966 				acc->idx = access_idx;
3967 				acc->name = name;
3968 				spec->len++;
3969 			}
3970 
3971 			id = m->type;
3972 		} else if (btf_is_array(t)) {
3973 			const struct btf_array *a = btf_array(t);
3974 			bool flex;
3975 
3976 			t = skip_mods_and_typedefs(btf, a->type, &id);
3977 			if (!t)
3978 				return -EINVAL;
3979 
3980 			flex = is_flex_arr(btf, acc - 1, a);
3981 			if (!flex && access_idx >= a->nelems)
3982 				return -EINVAL;
3983 
3984 			spec->spec[spec->len].type_id = id;
3985 			spec->spec[spec->len].idx = access_idx;
3986 			spec->len++;
3987 
3988 			sz = btf__resolve_size(btf, id);
3989 			if (sz < 0)
3990 				return sz;
3991 			spec->bit_offset += access_idx * sz * 8;
3992 		} else {
3993 			pr_warn("relo for [%u] %s (at idx %d) captures type [%d] of unexpected kind %d\n",
3994 				type_id, spec_str, i, id, btf_kind(t));
3995 			return -EINVAL;
3996 		}
3997 	}
3998 
3999 	return 0;
4000 }
4001 
4002 static bool bpf_core_is_flavor_sep(const char *s)
4003 {
4004 	/* check X___Y name pattern, where X and Y are not underscores */
4005 	return s[0] != '_' &&				      /* X */
4006 	       s[1] == '_' && s[2] == '_' && s[3] == '_' &&   /* ___ */
4007 	       s[4] != '_';				      /* Y */
4008 }
4009 
4010 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
4011  * before last triple underscore. Struct name part after last triple
4012  * underscore is ignored by BPF CO-RE relocation during relocation matching.
4013  */
4014 static size_t bpf_core_essential_name_len(const char *name)
4015 {
4016 	size_t n = strlen(name);
4017 	int i;
4018 
4019 	for (i = n - 5; i >= 0; i--) {
4020 		if (bpf_core_is_flavor_sep(name + i))
4021 			return i + 1;
4022 	}
4023 	return n;
4024 }
4025 
4026 /* dynamically sized list of type IDs */
4027 struct ids_vec {
4028 	__u32 *data;
4029 	int len;
4030 };
4031 
4032 static void bpf_core_free_cands(struct ids_vec *cand_ids)
4033 {
4034 	free(cand_ids->data);
4035 	free(cand_ids);
4036 }
4037 
4038 static struct ids_vec *bpf_core_find_cands(const struct btf *local_btf,
4039 					   __u32 local_type_id,
4040 					   const struct btf *targ_btf)
4041 {
4042 	size_t local_essent_len, targ_essent_len;
4043 	const char *local_name, *targ_name;
4044 	const struct btf_type *t;
4045 	struct ids_vec *cand_ids;
4046 	__u32 *new_ids;
4047 	int i, err, n;
4048 
4049 	t = btf__type_by_id(local_btf, local_type_id);
4050 	if (!t)
4051 		return ERR_PTR(-EINVAL);
4052 
4053 	local_name = btf__name_by_offset(local_btf, t->name_off);
4054 	if (str_is_empty(local_name))
4055 		return ERR_PTR(-EINVAL);
4056 	local_essent_len = bpf_core_essential_name_len(local_name);
4057 
4058 	cand_ids = calloc(1, sizeof(*cand_ids));
4059 	if (!cand_ids)
4060 		return ERR_PTR(-ENOMEM);
4061 
4062 	n = btf__get_nr_types(targ_btf);
4063 	for (i = 1; i <= n; i++) {
4064 		t = btf__type_by_id(targ_btf, i);
4065 		targ_name = btf__name_by_offset(targ_btf, t->name_off);
4066 		if (str_is_empty(targ_name))
4067 			continue;
4068 
4069 		t = skip_mods_and_typedefs(targ_btf, i, NULL);
4070 		if (!btf_is_composite(t) && !btf_is_array(t))
4071 			continue;
4072 
4073 		targ_essent_len = bpf_core_essential_name_len(targ_name);
4074 		if (targ_essent_len != local_essent_len)
4075 			continue;
4076 
4077 		if (strncmp(local_name, targ_name, local_essent_len) == 0) {
4078 			pr_debug("[%d] %s: found candidate [%d] %s\n",
4079 				 local_type_id, local_name, i, targ_name);
4080 			new_ids = reallocarray(cand_ids->data,
4081 					       cand_ids->len + 1,
4082 					       sizeof(*cand_ids->data));
4083 			if (!new_ids) {
4084 				err = -ENOMEM;
4085 				goto err_out;
4086 			}
4087 			cand_ids->data = new_ids;
4088 			cand_ids->data[cand_ids->len++] = i;
4089 		}
4090 	}
4091 	return cand_ids;
4092 err_out:
4093 	bpf_core_free_cands(cand_ids);
4094 	return ERR_PTR(err);
4095 }
4096 
4097 /* Check two types for compatibility, skipping const/volatile/restrict and
4098  * typedefs, to ensure we are relocating compatible entities:
4099  *   - any two STRUCTs/UNIONs are compatible and can be mixed;
4100  *   - any two FWDs are compatible, if their names match (modulo flavor suffix);
4101  *   - any two PTRs are always compatible;
4102  *   - for ENUMs, names should be the same (ignoring flavor suffix) or at
4103  *     least one of enums should be anonymous;
4104  *   - for ENUMs, check sizes, names are ignored;
4105  *   - for INT, size and signedness are ignored;
4106  *   - for ARRAY, dimensionality is ignored, element types are checked for
4107  *     compatibility recursively;
4108  *   - everything else shouldn't be ever a target of relocation.
4109  * These rules are not set in stone and probably will be adjusted as we get
4110  * more experience with using BPF CO-RE relocations.
4111  */
4112 static int bpf_core_fields_are_compat(const struct btf *local_btf,
4113 				      __u32 local_id,
4114 				      const struct btf *targ_btf,
4115 				      __u32 targ_id)
4116 {
4117 	const struct btf_type *local_type, *targ_type;
4118 
4119 recur:
4120 	local_type = skip_mods_and_typedefs(local_btf, local_id, &local_id);
4121 	targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
4122 	if (!local_type || !targ_type)
4123 		return -EINVAL;
4124 
4125 	if (btf_is_composite(local_type) && btf_is_composite(targ_type))
4126 		return 1;
4127 	if (btf_kind(local_type) != btf_kind(targ_type))
4128 		return 0;
4129 
4130 	switch (btf_kind(local_type)) {
4131 	case BTF_KIND_PTR:
4132 		return 1;
4133 	case BTF_KIND_FWD:
4134 	case BTF_KIND_ENUM: {
4135 		const char *local_name, *targ_name;
4136 		size_t local_len, targ_len;
4137 
4138 		local_name = btf__name_by_offset(local_btf,
4139 						 local_type->name_off);
4140 		targ_name = btf__name_by_offset(targ_btf, targ_type->name_off);
4141 		local_len = bpf_core_essential_name_len(local_name);
4142 		targ_len = bpf_core_essential_name_len(targ_name);
4143 		/* one of them is anonymous or both w/ same flavor-less names */
4144 		return local_len == 0 || targ_len == 0 ||
4145 		       (local_len == targ_len &&
4146 			strncmp(local_name, targ_name, local_len) == 0);
4147 	}
4148 	case BTF_KIND_INT:
4149 		/* just reject deprecated bitfield-like integers; all other
4150 		 * integers are by default compatible between each other
4151 		 */
4152 		return btf_int_offset(local_type) == 0 &&
4153 		       btf_int_offset(targ_type) == 0;
4154 	case BTF_KIND_ARRAY:
4155 		local_id = btf_array(local_type)->type;
4156 		targ_id = btf_array(targ_type)->type;
4157 		goto recur;
4158 	default:
4159 		pr_warn("unexpected kind %d relocated, local [%d], target [%d]\n",
4160 			btf_kind(local_type), local_id, targ_id);
4161 		return 0;
4162 	}
4163 }
4164 
4165 /*
4166  * Given single high-level named field accessor in local type, find
4167  * corresponding high-level accessor for a target type. Along the way,
4168  * maintain low-level spec for target as well. Also keep updating target
4169  * bit offset.
4170  *
4171  * Searching is performed through recursive exhaustive enumeration of all
4172  * fields of a struct/union. If there are any anonymous (embedded)
4173  * structs/unions, they are recursively searched as well. If field with
4174  * desired name is found, check compatibility between local and target types,
4175  * before returning result.
4176  *
4177  * 1 is returned, if field is found.
4178  * 0 is returned if no compatible field is found.
4179  * <0 is returned on error.
4180  */
4181 static int bpf_core_match_member(const struct btf *local_btf,
4182 				 const struct bpf_core_accessor *local_acc,
4183 				 const struct btf *targ_btf,
4184 				 __u32 targ_id,
4185 				 struct bpf_core_spec *spec,
4186 				 __u32 *next_targ_id)
4187 {
4188 	const struct btf_type *local_type, *targ_type;
4189 	const struct btf_member *local_member, *m;
4190 	const char *local_name, *targ_name;
4191 	__u32 local_id;
4192 	int i, n, found;
4193 
4194 	targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
4195 	if (!targ_type)
4196 		return -EINVAL;
4197 	if (!btf_is_composite(targ_type))
4198 		return 0;
4199 
4200 	local_id = local_acc->type_id;
4201 	local_type = btf__type_by_id(local_btf, local_id);
4202 	local_member = btf_members(local_type) + local_acc->idx;
4203 	local_name = btf__name_by_offset(local_btf, local_member->name_off);
4204 
4205 	n = btf_vlen(targ_type);
4206 	m = btf_members(targ_type);
4207 	for (i = 0; i < n; i++, m++) {
4208 		__u32 bit_offset;
4209 
4210 		bit_offset = btf_member_bit_offset(targ_type, i);
4211 
4212 		/* too deep struct/union/array nesting */
4213 		if (spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
4214 			return -E2BIG;
4215 
4216 		/* speculate this member will be the good one */
4217 		spec->bit_offset += bit_offset;
4218 		spec->raw_spec[spec->raw_len++] = i;
4219 
4220 		targ_name = btf__name_by_offset(targ_btf, m->name_off);
4221 		if (str_is_empty(targ_name)) {
4222 			/* embedded struct/union, we need to go deeper */
4223 			found = bpf_core_match_member(local_btf, local_acc,
4224 						      targ_btf, m->type,
4225 						      spec, next_targ_id);
4226 			if (found) /* either found or error */
4227 				return found;
4228 		} else if (strcmp(local_name, targ_name) == 0) {
4229 			/* matching named field */
4230 			struct bpf_core_accessor *targ_acc;
4231 
4232 			targ_acc = &spec->spec[spec->len++];
4233 			targ_acc->type_id = targ_id;
4234 			targ_acc->idx = i;
4235 			targ_acc->name = targ_name;
4236 
4237 			*next_targ_id = m->type;
4238 			found = bpf_core_fields_are_compat(local_btf,
4239 							   local_member->type,
4240 							   targ_btf, m->type);
4241 			if (!found)
4242 				spec->len--; /* pop accessor */
4243 			return found;
4244 		}
4245 		/* member turned out not to be what we looked for */
4246 		spec->bit_offset -= bit_offset;
4247 		spec->raw_len--;
4248 	}
4249 
4250 	return 0;
4251 }
4252 
4253 /*
4254  * Try to match local spec to a target type and, if successful, produce full
4255  * target spec (high-level, low-level + bit offset).
4256  */
4257 static int bpf_core_spec_match(struct bpf_core_spec *local_spec,
4258 			       const struct btf *targ_btf, __u32 targ_id,
4259 			       struct bpf_core_spec *targ_spec)
4260 {
4261 	const struct btf_type *targ_type;
4262 	const struct bpf_core_accessor *local_acc;
4263 	struct bpf_core_accessor *targ_acc;
4264 	int i, sz, matched;
4265 
4266 	memset(targ_spec, 0, sizeof(*targ_spec));
4267 	targ_spec->btf = targ_btf;
4268 
4269 	local_acc = &local_spec->spec[0];
4270 	targ_acc = &targ_spec->spec[0];
4271 
4272 	for (i = 0; i < local_spec->len; i++, local_acc++, targ_acc++) {
4273 		targ_type = skip_mods_and_typedefs(targ_spec->btf, targ_id,
4274 						   &targ_id);
4275 		if (!targ_type)
4276 			return -EINVAL;
4277 
4278 		if (local_acc->name) {
4279 			matched = bpf_core_match_member(local_spec->btf,
4280 							local_acc,
4281 							targ_btf, targ_id,
4282 							targ_spec, &targ_id);
4283 			if (matched <= 0)
4284 				return matched;
4285 		} else {
4286 			/* for i=0, targ_id is already treated as array element
4287 			 * type (because it's the original struct), for others
4288 			 * we should find array element type first
4289 			 */
4290 			if (i > 0) {
4291 				const struct btf_array *a;
4292 				bool flex;
4293 
4294 				if (!btf_is_array(targ_type))
4295 					return 0;
4296 
4297 				a = btf_array(targ_type);
4298 				flex = is_flex_arr(targ_btf, targ_acc - 1, a);
4299 				if (!flex && local_acc->idx >= a->nelems)
4300 					return 0;
4301 				if (!skip_mods_and_typedefs(targ_btf, a->type,
4302 							    &targ_id))
4303 					return -EINVAL;
4304 			}
4305 
4306 			/* too deep struct/union/array nesting */
4307 			if (targ_spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
4308 				return -E2BIG;
4309 
4310 			targ_acc->type_id = targ_id;
4311 			targ_acc->idx = local_acc->idx;
4312 			targ_acc->name = NULL;
4313 			targ_spec->len++;
4314 			targ_spec->raw_spec[targ_spec->raw_len] = targ_acc->idx;
4315 			targ_spec->raw_len++;
4316 
4317 			sz = btf__resolve_size(targ_btf, targ_id);
4318 			if (sz < 0)
4319 				return sz;
4320 			targ_spec->bit_offset += local_acc->idx * sz * 8;
4321 		}
4322 	}
4323 
4324 	return 1;
4325 }
4326 
4327 static int bpf_core_calc_field_relo(const struct bpf_program *prog,
4328 				    const struct bpf_field_reloc *relo,
4329 				    const struct bpf_core_spec *spec,
4330 				    __u32 *val, bool *validate)
4331 {
4332 	const struct bpf_core_accessor *acc = &spec->spec[spec->len - 1];
4333 	const struct btf_type *t = btf__type_by_id(spec->btf, acc->type_id);
4334 	__u32 byte_off, byte_sz, bit_off, bit_sz;
4335 	const struct btf_member *m;
4336 	const struct btf_type *mt;
4337 	bool bitfield;
4338 	__s64 sz;
4339 
4340 	/* a[n] accessor needs special handling */
4341 	if (!acc->name) {
4342 		if (relo->kind == BPF_FIELD_BYTE_OFFSET) {
4343 			*val = spec->bit_offset / 8;
4344 		} else if (relo->kind == BPF_FIELD_BYTE_SIZE) {
4345 			sz = btf__resolve_size(spec->btf, acc->type_id);
4346 			if (sz < 0)
4347 				return -EINVAL;
4348 			*val = sz;
4349 		} else {
4350 			pr_warn("prog '%s': relo %d at insn #%d can't be applied to array access\n",
4351 				bpf_program__title(prog, false),
4352 				relo->kind, relo->insn_off / 8);
4353 			return -EINVAL;
4354 		}
4355 		if (validate)
4356 			*validate = true;
4357 		return 0;
4358 	}
4359 
4360 	m = btf_members(t) + acc->idx;
4361 	mt = skip_mods_and_typedefs(spec->btf, m->type, NULL);
4362 	bit_off = spec->bit_offset;
4363 	bit_sz = btf_member_bitfield_size(t, acc->idx);
4364 
4365 	bitfield = bit_sz > 0;
4366 	if (bitfield) {
4367 		byte_sz = mt->size;
4368 		byte_off = bit_off / 8 / byte_sz * byte_sz;
4369 		/* figure out smallest int size necessary for bitfield load */
4370 		while (bit_off + bit_sz - byte_off * 8 > byte_sz * 8) {
4371 			if (byte_sz >= 8) {
4372 				/* bitfield can't be read with 64-bit read */
4373 				pr_warn("prog '%s': relo %d at insn #%d can't be satisfied for bitfield\n",
4374 					bpf_program__title(prog, false),
4375 					relo->kind, relo->insn_off / 8);
4376 				return -E2BIG;
4377 			}
4378 			byte_sz *= 2;
4379 			byte_off = bit_off / 8 / byte_sz * byte_sz;
4380 		}
4381 	} else {
4382 		sz = btf__resolve_size(spec->btf, m->type);
4383 		if (sz < 0)
4384 			return -EINVAL;
4385 		byte_sz = sz;
4386 		byte_off = spec->bit_offset / 8;
4387 		bit_sz = byte_sz * 8;
4388 	}
4389 
4390 	/* for bitfields, all the relocatable aspects are ambiguous and we
4391 	 * might disagree with compiler, so turn off validation of expected
4392 	 * value, except for signedness
4393 	 */
4394 	if (validate)
4395 		*validate = !bitfield;
4396 
4397 	switch (relo->kind) {
4398 	case BPF_FIELD_BYTE_OFFSET:
4399 		*val = byte_off;
4400 		break;
4401 	case BPF_FIELD_BYTE_SIZE:
4402 		*val = byte_sz;
4403 		break;
4404 	case BPF_FIELD_SIGNED:
4405 		/* enums will be assumed unsigned */
4406 		*val = btf_is_enum(mt) ||
4407 		       (btf_int_encoding(mt) & BTF_INT_SIGNED);
4408 		if (validate)
4409 			*validate = true; /* signedness is never ambiguous */
4410 		break;
4411 	case BPF_FIELD_LSHIFT_U64:
4412 #if __BYTE_ORDER == __LITTLE_ENDIAN
4413 		*val = 64 - (bit_off + bit_sz - byte_off  * 8);
4414 #else
4415 		*val = (8 - byte_sz) * 8 + (bit_off - byte_off * 8);
4416 #endif
4417 		break;
4418 	case BPF_FIELD_RSHIFT_U64:
4419 		*val = 64 - bit_sz;
4420 		if (validate)
4421 			*validate = true; /* right shift is never ambiguous */
4422 		break;
4423 	case BPF_FIELD_EXISTS:
4424 	default:
4425 		pr_warn("prog '%s': unknown relo %d at insn #%d\n",
4426 			bpf_program__title(prog, false),
4427 			relo->kind, relo->insn_off / 8);
4428 		return -EINVAL;
4429 	}
4430 
4431 	return 0;
4432 }
4433 
4434 /*
4435  * Patch relocatable BPF instruction.
4436  *
4437  * Patched value is determined by relocation kind and target specification.
4438  * For field existence relocation target spec will be NULL if field is not
4439  * found.
4440  * Expected insn->imm value is determined using relocation kind and local
4441  * spec, and is checked before patching instruction. If actual insn->imm value
4442  * is wrong, bail out with error.
4443  *
4444  * Currently three kinds of BPF instructions are supported:
4445  * 1. rX = <imm> (assignment with immediate operand);
4446  * 2. rX += <imm> (arithmetic operations with immediate operand);
4447  */
4448 static int bpf_core_reloc_insn(struct bpf_program *prog,
4449 			       const struct bpf_field_reloc *relo,
4450 			       int relo_idx,
4451 			       const struct bpf_core_spec *local_spec,
4452 			       const struct bpf_core_spec *targ_spec)
4453 {
4454 	__u32 orig_val, new_val;
4455 	struct bpf_insn *insn;
4456 	bool validate = true;
4457 	int insn_idx, err;
4458 	__u8 class;
4459 
4460 	if (relo->insn_off % sizeof(struct bpf_insn))
4461 		return -EINVAL;
4462 	insn_idx = relo->insn_off / sizeof(struct bpf_insn);
4463 	insn = &prog->insns[insn_idx];
4464 	class = BPF_CLASS(insn->code);
4465 
4466 	if (relo->kind == BPF_FIELD_EXISTS) {
4467 		orig_val = 1; /* can't generate EXISTS relo w/o local field */
4468 		new_val = targ_spec ? 1 : 0;
4469 	} else if (!targ_spec) {
4470 		pr_debug("prog '%s': relo #%d: substituting insn #%d w/ invalid insn\n",
4471 			 bpf_program__title(prog, false), relo_idx, insn_idx);
4472 		insn->code = BPF_JMP | BPF_CALL;
4473 		insn->dst_reg = 0;
4474 		insn->src_reg = 0;
4475 		insn->off = 0;
4476 		/* if this instruction is reachable (not a dead code),
4477 		 * verifier will complain with the following message:
4478 		 * invalid func unknown#195896080
4479 		 */
4480 		insn->imm = 195896080; /* => 0xbad2310 => "bad relo" */
4481 		return 0;
4482 	} else {
4483 		err = bpf_core_calc_field_relo(prog, relo, local_spec,
4484 					       &orig_val, &validate);
4485 		if (err)
4486 			return err;
4487 		err = bpf_core_calc_field_relo(prog, relo, targ_spec,
4488 					       &new_val, NULL);
4489 		if (err)
4490 			return err;
4491 	}
4492 
4493 	switch (class) {
4494 	case BPF_ALU:
4495 	case BPF_ALU64:
4496 		if (BPF_SRC(insn->code) != BPF_K)
4497 			return -EINVAL;
4498 		if (validate && insn->imm != orig_val) {
4499 			pr_warn("prog '%s': relo #%d: unexpected insn #%d (ALU/ALU64) value: got %u, exp %u -> %u\n",
4500 				bpf_program__title(prog, false), relo_idx,
4501 				insn_idx, insn->imm, orig_val, new_val);
4502 			return -EINVAL;
4503 		}
4504 		orig_val = insn->imm;
4505 		insn->imm = new_val;
4506 		pr_debug("prog '%s': relo #%d: patched insn #%d (ALU/ALU64) imm %u -> %u\n",
4507 			 bpf_program__title(prog, false), relo_idx, insn_idx,
4508 			 orig_val, new_val);
4509 		break;
4510 	case BPF_LDX:
4511 	case BPF_ST:
4512 	case BPF_STX:
4513 		if (validate && insn->off != orig_val) {
4514 			pr_warn("prog '%s': relo #%d: unexpected insn #%d (LD/LDX/ST/STX) value: got %u, exp %u -> %u\n",
4515 				bpf_program__title(prog, false), relo_idx,
4516 				insn_idx, insn->off, orig_val, new_val);
4517 			return -EINVAL;
4518 		}
4519 		if (new_val > SHRT_MAX) {
4520 			pr_warn("prog '%s': relo #%d: insn #%d (LDX/ST/STX) value too big: %u\n",
4521 				bpf_program__title(prog, false), relo_idx,
4522 				insn_idx, new_val);
4523 			return -ERANGE;
4524 		}
4525 		orig_val = insn->off;
4526 		insn->off = new_val;
4527 		pr_debug("prog '%s': relo #%d: patched insn #%d (LDX/ST/STX) off %u -> %u\n",
4528 			 bpf_program__title(prog, false), relo_idx, insn_idx,
4529 			 orig_val, new_val);
4530 		break;
4531 	default:
4532 		pr_warn("prog '%s': relo #%d: trying to relocate unrecognized insn #%d, code:%x, src:%x, dst:%x, off:%x, imm:%x\n",
4533 			bpf_program__title(prog, false), relo_idx,
4534 			insn_idx, insn->code, insn->src_reg, insn->dst_reg,
4535 			insn->off, insn->imm);
4536 		return -EINVAL;
4537 	}
4538 
4539 	return 0;
4540 }
4541 
4542 /* Output spec definition in the format:
4543  * [<type-id>] (<type-name>) + <raw-spec> => <offset>@<spec>,
4544  * where <spec> is a C-syntax view of recorded field access, e.g.: x.a[3].b
4545  */
4546 static void bpf_core_dump_spec(int level, const struct bpf_core_spec *spec)
4547 {
4548 	const struct btf_type *t;
4549 	const char *s;
4550 	__u32 type_id;
4551 	int i;
4552 
4553 	type_id = spec->spec[0].type_id;
4554 	t = btf__type_by_id(spec->btf, type_id);
4555 	s = btf__name_by_offset(spec->btf, t->name_off);
4556 	libbpf_print(level, "[%u] %s + ", type_id, s);
4557 
4558 	for (i = 0; i < spec->raw_len; i++)
4559 		libbpf_print(level, "%d%s", spec->raw_spec[i],
4560 			     i == spec->raw_len - 1 ? " => " : ":");
4561 
4562 	libbpf_print(level, "%u.%u @ &x",
4563 		     spec->bit_offset / 8, spec->bit_offset % 8);
4564 
4565 	for (i = 0; i < spec->len; i++) {
4566 		if (spec->spec[i].name)
4567 			libbpf_print(level, ".%s", spec->spec[i].name);
4568 		else
4569 			libbpf_print(level, "[%u]", spec->spec[i].idx);
4570 	}
4571 
4572 }
4573 
4574 static size_t bpf_core_hash_fn(const void *key, void *ctx)
4575 {
4576 	return (size_t)key;
4577 }
4578 
4579 static bool bpf_core_equal_fn(const void *k1, const void *k2, void *ctx)
4580 {
4581 	return k1 == k2;
4582 }
4583 
4584 static void *u32_as_hash_key(__u32 x)
4585 {
4586 	return (void *)(uintptr_t)x;
4587 }
4588 
4589 /*
4590  * CO-RE relocate single instruction.
4591  *
4592  * The outline and important points of the algorithm:
4593  * 1. For given local type, find corresponding candidate target types.
4594  *    Candidate type is a type with the same "essential" name, ignoring
4595  *    everything after last triple underscore (___). E.g., `sample`,
4596  *    `sample___flavor_one`, `sample___flavor_another_one`, are all candidates
4597  *    for each other. Names with triple underscore are referred to as
4598  *    "flavors" and are useful, among other things, to allow to
4599  *    specify/support incompatible variations of the same kernel struct, which
4600  *    might differ between different kernel versions and/or build
4601  *    configurations.
4602  *
4603  *    N.B. Struct "flavors" could be generated by bpftool's BTF-to-C
4604  *    converter, when deduplicated BTF of a kernel still contains more than
4605  *    one different types with the same name. In that case, ___2, ___3, etc
4606  *    are appended starting from second name conflict. But start flavors are
4607  *    also useful to be defined "locally", in BPF program, to extract same
4608  *    data from incompatible changes between different kernel
4609  *    versions/configurations. For instance, to handle field renames between
4610  *    kernel versions, one can use two flavors of the struct name with the
4611  *    same common name and use conditional relocations to extract that field,
4612  *    depending on target kernel version.
4613  * 2. For each candidate type, try to match local specification to this
4614  *    candidate target type. Matching involves finding corresponding
4615  *    high-level spec accessors, meaning that all named fields should match,
4616  *    as well as all array accesses should be within the actual bounds. Also,
4617  *    types should be compatible (see bpf_core_fields_are_compat for details).
4618  * 3. It is supported and expected that there might be multiple flavors
4619  *    matching the spec. As long as all the specs resolve to the same set of
4620  *    offsets across all candidates, there is no error. If there is any
4621  *    ambiguity, CO-RE relocation will fail. This is necessary to accomodate
4622  *    imprefection of BTF deduplication, which can cause slight duplication of
4623  *    the same BTF type, if some directly or indirectly referenced (by
4624  *    pointer) type gets resolved to different actual types in different
4625  *    object files. If such situation occurs, deduplicated BTF will end up
4626  *    with two (or more) structurally identical types, which differ only in
4627  *    types they refer to through pointer. This should be OK in most cases and
4628  *    is not an error.
4629  * 4. Candidate types search is performed by linearly scanning through all
4630  *    types in target BTF. It is anticipated that this is overall more
4631  *    efficient memory-wise and not significantly worse (if not better)
4632  *    CPU-wise compared to prebuilding a map from all local type names to
4633  *    a list of candidate type names. It's also sped up by caching resolved
4634  *    list of matching candidates per each local "root" type ID, that has at
4635  *    least one bpf_field_reloc associated with it. This list is shared
4636  *    between multiple relocations for the same type ID and is updated as some
4637  *    of the candidates are pruned due to structural incompatibility.
4638  */
4639 static int bpf_core_reloc_field(struct bpf_program *prog,
4640 				 const struct bpf_field_reloc *relo,
4641 				 int relo_idx,
4642 				 const struct btf *local_btf,
4643 				 const struct btf *targ_btf,
4644 				 struct hashmap *cand_cache)
4645 {
4646 	const char *prog_name = bpf_program__title(prog, false);
4647 	struct bpf_core_spec local_spec, cand_spec, targ_spec;
4648 	const void *type_key = u32_as_hash_key(relo->type_id);
4649 	const struct btf_type *local_type, *cand_type;
4650 	const char *local_name, *cand_name;
4651 	struct ids_vec *cand_ids;
4652 	__u32 local_id, cand_id;
4653 	const char *spec_str;
4654 	int i, j, err;
4655 
4656 	local_id = relo->type_id;
4657 	local_type = btf__type_by_id(local_btf, local_id);
4658 	if (!local_type)
4659 		return -EINVAL;
4660 
4661 	local_name = btf__name_by_offset(local_btf, local_type->name_off);
4662 	if (str_is_empty(local_name))
4663 		return -EINVAL;
4664 
4665 	spec_str = btf__name_by_offset(local_btf, relo->access_str_off);
4666 	if (str_is_empty(spec_str))
4667 		return -EINVAL;
4668 
4669 	err = bpf_core_spec_parse(local_btf, local_id, spec_str, &local_spec);
4670 	if (err) {
4671 		pr_warn("prog '%s': relo #%d: parsing [%d] %s + %s failed: %d\n",
4672 			prog_name, relo_idx, local_id, local_name, spec_str,
4673 			err);
4674 		return -EINVAL;
4675 	}
4676 
4677 	pr_debug("prog '%s': relo #%d: kind %d, spec is ", prog_name, relo_idx,
4678 		 relo->kind);
4679 	bpf_core_dump_spec(LIBBPF_DEBUG, &local_spec);
4680 	libbpf_print(LIBBPF_DEBUG, "\n");
4681 
4682 	if (!hashmap__find(cand_cache, type_key, (void **)&cand_ids)) {
4683 		cand_ids = bpf_core_find_cands(local_btf, local_id, targ_btf);
4684 		if (IS_ERR(cand_ids)) {
4685 			pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s: %ld",
4686 				prog_name, relo_idx, local_id, local_name,
4687 				PTR_ERR(cand_ids));
4688 			return PTR_ERR(cand_ids);
4689 		}
4690 		err = hashmap__set(cand_cache, type_key, cand_ids, NULL, NULL);
4691 		if (err) {
4692 			bpf_core_free_cands(cand_ids);
4693 			return err;
4694 		}
4695 	}
4696 
4697 	for (i = 0, j = 0; i < cand_ids->len; i++) {
4698 		cand_id = cand_ids->data[i];
4699 		cand_type = btf__type_by_id(targ_btf, cand_id);
4700 		cand_name = btf__name_by_offset(targ_btf, cand_type->name_off);
4701 
4702 		err = bpf_core_spec_match(&local_spec, targ_btf,
4703 					  cand_id, &cand_spec);
4704 		pr_debug("prog '%s': relo #%d: matching candidate #%d %s against spec ",
4705 			 prog_name, relo_idx, i, cand_name);
4706 		bpf_core_dump_spec(LIBBPF_DEBUG, &cand_spec);
4707 		libbpf_print(LIBBPF_DEBUG, ": %d\n", err);
4708 		if (err < 0) {
4709 			pr_warn("prog '%s': relo #%d: matching error: %d\n",
4710 				prog_name, relo_idx, err);
4711 			return err;
4712 		}
4713 		if (err == 0)
4714 			continue;
4715 
4716 		if (j == 0) {
4717 			targ_spec = cand_spec;
4718 		} else if (cand_spec.bit_offset != targ_spec.bit_offset) {
4719 			/* if there are many candidates, they should all
4720 			 * resolve to the same bit offset
4721 			 */
4722 			pr_warn("prog '%s': relo #%d: offset ambiguity: %u != %u\n",
4723 				prog_name, relo_idx, cand_spec.bit_offset,
4724 				targ_spec.bit_offset);
4725 			return -EINVAL;
4726 		}
4727 
4728 		cand_ids->data[j++] = cand_spec.spec[0].type_id;
4729 	}
4730 
4731 	/*
4732 	 * For BPF_FIELD_EXISTS relo or when used BPF program has field
4733 	 * existence checks or kernel version/config checks, it's expected
4734 	 * that we might not find any candidates. In this case, if field
4735 	 * wasn't found in any candidate, the list of candidates shouldn't
4736 	 * change at all, we'll just handle relocating appropriately,
4737 	 * depending on relo's kind.
4738 	 */
4739 	if (j > 0)
4740 		cand_ids->len = j;
4741 
4742 	/*
4743 	 * If no candidates were found, it might be both a programmer error,
4744 	 * as well as expected case, depending whether instruction w/
4745 	 * relocation is guarded in some way that makes it unreachable (dead
4746 	 * code) if relocation can't be resolved. This is handled in
4747 	 * bpf_core_reloc_insn() uniformly by replacing that instruction with
4748 	 * BPF helper call insn (using invalid helper ID). If that instruction
4749 	 * is indeed unreachable, then it will be ignored and eliminated by
4750 	 * verifier. If it was an error, then verifier will complain and point
4751 	 * to a specific instruction number in its log.
4752 	 */
4753 	if (j == 0)
4754 		pr_debug("prog '%s': relo #%d: no matching targets found for [%d] %s + %s\n",
4755 			 prog_name, relo_idx, local_id, local_name, spec_str);
4756 
4757 	/* bpf_core_reloc_insn should know how to handle missing targ_spec */
4758 	err = bpf_core_reloc_insn(prog, relo, relo_idx, &local_spec,
4759 				  j ? &targ_spec : NULL);
4760 	if (err) {
4761 		pr_warn("prog '%s': relo #%d: failed to patch insn at offset %d: %d\n",
4762 			prog_name, relo_idx, relo->insn_off, err);
4763 		return -EINVAL;
4764 	}
4765 
4766 	return 0;
4767 }
4768 
4769 static int
4770 bpf_core_reloc_fields(struct bpf_object *obj, const char *targ_btf_path)
4771 {
4772 	const struct btf_ext_info_sec *sec;
4773 	const struct bpf_field_reloc *rec;
4774 	const struct btf_ext_info *seg;
4775 	struct hashmap_entry *entry;
4776 	struct hashmap *cand_cache = NULL;
4777 	struct bpf_program *prog;
4778 	struct btf *targ_btf;
4779 	const char *sec_name;
4780 	int i, err = 0;
4781 
4782 	if (targ_btf_path)
4783 		targ_btf = btf__parse_elf(targ_btf_path, NULL);
4784 	else
4785 		targ_btf = libbpf_find_kernel_btf();
4786 	if (IS_ERR(targ_btf)) {
4787 		pr_warn("failed to get target BTF: %ld\n", PTR_ERR(targ_btf));
4788 		return PTR_ERR(targ_btf);
4789 	}
4790 
4791 	cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
4792 	if (IS_ERR(cand_cache)) {
4793 		err = PTR_ERR(cand_cache);
4794 		goto out;
4795 	}
4796 
4797 	seg = &obj->btf_ext->field_reloc_info;
4798 	for_each_btf_ext_sec(seg, sec) {
4799 		sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
4800 		if (str_is_empty(sec_name)) {
4801 			err = -EINVAL;
4802 			goto out;
4803 		}
4804 		prog = bpf_object__find_program_by_title(obj, sec_name);
4805 		if (!prog) {
4806 			pr_warn("failed to find program '%s' for CO-RE offset relocation\n",
4807 				sec_name);
4808 			err = -EINVAL;
4809 			goto out;
4810 		}
4811 
4812 		pr_debug("prog '%s': performing %d CO-RE offset relocs\n",
4813 			 sec_name, sec->num_info);
4814 
4815 		for_each_btf_ext_rec(seg, sec, i, rec) {
4816 			err = bpf_core_reloc_field(prog, rec, i, obj->btf,
4817 						   targ_btf, cand_cache);
4818 			if (err) {
4819 				pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
4820 					sec_name, i, err);
4821 				goto out;
4822 			}
4823 		}
4824 	}
4825 
4826 out:
4827 	btf__free(targ_btf);
4828 	if (!IS_ERR_OR_NULL(cand_cache)) {
4829 		hashmap__for_each_entry(cand_cache, entry, i) {
4830 			bpf_core_free_cands(entry->value);
4831 		}
4832 		hashmap__free(cand_cache);
4833 	}
4834 	return err;
4835 }
4836 
4837 static int
4838 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
4839 {
4840 	int err = 0;
4841 
4842 	if (obj->btf_ext->field_reloc_info.len)
4843 		err = bpf_core_reloc_fields(obj, targ_btf_path);
4844 
4845 	return err;
4846 }
4847 
4848 static int
4849 bpf_program__reloc_text(struct bpf_program *prog, struct bpf_object *obj,
4850 			struct reloc_desc *relo)
4851 {
4852 	struct bpf_insn *insn, *new_insn;
4853 	struct bpf_program *text;
4854 	size_t new_cnt;
4855 	int err;
4856 
4857 	if (prog->idx != obj->efile.text_shndx && prog->main_prog_cnt == 0) {
4858 		text = bpf_object__find_prog_by_idx(obj, obj->efile.text_shndx);
4859 		if (!text) {
4860 			pr_warn("no .text section found yet relo into text exist\n");
4861 			return -LIBBPF_ERRNO__RELOC;
4862 		}
4863 		new_cnt = prog->insns_cnt + text->insns_cnt;
4864 		new_insn = reallocarray(prog->insns, new_cnt, sizeof(*insn));
4865 		if (!new_insn) {
4866 			pr_warn("oom in prog realloc\n");
4867 			return -ENOMEM;
4868 		}
4869 		prog->insns = new_insn;
4870 
4871 		if (obj->btf_ext) {
4872 			err = bpf_program_reloc_btf_ext(prog, obj,
4873 							text->section_name,
4874 							prog->insns_cnt);
4875 			if (err)
4876 				return err;
4877 		}
4878 
4879 		memcpy(new_insn + prog->insns_cnt, text->insns,
4880 		       text->insns_cnt * sizeof(*insn));
4881 		prog->main_prog_cnt = prog->insns_cnt;
4882 		prog->insns_cnt = new_cnt;
4883 		pr_debug("added %zd insn from %s to prog %s\n",
4884 			 text->insns_cnt, text->section_name,
4885 			 prog->section_name);
4886 	}
4887 
4888 	insn = &prog->insns[relo->insn_idx];
4889 	insn->imm += relo->sym_off / 8 + prog->main_prog_cnt - relo->insn_idx;
4890 	return 0;
4891 }
4892 
4893 static int
4894 bpf_program__relocate(struct bpf_program *prog, struct bpf_object *obj)
4895 {
4896 	int i, err;
4897 
4898 	if (!prog)
4899 		return 0;
4900 
4901 	if (obj->btf_ext) {
4902 		err = bpf_program_reloc_btf_ext(prog, obj,
4903 						prog->section_name, 0);
4904 		if (err)
4905 			return err;
4906 	}
4907 
4908 	if (!prog->reloc_desc)
4909 		return 0;
4910 
4911 	for (i = 0; i < prog->nr_reloc; i++) {
4912 		struct reloc_desc *relo = &prog->reloc_desc[i];
4913 		struct bpf_insn *insn = &prog->insns[relo->insn_idx];
4914 
4915 		if (relo->insn_idx + 1 >= (int)prog->insns_cnt) {
4916 			pr_warn("relocation out of range: '%s'\n",
4917 				prog->section_name);
4918 			return -LIBBPF_ERRNO__RELOC;
4919 		}
4920 
4921 		switch (relo->type) {
4922 		case RELO_LD64:
4923 			insn[0].src_reg = BPF_PSEUDO_MAP_FD;
4924 			insn[0].imm = obj->maps[relo->map_idx].fd;
4925 			break;
4926 		case RELO_DATA:
4927 			insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
4928 			insn[1].imm = insn[0].imm + relo->sym_off;
4929 			insn[0].imm = obj->maps[relo->map_idx].fd;
4930 			break;
4931 		case RELO_EXTERN:
4932 			insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
4933 			insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
4934 			insn[1].imm = relo->sym_off;
4935 			break;
4936 		case RELO_CALL:
4937 			err = bpf_program__reloc_text(prog, obj, relo);
4938 			if (err)
4939 				return err;
4940 			break;
4941 		default:
4942 			pr_warn("relo #%d: bad relo type %d\n", i, relo->type);
4943 			return -EINVAL;
4944 		}
4945 	}
4946 
4947 	zfree(&prog->reloc_desc);
4948 	prog->nr_reloc = 0;
4949 	return 0;
4950 }
4951 
4952 static int
4953 bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
4954 {
4955 	struct bpf_program *prog;
4956 	size_t i;
4957 	int err;
4958 
4959 	if (obj->btf_ext) {
4960 		err = bpf_object__relocate_core(obj, targ_btf_path);
4961 		if (err) {
4962 			pr_warn("failed to perform CO-RE relocations: %d\n",
4963 				err);
4964 			return err;
4965 		}
4966 	}
4967 	/* ensure .text is relocated first, as it's going to be copied as-is
4968 	 * later for sub-program calls
4969 	 */
4970 	for (i = 0; i < obj->nr_programs; i++) {
4971 		prog = &obj->programs[i];
4972 		if (prog->idx != obj->efile.text_shndx)
4973 			continue;
4974 
4975 		err = bpf_program__relocate(prog, obj);
4976 		if (err) {
4977 			pr_warn("failed to relocate '%s'\n", prog->section_name);
4978 			return err;
4979 		}
4980 		break;
4981 	}
4982 	/* now relocate everything but .text, which by now is relocated
4983 	 * properly, so we can copy raw sub-program instructions as is safely
4984 	 */
4985 	for (i = 0; i < obj->nr_programs; i++) {
4986 		prog = &obj->programs[i];
4987 		if (prog->idx == obj->efile.text_shndx)
4988 			continue;
4989 
4990 		err = bpf_program__relocate(prog, obj);
4991 		if (err) {
4992 			pr_warn("failed to relocate '%s'\n", prog->section_name);
4993 			return err;
4994 		}
4995 	}
4996 	return 0;
4997 }
4998 
4999 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
5000 					    GElf_Shdr *shdr, Elf_Data *data);
5001 
5002 static int bpf_object__collect_map_relos(struct bpf_object *obj,
5003 					 GElf_Shdr *shdr, Elf_Data *data)
5004 {
5005 	int i, j, nrels, new_sz, ptr_sz = sizeof(void *);
5006 	const struct btf_var_secinfo *vi = NULL;
5007 	const struct btf_type *sec, *var, *def;
5008 	const struct btf_member *member;
5009 	struct bpf_map *map, *targ_map;
5010 	const char *name, *mname;
5011 	Elf_Data *symbols;
5012 	unsigned int moff;
5013 	GElf_Sym sym;
5014 	GElf_Rel rel;
5015 	void *tmp;
5016 
5017 	if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
5018 		return -EINVAL;
5019 	sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
5020 	if (!sec)
5021 		return -EINVAL;
5022 
5023 	symbols = obj->efile.symbols;
5024 	nrels = shdr->sh_size / shdr->sh_entsize;
5025 	for (i = 0; i < nrels; i++) {
5026 		if (!gelf_getrel(data, i, &rel)) {
5027 			pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
5028 			return -LIBBPF_ERRNO__FORMAT;
5029 		}
5030 		if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) {
5031 			pr_warn(".maps relo #%d: symbol %zx not found\n",
5032 				i, (size_t)GELF_R_SYM(rel.r_info));
5033 			return -LIBBPF_ERRNO__FORMAT;
5034 		}
5035 		name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
5036 				  sym.st_name) ? : "<?>";
5037 		if (sym.st_shndx != obj->efile.btf_maps_shndx) {
5038 			pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
5039 				i, name);
5040 			return -LIBBPF_ERRNO__RELOC;
5041 		}
5042 
5043 		pr_debug(".maps relo #%d: for %zd value %zd rel.r_offset %zu name %d ('%s')\n",
5044 			 i, (ssize_t)(rel.r_info >> 32), (size_t)sym.st_value,
5045 			 (size_t)rel.r_offset, sym.st_name, name);
5046 
5047 		for (j = 0; j < obj->nr_maps; j++) {
5048 			map = &obj->maps[j];
5049 			if (map->sec_idx != obj->efile.btf_maps_shndx)
5050 				continue;
5051 
5052 			vi = btf_var_secinfos(sec) + map->btf_var_idx;
5053 			if (vi->offset <= rel.r_offset &&
5054 			    rel.r_offset + sizeof(void *) <= vi->offset + vi->size)
5055 				break;
5056 		}
5057 		if (j == obj->nr_maps) {
5058 			pr_warn(".maps relo #%d: cannot find map '%s' at rel.r_offset %zu\n",
5059 				i, name, (size_t)rel.r_offset);
5060 			return -EINVAL;
5061 		}
5062 
5063 		if (!bpf_map_type__is_map_in_map(map->def.type))
5064 			return -EINVAL;
5065 		if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
5066 		    map->def.key_size != sizeof(int)) {
5067 			pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
5068 				i, map->name, sizeof(int));
5069 			return -EINVAL;
5070 		}
5071 
5072 		targ_map = bpf_object__find_map_by_name(obj, name);
5073 		if (!targ_map)
5074 			return -ESRCH;
5075 
5076 		var = btf__type_by_id(obj->btf, vi->type);
5077 		def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
5078 		if (btf_vlen(def) == 0)
5079 			return -EINVAL;
5080 		member = btf_members(def) + btf_vlen(def) - 1;
5081 		mname = btf__name_by_offset(obj->btf, member->name_off);
5082 		if (strcmp(mname, "values"))
5083 			return -EINVAL;
5084 
5085 		moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
5086 		if (rel.r_offset - vi->offset < moff)
5087 			return -EINVAL;
5088 
5089 		moff = rel.r_offset - vi->offset - moff;
5090 		if (moff % ptr_sz)
5091 			return -EINVAL;
5092 		moff /= ptr_sz;
5093 		if (moff >= map->init_slots_sz) {
5094 			new_sz = moff + 1;
5095 			tmp = realloc(map->init_slots, new_sz * ptr_sz);
5096 			if (!tmp)
5097 				return -ENOMEM;
5098 			map->init_slots = tmp;
5099 			memset(map->init_slots + map->init_slots_sz, 0,
5100 			       (new_sz - map->init_slots_sz) * ptr_sz);
5101 			map->init_slots_sz = new_sz;
5102 		}
5103 		map->init_slots[moff] = targ_map;
5104 
5105 		pr_debug(".maps relo #%d: map '%s' slot [%d] points to map '%s'\n",
5106 			 i, map->name, moff, name);
5107 	}
5108 
5109 	return 0;
5110 }
5111 
5112 static int bpf_object__collect_reloc(struct bpf_object *obj)
5113 {
5114 	int i, err;
5115 
5116 	if (!obj_elf_valid(obj)) {
5117 		pr_warn("Internal error: elf object is closed\n");
5118 		return -LIBBPF_ERRNO__INTERNAL;
5119 	}
5120 
5121 	for (i = 0; i < obj->efile.nr_reloc_sects; i++) {
5122 		GElf_Shdr *shdr = &obj->efile.reloc_sects[i].shdr;
5123 		Elf_Data *data = obj->efile.reloc_sects[i].data;
5124 		int idx = shdr->sh_info;
5125 		struct bpf_program *prog;
5126 
5127 		if (shdr->sh_type != SHT_REL) {
5128 			pr_warn("internal error at %d\n", __LINE__);
5129 			return -LIBBPF_ERRNO__INTERNAL;
5130 		}
5131 
5132 		if (idx == obj->efile.st_ops_shndx) {
5133 			err = bpf_object__collect_st_ops_relos(obj, shdr, data);
5134 		} else if (idx == obj->efile.btf_maps_shndx) {
5135 			err = bpf_object__collect_map_relos(obj, shdr, data);
5136 		} else {
5137 			prog = bpf_object__find_prog_by_idx(obj, idx);
5138 			if (!prog) {
5139 				pr_warn("relocation failed: no prog in section(%d)\n", idx);
5140 				return -LIBBPF_ERRNO__RELOC;
5141 			}
5142 			err = bpf_program__collect_reloc(prog, shdr, data, obj);
5143 		}
5144 		if (err)
5145 			return err;
5146 	}
5147 	return 0;
5148 }
5149 
5150 static int
5151 load_program(struct bpf_program *prog, struct bpf_insn *insns, int insns_cnt,
5152 	     char *license, __u32 kern_version, int *pfd)
5153 {
5154 	struct bpf_load_program_attr load_attr;
5155 	char *cp, errmsg[STRERR_BUFSIZE];
5156 	size_t log_buf_size = 0;
5157 	char *log_buf = NULL;
5158 	int btf_fd, ret;
5159 
5160 	if (!insns || !insns_cnt)
5161 		return -EINVAL;
5162 
5163 	memset(&load_attr, 0, sizeof(struct bpf_load_program_attr));
5164 	load_attr.prog_type = prog->type;
5165 	/* old kernels might not support specifying expected_attach_type */
5166 	if (!prog->caps->exp_attach_type && prog->sec_def &&
5167 	    prog->sec_def->is_exp_attach_type_optional)
5168 		load_attr.expected_attach_type = 0;
5169 	else
5170 		load_attr.expected_attach_type = prog->expected_attach_type;
5171 	if (prog->caps->name)
5172 		load_attr.name = prog->name;
5173 	load_attr.insns = insns;
5174 	load_attr.insns_cnt = insns_cnt;
5175 	load_attr.license = license;
5176 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
5177 	    prog->type == BPF_PROG_TYPE_LSM) {
5178 		load_attr.attach_btf_id = prog->attach_btf_id;
5179 	} else if (prog->type == BPF_PROG_TYPE_TRACING ||
5180 		   prog->type == BPF_PROG_TYPE_EXT) {
5181 		load_attr.attach_prog_fd = prog->attach_prog_fd;
5182 		load_attr.attach_btf_id = prog->attach_btf_id;
5183 	} else {
5184 		load_attr.kern_version = kern_version;
5185 		load_attr.prog_ifindex = prog->prog_ifindex;
5186 	}
5187 	/* if .BTF.ext was loaded, kernel supports associated BTF for prog */
5188 	if (prog->obj->btf_ext)
5189 		btf_fd = bpf_object__btf_fd(prog->obj);
5190 	else
5191 		btf_fd = -1;
5192 	load_attr.prog_btf_fd = btf_fd >= 0 ? btf_fd : 0;
5193 	load_attr.func_info = prog->func_info;
5194 	load_attr.func_info_rec_size = prog->func_info_rec_size;
5195 	load_attr.func_info_cnt = prog->func_info_cnt;
5196 	load_attr.line_info = prog->line_info;
5197 	load_attr.line_info_rec_size = prog->line_info_rec_size;
5198 	load_attr.line_info_cnt = prog->line_info_cnt;
5199 	load_attr.log_level = prog->log_level;
5200 	load_attr.prog_flags = prog->prog_flags;
5201 
5202 retry_load:
5203 	if (log_buf_size) {
5204 		log_buf = malloc(log_buf_size);
5205 		if (!log_buf)
5206 			return -ENOMEM;
5207 
5208 		*log_buf = 0;
5209 	}
5210 
5211 	ret = bpf_load_program_xattr(&load_attr, log_buf, log_buf_size);
5212 
5213 	if (ret >= 0) {
5214 		if (log_buf && load_attr.log_level)
5215 			pr_debug("verifier log:\n%s", log_buf);
5216 		*pfd = ret;
5217 		ret = 0;
5218 		goto out;
5219 	}
5220 
5221 	if (!log_buf || errno == ENOSPC) {
5222 		log_buf_size = max((size_t)BPF_LOG_BUF_SIZE,
5223 				   log_buf_size << 1);
5224 
5225 		free(log_buf);
5226 		goto retry_load;
5227 	}
5228 	ret = -errno;
5229 	cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
5230 	pr_warn("load bpf program failed: %s\n", cp);
5231 	pr_perm_msg(ret);
5232 
5233 	if (log_buf && log_buf[0] != '\0') {
5234 		ret = -LIBBPF_ERRNO__VERIFY;
5235 		pr_warn("-- BEGIN DUMP LOG ---\n");
5236 		pr_warn("\n%s\n", log_buf);
5237 		pr_warn("-- END LOG --\n");
5238 	} else if (load_attr.insns_cnt >= BPF_MAXINSNS) {
5239 		pr_warn("Program too large (%zu insns), at most %d insns\n",
5240 			load_attr.insns_cnt, BPF_MAXINSNS);
5241 		ret = -LIBBPF_ERRNO__PROG2BIG;
5242 	} else if (load_attr.prog_type != BPF_PROG_TYPE_KPROBE) {
5243 		/* Wrong program type? */
5244 		int fd;
5245 
5246 		load_attr.prog_type = BPF_PROG_TYPE_KPROBE;
5247 		load_attr.expected_attach_type = 0;
5248 		fd = bpf_load_program_xattr(&load_attr, NULL, 0);
5249 		if (fd >= 0) {
5250 			close(fd);
5251 			ret = -LIBBPF_ERRNO__PROGTYPE;
5252 			goto out;
5253 		}
5254 	}
5255 
5256 out:
5257 	free(log_buf);
5258 	return ret;
5259 }
5260 
5261 static int libbpf_find_attach_btf_id(struct bpf_program *prog);
5262 
5263 int bpf_program__load(struct bpf_program *prog, char *license, __u32 kern_ver)
5264 {
5265 	int err = 0, fd, i, btf_id;
5266 
5267 	if ((prog->type == BPF_PROG_TYPE_TRACING ||
5268 	     prog->type == BPF_PROG_TYPE_LSM ||
5269 	     prog->type == BPF_PROG_TYPE_EXT) && !prog->attach_btf_id) {
5270 		btf_id = libbpf_find_attach_btf_id(prog);
5271 		if (btf_id <= 0)
5272 			return btf_id;
5273 		prog->attach_btf_id = btf_id;
5274 	}
5275 
5276 	if (prog->instances.nr < 0 || !prog->instances.fds) {
5277 		if (prog->preprocessor) {
5278 			pr_warn("Internal error: can't load program '%s'\n",
5279 				prog->section_name);
5280 			return -LIBBPF_ERRNO__INTERNAL;
5281 		}
5282 
5283 		prog->instances.fds = malloc(sizeof(int));
5284 		if (!prog->instances.fds) {
5285 			pr_warn("Not enough memory for BPF fds\n");
5286 			return -ENOMEM;
5287 		}
5288 		prog->instances.nr = 1;
5289 		prog->instances.fds[0] = -1;
5290 	}
5291 
5292 	if (!prog->preprocessor) {
5293 		if (prog->instances.nr != 1) {
5294 			pr_warn("Program '%s' is inconsistent: nr(%d) != 1\n",
5295 				prog->section_name, prog->instances.nr);
5296 		}
5297 		err = load_program(prog, prog->insns, prog->insns_cnt,
5298 				   license, kern_ver, &fd);
5299 		if (!err)
5300 			prog->instances.fds[0] = fd;
5301 		goto out;
5302 	}
5303 
5304 	for (i = 0; i < prog->instances.nr; i++) {
5305 		struct bpf_prog_prep_result result;
5306 		bpf_program_prep_t preprocessor = prog->preprocessor;
5307 
5308 		memset(&result, 0, sizeof(result));
5309 		err = preprocessor(prog, i, prog->insns,
5310 				   prog->insns_cnt, &result);
5311 		if (err) {
5312 			pr_warn("Preprocessing the %dth instance of program '%s' failed\n",
5313 				i, prog->section_name);
5314 			goto out;
5315 		}
5316 
5317 		if (!result.new_insn_ptr || !result.new_insn_cnt) {
5318 			pr_debug("Skip loading the %dth instance of program '%s'\n",
5319 				 i, prog->section_name);
5320 			prog->instances.fds[i] = -1;
5321 			if (result.pfd)
5322 				*result.pfd = -1;
5323 			continue;
5324 		}
5325 
5326 		err = load_program(prog, result.new_insn_ptr,
5327 				   result.new_insn_cnt, license, kern_ver, &fd);
5328 		if (err) {
5329 			pr_warn("Loading the %dth instance of program '%s' failed\n",
5330 				i, prog->section_name);
5331 			goto out;
5332 		}
5333 
5334 		if (result.pfd)
5335 			*result.pfd = fd;
5336 		prog->instances.fds[i] = fd;
5337 	}
5338 out:
5339 	if (err)
5340 		pr_warn("failed to load program '%s'\n", prog->section_name);
5341 	zfree(&prog->insns);
5342 	prog->insns_cnt = 0;
5343 	return err;
5344 }
5345 
5346 static bool bpf_program__is_function_storage(const struct bpf_program *prog,
5347 					     const struct bpf_object *obj)
5348 {
5349 	return prog->idx == obj->efile.text_shndx && obj->has_pseudo_calls;
5350 }
5351 
5352 static int
5353 bpf_object__load_progs(struct bpf_object *obj, int log_level)
5354 {
5355 	size_t i;
5356 	int err;
5357 
5358 	for (i = 0; i < obj->nr_programs; i++) {
5359 		if (bpf_program__is_function_storage(&obj->programs[i], obj))
5360 			continue;
5361 		obj->programs[i].log_level |= log_level;
5362 		err = bpf_program__load(&obj->programs[i],
5363 					obj->license,
5364 					obj->kern_version);
5365 		if (err)
5366 			return err;
5367 	}
5368 	return 0;
5369 }
5370 
5371 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
5372 
5373 static struct bpf_object *
5374 __bpf_object__open(const char *path, const void *obj_buf, size_t obj_buf_sz,
5375 		   const struct bpf_object_open_opts *opts)
5376 {
5377 	const char *obj_name, *kconfig;
5378 	struct bpf_program *prog;
5379 	struct bpf_object *obj;
5380 	char tmp_name[64];
5381 	int err;
5382 
5383 	if (elf_version(EV_CURRENT) == EV_NONE) {
5384 		pr_warn("failed to init libelf for %s\n",
5385 			path ? : "(mem buf)");
5386 		return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
5387 	}
5388 
5389 	if (!OPTS_VALID(opts, bpf_object_open_opts))
5390 		return ERR_PTR(-EINVAL);
5391 
5392 	obj_name = OPTS_GET(opts, object_name, NULL);
5393 	if (obj_buf) {
5394 		if (!obj_name) {
5395 			snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
5396 				 (unsigned long)obj_buf,
5397 				 (unsigned long)obj_buf_sz);
5398 			obj_name = tmp_name;
5399 		}
5400 		path = obj_name;
5401 		pr_debug("loading object '%s' from buffer\n", obj_name);
5402 	}
5403 
5404 	obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
5405 	if (IS_ERR(obj))
5406 		return obj;
5407 
5408 	kconfig = OPTS_GET(opts, kconfig, NULL);
5409 	if (kconfig) {
5410 		obj->kconfig = strdup(kconfig);
5411 		if (!obj->kconfig)
5412 			return ERR_PTR(-ENOMEM);
5413 	}
5414 
5415 	err = bpf_object__elf_init(obj);
5416 	err = err ? : bpf_object__check_endianness(obj);
5417 	err = err ? : bpf_object__elf_collect(obj);
5418 	err = err ? : bpf_object__collect_externs(obj);
5419 	err = err ? : bpf_object__finalize_btf(obj);
5420 	err = err ? : bpf_object__init_maps(obj, opts);
5421 	err = err ? : bpf_object__init_prog_names(obj);
5422 	err = err ? : bpf_object__collect_reloc(obj);
5423 	if (err)
5424 		goto out;
5425 	bpf_object__elf_finish(obj);
5426 
5427 	bpf_object__for_each_program(prog, obj) {
5428 		prog->sec_def = find_sec_def(prog->section_name);
5429 		if (!prog->sec_def)
5430 			/* couldn't guess, but user might manually specify */
5431 			continue;
5432 
5433 		bpf_program__set_type(prog, prog->sec_def->prog_type);
5434 		bpf_program__set_expected_attach_type(prog,
5435 				prog->sec_def->expected_attach_type);
5436 
5437 		if (prog->sec_def->prog_type == BPF_PROG_TYPE_TRACING ||
5438 		    prog->sec_def->prog_type == BPF_PROG_TYPE_EXT)
5439 			prog->attach_prog_fd = OPTS_GET(opts, attach_prog_fd, 0);
5440 	}
5441 
5442 	return obj;
5443 out:
5444 	bpf_object__close(obj);
5445 	return ERR_PTR(err);
5446 }
5447 
5448 static struct bpf_object *
5449 __bpf_object__open_xattr(struct bpf_object_open_attr *attr, int flags)
5450 {
5451 	DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
5452 		.relaxed_maps = flags & MAPS_RELAX_COMPAT,
5453 	);
5454 
5455 	/* param validation */
5456 	if (!attr->file)
5457 		return NULL;
5458 
5459 	pr_debug("loading %s\n", attr->file);
5460 	return __bpf_object__open(attr->file, NULL, 0, &opts);
5461 }
5462 
5463 struct bpf_object *bpf_object__open_xattr(struct bpf_object_open_attr *attr)
5464 {
5465 	return __bpf_object__open_xattr(attr, 0);
5466 }
5467 
5468 struct bpf_object *bpf_object__open(const char *path)
5469 {
5470 	struct bpf_object_open_attr attr = {
5471 		.file		= path,
5472 		.prog_type	= BPF_PROG_TYPE_UNSPEC,
5473 	};
5474 
5475 	return bpf_object__open_xattr(&attr);
5476 }
5477 
5478 struct bpf_object *
5479 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
5480 {
5481 	if (!path)
5482 		return ERR_PTR(-EINVAL);
5483 
5484 	pr_debug("loading %s\n", path);
5485 
5486 	return __bpf_object__open(path, NULL, 0, opts);
5487 }
5488 
5489 struct bpf_object *
5490 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
5491 		     const struct bpf_object_open_opts *opts)
5492 {
5493 	if (!obj_buf || obj_buf_sz == 0)
5494 		return ERR_PTR(-EINVAL);
5495 
5496 	return __bpf_object__open(NULL, obj_buf, obj_buf_sz, opts);
5497 }
5498 
5499 struct bpf_object *
5500 bpf_object__open_buffer(const void *obj_buf, size_t obj_buf_sz,
5501 			const char *name)
5502 {
5503 	DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
5504 		.object_name = name,
5505 		/* wrong default, but backwards-compatible */
5506 		.relaxed_maps = true,
5507 	);
5508 
5509 	/* returning NULL is wrong, but backwards-compatible */
5510 	if (!obj_buf || obj_buf_sz == 0)
5511 		return NULL;
5512 
5513 	return bpf_object__open_mem(obj_buf, obj_buf_sz, &opts);
5514 }
5515 
5516 int bpf_object__unload(struct bpf_object *obj)
5517 {
5518 	size_t i;
5519 
5520 	if (!obj)
5521 		return -EINVAL;
5522 
5523 	for (i = 0; i < obj->nr_maps; i++) {
5524 		zclose(obj->maps[i].fd);
5525 		if (obj->maps[i].st_ops)
5526 			zfree(&obj->maps[i].st_ops->kern_vdata);
5527 	}
5528 
5529 	for (i = 0; i < obj->nr_programs; i++)
5530 		bpf_program__unload(&obj->programs[i]);
5531 
5532 	return 0;
5533 }
5534 
5535 static int bpf_object__sanitize_maps(struct bpf_object *obj)
5536 {
5537 	struct bpf_map *m;
5538 
5539 	bpf_object__for_each_map(m, obj) {
5540 		if (!bpf_map__is_internal(m))
5541 			continue;
5542 		if (!obj->caps.global_data) {
5543 			pr_warn("kernel doesn't support global data\n");
5544 			return -ENOTSUP;
5545 		}
5546 		if (!obj->caps.array_mmap)
5547 			m->def.map_flags ^= BPF_F_MMAPABLE;
5548 	}
5549 
5550 	return 0;
5551 }
5552 
5553 static int bpf_object__resolve_externs(struct bpf_object *obj,
5554 				       const char *extra_kconfig)
5555 {
5556 	bool need_config = false;
5557 	struct extern_desc *ext;
5558 	int err, i;
5559 	void *data;
5560 
5561 	if (obj->nr_extern == 0)
5562 		return 0;
5563 
5564 	data = obj->maps[obj->kconfig_map_idx].mmaped;
5565 
5566 	for (i = 0; i < obj->nr_extern; i++) {
5567 		ext = &obj->externs[i];
5568 
5569 		if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
5570 			void *ext_val = data + ext->data_off;
5571 			__u32 kver = get_kernel_version();
5572 
5573 			if (!kver) {
5574 				pr_warn("failed to get kernel version\n");
5575 				return -EINVAL;
5576 			}
5577 			err = set_ext_value_num(ext, ext_val, kver);
5578 			if (err)
5579 				return err;
5580 			pr_debug("extern %s=0x%x\n", ext->name, kver);
5581 		} else if (strncmp(ext->name, "CONFIG_", 7) == 0) {
5582 			need_config = true;
5583 		} else {
5584 			pr_warn("unrecognized extern '%s'\n", ext->name);
5585 			return -EINVAL;
5586 		}
5587 	}
5588 	if (need_config && extra_kconfig) {
5589 		err = bpf_object__read_kconfig_mem(obj, extra_kconfig, data);
5590 		if (err)
5591 			return -EINVAL;
5592 		need_config = false;
5593 		for (i = 0; i < obj->nr_extern; i++) {
5594 			ext = &obj->externs[i];
5595 			if (!ext->is_set) {
5596 				need_config = true;
5597 				break;
5598 			}
5599 		}
5600 	}
5601 	if (need_config) {
5602 		err = bpf_object__read_kconfig_file(obj, data);
5603 		if (err)
5604 			return -EINVAL;
5605 	}
5606 	for (i = 0; i < obj->nr_extern; i++) {
5607 		ext = &obj->externs[i];
5608 
5609 		if (!ext->is_set && !ext->is_weak) {
5610 			pr_warn("extern %s (strong) not resolved\n", ext->name);
5611 			return -ESRCH;
5612 		} else if (!ext->is_set) {
5613 			pr_debug("extern %s (weak) not resolved, defaulting to zero\n",
5614 				 ext->name);
5615 		}
5616 	}
5617 
5618 	return 0;
5619 }
5620 
5621 int bpf_object__load_xattr(struct bpf_object_load_attr *attr)
5622 {
5623 	struct bpf_object *obj;
5624 	int err, i;
5625 
5626 	if (!attr)
5627 		return -EINVAL;
5628 	obj = attr->obj;
5629 	if (!obj)
5630 		return -EINVAL;
5631 
5632 	if (obj->loaded) {
5633 		pr_warn("object should not be loaded twice\n");
5634 		return -EINVAL;
5635 	}
5636 
5637 	obj->loaded = true;
5638 
5639 	err = bpf_object__probe_caps(obj);
5640 	err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
5641 	err = err ? : bpf_object__sanitize_and_load_btf(obj);
5642 	err = err ? : bpf_object__sanitize_maps(obj);
5643 	err = err ? : bpf_object__load_vmlinux_btf(obj);
5644 	err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
5645 	err = err ? : bpf_object__create_maps(obj);
5646 	err = err ? : bpf_object__relocate(obj, attr->target_btf_path);
5647 	err = err ? : bpf_object__load_progs(obj, attr->log_level);
5648 
5649 	btf__free(obj->btf_vmlinux);
5650 	obj->btf_vmlinux = NULL;
5651 
5652 	if (err)
5653 		goto out;
5654 
5655 	return 0;
5656 out:
5657 	/* unpin any maps that were auto-pinned during load */
5658 	for (i = 0; i < obj->nr_maps; i++)
5659 		if (obj->maps[i].pinned && !obj->maps[i].reused)
5660 			bpf_map__unpin(&obj->maps[i], NULL);
5661 
5662 	bpf_object__unload(obj);
5663 	pr_warn("failed to load object '%s'\n", obj->path);
5664 	return err;
5665 }
5666 
5667 int bpf_object__load(struct bpf_object *obj)
5668 {
5669 	struct bpf_object_load_attr attr = {
5670 		.obj = obj,
5671 	};
5672 
5673 	return bpf_object__load_xattr(&attr);
5674 }
5675 
5676 static int make_parent_dir(const char *path)
5677 {
5678 	char *cp, errmsg[STRERR_BUFSIZE];
5679 	char *dname, *dir;
5680 	int err = 0;
5681 
5682 	dname = strdup(path);
5683 	if (dname == NULL)
5684 		return -ENOMEM;
5685 
5686 	dir = dirname(dname);
5687 	if (mkdir(dir, 0700) && errno != EEXIST)
5688 		err = -errno;
5689 
5690 	free(dname);
5691 	if (err) {
5692 		cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
5693 		pr_warn("failed to mkdir %s: %s\n", path, cp);
5694 	}
5695 	return err;
5696 }
5697 
5698 static int check_path(const char *path)
5699 {
5700 	char *cp, errmsg[STRERR_BUFSIZE];
5701 	struct statfs st_fs;
5702 	char *dname, *dir;
5703 	int err = 0;
5704 
5705 	if (path == NULL)
5706 		return -EINVAL;
5707 
5708 	dname = strdup(path);
5709 	if (dname == NULL)
5710 		return -ENOMEM;
5711 
5712 	dir = dirname(dname);
5713 	if (statfs(dir, &st_fs)) {
5714 		cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
5715 		pr_warn("failed to statfs %s: %s\n", dir, cp);
5716 		err = -errno;
5717 	}
5718 	free(dname);
5719 
5720 	if (!err && st_fs.f_type != BPF_FS_MAGIC) {
5721 		pr_warn("specified path %s is not on BPF FS\n", path);
5722 		err = -EINVAL;
5723 	}
5724 
5725 	return err;
5726 }
5727 
5728 int bpf_program__pin_instance(struct bpf_program *prog, const char *path,
5729 			      int instance)
5730 {
5731 	char *cp, errmsg[STRERR_BUFSIZE];
5732 	int err;
5733 
5734 	err = make_parent_dir(path);
5735 	if (err)
5736 		return err;
5737 
5738 	err = check_path(path);
5739 	if (err)
5740 		return err;
5741 
5742 	if (prog == NULL) {
5743 		pr_warn("invalid program pointer\n");
5744 		return -EINVAL;
5745 	}
5746 
5747 	if (instance < 0 || instance >= prog->instances.nr) {
5748 		pr_warn("invalid prog instance %d of prog %s (max %d)\n",
5749 			instance, prog->section_name, prog->instances.nr);
5750 		return -EINVAL;
5751 	}
5752 
5753 	if (bpf_obj_pin(prog->instances.fds[instance], path)) {
5754 		cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
5755 		pr_warn("failed to pin program: %s\n", cp);
5756 		return -errno;
5757 	}
5758 	pr_debug("pinned program '%s'\n", path);
5759 
5760 	return 0;
5761 }
5762 
5763 int bpf_program__unpin_instance(struct bpf_program *prog, const char *path,
5764 				int instance)
5765 {
5766 	int err;
5767 
5768 	err = check_path(path);
5769 	if (err)
5770 		return err;
5771 
5772 	if (prog == NULL) {
5773 		pr_warn("invalid program pointer\n");
5774 		return -EINVAL;
5775 	}
5776 
5777 	if (instance < 0 || instance >= prog->instances.nr) {
5778 		pr_warn("invalid prog instance %d of prog %s (max %d)\n",
5779 			instance, prog->section_name, prog->instances.nr);
5780 		return -EINVAL;
5781 	}
5782 
5783 	err = unlink(path);
5784 	if (err != 0)
5785 		return -errno;
5786 	pr_debug("unpinned program '%s'\n", path);
5787 
5788 	return 0;
5789 }
5790 
5791 int bpf_program__pin(struct bpf_program *prog, const char *path)
5792 {
5793 	int i, err;
5794 
5795 	err = make_parent_dir(path);
5796 	if (err)
5797 		return err;
5798 
5799 	err = check_path(path);
5800 	if (err)
5801 		return err;
5802 
5803 	if (prog == NULL) {
5804 		pr_warn("invalid program pointer\n");
5805 		return -EINVAL;
5806 	}
5807 
5808 	if (prog->instances.nr <= 0) {
5809 		pr_warn("no instances of prog %s to pin\n",
5810 			   prog->section_name);
5811 		return -EINVAL;
5812 	}
5813 
5814 	if (prog->instances.nr == 1) {
5815 		/* don't create subdirs when pinning single instance */
5816 		return bpf_program__pin_instance(prog, path, 0);
5817 	}
5818 
5819 	for (i = 0; i < prog->instances.nr; i++) {
5820 		char buf[PATH_MAX];
5821 		int len;
5822 
5823 		len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
5824 		if (len < 0) {
5825 			err = -EINVAL;
5826 			goto err_unpin;
5827 		} else if (len >= PATH_MAX) {
5828 			err = -ENAMETOOLONG;
5829 			goto err_unpin;
5830 		}
5831 
5832 		err = bpf_program__pin_instance(prog, buf, i);
5833 		if (err)
5834 			goto err_unpin;
5835 	}
5836 
5837 	return 0;
5838 
5839 err_unpin:
5840 	for (i = i - 1; i >= 0; i--) {
5841 		char buf[PATH_MAX];
5842 		int len;
5843 
5844 		len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
5845 		if (len < 0)
5846 			continue;
5847 		else if (len >= PATH_MAX)
5848 			continue;
5849 
5850 		bpf_program__unpin_instance(prog, buf, i);
5851 	}
5852 
5853 	rmdir(path);
5854 
5855 	return err;
5856 }
5857 
5858 int bpf_program__unpin(struct bpf_program *prog, const char *path)
5859 {
5860 	int i, err;
5861 
5862 	err = check_path(path);
5863 	if (err)
5864 		return err;
5865 
5866 	if (prog == NULL) {
5867 		pr_warn("invalid program pointer\n");
5868 		return -EINVAL;
5869 	}
5870 
5871 	if (prog->instances.nr <= 0) {
5872 		pr_warn("no instances of prog %s to pin\n",
5873 			   prog->section_name);
5874 		return -EINVAL;
5875 	}
5876 
5877 	if (prog->instances.nr == 1) {
5878 		/* don't create subdirs when pinning single instance */
5879 		return bpf_program__unpin_instance(prog, path, 0);
5880 	}
5881 
5882 	for (i = 0; i < prog->instances.nr; i++) {
5883 		char buf[PATH_MAX];
5884 		int len;
5885 
5886 		len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
5887 		if (len < 0)
5888 			return -EINVAL;
5889 		else if (len >= PATH_MAX)
5890 			return -ENAMETOOLONG;
5891 
5892 		err = bpf_program__unpin_instance(prog, buf, i);
5893 		if (err)
5894 			return err;
5895 	}
5896 
5897 	err = rmdir(path);
5898 	if (err)
5899 		return -errno;
5900 
5901 	return 0;
5902 }
5903 
5904 int bpf_map__pin(struct bpf_map *map, const char *path)
5905 {
5906 	char *cp, errmsg[STRERR_BUFSIZE];
5907 	int err;
5908 
5909 	if (map == NULL) {
5910 		pr_warn("invalid map pointer\n");
5911 		return -EINVAL;
5912 	}
5913 
5914 	if (map->pin_path) {
5915 		if (path && strcmp(path, map->pin_path)) {
5916 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
5917 				bpf_map__name(map), map->pin_path, path);
5918 			return -EINVAL;
5919 		} else if (map->pinned) {
5920 			pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
5921 				 bpf_map__name(map), map->pin_path);
5922 			return 0;
5923 		}
5924 	} else {
5925 		if (!path) {
5926 			pr_warn("missing a path to pin map '%s' at\n",
5927 				bpf_map__name(map));
5928 			return -EINVAL;
5929 		} else if (map->pinned) {
5930 			pr_warn("map '%s' already pinned\n", bpf_map__name(map));
5931 			return -EEXIST;
5932 		}
5933 
5934 		map->pin_path = strdup(path);
5935 		if (!map->pin_path) {
5936 			err = -errno;
5937 			goto out_err;
5938 		}
5939 	}
5940 
5941 	err = make_parent_dir(map->pin_path);
5942 	if (err)
5943 		return err;
5944 
5945 	err = check_path(map->pin_path);
5946 	if (err)
5947 		return err;
5948 
5949 	if (bpf_obj_pin(map->fd, map->pin_path)) {
5950 		err = -errno;
5951 		goto out_err;
5952 	}
5953 
5954 	map->pinned = true;
5955 	pr_debug("pinned map '%s'\n", map->pin_path);
5956 
5957 	return 0;
5958 
5959 out_err:
5960 	cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
5961 	pr_warn("failed to pin map: %s\n", cp);
5962 	return err;
5963 }
5964 
5965 int bpf_map__unpin(struct bpf_map *map, const char *path)
5966 {
5967 	int err;
5968 
5969 	if (map == NULL) {
5970 		pr_warn("invalid map pointer\n");
5971 		return -EINVAL;
5972 	}
5973 
5974 	if (map->pin_path) {
5975 		if (path && strcmp(path, map->pin_path)) {
5976 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
5977 				bpf_map__name(map), map->pin_path, path);
5978 			return -EINVAL;
5979 		}
5980 		path = map->pin_path;
5981 	} else if (!path) {
5982 		pr_warn("no path to unpin map '%s' from\n",
5983 			bpf_map__name(map));
5984 		return -EINVAL;
5985 	}
5986 
5987 	err = check_path(path);
5988 	if (err)
5989 		return err;
5990 
5991 	err = unlink(path);
5992 	if (err != 0)
5993 		return -errno;
5994 
5995 	map->pinned = false;
5996 	pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
5997 
5998 	return 0;
5999 }
6000 
6001 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
6002 {
6003 	char *new = NULL;
6004 
6005 	if (path) {
6006 		new = strdup(path);
6007 		if (!new)
6008 			return -errno;
6009 	}
6010 
6011 	free(map->pin_path);
6012 	map->pin_path = new;
6013 	return 0;
6014 }
6015 
6016 const char *bpf_map__get_pin_path(const struct bpf_map *map)
6017 {
6018 	return map->pin_path;
6019 }
6020 
6021 bool bpf_map__is_pinned(const struct bpf_map *map)
6022 {
6023 	return map->pinned;
6024 }
6025 
6026 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
6027 {
6028 	struct bpf_map *map;
6029 	int err;
6030 
6031 	if (!obj)
6032 		return -ENOENT;
6033 
6034 	if (!obj->loaded) {
6035 		pr_warn("object not yet loaded; load it first\n");
6036 		return -ENOENT;
6037 	}
6038 
6039 	bpf_object__for_each_map(map, obj) {
6040 		char *pin_path = NULL;
6041 		char buf[PATH_MAX];
6042 
6043 		if (path) {
6044 			int len;
6045 
6046 			len = snprintf(buf, PATH_MAX, "%s/%s", path,
6047 				       bpf_map__name(map));
6048 			if (len < 0) {
6049 				err = -EINVAL;
6050 				goto err_unpin_maps;
6051 			} else if (len >= PATH_MAX) {
6052 				err = -ENAMETOOLONG;
6053 				goto err_unpin_maps;
6054 			}
6055 			pin_path = buf;
6056 		} else if (!map->pin_path) {
6057 			continue;
6058 		}
6059 
6060 		err = bpf_map__pin(map, pin_path);
6061 		if (err)
6062 			goto err_unpin_maps;
6063 	}
6064 
6065 	return 0;
6066 
6067 err_unpin_maps:
6068 	while ((map = bpf_map__prev(map, obj))) {
6069 		if (!map->pin_path)
6070 			continue;
6071 
6072 		bpf_map__unpin(map, NULL);
6073 	}
6074 
6075 	return err;
6076 }
6077 
6078 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
6079 {
6080 	struct bpf_map *map;
6081 	int err;
6082 
6083 	if (!obj)
6084 		return -ENOENT;
6085 
6086 	bpf_object__for_each_map(map, obj) {
6087 		char *pin_path = NULL;
6088 		char buf[PATH_MAX];
6089 
6090 		if (path) {
6091 			int len;
6092 
6093 			len = snprintf(buf, PATH_MAX, "%s/%s", path,
6094 				       bpf_map__name(map));
6095 			if (len < 0)
6096 				return -EINVAL;
6097 			else if (len >= PATH_MAX)
6098 				return -ENAMETOOLONG;
6099 			pin_path = buf;
6100 		} else if (!map->pin_path) {
6101 			continue;
6102 		}
6103 
6104 		err = bpf_map__unpin(map, pin_path);
6105 		if (err)
6106 			return err;
6107 	}
6108 
6109 	return 0;
6110 }
6111 
6112 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
6113 {
6114 	struct bpf_program *prog;
6115 	int err;
6116 
6117 	if (!obj)
6118 		return -ENOENT;
6119 
6120 	if (!obj->loaded) {
6121 		pr_warn("object not yet loaded; load it first\n");
6122 		return -ENOENT;
6123 	}
6124 
6125 	bpf_object__for_each_program(prog, obj) {
6126 		char buf[PATH_MAX];
6127 		int len;
6128 
6129 		len = snprintf(buf, PATH_MAX, "%s/%s", path,
6130 			       prog->pin_name);
6131 		if (len < 0) {
6132 			err = -EINVAL;
6133 			goto err_unpin_programs;
6134 		} else if (len >= PATH_MAX) {
6135 			err = -ENAMETOOLONG;
6136 			goto err_unpin_programs;
6137 		}
6138 
6139 		err = bpf_program__pin(prog, buf);
6140 		if (err)
6141 			goto err_unpin_programs;
6142 	}
6143 
6144 	return 0;
6145 
6146 err_unpin_programs:
6147 	while ((prog = bpf_program__prev(prog, obj))) {
6148 		char buf[PATH_MAX];
6149 		int len;
6150 
6151 		len = snprintf(buf, PATH_MAX, "%s/%s", path,
6152 			       prog->pin_name);
6153 		if (len < 0)
6154 			continue;
6155 		else if (len >= PATH_MAX)
6156 			continue;
6157 
6158 		bpf_program__unpin(prog, buf);
6159 	}
6160 
6161 	return err;
6162 }
6163 
6164 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
6165 {
6166 	struct bpf_program *prog;
6167 	int err;
6168 
6169 	if (!obj)
6170 		return -ENOENT;
6171 
6172 	bpf_object__for_each_program(prog, obj) {
6173 		char buf[PATH_MAX];
6174 		int len;
6175 
6176 		len = snprintf(buf, PATH_MAX, "%s/%s", path,
6177 			       prog->pin_name);
6178 		if (len < 0)
6179 			return -EINVAL;
6180 		else if (len >= PATH_MAX)
6181 			return -ENAMETOOLONG;
6182 
6183 		err = bpf_program__unpin(prog, buf);
6184 		if (err)
6185 			return err;
6186 	}
6187 
6188 	return 0;
6189 }
6190 
6191 int bpf_object__pin(struct bpf_object *obj, const char *path)
6192 {
6193 	int err;
6194 
6195 	err = bpf_object__pin_maps(obj, path);
6196 	if (err)
6197 		return err;
6198 
6199 	err = bpf_object__pin_programs(obj, path);
6200 	if (err) {
6201 		bpf_object__unpin_maps(obj, path);
6202 		return err;
6203 	}
6204 
6205 	return 0;
6206 }
6207 
6208 static void bpf_map__destroy(struct bpf_map *map)
6209 {
6210 	if (map->clear_priv)
6211 		map->clear_priv(map, map->priv);
6212 	map->priv = NULL;
6213 	map->clear_priv = NULL;
6214 
6215 	if (map->inner_map) {
6216 		bpf_map__destroy(map->inner_map);
6217 		zfree(&map->inner_map);
6218 	}
6219 
6220 	zfree(&map->init_slots);
6221 	map->init_slots_sz = 0;
6222 
6223 	if (map->mmaped) {
6224 		munmap(map->mmaped, bpf_map_mmap_sz(map));
6225 		map->mmaped = NULL;
6226 	}
6227 
6228 	if (map->st_ops) {
6229 		zfree(&map->st_ops->data);
6230 		zfree(&map->st_ops->progs);
6231 		zfree(&map->st_ops->kern_func_off);
6232 		zfree(&map->st_ops);
6233 	}
6234 
6235 	zfree(&map->name);
6236 	zfree(&map->pin_path);
6237 
6238 	if (map->fd >= 0)
6239 		zclose(map->fd);
6240 }
6241 
6242 void bpf_object__close(struct bpf_object *obj)
6243 {
6244 	size_t i;
6245 
6246 	if (!obj)
6247 		return;
6248 
6249 	if (obj->clear_priv)
6250 		obj->clear_priv(obj, obj->priv);
6251 
6252 	bpf_object__elf_finish(obj);
6253 	bpf_object__unload(obj);
6254 	btf__free(obj->btf);
6255 	btf_ext__free(obj->btf_ext);
6256 
6257 	for (i = 0; i < obj->nr_maps; i++)
6258 		bpf_map__destroy(&obj->maps[i]);
6259 
6260 	zfree(&obj->kconfig);
6261 	zfree(&obj->externs);
6262 	obj->nr_extern = 0;
6263 
6264 	zfree(&obj->maps);
6265 	obj->nr_maps = 0;
6266 
6267 	if (obj->programs && obj->nr_programs) {
6268 		for (i = 0; i < obj->nr_programs; i++)
6269 			bpf_program__exit(&obj->programs[i]);
6270 	}
6271 	zfree(&obj->programs);
6272 
6273 	list_del(&obj->list);
6274 	free(obj);
6275 }
6276 
6277 struct bpf_object *
6278 bpf_object__next(struct bpf_object *prev)
6279 {
6280 	struct bpf_object *next;
6281 
6282 	if (!prev)
6283 		next = list_first_entry(&bpf_objects_list,
6284 					struct bpf_object,
6285 					list);
6286 	else
6287 		next = list_next_entry(prev, list);
6288 
6289 	/* Empty list is noticed here so don't need checking on entry. */
6290 	if (&next->list == &bpf_objects_list)
6291 		return NULL;
6292 
6293 	return next;
6294 }
6295 
6296 const char *bpf_object__name(const struct bpf_object *obj)
6297 {
6298 	return obj ? obj->name : ERR_PTR(-EINVAL);
6299 }
6300 
6301 unsigned int bpf_object__kversion(const struct bpf_object *obj)
6302 {
6303 	return obj ? obj->kern_version : 0;
6304 }
6305 
6306 struct btf *bpf_object__btf(const struct bpf_object *obj)
6307 {
6308 	return obj ? obj->btf : NULL;
6309 }
6310 
6311 int bpf_object__btf_fd(const struct bpf_object *obj)
6312 {
6313 	return obj->btf ? btf__fd(obj->btf) : -1;
6314 }
6315 
6316 int bpf_object__set_priv(struct bpf_object *obj, void *priv,
6317 			 bpf_object_clear_priv_t clear_priv)
6318 {
6319 	if (obj->priv && obj->clear_priv)
6320 		obj->clear_priv(obj, obj->priv);
6321 
6322 	obj->priv = priv;
6323 	obj->clear_priv = clear_priv;
6324 	return 0;
6325 }
6326 
6327 void *bpf_object__priv(const struct bpf_object *obj)
6328 {
6329 	return obj ? obj->priv : ERR_PTR(-EINVAL);
6330 }
6331 
6332 static struct bpf_program *
6333 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
6334 		    bool forward)
6335 {
6336 	size_t nr_programs = obj->nr_programs;
6337 	ssize_t idx;
6338 
6339 	if (!nr_programs)
6340 		return NULL;
6341 
6342 	if (!p)
6343 		/* Iter from the beginning */
6344 		return forward ? &obj->programs[0] :
6345 			&obj->programs[nr_programs - 1];
6346 
6347 	if (p->obj != obj) {
6348 		pr_warn("error: program handler doesn't match object\n");
6349 		return NULL;
6350 	}
6351 
6352 	idx = (p - obj->programs) + (forward ? 1 : -1);
6353 	if (idx >= obj->nr_programs || idx < 0)
6354 		return NULL;
6355 	return &obj->programs[idx];
6356 }
6357 
6358 struct bpf_program *
6359 bpf_program__next(struct bpf_program *prev, const struct bpf_object *obj)
6360 {
6361 	struct bpf_program *prog = prev;
6362 
6363 	do {
6364 		prog = __bpf_program__iter(prog, obj, true);
6365 	} while (prog && bpf_program__is_function_storage(prog, obj));
6366 
6367 	return prog;
6368 }
6369 
6370 struct bpf_program *
6371 bpf_program__prev(struct bpf_program *next, const struct bpf_object *obj)
6372 {
6373 	struct bpf_program *prog = next;
6374 
6375 	do {
6376 		prog = __bpf_program__iter(prog, obj, false);
6377 	} while (prog && bpf_program__is_function_storage(prog, obj));
6378 
6379 	return prog;
6380 }
6381 
6382 int bpf_program__set_priv(struct bpf_program *prog, void *priv,
6383 			  bpf_program_clear_priv_t clear_priv)
6384 {
6385 	if (prog->priv && prog->clear_priv)
6386 		prog->clear_priv(prog, prog->priv);
6387 
6388 	prog->priv = priv;
6389 	prog->clear_priv = clear_priv;
6390 	return 0;
6391 }
6392 
6393 void *bpf_program__priv(const struct bpf_program *prog)
6394 {
6395 	return prog ? prog->priv : ERR_PTR(-EINVAL);
6396 }
6397 
6398 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
6399 {
6400 	prog->prog_ifindex = ifindex;
6401 }
6402 
6403 const char *bpf_program__name(const struct bpf_program *prog)
6404 {
6405 	return prog->name;
6406 }
6407 
6408 const char *bpf_program__title(const struct bpf_program *prog, bool needs_copy)
6409 {
6410 	const char *title;
6411 
6412 	title = prog->section_name;
6413 	if (needs_copy) {
6414 		title = strdup(title);
6415 		if (!title) {
6416 			pr_warn("failed to strdup program title\n");
6417 			return ERR_PTR(-ENOMEM);
6418 		}
6419 	}
6420 
6421 	return title;
6422 }
6423 
6424 int bpf_program__fd(const struct bpf_program *prog)
6425 {
6426 	return bpf_program__nth_fd(prog, 0);
6427 }
6428 
6429 size_t bpf_program__size(const struct bpf_program *prog)
6430 {
6431 	return prog->insns_cnt * sizeof(struct bpf_insn);
6432 }
6433 
6434 int bpf_program__set_prep(struct bpf_program *prog, int nr_instances,
6435 			  bpf_program_prep_t prep)
6436 {
6437 	int *instances_fds;
6438 
6439 	if (nr_instances <= 0 || !prep)
6440 		return -EINVAL;
6441 
6442 	if (prog->instances.nr > 0 || prog->instances.fds) {
6443 		pr_warn("Can't set pre-processor after loading\n");
6444 		return -EINVAL;
6445 	}
6446 
6447 	instances_fds = malloc(sizeof(int) * nr_instances);
6448 	if (!instances_fds) {
6449 		pr_warn("alloc memory failed for fds\n");
6450 		return -ENOMEM;
6451 	}
6452 
6453 	/* fill all fd with -1 */
6454 	memset(instances_fds, -1, sizeof(int) * nr_instances);
6455 
6456 	prog->instances.nr = nr_instances;
6457 	prog->instances.fds = instances_fds;
6458 	prog->preprocessor = prep;
6459 	return 0;
6460 }
6461 
6462 int bpf_program__nth_fd(const struct bpf_program *prog, int n)
6463 {
6464 	int fd;
6465 
6466 	if (!prog)
6467 		return -EINVAL;
6468 
6469 	if (n >= prog->instances.nr || n < 0) {
6470 		pr_warn("Can't get the %dth fd from program %s: only %d instances\n",
6471 			n, prog->section_name, prog->instances.nr);
6472 		return -EINVAL;
6473 	}
6474 
6475 	fd = prog->instances.fds[n];
6476 	if (fd < 0) {
6477 		pr_warn("%dth instance of program '%s' is invalid\n",
6478 			n, prog->section_name);
6479 		return -ENOENT;
6480 	}
6481 
6482 	return fd;
6483 }
6484 
6485 enum bpf_prog_type bpf_program__get_type(struct bpf_program *prog)
6486 {
6487 	return prog->type;
6488 }
6489 
6490 void bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
6491 {
6492 	prog->type = type;
6493 }
6494 
6495 static bool bpf_program__is_type(const struct bpf_program *prog,
6496 				 enum bpf_prog_type type)
6497 {
6498 	return prog ? (prog->type == type) : false;
6499 }
6500 
6501 #define BPF_PROG_TYPE_FNS(NAME, TYPE)				\
6502 int bpf_program__set_##NAME(struct bpf_program *prog)		\
6503 {								\
6504 	if (!prog)						\
6505 		return -EINVAL;					\
6506 	bpf_program__set_type(prog, TYPE);			\
6507 	return 0;						\
6508 }								\
6509 								\
6510 bool bpf_program__is_##NAME(const struct bpf_program *prog)	\
6511 {								\
6512 	return bpf_program__is_type(prog, TYPE);		\
6513 }								\
6514 
6515 BPF_PROG_TYPE_FNS(socket_filter, BPF_PROG_TYPE_SOCKET_FILTER);
6516 BPF_PROG_TYPE_FNS(lsm, BPF_PROG_TYPE_LSM);
6517 BPF_PROG_TYPE_FNS(kprobe, BPF_PROG_TYPE_KPROBE);
6518 BPF_PROG_TYPE_FNS(sched_cls, BPF_PROG_TYPE_SCHED_CLS);
6519 BPF_PROG_TYPE_FNS(sched_act, BPF_PROG_TYPE_SCHED_ACT);
6520 BPF_PROG_TYPE_FNS(tracepoint, BPF_PROG_TYPE_TRACEPOINT);
6521 BPF_PROG_TYPE_FNS(raw_tracepoint, BPF_PROG_TYPE_RAW_TRACEPOINT);
6522 BPF_PROG_TYPE_FNS(xdp, BPF_PROG_TYPE_XDP);
6523 BPF_PROG_TYPE_FNS(perf_event, BPF_PROG_TYPE_PERF_EVENT);
6524 BPF_PROG_TYPE_FNS(tracing, BPF_PROG_TYPE_TRACING);
6525 BPF_PROG_TYPE_FNS(struct_ops, BPF_PROG_TYPE_STRUCT_OPS);
6526 BPF_PROG_TYPE_FNS(extension, BPF_PROG_TYPE_EXT);
6527 
6528 enum bpf_attach_type
6529 bpf_program__get_expected_attach_type(struct bpf_program *prog)
6530 {
6531 	return prog->expected_attach_type;
6532 }
6533 
6534 void bpf_program__set_expected_attach_type(struct bpf_program *prog,
6535 					   enum bpf_attach_type type)
6536 {
6537 	prog->expected_attach_type = type;
6538 }
6539 
6540 #define BPF_PROG_SEC_IMPL(string, ptype, eatype, eatype_optional,	    \
6541 			  attachable, attach_btf)			    \
6542 	{								    \
6543 		.sec = string,						    \
6544 		.len = sizeof(string) - 1,				    \
6545 		.prog_type = ptype,					    \
6546 		.expected_attach_type = eatype,				    \
6547 		.is_exp_attach_type_optional = eatype_optional,		    \
6548 		.is_attachable = attachable,				    \
6549 		.is_attach_btf = attach_btf,				    \
6550 	}
6551 
6552 /* Programs that can NOT be attached. */
6553 #define BPF_PROG_SEC(string, ptype) BPF_PROG_SEC_IMPL(string, ptype, 0, 0, 0, 0)
6554 
6555 /* Programs that can be attached. */
6556 #define BPF_APROG_SEC(string, ptype, atype) \
6557 	BPF_PROG_SEC_IMPL(string, ptype, atype, true, 1, 0)
6558 
6559 /* Programs that must specify expected attach type at load time. */
6560 #define BPF_EAPROG_SEC(string, ptype, eatype) \
6561 	BPF_PROG_SEC_IMPL(string, ptype, eatype, false, 1, 0)
6562 
6563 /* Programs that use BTF to identify attach point */
6564 #define BPF_PROG_BTF(string, ptype, eatype) \
6565 	BPF_PROG_SEC_IMPL(string, ptype, eatype, false, 0, 1)
6566 
6567 /* Programs that can be attached but attach type can't be identified by section
6568  * name. Kept for backward compatibility.
6569  */
6570 #define BPF_APROG_COMPAT(string, ptype) BPF_PROG_SEC(string, ptype)
6571 
6572 #define SEC_DEF(sec_pfx, ptype, ...) {					    \
6573 	.sec = sec_pfx,							    \
6574 	.len = sizeof(sec_pfx) - 1,					    \
6575 	.prog_type = BPF_PROG_TYPE_##ptype,				    \
6576 	__VA_ARGS__							    \
6577 }
6578 
6579 static struct bpf_link *attach_kprobe(const struct bpf_sec_def *sec,
6580 				      struct bpf_program *prog);
6581 static struct bpf_link *attach_tp(const struct bpf_sec_def *sec,
6582 				  struct bpf_program *prog);
6583 static struct bpf_link *attach_raw_tp(const struct bpf_sec_def *sec,
6584 				      struct bpf_program *prog);
6585 static struct bpf_link *attach_trace(const struct bpf_sec_def *sec,
6586 				     struct bpf_program *prog);
6587 static struct bpf_link *attach_lsm(const struct bpf_sec_def *sec,
6588 				   struct bpf_program *prog);
6589 
6590 static const struct bpf_sec_def section_defs[] = {
6591 	BPF_PROG_SEC("socket",			BPF_PROG_TYPE_SOCKET_FILTER),
6592 	BPF_PROG_SEC("sk_reuseport",		BPF_PROG_TYPE_SK_REUSEPORT),
6593 	SEC_DEF("kprobe/", KPROBE,
6594 		.attach_fn = attach_kprobe),
6595 	BPF_PROG_SEC("uprobe/",			BPF_PROG_TYPE_KPROBE),
6596 	SEC_DEF("kretprobe/", KPROBE,
6597 		.attach_fn = attach_kprobe),
6598 	BPF_PROG_SEC("uretprobe/",		BPF_PROG_TYPE_KPROBE),
6599 	BPF_PROG_SEC("classifier",		BPF_PROG_TYPE_SCHED_CLS),
6600 	BPF_PROG_SEC("action",			BPF_PROG_TYPE_SCHED_ACT),
6601 	SEC_DEF("tracepoint/", TRACEPOINT,
6602 		.attach_fn = attach_tp),
6603 	SEC_DEF("tp/", TRACEPOINT,
6604 		.attach_fn = attach_tp),
6605 	SEC_DEF("raw_tracepoint/", RAW_TRACEPOINT,
6606 		.attach_fn = attach_raw_tp),
6607 	SEC_DEF("raw_tp/", RAW_TRACEPOINT,
6608 		.attach_fn = attach_raw_tp),
6609 	SEC_DEF("tp_btf/", TRACING,
6610 		.expected_attach_type = BPF_TRACE_RAW_TP,
6611 		.is_attach_btf = true,
6612 		.attach_fn = attach_trace),
6613 	SEC_DEF("fentry/", TRACING,
6614 		.expected_attach_type = BPF_TRACE_FENTRY,
6615 		.is_attach_btf = true,
6616 		.attach_fn = attach_trace),
6617 	SEC_DEF("fmod_ret/", TRACING,
6618 		.expected_attach_type = BPF_MODIFY_RETURN,
6619 		.is_attach_btf = true,
6620 		.attach_fn = attach_trace),
6621 	SEC_DEF("fexit/", TRACING,
6622 		.expected_attach_type = BPF_TRACE_FEXIT,
6623 		.is_attach_btf = true,
6624 		.attach_fn = attach_trace),
6625 	SEC_DEF("freplace/", EXT,
6626 		.is_attach_btf = true,
6627 		.attach_fn = attach_trace),
6628 	SEC_DEF("lsm/", LSM,
6629 		.is_attach_btf = true,
6630 		.expected_attach_type = BPF_LSM_MAC,
6631 		.attach_fn = attach_lsm),
6632 	BPF_PROG_SEC("xdp",			BPF_PROG_TYPE_XDP),
6633 	BPF_PROG_SEC("perf_event",		BPF_PROG_TYPE_PERF_EVENT),
6634 	BPF_PROG_SEC("lwt_in",			BPF_PROG_TYPE_LWT_IN),
6635 	BPF_PROG_SEC("lwt_out",			BPF_PROG_TYPE_LWT_OUT),
6636 	BPF_PROG_SEC("lwt_xmit",		BPF_PROG_TYPE_LWT_XMIT),
6637 	BPF_PROG_SEC("lwt_seg6local",		BPF_PROG_TYPE_LWT_SEG6LOCAL),
6638 	BPF_APROG_SEC("cgroup_skb/ingress",	BPF_PROG_TYPE_CGROUP_SKB,
6639 						BPF_CGROUP_INET_INGRESS),
6640 	BPF_APROG_SEC("cgroup_skb/egress",	BPF_PROG_TYPE_CGROUP_SKB,
6641 						BPF_CGROUP_INET_EGRESS),
6642 	BPF_APROG_COMPAT("cgroup/skb",		BPF_PROG_TYPE_CGROUP_SKB),
6643 	BPF_APROG_SEC("cgroup/sock",		BPF_PROG_TYPE_CGROUP_SOCK,
6644 						BPF_CGROUP_INET_SOCK_CREATE),
6645 	BPF_EAPROG_SEC("cgroup/post_bind4",	BPF_PROG_TYPE_CGROUP_SOCK,
6646 						BPF_CGROUP_INET4_POST_BIND),
6647 	BPF_EAPROG_SEC("cgroup/post_bind6",	BPF_PROG_TYPE_CGROUP_SOCK,
6648 						BPF_CGROUP_INET6_POST_BIND),
6649 	BPF_APROG_SEC("cgroup/dev",		BPF_PROG_TYPE_CGROUP_DEVICE,
6650 						BPF_CGROUP_DEVICE),
6651 	BPF_APROG_SEC("sockops",		BPF_PROG_TYPE_SOCK_OPS,
6652 						BPF_CGROUP_SOCK_OPS),
6653 	BPF_APROG_SEC("sk_skb/stream_parser",	BPF_PROG_TYPE_SK_SKB,
6654 						BPF_SK_SKB_STREAM_PARSER),
6655 	BPF_APROG_SEC("sk_skb/stream_verdict",	BPF_PROG_TYPE_SK_SKB,
6656 						BPF_SK_SKB_STREAM_VERDICT),
6657 	BPF_APROG_COMPAT("sk_skb",		BPF_PROG_TYPE_SK_SKB),
6658 	BPF_APROG_SEC("sk_msg",			BPF_PROG_TYPE_SK_MSG,
6659 						BPF_SK_MSG_VERDICT),
6660 	BPF_APROG_SEC("lirc_mode2",		BPF_PROG_TYPE_LIRC_MODE2,
6661 						BPF_LIRC_MODE2),
6662 	BPF_APROG_SEC("flow_dissector",		BPF_PROG_TYPE_FLOW_DISSECTOR,
6663 						BPF_FLOW_DISSECTOR),
6664 	BPF_EAPROG_SEC("cgroup/bind4",		BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6665 						BPF_CGROUP_INET4_BIND),
6666 	BPF_EAPROG_SEC("cgroup/bind6",		BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6667 						BPF_CGROUP_INET6_BIND),
6668 	BPF_EAPROG_SEC("cgroup/connect4",	BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6669 						BPF_CGROUP_INET4_CONNECT),
6670 	BPF_EAPROG_SEC("cgroup/connect6",	BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6671 						BPF_CGROUP_INET6_CONNECT),
6672 	BPF_EAPROG_SEC("cgroup/sendmsg4",	BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6673 						BPF_CGROUP_UDP4_SENDMSG),
6674 	BPF_EAPROG_SEC("cgroup/sendmsg6",	BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6675 						BPF_CGROUP_UDP6_SENDMSG),
6676 	BPF_EAPROG_SEC("cgroup/recvmsg4",	BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6677 						BPF_CGROUP_UDP4_RECVMSG),
6678 	BPF_EAPROG_SEC("cgroup/recvmsg6",	BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6679 						BPF_CGROUP_UDP6_RECVMSG),
6680 	BPF_EAPROG_SEC("cgroup/sysctl",		BPF_PROG_TYPE_CGROUP_SYSCTL,
6681 						BPF_CGROUP_SYSCTL),
6682 	BPF_EAPROG_SEC("cgroup/getsockopt",	BPF_PROG_TYPE_CGROUP_SOCKOPT,
6683 						BPF_CGROUP_GETSOCKOPT),
6684 	BPF_EAPROG_SEC("cgroup/setsockopt",	BPF_PROG_TYPE_CGROUP_SOCKOPT,
6685 						BPF_CGROUP_SETSOCKOPT),
6686 	BPF_PROG_SEC("struct_ops",		BPF_PROG_TYPE_STRUCT_OPS),
6687 };
6688 
6689 #undef BPF_PROG_SEC_IMPL
6690 #undef BPF_PROG_SEC
6691 #undef BPF_APROG_SEC
6692 #undef BPF_EAPROG_SEC
6693 #undef BPF_APROG_COMPAT
6694 #undef SEC_DEF
6695 
6696 #define MAX_TYPE_NAME_SIZE 32
6697 
6698 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
6699 {
6700 	int i, n = ARRAY_SIZE(section_defs);
6701 
6702 	for (i = 0; i < n; i++) {
6703 		if (strncmp(sec_name,
6704 			    section_defs[i].sec, section_defs[i].len))
6705 			continue;
6706 		return &section_defs[i];
6707 	}
6708 	return NULL;
6709 }
6710 
6711 static char *libbpf_get_type_names(bool attach_type)
6712 {
6713 	int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
6714 	char *buf;
6715 
6716 	buf = malloc(len);
6717 	if (!buf)
6718 		return NULL;
6719 
6720 	buf[0] = '\0';
6721 	/* Forge string buf with all available names */
6722 	for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
6723 		if (attach_type && !section_defs[i].is_attachable)
6724 			continue;
6725 
6726 		if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
6727 			free(buf);
6728 			return NULL;
6729 		}
6730 		strcat(buf, " ");
6731 		strcat(buf, section_defs[i].sec);
6732 	}
6733 
6734 	return buf;
6735 }
6736 
6737 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
6738 			     enum bpf_attach_type *expected_attach_type)
6739 {
6740 	const struct bpf_sec_def *sec_def;
6741 	char *type_names;
6742 
6743 	if (!name)
6744 		return -EINVAL;
6745 
6746 	sec_def = find_sec_def(name);
6747 	if (sec_def) {
6748 		*prog_type = sec_def->prog_type;
6749 		*expected_attach_type = sec_def->expected_attach_type;
6750 		return 0;
6751 	}
6752 
6753 	pr_debug("failed to guess program type from ELF section '%s'\n", name);
6754 	type_names = libbpf_get_type_names(false);
6755 	if (type_names != NULL) {
6756 		pr_debug("supported section(type) names are:%s\n", type_names);
6757 		free(type_names);
6758 	}
6759 
6760 	return -ESRCH;
6761 }
6762 
6763 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
6764 						     size_t offset)
6765 {
6766 	struct bpf_map *map;
6767 	size_t i;
6768 
6769 	for (i = 0; i < obj->nr_maps; i++) {
6770 		map = &obj->maps[i];
6771 		if (!bpf_map__is_struct_ops(map))
6772 			continue;
6773 		if (map->sec_offset <= offset &&
6774 		    offset - map->sec_offset < map->def.value_size)
6775 			return map;
6776 	}
6777 
6778 	return NULL;
6779 }
6780 
6781 /* Collect the reloc from ELF and populate the st_ops->progs[] */
6782 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
6783 					    GElf_Shdr *shdr, Elf_Data *data)
6784 {
6785 	const struct btf_member *member;
6786 	struct bpf_struct_ops *st_ops;
6787 	struct bpf_program *prog;
6788 	unsigned int shdr_idx;
6789 	const struct btf *btf;
6790 	struct bpf_map *map;
6791 	Elf_Data *symbols;
6792 	unsigned int moff;
6793 	const char *name;
6794 	__u32 member_idx;
6795 	GElf_Sym sym;
6796 	GElf_Rel rel;
6797 	int i, nrels;
6798 
6799 	symbols = obj->efile.symbols;
6800 	btf = obj->btf;
6801 	nrels = shdr->sh_size / shdr->sh_entsize;
6802 	for (i = 0; i < nrels; i++) {
6803 		if (!gelf_getrel(data, i, &rel)) {
6804 			pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
6805 			return -LIBBPF_ERRNO__FORMAT;
6806 		}
6807 
6808 		if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) {
6809 			pr_warn("struct_ops reloc: symbol %zx not found\n",
6810 				(size_t)GELF_R_SYM(rel.r_info));
6811 			return -LIBBPF_ERRNO__FORMAT;
6812 		}
6813 
6814 		name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
6815 				  sym.st_name) ? : "<?>";
6816 		map = find_struct_ops_map_by_offset(obj, rel.r_offset);
6817 		if (!map) {
6818 			pr_warn("struct_ops reloc: cannot find map at rel.r_offset %zu\n",
6819 				(size_t)rel.r_offset);
6820 			return -EINVAL;
6821 		}
6822 
6823 		moff = rel.r_offset - map->sec_offset;
6824 		shdr_idx = sym.st_shndx;
6825 		st_ops = map->st_ops;
6826 		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",
6827 			 map->name,
6828 			 (long long)(rel.r_info >> 32),
6829 			 (long long)sym.st_value,
6830 			 shdr_idx, (size_t)rel.r_offset,
6831 			 map->sec_offset, sym.st_name, name);
6832 
6833 		if (shdr_idx >= SHN_LORESERVE) {
6834 			pr_warn("struct_ops reloc %s: rel.r_offset %zu shdr_idx %u unsupported non-static function\n",
6835 				map->name, (size_t)rel.r_offset, shdr_idx);
6836 			return -LIBBPF_ERRNO__RELOC;
6837 		}
6838 
6839 		member = find_member_by_offset(st_ops->type, moff * 8);
6840 		if (!member) {
6841 			pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
6842 				map->name, moff);
6843 			return -EINVAL;
6844 		}
6845 		member_idx = member - btf_members(st_ops->type);
6846 		name = btf__name_by_offset(btf, member->name_off);
6847 
6848 		if (!resolve_func_ptr(btf, member->type, NULL)) {
6849 			pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
6850 				map->name, name);
6851 			return -EINVAL;
6852 		}
6853 
6854 		prog = bpf_object__find_prog_by_idx(obj, shdr_idx);
6855 		if (!prog) {
6856 			pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
6857 				map->name, shdr_idx, name);
6858 			return -EINVAL;
6859 		}
6860 
6861 		if (prog->type == BPF_PROG_TYPE_UNSPEC) {
6862 			const struct bpf_sec_def *sec_def;
6863 
6864 			sec_def = find_sec_def(prog->section_name);
6865 			if (sec_def &&
6866 			    sec_def->prog_type != BPF_PROG_TYPE_STRUCT_OPS) {
6867 				/* for pr_warn */
6868 				prog->type = sec_def->prog_type;
6869 				goto invalid_prog;
6870 			}
6871 
6872 			prog->type = BPF_PROG_TYPE_STRUCT_OPS;
6873 			prog->attach_btf_id = st_ops->type_id;
6874 			prog->expected_attach_type = member_idx;
6875 		} else if (prog->type != BPF_PROG_TYPE_STRUCT_OPS ||
6876 			   prog->attach_btf_id != st_ops->type_id ||
6877 			   prog->expected_attach_type != member_idx) {
6878 			goto invalid_prog;
6879 		}
6880 		st_ops->progs[member_idx] = prog;
6881 	}
6882 
6883 	return 0;
6884 
6885 invalid_prog:
6886 	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",
6887 		map->name, prog->name, prog->section_name, prog->type,
6888 		prog->attach_btf_id, prog->expected_attach_type, name);
6889 	return -EINVAL;
6890 }
6891 
6892 #define BTF_TRACE_PREFIX "btf_trace_"
6893 #define BTF_LSM_PREFIX "bpf_lsm_"
6894 #define BTF_MAX_NAME_SIZE 128
6895 
6896 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
6897 				   const char *name, __u32 kind)
6898 {
6899 	char btf_type_name[BTF_MAX_NAME_SIZE];
6900 	int ret;
6901 
6902 	ret = snprintf(btf_type_name, sizeof(btf_type_name),
6903 		       "%s%s", prefix, name);
6904 	/* snprintf returns the number of characters written excluding the
6905 	 * the terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
6906 	 * indicates truncation.
6907 	 */
6908 	if (ret < 0 || ret >= sizeof(btf_type_name))
6909 		return -ENAMETOOLONG;
6910 	return btf__find_by_name_kind(btf, btf_type_name, kind);
6911 }
6912 
6913 static inline int __find_vmlinux_btf_id(struct btf *btf, const char *name,
6914 					enum bpf_attach_type attach_type)
6915 {
6916 	int err;
6917 
6918 	if (attach_type == BPF_TRACE_RAW_TP)
6919 		err = find_btf_by_prefix_kind(btf, BTF_TRACE_PREFIX, name,
6920 					      BTF_KIND_TYPEDEF);
6921 	else if (attach_type == BPF_LSM_MAC)
6922 		err = find_btf_by_prefix_kind(btf, BTF_LSM_PREFIX, name,
6923 					      BTF_KIND_FUNC);
6924 	else
6925 		err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
6926 
6927 	if (err <= 0)
6928 		pr_warn("%s is not found in vmlinux BTF\n", name);
6929 
6930 	return err;
6931 }
6932 
6933 int libbpf_find_vmlinux_btf_id(const char *name,
6934 			       enum bpf_attach_type attach_type)
6935 {
6936 	struct btf *btf;
6937 	int err;
6938 
6939 	btf = libbpf_find_kernel_btf();
6940 	if (IS_ERR(btf)) {
6941 		pr_warn("vmlinux BTF is not found\n");
6942 		return -EINVAL;
6943 	}
6944 
6945 	err = __find_vmlinux_btf_id(btf, name, attach_type);
6946 	btf__free(btf);
6947 	return err;
6948 }
6949 
6950 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
6951 {
6952 	struct bpf_prog_info_linear *info_linear;
6953 	struct bpf_prog_info *info;
6954 	struct btf *btf = NULL;
6955 	int err = -EINVAL;
6956 
6957 	info_linear = bpf_program__get_prog_info_linear(attach_prog_fd, 0);
6958 	if (IS_ERR_OR_NULL(info_linear)) {
6959 		pr_warn("failed get_prog_info_linear for FD %d\n",
6960 			attach_prog_fd);
6961 		return -EINVAL;
6962 	}
6963 	info = &info_linear->info;
6964 	if (!info->btf_id) {
6965 		pr_warn("The target program doesn't have BTF\n");
6966 		goto out;
6967 	}
6968 	if (btf__get_from_id(info->btf_id, &btf)) {
6969 		pr_warn("Failed to get BTF of the program\n");
6970 		goto out;
6971 	}
6972 	err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
6973 	btf__free(btf);
6974 	if (err <= 0) {
6975 		pr_warn("%s is not found in prog's BTF\n", name);
6976 		goto out;
6977 	}
6978 out:
6979 	free(info_linear);
6980 	return err;
6981 }
6982 
6983 static int libbpf_find_attach_btf_id(struct bpf_program *prog)
6984 {
6985 	enum bpf_attach_type attach_type = prog->expected_attach_type;
6986 	__u32 attach_prog_fd = prog->attach_prog_fd;
6987 	const char *name = prog->section_name;
6988 	int i, err;
6989 
6990 	if (!name)
6991 		return -EINVAL;
6992 
6993 	for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
6994 		if (!section_defs[i].is_attach_btf)
6995 			continue;
6996 		if (strncmp(name, section_defs[i].sec, section_defs[i].len))
6997 			continue;
6998 		if (attach_prog_fd)
6999 			err = libbpf_find_prog_btf_id(name + section_defs[i].len,
7000 						      attach_prog_fd);
7001 		else
7002 			err = __find_vmlinux_btf_id(prog->obj->btf_vmlinux,
7003 						    name + section_defs[i].len,
7004 						    attach_type);
7005 		return err;
7006 	}
7007 	pr_warn("failed to identify btf_id based on ELF section name '%s'\n", name);
7008 	return -ESRCH;
7009 }
7010 
7011 int libbpf_attach_type_by_name(const char *name,
7012 			       enum bpf_attach_type *attach_type)
7013 {
7014 	char *type_names;
7015 	int i;
7016 
7017 	if (!name)
7018 		return -EINVAL;
7019 
7020 	for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
7021 		if (strncmp(name, section_defs[i].sec, section_defs[i].len))
7022 			continue;
7023 		if (!section_defs[i].is_attachable)
7024 			return -EINVAL;
7025 		*attach_type = section_defs[i].expected_attach_type;
7026 		return 0;
7027 	}
7028 	pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
7029 	type_names = libbpf_get_type_names(true);
7030 	if (type_names != NULL) {
7031 		pr_debug("attachable section(type) names are:%s\n", type_names);
7032 		free(type_names);
7033 	}
7034 
7035 	return -EINVAL;
7036 }
7037 
7038 int bpf_map__fd(const struct bpf_map *map)
7039 {
7040 	return map ? map->fd : -EINVAL;
7041 }
7042 
7043 const struct bpf_map_def *bpf_map__def(const struct bpf_map *map)
7044 {
7045 	return map ? &map->def : ERR_PTR(-EINVAL);
7046 }
7047 
7048 const char *bpf_map__name(const struct bpf_map *map)
7049 {
7050 	return map ? map->name : NULL;
7051 }
7052 
7053 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
7054 {
7055 	return map ? map->btf_key_type_id : 0;
7056 }
7057 
7058 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
7059 {
7060 	return map ? map->btf_value_type_id : 0;
7061 }
7062 
7063 int bpf_map__set_priv(struct bpf_map *map, void *priv,
7064 		     bpf_map_clear_priv_t clear_priv)
7065 {
7066 	if (!map)
7067 		return -EINVAL;
7068 
7069 	if (map->priv) {
7070 		if (map->clear_priv)
7071 			map->clear_priv(map, map->priv);
7072 	}
7073 
7074 	map->priv = priv;
7075 	map->clear_priv = clear_priv;
7076 	return 0;
7077 }
7078 
7079 void *bpf_map__priv(const struct bpf_map *map)
7080 {
7081 	return map ? map->priv : ERR_PTR(-EINVAL);
7082 }
7083 
7084 int bpf_map__set_initial_value(struct bpf_map *map,
7085 			       const void *data, size_t size)
7086 {
7087 	if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG ||
7088 	    size != map->def.value_size || map->fd >= 0)
7089 		return -EINVAL;
7090 
7091 	memcpy(map->mmaped, data, size);
7092 	return 0;
7093 }
7094 
7095 bool bpf_map__is_offload_neutral(const struct bpf_map *map)
7096 {
7097 	return map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY;
7098 }
7099 
7100 bool bpf_map__is_internal(const struct bpf_map *map)
7101 {
7102 	return map->libbpf_type != LIBBPF_MAP_UNSPEC;
7103 }
7104 
7105 void bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
7106 {
7107 	map->map_ifindex = ifindex;
7108 }
7109 
7110 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
7111 {
7112 	if (!bpf_map_type__is_map_in_map(map->def.type)) {
7113 		pr_warn("error: unsupported map type\n");
7114 		return -EINVAL;
7115 	}
7116 	if (map->inner_map_fd != -1) {
7117 		pr_warn("error: inner_map_fd already specified\n");
7118 		return -EINVAL;
7119 	}
7120 	map->inner_map_fd = fd;
7121 	return 0;
7122 }
7123 
7124 static struct bpf_map *
7125 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
7126 {
7127 	ssize_t idx;
7128 	struct bpf_map *s, *e;
7129 
7130 	if (!obj || !obj->maps)
7131 		return NULL;
7132 
7133 	s = obj->maps;
7134 	e = obj->maps + obj->nr_maps;
7135 
7136 	if ((m < s) || (m >= e)) {
7137 		pr_warn("error in %s: map handler doesn't belong to object\n",
7138 			 __func__);
7139 		return NULL;
7140 	}
7141 
7142 	idx = (m - obj->maps) + i;
7143 	if (idx >= obj->nr_maps || idx < 0)
7144 		return NULL;
7145 	return &obj->maps[idx];
7146 }
7147 
7148 struct bpf_map *
7149 bpf_map__next(const struct bpf_map *prev, const struct bpf_object *obj)
7150 {
7151 	if (prev == NULL)
7152 		return obj->maps;
7153 
7154 	return __bpf_map__iter(prev, obj, 1);
7155 }
7156 
7157 struct bpf_map *
7158 bpf_map__prev(const struct bpf_map *next, const struct bpf_object *obj)
7159 {
7160 	if (next == NULL) {
7161 		if (!obj->nr_maps)
7162 			return NULL;
7163 		return obj->maps + obj->nr_maps - 1;
7164 	}
7165 
7166 	return __bpf_map__iter(next, obj, -1);
7167 }
7168 
7169 struct bpf_map *
7170 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
7171 {
7172 	struct bpf_map *pos;
7173 
7174 	bpf_object__for_each_map(pos, obj) {
7175 		if (pos->name && !strcmp(pos->name, name))
7176 			return pos;
7177 	}
7178 	return NULL;
7179 }
7180 
7181 int
7182 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
7183 {
7184 	return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
7185 }
7186 
7187 struct bpf_map *
7188 bpf_object__find_map_by_offset(struct bpf_object *obj, size_t offset)
7189 {
7190 	return ERR_PTR(-ENOTSUP);
7191 }
7192 
7193 long libbpf_get_error(const void *ptr)
7194 {
7195 	return PTR_ERR_OR_ZERO(ptr);
7196 }
7197 
7198 int bpf_prog_load(const char *file, enum bpf_prog_type type,
7199 		  struct bpf_object **pobj, int *prog_fd)
7200 {
7201 	struct bpf_prog_load_attr attr;
7202 
7203 	memset(&attr, 0, sizeof(struct bpf_prog_load_attr));
7204 	attr.file = file;
7205 	attr.prog_type = type;
7206 	attr.expected_attach_type = 0;
7207 
7208 	return bpf_prog_load_xattr(&attr, pobj, prog_fd);
7209 }
7210 
7211 int bpf_prog_load_xattr(const struct bpf_prog_load_attr *attr,
7212 			struct bpf_object **pobj, int *prog_fd)
7213 {
7214 	struct bpf_object_open_attr open_attr = {};
7215 	struct bpf_program *prog, *first_prog = NULL;
7216 	struct bpf_object *obj;
7217 	struct bpf_map *map;
7218 	int err;
7219 
7220 	if (!attr)
7221 		return -EINVAL;
7222 	if (!attr->file)
7223 		return -EINVAL;
7224 
7225 	open_attr.file = attr->file;
7226 	open_attr.prog_type = attr->prog_type;
7227 
7228 	obj = bpf_object__open_xattr(&open_attr);
7229 	if (IS_ERR_OR_NULL(obj))
7230 		return -ENOENT;
7231 
7232 	bpf_object__for_each_program(prog, obj) {
7233 		enum bpf_attach_type attach_type = attr->expected_attach_type;
7234 		/*
7235 		 * to preserve backwards compatibility, bpf_prog_load treats
7236 		 * attr->prog_type, if specified, as an override to whatever
7237 		 * bpf_object__open guessed
7238 		 */
7239 		if (attr->prog_type != BPF_PROG_TYPE_UNSPEC) {
7240 			bpf_program__set_type(prog, attr->prog_type);
7241 			bpf_program__set_expected_attach_type(prog,
7242 							      attach_type);
7243 		}
7244 		if (bpf_program__get_type(prog) == BPF_PROG_TYPE_UNSPEC) {
7245 			/*
7246 			 * we haven't guessed from section name and user
7247 			 * didn't provide a fallback type, too bad...
7248 			 */
7249 			bpf_object__close(obj);
7250 			return -EINVAL;
7251 		}
7252 
7253 		prog->prog_ifindex = attr->ifindex;
7254 		prog->log_level = attr->log_level;
7255 		prog->prog_flags = attr->prog_flags;
7256 		if (!first_prog)
7257 			first_prog = prog;
7258 	}
7259 
7260 	bpf_object__for_each_map(map, obj) {
7261 		if (!bpf_map__is_offload_neutral(map))
7262 			map->map_ifindex = attr->ifindex;
7263 	}
7264 
7265 	if (!first_prog) {
7266 		pr_warn("object file doesn't contain bpf program\n");
7267 		bpf_object__close(obj);
7268 		return -ENOENT;
7269 	}
7270 
7271 	err = bpf_object__load(obj);
7272 	if (err) {
7273 		bpf_object__close(obj);
7274 		return err;
7275 	}
7276 
7277 	*pobj = obj;
7278 	*prog_fd = bpf_program__fd(first_prog);
7279 	return 0;
7280 }
7281 
7282 struct bpf_link {
7283 	int (*detach)(struct bpf_link *link);
7284 	int (*destroy)(struct bpf_link *link);
7285 	char *pin_path;		/* NULL, if not pinned */
7286 	int fd;			/* hook FD, -1 if not applicable */
7287 	bool disconnected;
7288 };
7289 
7290 /* Replace link's underlying BPF program with the new one */
7291 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
7292 {
7293 	return bpf_link_update(bpf_link__fd(link), bpf_program__fd(prog), NULL);
7294 }
7295 
7296 /* Release "ownership" of underlying BPF resource (typically, BPF program
7297  * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
7298  * link, when destructed through bpf_link__destroy() call won't attempt to
7299  * detach/unregisted that BPF resource. This is useful in situations where,
7300  * say, attached BPF program has to outlive userspace program that attached it
7301  * in the system. Depending on type of BPF program, though, there might be
7302  * additional steps (like pinning BPF program in BPF FS) necessary to ensure
7303  * exit of userspace program doesn't trigger automatic detachment and clean up
7304  * inside the kernel.
7305  */
7306 void bpf_link__disconnect(struct bpf_link *link)
7307 {
7308 	link->disconnected = true;
7309 }
7310 
7311 int bpf_link__destroy(struct bpf_link *link)
7312 {
7313 	int err = 0;
7314 
7315 	if (!link)
7316 		return 0;
7317 
7318 	if (!link->disconnected && link->detach)
7319 		err = link->detach(link);
7320 	if (link->destroy)
7321 		link->destroy(link);
7322 	if (link->pin_path)
7323 		free(link->pin_path);
7324 	free(link);
7325 
7326 	return err;
7327 }
7328 
7329 int bpf_link__fd(const struct bpf_link *link)
7330 {
7331 	return link->fd;
7332 }
7333 
7334 const char *bpf_link__pin_path(const struct bpf_link *link)
7335 {
7336 	return link->pin_path;
7337 }
7338 
7339 static int bpf_link__detach_fd(struct bpf_link *link)
7340 {
7341 	return close(link->fd);
7342 }
7343 
7344 struct bpf_link *bpf_link__open(const char *path)
7345 {
7346 	struct bpf_link *link;
7347 	int fd;
7348 
7349 	fd = bpf_obj_get(path);
7350 	if (fd < 0) {
7351 		fd = -errno;
7352 		pr_warn("failed to open link at %s: %d\n", path, fd);
7353 		return ERR_PTR(fd);
7354 	}
7355 
7356 	link = calloc(1, sizeof(*link));
7357 	if (!link) {
7358 		close(fd);
7359 		return ERR_PTR(-ENOMEM);
7360 	}
7361 	link->detach = &bpf_link__detach_fd;
7362 	link->fd = fd;
7363 
7364 	link->pin_path = strdup(path);
7365 	if (!link->pin_path) {
7366 		bpf_link__destroy(link);
7367 		return ERR_PTR(-ENOMEM);
7368 	}
7369 
7370 	return link;
7371 }
7372 
7373 int bpf_link__pin(struct bpf_link *link, const char *path)
7374 {
7375 	int err;
7376 
7377 	if (link->pin_path)
7378 		return -EBUSY;
7379 	err = make_parent_dir(path);
7380 	if (err)
7381 		return err;
7382 	err = check_path(path);
7383 	if (err)
7384 		return err;
7385 
7386 	link->pin_path = strdup(path);
7387 	if (!link->pin_path)
7388 		return -ENOMEM;
7389 
7390 	if (bpf_obj_pin(link->fd, link->pin_path)) {
7391 		err = -errno;
7392 		zfree(&link->pin_path);
7393 		return err;
7394 	}
7395 
7396 	pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
7397 	return 0;
7398 }
7399 
7400 int bpf_link__unpin(struct bpf_link *link)
7401 {
7402 	int err;
7403 
7404 	if (!link->pin_path)
7405 		return -EINVAL;
7406 
7407 	err = unlink(link->pin_path);
7408 	if (err != 0)
7409 		return -errno;
7410 
7411 	pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
7412 	zfree(&link->pin_path);
7413 	return 0;
7414 }
7415 
7416 static int bpf_link__detach_perf_event(struct bpf_link *link)
7417 {
7418 	int err;
7419 
7420 	err = ioctl(link->fd, PERF_EVENT_IOC_DISABLE, 0);
7421 	if (err)
7422 		err = -errno;
7423 
7424 	close(link->fd);
7425 	return err;
7426 }
7427 
7428 struct bpf_link *bpf_program__attach_perf_event(struct bpf_program *prog,
7429 						int pfd)
7430 {
7431 	char errmsg[STRERR_BUFSIZE];
7432 	struct bpf_link *link;
7433 	int prog_fd, err;
7434 
7435 	if (pfd < 0) {
7436 		pr_warn("program '%s': invalid perf event FD %d\n",
7437 			bpf_program__title(prog, false), pfd);
7438 		return ERR_PTR(-EINVAL);
7439 	}
7440 	prog_fd = bpf_program__fd(prog);
7441 	if (prog_fd < 0) {
7442 		pr_warn("program '%s': can't attach BPF program w/o FD (did you load it?)\n",
7443 			bpf_program__title(prog, false));
7444 		return ERR_PTR(-EINVAL);
7445 	}
7446 
7447 	link = calloc(1, sizeof(*link));
7448 	if (!link)
7449 		return ERR_PTR(-ENOMEM);
7450 	link->detach = &bpf_link__detach_perf_event;
7451 	link->fd = pfd;
7452 
7453 	if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
7454 		err = -errno;
7455 		free(link);
7456 		pr_warn("program '%s': failed to attach to pfd %d: %s\n",
7457 			bpf_program__title(prog, false), pfd,
7458 			   libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
7459 		return ERR_PTR(err);
7460 	}
7461 	if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
7462 		err = -errno;
7463 		free(link);
7464 		pr_warn("program '%s': failed to enable pfd %d: %s\n",
7465 			bpf_program__title(prog, false), pfd,
7466 			   libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
7467 		return ERR_PTR(err);
7468 	}
7469 	return link;
7470 }
7471 
7472 /*
7473  * this function is expected to parse integer in the range of [0, 2^31-1] from
7474  * given file using scanf format string fmt. If actual parsed value is
7475  * negative, the result might be indistinguishable from error
7476  */
7477 static int parse_uint_from_file(const char *file, const char *fmt)
7478 {
7479 	char buf[STRERR_BUFSIZE];
7480 	int err, ret;
7481 	FILE *f;
7482 
7483 	f = fopen(file, "r");
7484 	if (!f) {
7485 		err = -errno;
7486 		pr_debug("failed to open '%s': %s\n", file,
7487 			 libbpf_strerror_r(err, buf, sizeof(buf)));
7488 		return err;
7489 	}
7490 	err = fscanf(f, fmt, &ret);
7491 	if (err != 1) {
7492 		err = err == EOF ? -EIO : -errno;
7493 		pr_debug("failed to parse '%s': %s\n", file,
7494 			libbpf_strerror_r(err, buf, sizeof(buf)));
7495 		fclose(f);
7496 		return err;
7497 	}
7498 	fclose(f);
7499 	return ret;
7500 }
7501 
7502 static int determine_kprobe_perf_type(void)
7503 {
7504 	const char *file = "/sys/bus/event_source/devices/kprobe/type";
7505 
7506 	return parse_uint_from_file(file, "%d\n");
7507 }
7508 
7509 static int determine_uprobe_perf_type(void)
7510 {
7511 	const char *file = "/sys/bus/event_source/devices/uprobe/type";
7512 
7513 	return parse_uint_from_file(file, "%d\n");
7514 }
7515 
7516 static int determine_kprobe_retprobe_bit(void)
7517 {
7518 	const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
7519 
7520 	return parse_uint_from_file(file, "config:%d\n");
7521 }
7522 
7523 static int determine_uprobe_retprobe_bit(void)
7524 {
7525 	const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
7526 
7527 	return parse_uint_from_file(file, "config:%d\n");
7528 }
7529 
7530 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
7531 				 uint64_t offset, int pid)
7532 {
7533 	struct perf_event_attr attr = {};
7534 	char errmsg[STRERR_BUFSIZE];
7535 	int type, pfd, err;
7536 
7537 	type = uprobe ? determine_uprobe_perf_type()
7538 		      : determine_kprobe_perf_type();
7539 	if (type < 0) {
7540 		pr_warn("failed to determine %s perf type: %s\n",
7541 			uprobe ? "uprobe" : "kprobe",
7542 			libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
7543 		return type;
7544 	}
7545 	if (retprobe) {
7546 		int bit = uprobe ? determine_uprobe_retprobe_bit()
7547 				 : determine_kprobe_retprobe_bit();
7548 
7549 		if (bit < 0) {
7550 			pr_warn("failed to determine %s retprobe bit: %s\n",
7551 				uprobe ? "uprobe" : "kprobe",
7552 				libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
7553 			return bit;
7554 		}
7555 		attr.config |= 1 << bit;
7556 	}
7557 	attr.size = sizeof(attr);
7558 	attr.type = type;
7559 	attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
7560 	attr.config2 = offset;		 /* kprobe_addr or probe_offset */
7561 
7562 	/* pid filter is meaningful only for uprobes */
7563 	pfd = syscall(__NR_perf_event_open, &attr,
7564 		      pid < 0 ? -1 : pid /* pid */,
7565 		      pid == -1 ? 0 : -1 /* cpu */,
7566 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
7567 	if (pfd < 0) {
7568 		err = -errno;
7569 		pr_warn("%s perf_event_open() failed: %s\n",
7570 			uprobe ? "uprobe" : "kprobe",
7571 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
7572 		return err;
7573 	}
7574 	return pfd;
7575 }
7576 
7577 struct bpf_link *bpf_program__attach_kprobe(struct bpf_program *prog,
7578 					    bool retprobe,
7579 					    const char *func_name)
7580 {
7581 	char errmsg[STRERR_BUFSIZE];
7582 	struct bpf_link *link;
7583 	int pfd, err;
7584 
7585 	pfd = perf_event_open_probe(false /* uprobe */, retprobe, func_name,
7586 				    0 /* offset */, -1 /* pid */);
7587 	if (pfd < 0) {
7588 		pr_warn("program '%s': failed to create %s '%s' perf event: %s\n",
7589 			bpf_program__title(prog, false),
7590 			retprobe ? "kretprobe" : "kprobe", func_name,
7591 			libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
7592 		return ERR_PTR(pfd);
7593 	}
7594 	link = bpf_program__attach_perf_event(prog, pfd);
7595 	if (IS_ERR(link)) {
7596 		close(pfd);
7597 		err = PTR_ERR(link);
7598 		pr_warn("program '%s': failed to attach to %s '%s': %s\n",
7599 			bpf_program__title(prog, false),
7600 			retprobe ? "kretprobe" : "kprobe", func_name,
7601 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
7602 		return link;
7603 	}
7604 	return link;
7605 }
7606 
7607 static struct bpf_link *attach_kprobe(const struct bpf_sec_def *sec,
7608 				      struct bpf_program *prog)
7609 {
7610 	const char *func_name;
7611 	bool retprobe;
7612 
7613 	func_name = bpf_program__title(prog, false) + sec->len;
7614 	retprobe = strcmp(sec->sec, "kretprobe/") == 0;
7615 
7616 	return bpf_program__attach_kprobe(prog, retprobe, func_name);
7617 }
7618 
7619 struct bpf_link *bpf_program__attach_uprobe(struct bpf_program *prog,
7620 					    bool retprobe, pid_t pid,
7621 					    const char *binary_path,
7622 					    size_t func_offset)
7623 {
7624 	char errmsg[STRERR_BUFSIZE];
7625 	struct bpf_link *link;
7626 	int pfd, err;
7627 
7628 	pfd = perf_event_open_probe(true /* uprobe */, retprobe,
7629 				    binary_path, func_offset, pid);
7630 	if (pfd < 0) {
7631 		pr_warn("program '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
7632 			bpf_program__title(prog, false),
7633 			retprobe ? "uretprobe" : "uprobe",
7634 			binary_path, func_offset,
7635 			libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
7636 		return ERR_PTR(pfd);
7637 	}
7638 	link = bpf_program__attach_perf_event(prog, pfd);
7639 	if (IS_ERR(link)) {
7640 		close(pfd);
7641 		err = PTR_ERR(link);
7642 		pr_warn("program '%s': failed to attach to %s '%s:0x%zx': %s\n",
7643 			bpf_program__title(prog, false),
7644 			retprobe ? "uretprobe" : "uprobe",
7645 			binary_path, func_offset,
7646 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
7647 		return link;
7648 	}
7649 	return link;
7650 }
7651 
7652 static int determine_tracepoint_id(const char *tp_category,
7653 				   const char *tp_name)
7654 {
7655 	char file[PATH_MAX];
7656 	int ret;
7657 
7658 	ret = snprintf(file, sizeof(file),
7659 		       "/sys/kernel/debug/tracing/events/%s/%s/id",
7660 		       tp_category, tp_name);
7661 	if (ret < 0)
7662 		return -errno;
7663 	if (ret >= sizeof(file)) {
7664 		pr_debug("tracepoint %s/%s path is too long\n",
7665 			 tp_category, tp_name);
7666 		return -E2BIG;
7667 	}
7668 	return parse_uint_from_file(file, "%d\n");
7669 }
7670 
7671 static int perf_event_open_tracepoint(const char *tp_category,
7672 				      const char *tp_name)
7673 {
7674 	struct perf_event_attr attr = {};
7675 	char errmsg[STRERR_BUFSIZE];
7676 	int tp_id, pfd, err;
7677 
7678 	tp_id = determine_tracepoint_id(tp_category, tp_name);
7679 	if (tp_id < 0) {
7680 		pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
7681 			tp_category, tp_name,
7682 			libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
7683 		return tp_id;
7684 	}
7685 
7686 	attr.type = PERF_TYPE_TRACEPOINT;
7687 	attr.size = sizeof(attr);
7688 	attr.config = tp_id;
7689 
7690 	pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
7691 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
7692 	if (pfd < 0) {
7693 		err = -errno;
7694 		pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
7695 			tp_category, tp_name,
7696 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
7697 		return err;
7698 	}
7699 	return pfd;
7700 }
7701 
7702 struct bpf_link *bpf_program__attach_tracepoint(struct bpf_program *prog,
7703 						const char *tp_category,
7704 						const char *tp_name)
7705 {
7706 	char errmsg[STRERR_BUFSIZE];
7707 	struct bpf_link *link;
7708 	int pfd, err;
7709 
7710 	pfd = perf_event_open_tracepoint(tp_category, tp_name);
7711 	if (pfd < 0) {
7712 		pr_warn("program '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
7713 			bpf_program__title(prog, false),
7714 			tp_category, tp_name,
7715 			libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
7716 		return ERR_PTR(pfd);
7717 	}
7718 	link = bpf_program__attach_perf_event(prog, pfd);
7719 	if (IS_ERR(link)) {
7720 		close(pfd);
7721 		err = PTR_ERR(link);
7722 		pr_warn("program '%s': failed to attach to tracepoint '%s/%s': %s\n",
7723 			bpf_program__title(prog, false),
7724 			tp_category, tp_name,
7725 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
7726 		return link;
7727 	}
7728 	return link;
7729 }
7730 
7731 static struct bpf_link *attach_tp(const struct bpf_sec_def *sec,
7732 				  struct bpf_program *prog)
7733 {
7734 	char *sec_name, *tp_cat, *tp_name;
7735 	struct bpf_link *link;
7736 
7737 	sec_name = strdup(bpf_program__title(prog, false));
7738 	if (!sec_name)
7739 		return ERR_PTR(-ENOMEM);
7740 
7741 	/* extract "tp/<category>/<name>" */
7742 	tp_cat = sec_name + sec->len;
7743 	tp_name = strchr(tp_cat, '/');
7744 	if (!tp_name) {
7745 		link = ERR_PTR(-EINVAL);
7746 		goto out;
7747 	}
7748 	*tp_name = '\0';
7749 	tp_name++;
7750 
7751 	link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
7752 out:
7753 	free(sec_name);
7754 	return link;
7755 }
7756 
7757 struct bpf_link *bpf_program__attach_raw_tracepoint(struct bpf_program *prog,
7758 						    const char *tp_name)
7759 {
7760 	char errmsg[STRERR_BUFSIZE];
7761 	struct bpf_link *link;
7762 	int prog_fd, pfd;
7763 
7764 	prog_fd = bpf_program__fd(prog);
7765 	if (prog_fd < 0) {
7766 		pr_warn("program '%s': can't attach before loaded\n",
7767 			bpf_program__title(prog, false));
7768 		return ERR_PTR(-EINVAL);
7769 	}
7770 
7771 	link = calloc(1, sizeof(*link));
7772 	if (!link)
7773 		return ERR_PTR(-ENOMEM);
7774 	link->detach = &bpf_link__detach_fd;
7775 
7776 	pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
7777 	if (pfd < 0) {
7778 		pfd = -errno;
7779 		free(link);
7780 		pr_warn("program '%s': failed to attach to raw tracepoint '%s': %s\n",
7781 			bpf_program__title(prog, false), tp_name,
7782 			libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
7783 		return ERR_PTR(pfd);
7784 	}
7785 	link->fd = pfd;
7786 	return link;
7787 }
7788 
7789 static struct bpf_link *attach_raw_tp(const struct bpf_sec_def *sec,
7790 				      struct bpf_program *prog)
7791 {
7792 	const char *tp_name = bpf_program__title(prog, false) + sec->len;
7793 
7794 	return bpf_program__attach_raw_tracepoint(prog, tp_name);
7795 }
7796 
7797 /* Common logic for all BPF program types that attach to a btf_id */
7798 static struct bpf_link *bpf_program__attach_btf_id(struct bpf_program *prog)
7799 {
7800 	char errmsg[STRERR_BUFSIZE];
7801 	struct bpf_link *link;
7802 	int prog_fd, pfd;
7803 
7804 	prog_fd = bpf_program__fd(prog);
7805 	if (prog_fd < 0) {
7806 		pr_warn("program '%s': can't attach before loaded\n",
7807 			bpf_program__title(prog, false));
7808 		return ERR_PTR(-EINVAL);
7809 	}
7810 
7811 	link = calloc(1, sizeof(*link));
7812 	if (!link)
7813 		return ERR_PTR(-ENOMEM);
7814 	link->detach = &bpf_link__detach_fd;
7815 
7816 	pfd = bpf_raw_tracepoint_open(NULL, prog_fd);
7817 	if (pfd < 0) {
7818 		pfd = -errno;
7819 		free(link);
7820 		pr_warn("program '%s': failed to attach: %s\n",
7821 			bpf_program__title(prog, false),
7822 			libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
7823 		return ERR_PTR(pfd);
7824 	}
7825 	link->fd = pfd;
7826 	return (struct bpf_link *)link;
7827 }
7828 
7829 struct bpf_link *bpf_program__attach_trace(struct bpf_program *prog)
7830 {
7831 	return bpf_program__attach_btf_id(prog);
7832 }
7833 
7834 struct bpf_link *bpf_program__attach_lsm(struct bpf_program *prog)
7835 {
7836 	return bpf_program__attach_btf_id(prog);
7837 }
7838 
7839 static struct bpf_link *attach_trace(const struct bpf_sec_def *sec,
7840 				     struct bpf_program *prog)
7841 {
7842 	return bpf_program__attach_trace(prog);
7843 }
7844 
7845 static struct bpf_link *attach_lsm(const struct bpf_sec_def *sec,
7846 				   struct bpf_program *prog)
7847 {
7848 	return bpf_program__attach_lsm(prog);
7849 }
7850 
7851 struct bpf_link *
7852 bpf_program__attach_cgroup(struct bpf_program *prog, int cgroup_fd)
7853 {
7854 	enum bpf_attach_type attach_type;
7855 	char errmsg[STRERR_BUFSIZE];
7856 	struct bpf_link *link;
7857 	int prog_fd, link_fd;
7858 
7859 	prog_fd = bpf_program__fd(prog);
7860 	if (prog_fd < 0) {
7861 		pr_warn("program '%s': can't attach before loaded\n",
7862 			bpf_program__title(prog, false));
7863 		return ERR_PTR(-EINVAL);
7864 	}
7865 
7866 	link = calloc(1, sizeof(*link));
7867 	if (!link)
7868 		return ERR_PTR(-ENOMEM);
7869 	link->detach = &bpf_link__detach_fd;
7870 
7871 	attach_type = bpf_program__get_expected_attach_type(prog);
7872 	link_fd = bpf_link_create(prog_fd, cgroup_fd, attach_type, NULL);
7873 	if (link_fd < 0) {
7874 		link_fd = -errno;
7875 		free(link);
7876 		pr_warn("program '%s': failed to attach to cgroup: %s\n",
7877 			bpf_program__title(prog, false),
7878 			libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
7879 		return ERR_PTR(link_fd);
7880 	}
7881 	link->fd = link_fd;
7882 	return link;
7883 }
7884 
7885 struct bpf_link *bpf_program__attach(struct bpf_program *prog)
7886 {
7887 	const struct bpf_sec_def *sec_def;
7888 
7889 	sec_def = find_sec_def(bpf_program__title(prog, false));
7890 	if (!sec_def || !sec_def->attach_fn)
7891 		return ERR_PTR(-ESRCH);
7892 
7893 	return sec_def->attach_fn(sec_def, prog);
7894 }
7895 
7896 static int bpf_link__detach_struct_ops(struct bpf_link *link)
7897 {
7898 	__u32 zero = 0;
7899 
7900 	if (bpf_map_delete_elem(link->fd, &zero))
7901 		return -errno;
7902 
7903 	return 0;
7904 }
7905 
7906 struct bpf_link *bpf_map__attach_struct_ops(struct bpf_map *map)
7907 {
7908 	struct bpf_struct_ops *st_ops;
7909 	struct bpf_link *link;
7910 	__u32 i, zero = 0;
7911 	int err;
7912 
7913 	if (!bpf_map__is_struct_ops(map) || map->fd == -1)
7914 		return ERR_PTR(-EINVAL);
7915 
7916 	link = calloc(1, sizeof(*link));
7917 	if (!link)
7918 		return ERR_PTR(-EINVAL);
7919 
7920 	st_ops = map->st_ops;
7921 	for (i = 0; i < btf_vlen(st_ops->type); i++) {
7922 		struct bpf_program *prog = st_ops->progs[i];
7923 		void *kern_data;
7924 		int prog_fd;
7925 
7926 		if (!prog)
7927 			continue;
7928 
7929 		prog_fd = bpf_program__fd(prog);
7930 		kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
7931 		*(unsigned long *)kern_data = prog_fd;
7932 	}
7933 
7934 	err = bpf_map_update_elem(map->fd, &zero, st_ops->kern_vdata, 0);
7935 	if (err) {
7936 		err = -errno;
7937 		free(link);
7938 		return ERR_PTR(err);
7939 	}
7940 
7941 	link->detach = bpf_link__detach_struct_ops;
7942 	link->fd = map->fd;
7943 
7944 	return link;
7945 }
7946 
7947 enum bpf_perf_event_ret
7948 bpf_perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
7949 			   void **copy_mem, size_t *copy_size,
7950 			   bpf_perf_event_print_t fn, void *private_data)
7951 {
7952 	struct perf_event_mmap_page *header = mmap_mem;
7953 	__u64 data_head = ring_buffer_read_head(header);
7954 	__u64 data_tail = header->data_tail;
7955 	void *base = ((__u8 *)header) + page_size;
7956 	int ret = LIBBPF_PERF_EVENT_CONT;
7957 	struct perf_event_header *ehdr;
7958 	size_t ehdr_size;
7959 
7960 	while (data_head != data_tail) {
7961 		ehdr = base + (data_tail & (mmap_size - 1));
7962 		ehdr_size = ehdr->size;
7963 
7964 		if (((void *)ehdr) + ehdr_size > base + mmap_size) {
7965 			void *copy_start = ehdr;
7966 			size_t len_first = base + mmap_size - copy_start;
7967 			size_t len_secnd = ehdr_size - len_first;
7968 
7969 			if (*copy_size < ehdr_size) {
7970 				free(*copy_mem);
7971 				*copy_mem = malloc(ehdr_size);
7972 				if (!*copy_mem) {
7973 					*copy_size = 0;
7974 					ret = LIBBPF_PERF_EVENT_ERROR;
7975 					break;
7976 				}
7977 				*copy_size = ehdr_size;
7978 			}
7979 
7980 			memcpy(*copy_mem, copy_start, len_first);
7981 			memcpy(*copy_mem + len_first, base, len_secnd);
7982 			ehdr = *copy_mem;
7983 		}
7984 
7985 		ret = fn(ehdr, private_data);
7986 		data_tail += ehdr_size;
7987 		if (ret != LIBBPF_PERF_EVENT_CONT)
7988 			break;
7989 	}
7990 
7991 	ring_buffer_write_tail(header, data_tail);
7992 	return ret;
7993 }
7994 
7995 struct perf_buffer;
7996 
7997 struct perf_buffer_params {
7998 	struct perf_event_attr *attr;
7999 	/* if event_cb is specified, it takes precendence */
8000 	perf_buffer_event_fn event_cb;
8001 	/* sample_cb and lost_cb are higher-level common-case callbacks */
8002 	perf_buffer_sample_fn sample_cb;
8003 	perf_buffer_lost_fn lost_cb;
8004 	void *ctx;
8005 	int cpu_cnt;
8006 	int *cpus;
8007 	int *map_keys;
8008 };
8009 
8010 struct perf_cpu_buf {
8011 	struct perf_buffer *pb;
8012 	void *base; /* mmap()'ed memory */
8013 	void *buf; /* for reconstructing segmented data */
8014 	size_t buf_size;
8015 	int fd;
8016 	int cpu;
8017 	int map_key;
8018 };
8019 
8020 struct perf_buffer {
8021 	perf_buffer_event_fn event_cb;
8022 	perf_buffer_sample_fn sample_cb;
8023 	perf_buffer_lost_fn lost_cb;
8024 	void *ctx; /* passed into callbacks */
8025 
8026 	size_t page_size;
8027 	size_t mmap_size;
8028 	struct perf_cpu_buf **cpu_bufs;
8029 	struct epoll_event *events;
8030 	int cpu_cnt; /* number of allocated CPU buffers */
8031 	int epoll_fd; /* perf event FD */
8032 	int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
8033 };
8034 
8035 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
8036 				      struct perf_cpu_buf *cpu_buf)
8037 {
8038 	if (!cpu_buf)
8039 		return;
8040 	if (cpu_buf->base &&
8041 	    munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
8042 		pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
8043 	if (cpu_buf->fd >= 0) {
8044 		ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
8045 		close(cpu_buf->fd);
8046 	}
8047 	free(cpu_buf->buf);
8048 	free(cpu_buf);
8049 }
8050 
8051 void perf_buffer__free(struct perf_buffer *pb)
8052 {
8053 	int i;
8054 
8055 	if (!pb)
8056 		return;
8057 	if (pb->cpu_bufs) {
8058 		for (i = 0; i < pb->cpu_cnt && pb->cpu_bufs[i]; i++) {
8059 			struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
8060 
8061 			bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
8062 			perf_buffer__free_cpu_buf(pb, cpu_buf);
8063 		}
8064 		free(pb->cpu_bufs);
8065 	}
8066 	if (pb->epoll_fd >= 0)
8067 		close(pb->epoll_fd);
8068 	free(pb->events);
8069 	free(pb);
8070 }
8071 
8072 static struct perf_cpu_buf *
8073 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
8074 			  int cpu, int map_key)
8075 {
8076 	struct perf_cpu_buf *cpu_buf;
8077 	char msg[STRERR_BUFSIZE];
8078 	int err;
8079 
8080 	cpu_buf = calloc(1, sizeof(*cpu_buf));
8081 	if (!cpu_buf)
8082 		return ERR_PTR(-ENOMEM);
8083 
8084 	cpu_buf->pb = pb;
8085 	cpu_buf->cpu = cpu;
8086 	cpu_buf->map_key = map_key;
8087 
8088 	cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
8089 			      -1, PERF_FLAG_FD_CLOEXEC);
8090 	if (cpu_buf->fd < 0) {
8091 		err = -errno;
8092 		pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
8093 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
8094 		goto error;
8095 	}
8096 
8097 	cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
8098 			     PROT_READ | PROT_WRITE, MAP_SHARED,
8099 			     cpu_buf->fd, 0);
8100 	if (cpu_buf->base == MAP_FAILED) {
8101 		cpu_buf->base = NULL;
8102 		err = -errno;
8103 		pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
8104 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
8105 		goto error;
8106 	}
8107 
8108 	if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
8109 		err = -errno;
8110 		pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
8111 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
8112 		goto error;
8113 	}
8114 
8115 	return cpu_buf;
8116 
8117 error:
8118 	perf_buffer__free_cpu_buf(pb, cpu_buf);
8119 	return (struct perf_cpu_buf *)ERR_PTR(err);
8120 }
8121 
8122 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
8123 					      struct perf_buffer_params *p);
8124 
8125 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
8126 				     const struct perf_buffer_opts *opts)
8127 {
8128 	struct perf_buffer_params p = {};
8129 	struct perf_event_attr attr = { 0, };
8130 
8131 	attr.config = PERF_COUNT_SW_BPF_OUTPUT,
8132 	attr.type = PERF_TYPE_SOFTWARE;
8133 	attr.sample_type = PERF_SAMPLE_RAW;
8134 	attr.sample_period = 1;
8135 	attr.wakeup_events = 1;
8136 
8137 	p.attr = &attr;
8138 	p.sample_cb = opts ? opts->sample_cb : NULL;
8139 	p.lost_cb = opts ? opts->lost_cb : NULL;
8140 	p.ctx = opts ? opts->ctx : NULL;
8141 
8142 	return __perf_buffer__new(map_fd, page_cnt, &p);
8143 }
8144 
8145 struct perf_buffer *
8146 perf_buffer__new_raw(int map_fd, size_t page_cnt,
8147 		     const struct perf_buffer_raw_opts *opts)
8148 {
8149 	struct perf_buffer_params p = {};
8150 
8151 	p.attr = opts->attr;
8152 	p.event_cb = opts->event_cb;
8153 	p.ctx = opts->ctx;
8154 	p.cpu_cnt = opts->cpu_cnt;
8155 	p.cpus = opts->cpus;
8156 	p.map_keys = opts->map_keys;
8157 
8158 	return __perf_buffer__new(map_fd, page_cnt, &p);
8159 }
8160 
8161 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
8162 					      struct perf_buffer_params *p)
8163 {
8164 	const char *online_cpus_file = "/sys/devices/system/cpu/online";
8165 	struct bpf_map_info map = {};
8166 	char msg[STRERR_BUFSIZE];
8167 	struct perf_buffer *pb;
8168 	bool *online = NULL;
8169 	__u32 map_info_len;
8170 	int err, i, j, n;
8171 
8172 	if (page_cnt & (page_cnt - 1)) {
8173 		pr_warn("page count should be power of two, but is %zu\n",
8174 			page_cnt);
8175 		return ERR_PTR(-EINVAL);
8176 	}
8177 
8178 	map_info_len = sizeof(map);
8179 	err = bpf_obj_get_info_by_fd(map_fd, &map, &map_info_len);
8180 	if (err) {
8181 		err = -errno;
8182 		pr_warn("failed to get map info for map FD %d: %s\n",
8183 			map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
8184 		return ERR_PTR(err);
8185 	}
8186 
8187 	if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
8188 		pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
8189 			map.name);
8190 		return ERR_PTR(-EINVAL);
8191 	}
8192 
8193 	pb = calloc(1, sizeof(*pb));
8194 	if (!pb)
8195 		return ERR_PTR(-ENOMEM);
8196 
8197 	pb->event_cb = p->event_cb;
8198 	pb->sample_cb = p->sample_cb;
8199 	pb->lost_cb = p->lost_cb;
8200 	pb->ctx = p->ctx;
8201 
8202 	pb->page_size = getpagesize();
8203 	pb->mmap_size = pb->page_size * page_cnt;
8204 	pb->map_fd = map_fd;
8205 
8206 	pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
8207 	if (pb->epoll_fd < 0) {
8208 		err = -errno;
8209 		pr_warn("failed to create epoll instance: %s\n",
8210 			libbpf_strerror_r(err, msg, sizeof(msg)));
8211 		goto error;
8212 	}
8213 
8214 	if (p->cpu_cnt > 0) {
8215 		pb->cpu_cnt = p->cpu_cnt;
8216 	} else {
8217 		pb->cpu_cnt = libbpf_num_possible_cpus();
8218 		if (pb->cpu_cnt < 0) {
8219 			err = pb->cpu_cnt;
8220 			goto error;
8221 		}
8222 		if (map.max_entries < pb->cpu_cnt)
8223 			pb->cpu_cnt = map.max_entries;
8224 	}
8225 
8226 	pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
8227 	if (!pb->events) {
8228 		err = -ENOMEM;
8229 		pr_warn("failed to allocate events: out of memory\n");
8230 		goto error;
8231 	}
8232 	pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
8233 	if (!pb->cpu_bufs) {
8234 		err = -ENOMEM;
8235 		pr_warn("failed to allocate buffers: out of memory\n");
8236 		goto error;
8237 	}
8238 
8239 	err = parse_cpu_mask_file(online_cpus_file, &online, &n);
8240 	if (err) {
8241 		pr_warn("failed to get online CPU mask: %d\n", err);
8242 		goto error;
8243 	}
8244 
8245 	for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
8246 		struct perf_cpu_buf *cpu_buf;
8247 		int cpu, map_key;
8248 
8249 		cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
8250 		map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
8251 
8252 		/* in case user didn't explicitly requested particular CPUs to
8253 		 * be attached to, skip offline/not present CPUs
8254 		 */
8255 		if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
8256 			continue;
8257 
8258 		cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
8259 		if (IS_ERR(cpu_buf)) {
8260 			err = PTR_ERR(cpu_buf);
8261 			goto error;
8262 		}
8263 
8264 		pb->cpu_bufs[j] = cpu_buf;
8265 
8266 		err = bpf_map_update_elem(pb->map_fd, &map_key,
8267 					  &cpu_buf->fd, 0);
8268 		if (err) {
8269 			err = -errno;
8270 			pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
8271 				cpu, map_key, cpu_buf->fd,
8272 				libbpf_strerror_r(err, msg, sizeof(msg)));
8273 			goto error;
8274 		}
8275 
8276 		pb->events[j].events = EPOLLIN;
8277 		pb->events[j].data.ptr = cpu_buf;
8278 		if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
8279 			      &pb->events[j]) < 0) {
8280 			err = -errno;
8281 			pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
8282 				cpu, cpu_buf->fd,
8283 				libbpf_strerror_r(err, msg, sizeof(msg)));
8284 			goto error;
8285 		}
8286 		j++;
8287 	}
8288 	pb->cpu_cnt = j;
8289 	free(online);
8290 
8291 	return pb;
8292 
8293 error:
8294 	free(online);
8295 	if (pb)
8296 		perf_buffer__free(pb);
8297 	return ERR_PTR(err);
8298 }
8299 
8300 struct perf_sample_raw {
8301 	struct perf_event_header header;
8302 	uint32_t size;
8303 	char data[0];
8304 };
8305 
8306 struct perf_sample_lost {
8307 	struct perf_event_header header;
8308 	uint64_t id;
8309 	uint64_t lost;
8310 	uint64_t sample_id;
8311 };
8312 
8313 static enum bpf_perf_event_ret
8314 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
8315 {
8316 	struct perf_cpu_buf *cpu_buf = ctx;
8317 	struct perf_buffer *pb = cpu_buf->pb;
8318 	void *data = e;
8319 
8320 	/* user wants full control over parsing perf event */
8321 	if (pb->event_cb)
8322 		return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
8323 
8324 	switch (e->type) {
8325 	case PERF_RECORD_SAMPLE: {
8326 		struct perf_sample_raw *s = data;
8327 
8328 		if (pb->sample_cb)
8329 			pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
8330 		break;
8331 	}
8332 	case PERF_RECORD_LOST: {
8333 		struct perf_sample_lost *s = data;
8334 
8335 		if (pb->lost_cb)
8336 			pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
8337 		break;
8338 	}
8339 	default:
8340 		pr_warn("unknown perf sample type %d\n", e->type);
8341 		return LIBBPF_PERF_EVENT_ERROR;
8342 	}
8343 	return LIBBPF_PERF_EVENT_CONT;
8344 }
8345 
8346 static int perf_buffer__process_records(struct perf_buffer *pb,
8347 					struct perf_cpu_buf *cpu_buf)
8348 {
8349 	enum bpf_perf_event_ret ret;
8350 
8351 	ret = bpf_perf_event_read_simple(cpu_buf->base, pb->mmap_size,
8352 					 pb->page_size, &cpu_buf->buf,
8353 					 &cpu_buf->buf_size,
8354 					 perf_buffer__process_record, cpu_buf);
8355 	if (ret != LIBBPF_PERF_EVENT_CONT)
8356 		return ret;
8357 	return 0;
8358 }
8359 
8360 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
8361 {
8362 	int i, cnt, err;
8363 
8364 	cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
8365 	for (i = 0; i < cnt; i++) {
8366 		struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
8367 
8368 		err = perf_buffer__process_records(pb, cpu_buf);
8369 		if (err) {
8370 			pr_warn("error while processing records: %d\n", err);
8371 			return err;
8372 		}
8373 	}
8374 	return cnt < 0 ? -errno : cnt;
8375 }
8376 
8377 struct bpf_prog_info_array_desc {
8378 	int	array_offset;	/* e.g. offset of jited_prog_insns */
8379 	int	count_offset;	/* e.g. offset of jited_prog_len */
8380 	int	size_offset;	/* > 0: offset of rec size,
8381 				 * < 0: fix size of -size_offset
8382 				 */
8383 };
8384 
8385 static struct bpf_prog_info_array_desc bpf_prog_info_array_desc[] = {
8386 	[BPF_PROG_INFO_JITED_INSNS] = {
8387 		offsetof(struct bpf_prog_info, jited_prog_insns),
8388 		offsetof(struct bpf_prog_info, jited_prog_len),
8389 		-1,
8390 	},
8391 	[BPF_PROG_INFO_XLATED_INSNS] = {
8392 		offsetof(struct bpf_prog_info, xlated_prog_insns),
8393 		offsetof(struct bpf_prog_info, xlated_prog_len),
8394 		-1,
8395 	},
8396 	[BPF_PROG_INFO_MAP_IDS] = {
8397 		offsetof(struct bpf_prog_info, map_ids),
8398 		offsetof(struct bpf_prog_info, nr_map_ids),
8399 		-(int)sizeof(__u32),
8400 	},
8401 	[BPF_PROG_INFO_JITED_KSYMS] = {
8402 		offsetof(struct bpf_prog_info, jited_ksyms),
8403 		offsetof(struct bpf_prog_info, nr_jited_ksyms),
8404 		-(int)sizeof(__u64),
8405 	},
8406 	[BPF_PROG_INFO_JITED_FUNC_LENS] = {
8407 		offsetof(struct bpf_prog_info, jited_func_lens),
8408 		offsetof(struct bpf_prog_info, nr_jited_func_lens),
8409 		-(int)sizeof(__u32),
8410 	},
8411 	[BPF_PROG_INFO_FUNC_INFO] = {
8412 		offsetof(struct bpf_prog_info, func_info),
8413 		offsetof(struct bpf_prog_info, nr_func_info),
8414 		offsetof(struct bpf_prog_info, func_info_rec_size),
8415 	},
8416 	[BPF_PROG_INFO_LINE_INFO] = {
8417 		offsetof(struct bpf_prog_info, line_info),
8418 		offsetof(struct bpf_prog_info, nr_line_info),
8419 		offsetof(struct bpf_prog_info, line_info_rec_size),
8420 	},
8421 	[BPF_PROG_INFO_JITED_LINE_INFO] = {
8422 		offsetof(struct bpf_prog_info, jited_line_info),
8423 		offsetof(struct bpf_prog_info, nr_jited_line_info),
8424 		offsetof(struct bpf_prog_info, jited_line_info_rec_size),
8425 	},
8426 	[BPF_PROG_INFO_PROG_TAGS] = {
8427 		offsetof(struct bpf_prog_info, prog_tags),
8428 		offsetof(struct bpf_prog_info, nr_prog_tags),
8429 		-(int)sizeof(__u8) * BPF_TAG_SIZE,
8430 	},
8431 
8432 };
8433 
8434 static __u32 bpf_prog_info_read_offset_u32(struct bpf_prog_info *info,
8435 					   int offset)
8436 {
8437 	__u32 *array = (__u32 *)info;
8438 
8439 	if (offset >= 0)
8440 		return array[offset / sizeof(__u32)];
8441 	return -(int)offset;
8442 }
8443 
8444 static __u64 bpf_prog_info_read_offset_u64(struct bpf_prog_info *info,
8445 					   int offset)
8446 {
8447 	__u64 *array = (__u64 *)info;
8448 
8449 	if (offset >= 0)
8450 		return array[offset / sizeof(__u64)];
8451 	return -(int)offset;
8452 }
8453 
8454 static void bpf_prog_info_set_offset_u32(struct bpf_prog_info *info, int offset,
8455 					 __u32 val)
8456 {
8457 	__u32 *array = (__u32 *)info;
8458 
8459 	if (offset >= 0)
8460 		array[offset / sizeof(__u32)] = val;
8461 }
8462 
8463 static void bpf_prog_info_set_offset_u64(struct bpf_prog_info *info, int offset,
8464 					 __u64 val)
8465 {
8466 	__u64 *array = (__u64 *)info;
8467 
8468 	if (offset >= 0)
8469 		array[offset / sizeof(__u64)] = val;
8470 }
8471 
8472 struct bpf_prog_info_linear *
8473 bpf_program__get_prog_info_linear(int fd, __u64 arrays)
8474 {
8475 	struct bpf_prog_info_linear *info_linear;
8476 	struct bpf_prog_info info = {};
8477 	__u32 info_len = sizeof(info);
8478 	__u32 data_len = 0;
8479 	int i, err;
8480 	void *ptr;
8481 
8482 	if (arrays >> BPF_PROG_INFO_LAST_ARRAY)
8483 		return ERR_PTR(-EINVAL);
8484 
8485 	/* step 1: get array dimensions */
8486 	err = bpf_obj_get_info_by_fd(fd, &info, &info_len);
8487 	if (err) {
8488 		pr_debug("can't get prog info: %s", strerror(errno));
8489 		return ERR_PTR(-EFAULT);
8490 	}
8491 
8492 	/* step 2: calculate total size of all arrays */
8493 	for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
8494 		bool include_array = (arrays & (1UL << i)) > 0;
8495 		struct bpf_prog_info_array_desc *desc;
8496 		__u32 count, size;
8497 
8498 		desc = bpf_prog_info_array_desc + i;
8499 
8500 		/* kernel is too old to support this field */
8501 		if (info_len < desc->array_offset + sizeof(__u32) ||
8502 		    info_len < desc->count_offset + sizeof(__u32) ||
8503 		    (desc->size_offset > 0 && info_len < desc->size_offset))
8504 			include_array = false;
8505 
8506 		if (!include_array) {
8507 			arrays &= ~(1UL << i);	/* clear the bit */
8508 			continue;
8509 		}
8510 
8511 		count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
8512 		size  = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
8513 
8514 		data_len += count * size;
8515 	}
8516 
8517 	/* step 3: allocate continuous memory */
8518 	data_len = roundup(data_len, sizeof(__u64));
8519 	info_linear = malloc(sizeof(struct bpf_prog_info_linear) + data_len);
8520 	if (!info_linear)
8521 		return ERR_PTR(-ENOMEM);
8522 
8523 	/* step 4: fill data to info_linear->info */
8524 	info_linear->arrays = arrays;
8525 	memset(&info_linear->info, 0, sizeof(info));
8526 	ptr = info_linear->data;
8527 
8528 	for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
8529 		struct bpf_prog_info_array_desc *desc;
8530 		__u32 count, size;
8531 
8532 		if ((arrays & (1UL << i)) == 0)
8533 			continue;
8534 
8535 		desc  = bpf_prog_info_array_desc + i;
8536 		count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
8537 		size  = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
8538 		bpf_prog_info_set_offset_u32(&info_linear->info,
8539 					     desc->count_offset, count);
8540 		bpf_prog_info_set_offset_u32(&info_linear->info,
8541 					     desc->size_offset, size);
8542 		bpf_prog_info_set_offset_u64(&info_linear->info,
8543 					     desc->array_offset,
8544 					     ptr_to_u64(ptr));
8545 		ptr += count * size;
8546 	}
8547 
8548 	/* step 5: call syscall again to get required arrays */
8549 	err = bpf_obj_get_info_by_fd(fd, &info_linear->info, &info_len);
8550 	if (err) {
8551 		pr_debug("can't get prog info: %s", strerror(errno));
8552 		free(info_linear);
8553 		return ERR_PTR(-EFAULT);
8554 	}
8555 
8556 	/* step 6: verify the data */
8557 	for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
8558 		struct bpf_prog_info_array_desc *desc;
8559 		__u32 v1, v2;
8560 
8561 		if ((arrays & (1UL << i)) == 0)
8562 			continue;
8563 
8564 		desc = bpf_prog_info_array_desc + i;
8565 		v1 = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
8566 		v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
8567 						   desc->count_offset);
8568 		if (v1 != v2)
8569 			pr_warn("%s: mismatch in element count\n", __func__);
8570 
8571 		v1 = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
8572 		v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
8573 						   desc->size_offset);
8574 		if (v1 != v2)
8575 			pr_warn("%s: mismatch in rec size\n", __func__);
8576 	}
8577 
8578 	/* step 7: update info_len and data_len */
8579 	info_linear->info_len = sizeof(struct bpf_prog_info);
8580 	info_linear->data_len = data_len;
8581 
8582 	return info_linear;
8583 }
8584 
8585 void bpf_program__bpil_addr_to_offs(struct bpf_prog_info_linear *info_linear)
8586 {
8587 	int i;
8588 
8589 	for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
8590 		struct bpf_prog_info_array_desc *desc;
8591 		__u64 addr, offs;
8592 
8593 		if ((info_linear->arrays & (1UL << i)) == 0)
8594 			continue;
8595 
8596 		desc = bpf_prog_info_array_desc + i;
8597 		addr = bpf_prog_info_read_offset_u64(&info_linear->info,
8598 						     desc->array_offset);
8599 		offs = addr - ptr_to_u64(info_linear->data);
8600 		bpf_prog_info_set_offset_u64(&info_linear->info,
8601 					     desc->array_offset, offs);
8602 	}
8603 }
8604 
8605 void bpf_program__bpil_offs_to_addr(struct bpf_prog_info_linear *info_linear)
8606 {
8607 	int i;
8608 
8609 	for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
8610 		struct bpf_prog_info_array_desc *desc;
8611 		__u64 addr, offs;
8612 
8613 		if ((info_linear->arrays & (1UL << i)) == 0)
8614 			continue;
8615 
8616 		desc = bpf_prog_info_array_desc + i;
8617 		offs = bpf_prog_info_read_offset_u64(&info_linear->info,
8618 						     desc->array_offset);
8619 		addr = offs + ptr_to_u64(info_linear->data);
8620 		bpf_prog_info_set_offset_u64(&info_linear->info,
8621 					     desc->array_offset, addr);
8622 	}
8623 }
8624 
8625 int bpf_program__set_attach_target(struct bpf_program *prog,
8626 				   int attach_prog_fd,
8627 				   const char *attach_func_name)
8628 {
8629 	int btf_id;
8630 
8631 	if (!prog || attach_prog_fd < 0 || !attach_func_name)
8632 		return -EINVAL;
8633 
8634 	if (attach_prog_fd)
8635 		btf_id = libbpf_find_prog_btf_id(attach_func_name,
8636 						 attach_prog_fd);
8637 	else
8638 		btf_id = __find_vmlinux_btf_id(prog->obj->btf_vmlinux,
8639 					       attach_func_name,
8640 					       prog->expected_attach_type);
8641 
8642 	if (btf_id < 0)
8643 		return btf_id;
8644 
8645 	prog->attach_btf_id = btf_id;
8646 	prog->attach_prog_fd = attach_prog_fd;
8647 	return 0;
8648 }
8649 
8650 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
8651 {
8652 	int err = 0, n, len, start, end = -1;
8653 	bool *tmp;
8654 
8655 	*mask = NULL;
8656 	*mask_sz = 0;
8657 
8658 	/* Each sub string separated by ',' has format \d+-\d+ or \d+ */
8659 	while (*s) {
8660 		if (*s == ',' || *s == '\n') {
8661 			s++;
8662 			continue;
8663 		}
8664 		n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
8665 		if (n <= 0 || n > 2) {
8666 			pr_warn("Failed to get CPU range %s: %d\n", s, n);
8667 			err = -EINVAL;
8668 			goto cleanup;
8669 		} else if (n == 1) {
8670 			end = start;
8671 		}
8672 		if (start < 0 || start > end) {
8673 			pr_warn("Invalid CPU range [%d,%d] in %s\n",
8674 				start, end, s);
8675 			err = -EINVAL;
8676 			goto cleanup;
8677 		}
8678 		tmp = realloc(*mask, end + 1);
8679 		if (!tmp) {
8680 			err = -ENOMEM;
8681 			goto cleanup;
8682 		}
8683 		*mask = tmp;
8684 		memset(tmp + *mask_sz, 0, start - *mask_sz);
8685 		memset(tmp + start, 1, end - start + 1);
8686 		*mask_sz = end + 1;
8687 		s += len;
8688 	}
8689 	if (!*mask_sz) {
8690 		pr_warn("Empty CPU range\n");
8691 		return -EINVAL;
8692 	}
8693 	return 0;
8694 cleanup:
8695 	free(*mask);
8696 	*mask = NULL;
8697 	return err;
8698 }
8699 
8700 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
8701 {
8702 	int fd, err = 0, len;
8703 	char buf[128];
8704 
8705 	fd = open(fcpu, O_RDONLY);
8706 	if (fd < 0) {
8707 		err = -errno;
8708 		pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
8709 		return err;
8710 	}
8711 	len = read(fd, buf, sizeof(buf));
8712 	close(fd);
8713 	if (len <= 0) {
8714 		err = len ? -errno : -EINVAL;
8715 		pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
8716 		return err;
8717 	}
8718 	if (len >= sizeof(buf)) {
8719 		pr_warn("CPU mask is too big in file %s\n", fcpu);
8720 		return -E2BIG;
8721 	}
8722 	buf[len] = '\0';
8723 
8724 	return parse_cpu_mask_str(buf, mask, mask_sz);
8725 }
8726 
8727 int libbpf_num_possible_cpus(void)
8728 {
8729 	static const char *fcpu = "/sys/devices/system/cpu/possible";
8730 	static int cpus;
8731 	int err, n, i, tmp_cpus;
8732 	bool *mask;
8733 
8734 	tmp_cpus = READ_ONCE(cpus);
8735 	if (tmp_cpus > 0)
8736 		return tmp_cpus;
8737 
8738 	err = parse_cpu_mask_file(fcpu, &mask, &n);
8739 	if (err)
8740 		return err;
8741 
8742 	tmp_cpus = 0;
8743 	for (i = 0; i < n; i++) {
8744 		if (mask[i])
8745 			tmp_cpus++;
8746 	}
8747 	free(mask);
8748 
8749 	WRITE_ONCE(cpus, tmp_cpus);
8750 	return tmp_cpus;
8751 }
8752 
8753 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
8754 			      const struct bpf_object_open_opts *opts)
8755 {
8756 	DECLARE_LIBBPF_OPTS(bpf_object_open_opts, skel_opts,
8757 		.object_name = s->name,
8758 	);
8759 	struct bpf_object *obj;
8760 	int i;
8761 
8762 	/* Attempt to preserve opts->object_name, unless overriden by user
8763 	 * explicitly. Overwriting object name for skeletons is discouraged,
8764 	 * as it breaks global data maps, because they contain object name
8765 	 * prefix as their own map name prefix. When skeleton is generated,
8766 	 * bpftool is making an assumption that this name will stay the same.
8767 	 */
8768 	if (opts) {
8769 		memcpy(&skel_opts, opts, sizeof(*opts));
8770 		if (!opts->object_name)
8771 			skel_opts.object_name = s->name;
8772 	}
8773 
8774 	obj = bpf_object__open_mem(s->data, s->data_sz, &skel_opts);
8775 	if (IS_ERR(obj)) {
8776 		pr_warn("failed to initialize skeleton BPF object '%s': %ld\n",
8777 			s->name, PTR_ERR(obj));
8778 		return PTR_ERR(obj);
8779 	}
8780 
8781 	*s->obj = obj;
8782 
8783 	for (i = 0; i < s->map_cnt; i++) {
8784 		struct bpf_map **map = s->maps[i].map;
8785 		const char *name = s->maps[i].name;
8786 		void **mmaped = s->maps[i].mmaped;
8787 
8788 		*map = bpf_object__find_map_by_name(obj, name);
8789 		if (!*map) {
8790 			pr_warn("failed to find skeleton map '%s'\n", name);
8791 			return -ESRCH;
8792 		}
8793 
8794 		/* externs shouldn't be pre-setup from user code */
8795 		if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
8796 			*mmaped = (*map)->mmaped;
8797 	}
8798 
8799 	for (i = 0; i < s->prog_cnt; i++) {
8800 		struct bpf_program **prog = s->progs[i].prog;
8801 		const char *name = s->progs[i].name;
8802 
8803 		*prog = bpf_object__find_program_by_name(obj, name);
8804 		if (!*prog) {
8805 			pr_warn("failed to find skeleton program '%s'\n", name);
8806 			return -ESRCH;
8807 		}
8808 	}
8809 
8810 	return 0;
8811 }
8812 
8813 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
8814 {
8815 	int i, err;
8816 
8817 	err = bpf_object__load(*s->obj);
8818 	if (err) {
8819 		pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
8820 		return err;
8821 	}
8822 
8823 	for (i = 0; i < s->map_cnt; i++) {
8824 		struct bpf_map *map = *s->maps[i].map;
8825 		size_t mmap_sz = bpf_map_mmap_sz(map);
8826 		int prot, map_fd = bpf_map__fd(map);
8827 		void **mmaped = s->maps[i].mmaped;
8828 
8829 		if (!mmaped)
8830 			continue;
8831 
8832 		if (!(map->def.map_flags & BPF_F_MMAPABLE)) {
8833 			*mmaped = NULL;
8834 			continue;
8835 		}
8836 
8837 		if (map->def.map_flags & BPF_F_RDONLY_PROG)
8838 			prot = PROT_READ;
8839 		else
8840 			prot = PROT_READ | PROT_WRITE;
8841 
8842 		/* Remap anonymous mmap()-ed "map initialization image" as
8843 		 * a BPF map-backed mmap()-ed memory, but preserving the same
8844 		 * memory address. This will cause kernel to change process'
8845 		 * page table to point to a different piece of kernel memory,
8846 		 * but from userspace point of view memory address (and its
8847 		 * contents, being identical at this point) will stay the
8848 		 * same. This mapping will be released by bpf_object__close()
8849 		 * as per normal clean up procedure, so we don't need to worry
8850 		 * about it from skeleton's clean up perspective.
8851 		 */
8852 		*mmaped = mmap(map->mmaped, mmap_sz, prot,
8853 				MAP_SHARED | MAP_FIXED, map_fd, 0);
8854 		if (*mmaped == MAP_FAILED) {
8855 			err = -errno;
8856 			*mmaped = NULL;
8857 			pr_warn("failed to re-mmap() map '%s': %d\n",
8858 				 bpf_map__name(map), err);
8859 			return err;
8860 		}
8861 	}
8862 
8863 	return 0;
8864 }
8865 
8866 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
8867 {
8868 	int i;
8869 
8870 	for (i = 0; i < s->prog_cnt; i++) {
8871 		struct bpf_program *prog = *s->progs[i].prog;
8872 		struct bpf_link **link = s->progs[i].link;
8873 		const struct bpf_sec_def *sec_def;
8874 		const char *sec_name = bpf_program__title(prog, false);
8875 
8876 		sec_def = find_sec_def(sec_name);
8877 		if (!sec_def || !sec_def->attach_fn)
8878 			continue;
8879 
8880 		*link = sec_def->attach_fn(sec_def, prog);
8881 		if (IS_ERR(*link)) {
8882 			pr_warn("failed to auto-attach program '%s': %ld\n",
8883 				bpf_program__name(prog), PTR_ERR(*link));
8884 			return PTR_ERR(*link);
8885 		}
8886 	}
8887 
8888 	return 0;
8889 }
8890 
8891 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
8892 {
8893 	int i;
8894 
8895 	for (i = 0; i < s->prog_cnt; i++) {
8896 		struct bpf_link **link = s->progs[i].link;
8897 
8898 		if (!IS_ERR_OR_NULL(*link))
8899 			bpf_link__destroy(*link);
8900 		*link = NULL;
8901 	}
8902 }
8903 
8904 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
8905 {
8906 	if (s->progs)
8907 		bpf_object__detach_skeleton(s);
8908 	if (s->obj)
8909 		bpf_object__close(*s->obj);
8910 	free(s->maps);
8911 	free(s->progs);
8912 	free(s);
8913 }
8914