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