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