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