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