xref: /linux/tools/lib/bpf/libbpf.c (revision 31d166642c7c601c65eccf0ff2e0afe9a0538be2)
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 <fcntl.h>
24 #include <errno.h>
25 #include <asm/unistd.h>
26 #include <linux/err.h>
27 #include <linux/kernel.h>
28 #include <linux/bpf.h>
29 #include <linux/btf.h>
30 #include <linux/filter.h>
31 #include <linux/list.h>
32 #include <linux/limits.h>
33 #include <linux/perf_event.h>
34 #include <linux/ring_buffer.h>
35 #include <sys/stat.h>
36 #include <sys/types.h>
37 #include <sys/vfs.h>
38 #include <tools/libc_compat.h>
39 #include <libelf.h>
40 #include <gelf.h>
41 
42 #include "libbpf.h"
43 #include "bpf.h"
44 #include "btf.h"
45 #include "str_error.h"
46 #include "libbpf_internal.h"
47 
48 #ifndef EM_BPF
49 #define EM_BPF 247
50 #endif
51 
52 #ifndef BPF_FS_MAGIC
53 #define BPF_FS_MAGIC		0xcafe4a11
54 #endif
55 
56 /* vsprintf() in __base_pr() uses nonliteral format string. It may break
57  * compilation if user enables corresponding warning. Disable it explicitly.
58  */
59 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
60 
61 #define __printf(a, b)	__attribute__((format(printf, a, b)))
62 
63 static int __base_pr(enum libbpf_print_level level, const char *format,
64 		     va_list args)
65 {
66 	if (level == LIBBPF_DEBUG)
67 		return 0;
68 
69 	return vfprintf(stderr, format, args);
70 }
71 
72 static libbpf_print_fn_t __libbpf_pr = __base_pr;
73 
74 void libbpf_set_print(libbpf_print_fn_t fn)
75 {
76 	__libbpf_pr = fn;
77 }
78 
79 __printf(2, 3)
80 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
81 {
82 	va_list args;
83 
84 	if (!__libbpf_pr)
85 		return;
86 
87 	va_start(args, format);
88 	__libbpf_pr(level, format, args);
89 	va_end(args);
90 }
91 
92 #define STRERR_BUFSIZE  128
93 
94 #define CHECK_ERR(action, err, out) do {	\
95 	err = action;			\
96 	if (err)			\
97 		goto out;		\
98 } while(0)
99 
100 
101 /* Copied from tools/perf/util/util.h */
102 #ifndef zfree
103 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
104 #endif
105 
106 #ifndef zclose
107 # define zclose(fd) ({			\
108 	int ___err = 0;			\
109 	if ((fd) >= 0)			\
110 		___err = close((fd));	\
111 	fd = -1;			\
112 	___err; })
113 #endif
114 
115 #ifdef HAVE_LIBELF_MMAP_SUPPORT
116 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ_MMAP
117 #else
118 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ
119 #endif
120 
121 static inline __u64 ptr_to_u64(const void *ptr)
122 {
123 	return (__u64) (unsigned long) ptr;
124 }
125 
126 struct bpf_capabilities {
127 	/* v4.14: kernel support for program & map names. */
128 	__u32 name:1;
129 	/* v5.2: kernel support for global data sections. */
130 	__u32 global_data:1;
131 	/* BTF_KIND_FUNC and BTF_KIND_FUNC_PROTO support */
132 	__u32 btf_func:1;
133 	/* BTF_KIND_VAR and BTF_KIND_DATASEC support */
134 	__u32 btf_datasec:1;
135 };
136 
137 /*
138  * bpf_prog should be a better name but it has been used in
139  * linux/filter.h.
140  */
141 struct bpf_program {
142 	/* Index in elf obj file, for relocation use. */
143 	int idx;
144 	char *name;
145 	int prog_ifindex;
146 	char *section_name;
147 	/* section_name with / replaced by _; makes recursive pinning
148 	 * in bpf_object__pin_programs easier
149 	 */
150 	char *pin_name;
151 	struct bpf_insn *insns;
152 	size_t insns_cnt, main_prog_cnt;
153 	enum bpf_prog_type type;
154 
155 	struct reloc_desc {
156 		enum {
157 			RELO_LD64,
158 			RELO_CALL,
159 			RELO_DATA,
160 		} type;
161 		int insn_idx;
162 		union {
163 			int map_idx;
164 			int text_off;
165 		};
166 	} *reloc_desc;
167 	int nr_reloc;
168 	int log_level;
169 
170 	struct {
171 		int nr;
172 		int *fds;
173 	} instances;
174 	bpf_program_prep_t preprocessor;
175 
176 	struct bpf_object *obj;
177 	void *priv;
178 	bpf_program_clear_priv_t clear_priv;
179 
180 	enum bpf_attach_type expected_attach_type;
181 	int btf_fd;
182 	void *func_info;
183 	__u32 func_info_rec_size;
184 	__u32 func_info_cnt;
185 
186 	struct bpf_capabilities *caps;
187 
188 	void *line_info;
189 	__u32 line_info_rec_size;
190 	__u32 line_info_cnt;
191 	__u32 prog_flags;
192 };
193 
194 enum libbpf_map_type {
195 	LIBBPF_MAP_UNSPEC,
196 	LIBBPF_MAP_DATA,
197 	LIBBPF_MAP_BSS,
198 	LIBBPF_MAP_RODATA,
199 };
200 
201 static const char * const libbpf_type_to_btf_name[] = {
202 	[LIBBPF_MAP_DATA]	= ".data",
203 	[LIBBPF_MAP_BSS]	= ".bss",
204 	[LIBBPF_MAP_RODATA]	= ".rodata",
205 };
206 
207 struct bpf_map {
208 	int fd;
209 	char *name;
210 	int sec_idx;
211 	size_t sec_offset;
212 	int map_ifindex;
213 	int inner_map_fd;
214 	struct bpf_map_def def;
215 	__u32 btf_key_type_id;
216 	__u32 btf_value_type_id;
217 	void *priv;
218 	bpf_map_clear_priv_t clear_priv;
219 	enum libbpf_map_type libbpf_type;
220 };
221 
222 struct bpf_secdata {
223 	void *rodata;
224 	void *data;
225 };
226 
227 static LIST_HEAD(bpf_objects_list);
228 
229 struct bpf_object {
230 	char name[BPF_OBJ_NAME_LEN];
231 	char license[64];
232 	__u32 kern_version;
233 
234 	struct bpf_program *programs;
235 	size_t nr_programs;
236 	struct bpf_map *maps;
237 	size_t nr_maps;
238 	size_t maps_cap;
239 	struct bpf_secdata sections;
240 
241 	bool loaded;
242 	bool has_pseudo_calls;
243 
244 	/*
245 	 * Information when doing elf related work. Only valid if fd
246 	 * is valid.
247 	 */
248 	struct {
249 		int fd;
250 		void *obj_buf;
251 		size_t obj_buf_sz;
252 		Elf *elf;
253 		GElf_Ehdr ehdr;
254 		Elf_Data *symbols;
255 		Elf_Data *data;
256 		Elf_Data *rodata;
257 		Elf_Data *bss;
258 		size_t strtabidx;
259 		struct {
260 			GElf_Shdr shdr;
261 			Elf_Data *data;
262 		} *reloc;
263 		int nr_reloc;
264 		int maps_shndx;
265 		int btf_maps_shndx;
266 		int text_shndx;
267 		int data_shndx;
268 		int rodata_shndx;
269 		int bss_shndx;
270 	} efile;
271 	/*
272 	 * All loaded bpf_object is linked in a list, which is
273 	 * hidden to caller. bpf_objects__<func> handlers deal with
274 	 * all objects.
275 	 */
276 	struct list_head list;
277 
278 	struct btf *btf;
279 	struct btf_ext *btf_ext;
280 
281 	void *priv;
282 	bpf_object_clear_priv_t clear_priv;
283 
284 	struct bpf_capabilities caps;
285 
286 	char path[];
287 };
288 #define obj_elf_valid(o)	((o)->efile.elf)
289 
290 void bpf_program__unload(struct bpf_program *prog)
291 {
292 	int i;
293 
294 	if (!prog)
295 		return;
296 
297 	/*
298 	 * If the object is opened but the program was never loaded,
299 	 * it is possible that prog->instances.nr == -1.
300 	 */
301 	if (prog->instances.nr > 0) {
302 		for (i = 0; i < prog->instances.nr; i++)
303 			zclose(prog->instances.fds[i]);
304 	} else if (prog->instances.nr != -1) {
305 		pr_warning("Internal error: instances.nr is %d\n",
306 			   prog->instances.nr);
307 	}
308 
309 	prog->instances.nr = -1;
310 	zfree(&prog->instances.fds);
311 
312 	zclose(prog->btf_fd);
313 	zfree(&prog->func_info);
314 	zfree(&prog->line_info);
315 }
316 
317 static void bpf_program__exit(struct bpf_program *prog)
318 {
319 	if (!prog)
320 		return;
321 
322 	if (prog->clear_priv)
323 		prog->clear_priv(prog, prog->priv);
324 
325 	prog->priv = NULL;
326 	prog->clear_priv = NULL;
327 
328 	bpf_program__unload(prog);
329 	zfree(&prog->name);
330 	zfree(&prog->section_name);
331 	zfree(&prog->pin_name);
332 	zfree(&prog->insns);
333 	zfree(&prog->reloc_desc);
334 
335 	prog->nr_reloc = 0;
336 	prog->insns_cnt = 0;
337 	prog->idx = -1;
338 }
339 
340 static char *__bpf_program__pin_name(struct bpf_program *prog)
341 {
342 	char *name, *p;
343 
344 	name = p = strdup(prog->section_name);
345 	while ((p = strchr(p, '/')))
346 		*p = '_';
347 
348 	return name;
349 }
350 
351 static int
352 bpf_program__init(void *data, size_t size, char *section_name, int idx,
353 		  struct bpf_program *prog)
354 {
355 	const size_t bpf_insn_sz = sizeof(struct bpf_insn);
356 
357 	if (size == 0 || size % bpf_insn_sz) {
358 		pr_warning("corrupted section '%s', size: %zu\n",
359 			   section_name, size);
360 		return -EINVAL;
361 	}
362 
363 	memset(prog, 0, sizeof(*prog));
364 
365 	prog->section_name = strdup(section_name);
366 	if (!prog->section_name) {
367 		pr_warning("failed to alloc name for prog under section(%d) %s\n",
368 			   idx, section_name);
369 		goto errout;
370 	}
371 
372 	prog->pin_name = __bpf_program__pin_name(prog);
373 	if (!prog->pin_name) {
374 		pr_warning("failed to alloc pin name for prog under section(%d) %s\n",
375 			   idx, section_name);
376 		goto errout;
377 	}
378 
379 	prog->insns = malloc(size);
380 	if (!prog->insns) {
381 		pr_warning("failed to alloc insns for prog under section %s\n",
382 			   section_name);
383 		goto errout;
384 	}
385 	prog->insns_cnt = size / bpf_insn_sz;
386 	memcpy(prog->insns, data, size);
387 	prog->idx = idx;
388 	prog->instances.fds = NULL;
389 	prog->instances.nr = -1;
390 	prog->type = BPF_PROG_TYPE_UNSPEC;
391 	prog->btf_fd = -1;
392 
393 	return 0;
394 errout:
395 	bpf_program__exit(prog);
396 	return -ENOMEM;
397 }
398 
399 static int
400 bpf_object__add_program(struct bpf_object *obj, void *data, size_t size,
401 			char *section_name, int idx)
402 {
403 	struct bpf_program prog, *progs;
404 	int nr_progs, err;
405 
406 	err = bpf_program__init(data, size, section_name, idx, &prog);
407 	if (err)
408 		return err;
409 
410 	prog.caps = &obj->caps;
411 	progs = obj->programs;
412 	nr_progs = obj->nr_programs;
413 
414 	progs = reallocarray(progs, nr_progs + 1, sizeof(progs[0]));
415 	if (!progs) {
416 		/*
417 		 * In this case the original obj->programs
418 		 * is still valid, so don't need special treat for
419 		 * bpf_close_object().
420 		 */
421 		pr_warning("failed to alloc a new program under section '%s'\n",
422 			   section_name);
423 		bpf_program__exit(&prog);
424 		return -ENOMEM;
425 	}
426 
427 	pr_debug("found program %s\n", prog.section_name);
428 	obj->programs = progs;
429 	obj->nr_programs = nr_progs + 1;
430 	prog.obj = obj;
431 	progs[nr_progs] = prog;
432 	return 0;
433 }
434 
435 static int
436 bpf_object__init_prog_names(struct bpf_object *obj)
437 {
438 	Elf_Data *symbols = obj->efile.symbols;
439 	struct bpf_program *prog;
440 	size_t pi, si;
441 
442 	for (pi = 0; pi < obj->nr_programs; pi++) {
443 		const char *name = NULL;
444 
445 		prog = &obj->programs[pi];
446 
447 		for (si = 0; si < symbols->d_size / sizeof(GElf_Sym) && !name;
448 		     si++) {
449 			GElf_Sym sym;
450 
451 			if (!gelf_getsym(symbols, si, &sym))
452 				continue;
453 			if (sym.st_shndx != prog->idx)
454 				continue;
455 			if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL)
456 				continue;
457 
458 			name = elf_strptr(obj->efile.elf,
459 					  obj->efile.strtabidx,
460 					  sym.st_name);
461 			if (!name) {
462 				pr_warning("failed to get sym name string for prog %s\n",
463 					   prog->section_name);
464 				return -LIBBPF_ERRNO__LIBELF;
465 			}
466 		}
467 
468 		if (!name && prog->idx == obj->efile.text_shndx)
469 			name = ".text";
470 
471 		if (!name) {
472 			pr_warning("failed to find sym for prog %s\n",
473 				   prog->section_name);
474 			return -EINVAL;
475 		}
476 
477 		prog->name = strdup(name);
478 		if (!prog->name) {
479 			pr_warning("failed to allocate memory for prog sym %s\n",
480 				   name);
481 			return -ENOMEM;
482 		}
483 	}
484 
485 	return 0;
486 }
487 
488 static struct bpf_object *bpf_object__new(const char *path,
489 					  void *obj_buf,
490 					  size_t obj_buf_sz)
491 {
492 	struct bpf_object *obj;
493 	char *end;
494 
495 	obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
496 	if (!obj) {
497 		pr_warning("alloc memory failed for %s\n", path);
498 		return ERR_PTR(-ENOMEM);
499 	}
500 
501 	strcpy(obj->path, path);
502 	/* Using basename() GNU version which doesn't modify arg. */
503 	strncpy(obj->name, basename((void *)path), sizeof(obj->name) - 1);
504 	end = strchr(obj->name, '.');
505 	if (end)
506 		*end = 0;
507 
508 	obj->efile.fd = -1;
509 	/*
510 	 * Caller of this function should also call
511 	 * bpf_object__elf_finish() after data collection to return
512 	 * obj_buf to user. If not, we should duplicate the buffer to
513 	 * avoid user freeing them before elf finish.
514 	 */
515 	obj->efile.obj_buf = obj_buf;
516 	obj->efile.obj_buf_sz = obj_buf_sz;
517 	obj->efile.maps_shndx = -1;
518 	obj->efile.btf_maps_shndx = -1;
519 	obj->efile.data_shndx = -1;
520 	obj->efile.rodata_shndx = -1;
521 	obj->efile.bss_shndx = -1;
522 
523 	obj->loaded = false;
524 
525 	INIT_LIST_HEAD(&obj->list);
526 	list_add(&obj->list, &bpf_objects_list);
527 	return obj;
528 }
529 
530 static void bpf_object__elf_finish(struct bpf_object *obj)
531 {
532 	if (!obj_elf_valid(obj))
533 		return;
534 
535 	if (obj->efile.elf) {
536 		elf_end(obj->efile.elf);
537 		obj->efile.elf = NULL;
538 	}
539 	obj->efile.symbols = NULL;
540 	obj->efile.data = NULL;
541 	obj->efile.rodata = NULL;
542 	obj->efile.bss = NULL;
543 
544 	zfree(&obj->efile.reloc);
545 	obj->efile.nr_reloc = 0;
546 	zclose(obj->efile.fd);
547 	obj->efile.obj_buf = NULL;
548 	obj->efile.obj_buf_sz = 0;
549 }
550 
551 static int bpf_object__elf_init(struct bpf_object *obj)
552 {
553 	int err = 0;
554 	GElf_Ehdr *ep;
555 
556 	if (obj_elf_valid(obj)) {
557 		pr_warning("elf init: internal error\n");
558 		return -LIBBPF_ERRNO__LIBELF;
559 	}
560 
561 	if (obj->efile.obj_buf_sz > 0) {
562 		/*
563 		 * obj_buf should have been validated by
564 		 * bpf_object__open_buffer().
565 		 */
566 		obj->efile.elf = elf_memory(obj->efile.obj_buf,
567 					    obj->efile.obj_buf_sz);
568 	} else {
569 		obj->efile.fd = open(obj->path, O_RDONLY);
570 		if (obj->efile.fd < 0) {
571 			char errmsg[STRERR_BUFSIZE], *cp;
572 
573 			err = -errno;
574 			cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
575 			pr_warning("failed to open %s: %s\n", obj->path, cp);
576 			return err;
577 		}
578 
579 		obj->efile.elf = elf_begin(obj->efile.fd,
580 					   LIBBPF_ELF_C_READ_MMAP, NULL);
581 	}
582 
583 	if (!obj->efile.elf) {
584 		pr_warning("failed to open %s as ELF file\n", obj->path);
585 		err = -LIBBPF_ERRNO__LIBELF;
586 		goto errout;
587 	}
588 
589 	if (!gelf_getehdr(obj->efile.elf, &obj->efile.ehdr)) {
590 		pr_warning("failed to get EHDR from %s\n", obj->path);
591 		err = -LIBBPF_ERRNO__FORMAT;
592 		goto errout;
593 	}
594 	ep = &obj->efile.ehdr;
595 
596 	/* Old LLVM set e_machine to EM_NONE */
597 	if (ep->e_type != ET_REL ||
598 	    (ep->e_machine && ep->e_machine != EM_BPF)) {
599 		pr_warning("%s is not an eBPF object file\n", obj->path);
600 		err = -LIBBPF_ERRNO__FORMAT;
601 		goto errout;
602 	}
603 
604 	return 0;
605 errout:
606 	bpf_object__elf_finish(obj);
607 	return err;
608 }
609 
610 static int bpf_object__check_endianness(struct bpf_object *obj)
611 {
612 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
613 	if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2LSB)
614 		return 0;
615 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
616 	if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2MSB)
617 		return 0;
618 #else
619 # error "Unrecognized __BYTE_ORDER__"
620 #endif
621 	pr_warning("endianness mismatch.\n");
622 	return -LIBBPF_ERRNO__ENDIAN;
623 }
624 
625 static int
626 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
627 {
628 	memcpy(obj->license, data, min(size, sizeof(obj->license) - 1));
629 	pr_debug("license of %s is %s\n", obj->path, obj->license);
630 	return 0;
631 }
632 
633 static int
634 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
635 {
636 	__u32 kver;
637 
638 	if (size != sizeof(kver)) {
639 		pr_warning("invalid kver section in %s\n", obj->path);
640 		return -LIBBPF_ERRNO__FORMAT;
641 	}
642 	memcpy(&kver, data, sizeof(kver));
643 	obj->kern_version = kver;
644 	pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
645 	return 0;
646 }
647 
648 static int compare_bpf_map(const void *_a, const void *_b)
649 {
650 	const struct bpf_map *a = _a;
651 	const struct bpf_map *b = _b;
652 
653 	if (a->sec_idx != b->sec_idx)
654 		return a->sec_idx - b->sec_idx;
655 	return a->sec_offset - b->sec_offset;
656 }
657 
658 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
659 {
660 	if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
661 	    type == BPF_MAP_TYPE_HASH_OF_MAPS)
662 		return true;
663 	return false;
664 }
665 
666 static int bpf_object_search_section_size(const struct bpf_object *obj,
667 					  const char *name, size_t *d_size)
668 {
669 	const GElf_Ehdr *ep = &obj->efile.ehdr;
670 	Elf *elf = obj->efile.elf;
671 	Elf_Scn *scn = NULL;
672 	int idx = 0;
673 
674 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
675 		const char *sec_name;
676 		Elf_Data *data;
677 		GElf_Shdr sh;
678 
679 		idx++;
680 		if (gelf_getshdr(scn, &sh) != &sh) {
681 			pr_warning("failed to get section(%d) header from %s\n",
682 				   idx, obj->path);
683 			return -EIO;
684 		}
685 
686 		sec_name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
687 		if (!sec_name) {
688 			pr_warning("failed to get section(%d) name from %s\n",
689 				   idx, obj->path);
690 			return -EIO;
691 		}
692 
693 		if (strcmp(name, sec_name))
694 			continue;
695 
696 		data = elf_getdata(scn, 0);
697 		if (!data) {
698 			pr_warning("failed to get section(%d) data from %s(%s)\n",
699 				   idx, name, obj->path);
700 			return -EIO;
701 		}
702 
703 		*d_size = data->d_size;
704 		return 0;
705 	}
706 
707 	return -ENOENT;
708 }
709 
710 int bpf_object__section_size(const struct bpf_object *obj, const char *name,
711 			     __u32 *size)
712 {
713 	int ret = -ENOENT;
714 	size_t d_size;
715 
716 	*size = 0;
717 	if (!name) {
718 		return -EINVAL;
719 	} else if (!strcmp(name, ".data")) {
720 		if (obj->efile.data)
721 			*size = obj->efile.data->d_size;
722 	} else if (!strcmp(name, ".bss")) {
723 		if (obj->efile.bss)
724 			*size = obj->efile.bss->d_size;
725 	} else if (!strcmp(name, ".rodata")) {
726 		if (obj->efile.rodata)
727 			*size = obj->efile.rodata->d_size;
728 	} else {
729 		ret = bpf_object_search_section_size(obj, name, &d_size);
730 		if (!ret)
731 			*size = d_size;
732 	}
733 
734 	return *size ? 0 : ret;
735 }
736 
737 int bpf_object__variable_offset(const struct bpf_object *obj, const char *name,
738 				__u32 *off)
739 {
740 	Elf_Data *symbols = obj->efile.symbols;
741 	const char *sname;
742 	size_t si;
743 
744 	if (!name || !off)
745 		return -EINVAL;
746 
747 	for (si = 0; si < symbols->d_size / sizeof(GElf_Sym); si++) {
748 		GElf_Sym sym;
749 
750 		if (!gelf_getsym(symbols, si, &sym))
751 			continue;
752 		if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL ||
753 		    GELF_ST_TYPE(sym.st_info) != STT_OBJECT)
754 			continue;
755 
756 		sname = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
757 				   sym.st_name);
758 		if (!sname) {
759 			pr_warning("failed to get sym name string for var %s\n",
760 				   name);
761 			return -EIO;
762 		}
763 		if (strcmp(name, sname) == 0) {
764 			*off = sym.st_value;
765 			return 0;
766 		}
767 	}
768 
769 	return -ENOENT;
770 }
771 
772 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
773 {
774 	struct bpf_map *new_maps;
775 	size_t new_cap;
776 	int i;
777 
778 	if (obj->nr_maps < obj->maps_cap)
779 		return &obj->maps[obj->nr_maps++];
780 
781 	new_cap = max((size_t)4, obj->maps_cap * 3 / 2);
782 	new_maps = realloc(obj->maps, new_cap * sizeof(*obj->maps));
783 	if (!new_maps) {
784 		pr_warning("alloc maps for object failed\n");
785 		return ERR_PTR(-ENOMEM);
786 	}
787 
788 	obj->maps_cap = new_cap;
789 	obj->maps = new_maps;
790 
791 	/* zero out new maps */
792 	memset(obj->maps + obj->nr_maps, 0,
793 	       (obj->maps_cap - obj->nr_maps) * sizeof(*obj->maps));
794 	/*
795 	 * fill all fd with -1 so won't close incorrect fd (fd=0 is stdin)
796 	 * when failure (zclose won't close negative fd)).
797 	 */
798 	for (i = obj->nr_maps; i < obj->maps_cap; i++) {
799 		obj->maps[i].fd = -1;
800 		obj->maps[i].inner_map_fd = -1;
801 	}
802 
803 	return &obj->maps[obj->nr_maps++];
804 }
805 
806 static int
807 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
808 			      int sec_idx, Elf_Data *data, void **data_buff)
809 {
810 	char map_name[BPF_OBJ_NAME_LEN];
811 	struct bpf_map_def *def;
812 	struct bpf_map *map;
813 
814 	map = bpf_object__add_map(obj);
815 	if (IS_ERR(map))
816 		return PTR_ERR(map);
817 
818 	map->libbpf_type = type;
819 	map->sec_idx = sec_idx;
820 	map->sec_offset = 0;
821 	snprintf(map_name, sizeof(map_name), "%.8s%.7s", obj->name,
822 		 libbpf_type_to_btf_name[type]);
823 	map->name = strdup(map_name);
824 	if (!map->name) {
825 		pr_warning("failed to alloc map name\n");
826 		return -ENOMEM;
827 	}
828 	pr_debug("map '%s' (global data): at sec_idx %d, offset %zu.\n",
829 		 map_name, map->sec_idx, map->sec_offset);
830 
831 	def = &map->def;
832 	def->type = BPF_MAP_TYPE_ARRAY;
833 	def->key_size = sizeof(int);
834 	def->value_size = data->d_size;
835 	def->max_entries = 1;
836 	def->map_flags = type == LIBBPF_MAP_RODATA ? BPF_F_RDONLY_PROG : 0;
837 	if (data_buff) {
838 		*data_buff = malloc(data->d_size);
839 		if (!*data_buff) {
840 			zfree(&map->name);
841 			pr_warning("failed to alloc map content buffer\n");
842 			return -ENOMEM;
843 		}
844 		memcpy(*data_buff, data->d_buf, data->d_size);
845 	}
846 
847 	pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
848 	return 0;
849 }
850 
851 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
852 {
853 	int err;
854 
855 	if (!obj->caps.global_data)
856 		return 0;
857 	/*
858 	 * Populate obj->maps with libbpf internal maps.
859 	 */
860 	if (obj->efile.data_shndx >= 0) {
861 		err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
862 						    obj->efile.data_shndx,
863 						    obj->efile.data,
864 						    &obj->sections.data);
865 		if (err)
866 			return err;
867 	}
868 	if (obj->efile.rodata_shndx >= 0) {
869 		err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
870 						    obj->efile.rodata_shndx,
871 						    obj->efile.rodata,
872 						    &obj->sections.rodata);
873 		if (err)
874 			return err;
875 	}
876 	if (obj->efile.bss_shndx >= 0) {
877 		err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
878 						    obj->efile.bss_shndx,
879 						    obj->efile.bss, NULL);
880 		if (err)
881 			return err;
882 	}
883 	return 0;
884 }
885 
886 static int bpf_object__init_user_maps(struct bpf_object *obj, bool strict)
887 {
888 	Elf_Data *symbols = obj->efile.symbols;
889 	int i, map_def_sz = 0, nr_maps = 0, nr_syms;
890 	Elf_Data *data = NULL;
891 	Elf_Scn *scn;
892 
893 	if (obj->efile.maps_shndx < 0)
894 		return 0;
895 
896 	if (!symbols)
897 		return -EINVAL;
898 
899 	scn = elf_getscn(obj->efile.elf, obj->efile.maps_shndx);
900 	if (scn)
901 		data = elf_getdata(scn, NULL);
902 	if (!scn || !data) {
903 		pr_warning("failed to get Elf_Data from map section %d\n",
904 			   obj->efile.maps_shndx);
905 		return -EINVAL;
906 	}
907 
908 	/*
909 	 * Count number of maps. Each map has a name.
910 	 * Array of maps is not supported: only the first element is
911 	 * considered.
912 	 *
913 	 * TODO: Detect array of map and report error.
914 	 */
915 	nr_syms = symbols->d_size / sizeof(GElf_Sym);
916 	for (i = 0; i < nr_syms; i++) {
917 		GElf_Sym sym;
918 
919 		if (!gelf_getsym(symbols, i, &sym))
920 			continue;
921 		if (sym.st_shndx != obj->efile.maps_shndx)
922 			continue;
923 		nr_maps++;
924 	}
925 	/* Assume equally sized map definitions */
926 	pr_debug("maps in %s: %d maps in %zd bytes\n",
927 		 obj->path, nr_maps, data->d_size);
928 
929 	map_def_sz = data->d_size / nr_maps;
930 	if (!data->d_size || (data->d_size % nr_maps) != 0) {
931 		pr_warning("unable to determine map definition size "
932 			   "section %s, %d maps in %zd bytes\n",
933 			   obj->path, nr_maps, data->d_size);
934 		return -EINVAL;
935 	}
936 
937 	/* Fill obj->maps using data in "maps" section.  */
938 	for (i = 0; i < nr_syms; i++) {
939 		GElf_Sym sym;
940 		const char *map_name;
941 		struct bpf_map_def *def;
942 		struct bpf_map *map;
943 
944 		if (!gelf_getsym(symbols, i, &sym))
945 			continue;
946 		if (sym.st_shndx != obj->efile.maps_shndx)
947 			continue;
948 
949 		map = bpf_object__add_map(obj);
950 		if (IS_ERR(map))
951 			return PTR_ERR(map);
952 
953 		map_name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
954 				      sym.st_name);
955 		if (!map_name) {
956 			pr_warning("failed to get map #%d name sym string for obj %s\n",
957 				   i, obj->path);
958 			return -LIBBPF_ERRNO__FORMAT;
959 		}
960 
961 		map->libbpf_type = LIBBPF_MAP_UNSPEC;
962 		map->sec_idx = sym.st_shndx;
963 		map->sec_offset = sym.st_value;
964 		pr_debug("map '%s' (legacy): at sec_idx %d, offset %zu.\n",
965 			 map_name, map->sec_idx, map->sec_offset);
966 		if (sym.st_value + map_def_sz > data->d_size) {
967 			pr_warning("corrupted maps section in %s: last map \"%s\" too small\n",
968 				   obj->path, map_name);
969 			return -EINVAL;
970 		}
971 
972 		map->name = strdup(map_name);
973 		if (!map->name) {
974 			pr_warning("failed to alloc map name\n");
975 			return -ENOMEM;
976 		}
977 		pr_debug("map %d is \"%s\"\n", i, map->name);
978 		def = (struct bpf_map_def *)(data->d_buf + sym.st_value);
979 		/*
980 		 * If the definition of the map in the object file fits in
981 		 * bpf_map_def, copy it.  Any extra fields in our version
982 		 * of bpf_map_def will default to zero as a result of the
983 		 * calloc above.
984 		 */
985 		if (map_def_sz <= sizeof(struct bpf_map_def)) {
986 			memcpy(&map->def, def, map_def_sz);
987 		} else {
988 			/*
989 			 * Here the map structure being read is bigger than what
990 			 * we expect, truncate if the excess bits are all zero.
991 			 * If they are not zero, reject this map as
992 			 * incompatible.
993 			 */
994 			char *b;
995 			for (b = ((char *)def) + sizeof(struct bpf_map_def);
996 			     b < ((char *)def) + map_def_sz; b++) {
997 				if (*b != 0) {
998 					pr_warning("maps section in %s: \"%s\" "
999 						   "has unrecognized, non-zero "
1000 						   "options\n",
1001 						   obj->path, map_name);
1002 					if (strict)
1003 						return -EINVAL;
1004 				}
1005 			}
1006 			memcpy(&map->def, def, sizeof(struct bpf_map_def));
1007 		}
1008 	}
1009 	return 0;
1010 }
1011 
1012 static const struct btf_type *skip_mods_and_typedefs(const struct btf *btf,
1013 						     __u32 id)
1014 {
1015 	const struct btf_type *t = btf__type_by_id(btf, id);
1016 
1017 	while (true) {
1018 		switch (BTF_INFO_KIND(t->info)) {
1019 		case BTF_KIND_VOLATILE:
1020 		case BTF_KIND_CONST:
1021 		case BTF_KIND_RESTRICT:
1022 		case BTF_KIND_TYPEDEF:
1023 			t = btf__type_by_id(btf, t->type);
1024 			break;
1025 		default:
1026 			return t;
1027 		}
1028 	}
1029 }
1030 
1031 static bool get_map_field_int(const char *map_name,
1032 			      const struct btf *btf,
1033 			      const struct btf_type *def,
1034 			      const struct btf_member *m,
1035 			      const void *data, __u32 *res) {
1036 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type);
1037 	const char *name = btf__name_by_offset(btf, m->name_off);
1038 	__u32 int_info = *(const __u32 *)(const void *)(t + 1);
1039 
1040 	if (BTF_INFO_KIND(t->info) != BTF_KIND_INT) {
1041 		pr_warning("map '%s': attr '%s': expected INT, got %u.\n",
1042 			   map_name, name, BTF_INFO_KIND(t->info));
1043 		return false;
1044 	}
1045 	if (t->size != 4 || BTF_INT_BITS(int_info) != 32 ||
1046 	    BTF_INT_OFFSET(int_info)) {
1047 		pr_warning("map '%s': attr '%s': expected 32-bit non-bitfield integer, "
1048 			   "got %u-byte (%d-bit) one with bit offset %d.\n",
1049 			   map_name, name, t->size, BTF_INT_BITS(int_info),
1050 			   BTF_INT_OFFSET(int_info));
1051 		return false;
1052 	}
1053 	if (BTF_INFO_KFLAG(def->info) && BTF_MEMBER_BITFIELD_SIZE(m->offset)) {
1054 		pr_warning("map '%s': attr '%s': bitfield is not supported.\n",
1055 			   map_name, name);
1056 		return false;
1057 	}
1058 	if (m->offset % 32) {
1059 		pr_warning("map '%s': attr '%s': unaligned fields are not supported.\n",
1060 			   map_name, name);
1061 		return false;
1062 	}
1063 
1064 	*res = *(const __u32 *)(data + m->offset / 8);
1065 	return true;
1066 }
1067 
1068 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
1069 					 const struct btf_type *sec,
1070 					 int var_idx, int sec_idx,
1071 					 const Elf_Data *data, bool strict)
1072 {
1073 	const struct btf_type *var, *def, *t;
1074 	const struct btf_var_secinfo *vi;
1075 	const struct btf_var *var_extra;
1076 	const struct btf_member *m;
1077 	const void *def_data;
1078 	const char *map_name;
1079 	struct bpf_map *map;
1080 	int vlen, i;
1081 
1082 	vi = (const struct btf_var_secinfo *)(const void *)(sec + 1) + var_idx;
1083 	var = btf__type_by_id(obj->btf, vi->type);
1084 	var_extra = (const void *)(var + 1);
1085 	map_name = btf__name_by_offset(obj->btf, var->name_off);
1086 	vlen = BTF_INFO_VLEN(var->info);
1087 
1088 	if (map_name == NULL || map_name[0] == '\0') {
1089 		pr_warning("map #%d: empty name.\n", var_idx);
1090 		return -EINVAL;
1091 	}
1092 	if ((__u64)vi->offset + vi->size > data->d_size) {
1093 		pr_warning("map '%s' BTF data is corrupted.\n", map_name);
1094 		return -EINVAL;
1095 	}
1096 	if (BTF_INFO_KIND(var->info) != BTF_KIND_VAR) {
1097 		pr_warning("map '%s': unexpected var kind %u.\n",
1098 			   map_name, BTF_INFO_KIND(var->info));
1099 		return -EINVAL;
1100 	}
1101 	if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED &&
1102 	    var_extra->linkage != BTF_VAR_STATIC) {
1103 		pr_warning("map '%s': unsupported var linkage %u.\n",
1104 			   map_name, var_extra->linkage);
1105 		return -EOPNOTSUPP;
1106 	}
1107 
1108 	def = skip_mods_and_typedefs(obj->btf, var->type);
1109 	if (BTF_INFO_KIND(def->info) != BTF_KIND_STRUCT) {
1110 		pr_warning("map '%s': unexpected def kind %u.\n",
1111 			   map_name, BTF_INFO_KIND(var->info));
1112 		return -EINVAL;
1113 	}
1114 	if (def->size > vi->size) {
1115 		pr_warning("map '%s': invalid def size.\n", map_name);
1116 		return -EINVAL;
1117 	}
1118 
1119 	map = bpf_object__add_map(obj);
1120 	if (IS_ERR(map))
1121 		return PTR_ERR(map);
1122 	map->name = strdup(map_name);
1123 	if (!map->name) {
1124 		pr_warning("map '%s': failed to alloc map name.\n", map_name);
1125 		return -ENOMEM;
1126 	}
1127 	map->libbpf_type = LIBBPF_MAP_UNSPEC;
1128 	map->def.type = BPF_MAP_TYPE_UNSPEC;
1129 	map->sec_idx = sec_idx;
1130 	map->sec_offset = vi->offset;
1131 	pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
1132 		 map_name, map->sec_idx, map->sec_offset);
1133 
1134 	def_data = data->d_buf + vi->offset;
1135 	vlen = BTF_INFO_VLEN(def->info);
1136 	m = (const void *)(def + 1);
1137 	for (i = 0; i < vlen; i++, m++) {
1138 		const char *name = btf__name_by_offset(obj->btf, m->name_off);
1139 
1140 		if (!name) {
1141 			pr_warning("map '%s': invalid field #%d.\n",
1142 				   map_name, i);
1143 			return -EINVAL;
1144 		}
1145 		if (strcmp(name, "type") == 0) {
1146 			if (!get_map_field_int(map_name, obj->btf, def, m,
1147 					       def_data, &map->def.type))
1148 				return -EINVAL;
1149 			pr_debug("map '%s': found type = %u.\n",
1150 				 map_name, map->def.type);
1151 		} else if (strcmp(name, "max_entries") == 0) {
1152 			if (!get_map_field_int(map_name, obj->btf, def, m,
1153 					       def_data, &map->def.max_entries))
1154 				return -EINVAL;
1155 			pr_debug("map '%s': found max_entries = %u.\n",
1156 				 map_name, map->def.max_entries);
1157 		} else if (strcmp(name, "map_flags") == 0) {
1158 			if (!get_map_field_int(map_name, obj->btf, def, m,
1159 					       def_data, &map->def.map_flags))
1160 				return -EINVAL;
1161 			pr_debug("map '%s': found map_flags = %u.\n",
1162 				 map_name, map->def.map_flags);
1163 		} else if (strcmp(name, "key_size") == 0) {
1164 			__u32 sz;
1165 
1166 			if (!get_map_field_int(map_name, obj->btf, def, m,
1167 					       def_data, &sz))
1168 				return -EINVAL;
1169 			pr_debug("map '%s': found key_size = %u.\n",
1170 				 map_name, sz);
1171 			if (map->def.key_size && map->def.key_size != sz) {
1172 				pr_warning("map '%s': conflicting key size %u != %u.\n",
1173 					   map_name, map->def.key_size, sz);
1174 				return -EINVAL;
1175 			}
1176 			map->def.key_size = sz;
1177 		} else if (strcmp(name, "key") == 0) {
1178 			__s64 sz;
1179 
1180 			t = btf__type_by_id(obj->btf, m->type);
1181 			if (!t) {
1182 				pr_warning("map '%s': key type [%d] not found.\n",
1183 					   map_name, m->type);
1184 				return -EINVAL;
1185 			}
1186 			if (BTF_INFO_KIND(t->info) != BTF_KIND_PTR) {
1187 				pr_warning("map '%s': key spec is not PTR: %u.\n",
1188 					   map_name, BTF_INFO_KIND(t->info));
1189 				return -EINVAL;
1190 			}
1191 			sz = btf__resolve_size(obj->btf, t->type);
1192 			if (sz < 0) {
1193 				pr_warning("map '%s': can't determine key size for type [%u]: %lld.\n",
1194 					   map_name, t->type, sz);
1195 				return sz;
1196 			}
1197 			pr_debug("map '%s': found key [%u], sz = %lld.\n",
1198 				 map_name, t->type, sz);
1199 			if (map->def.key_size && map->def.key_size != sz) {
1200 				pr_warning("map '%s': conflicting key size %u != %lld.\n",
1201 					   map_name, map->def.key_size, sz);
1202 				return -EINVAL;
1203 			}
1204 			map->def.key_size = sz;
1205 			map->btf_key_type_id = t->type;
1206 		} else if (strcmp(name, "value_size") == 0) {
1207 			__u32 sz;
1208 
1209 			if (!get_map_field_int(map_name, obj->btf, def, m,
1210 					       def_data, &sz))
1211 				return -EINVAL;
1212 			pr_debug("map '%s': found value_size = %u.\n",
1213 				 map_name, sz);
1214 			if (map->def.value_size && map->def.value_size != sz) {
1215 				pr_warning("map '%s': conflicting value size %u != %u.\n",
1216 					   map_name, map->def.value_size, sz);
1217 				return -EINVAL;
1218 			}
1219 			map->def.value_size = sz;
1220 		} else if (strcmp(name, "value") == 0) {
1221 			__s64 sz;
1222 
1223 			t = btf__type_by_id(obj->btf, m->type);
1224 			if (!t) {
1225 				pr_warning("map '%s': value type [%d] not found.\n",
1226 					   map_name, m->type);
1227 				return -EINVAL;
1228 			}
1229 			if (BTF_INFO_KIND(t->info) != BTF_KIND_PTR) {
1230 				pr_warning("map '%s': value spec is not PTR: %u.\n",
1231 					   map_name, BTF_INFO_KIND(t->info));
1232 				return -EINVAL;
1233 			}
1234 			sz = btf__resolve_size(obj->btf, t->type);
1235 			if (sz < 0) {
1236 				pr_warning("map '%s': can't determine value size for type [%u]: %lld.\n",
1237 					   map_name, t->type, sz);
1238 				return sz;
1239 			}
1240 			pr_debug("map '%s': found value [%u], sz = %lld.\n",
1241 				 map_name, t->type, sz);
1242 			if (map->def.value_size && map->def.value_size != sz) {
1243 				pr_warning("map '%s': conflicting value size %u != %lld.\n",
1244 					   map_name, map->def.value_size, sz);
1245 				return -EINVAL;
1246 			}
1247 			map->def.value_size = sz;
1248 			map->btf_value_type_id = t->type;
1249 		} else {
1250 			if (strict) {
1251 				pr_warning("map '%s': unknown field '%s'.\n",
1252 					   map_name, name);
1253 				return -ENOTSUP;
1254 			}
1255 			pr_debug("map '%s': ignoring unknown field '%s'.\n",
1256 				 map_name, name);
1257 		}
1258 	}
1259 
1260 	if (map->def.type == BPF_MAP_TYPE_UNSPEC) {
1261 		pr_warning("map '%s': map type isn't specified.\n", map_name);
1262 		return -EINVAL;
1263 	}
1264 
1265 	return 0;
1266 }
1267 
1268 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict)
1269 {
1270 	const struct btf_type *sec = NULL;
1271 	int nr_types, i, vlen, err;
1272 	const struct btf_type *t;
1273 	const char *name;
1274 	Elf_Data *data;
1275 	Elf_Scn *scn;
1276 
1277 	if (obj->efile.btf_maps_shndx < 0)
1278 		return 0;
1279 
1280 	scn = elf_getscn(obj->efile.elf, obj->efile.btf_maps_shndx);
1281 	if (scn)
1282 		data = elf_getdata(scn, NULL);
1283 	if (!scn || !data) {
1284 		pr_warning("failed to get Elf_Data from map section %d (%s)\n",
1285 			   obj->efile.maps_shndx, MAPS_ELF_SEC);
1286 		return -EINVAL;
1287 	}
1288 
1289 	nr_types = btf__get_nr_types(obj->btf);
1290 	for (i = 1; i <= nr_types; i++) {
1291 		t = btf__type_by_id(obj->btf, i);
1292 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
1293 			continue;
1294 		name = btf__name_by_offset(obj->btf, t->name_off);
1295 		if (strcmp(name, MAPS_ELF_SEC) == 0) {
1296 			sec = t;
1297 			break;
1298 		}
1299 	}
1300 
1301 	if (!sec) {
1302 		pr_warning("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
1303 		return -ENOENT;
1304 	}
1305 
1306 	vlen = BTF_INFO_VLEN(sec->info);
1307 	for (i = 0; i < vlen; i++) {
1308 		err = bpf_object__init_user_btf_map(obj, sec, i,
1309 						    obj->efile.btf_maps_shndx,
1310 						    data, strict);
1311 		if (err)
1312 			return err;
1313 	}
1314 
1315 	return 0;
1316 }
1317 
1318 static int bpf_object__init_maps(struct bpf_object *obj, int flags)
1319 {
1320 	bool strict = !(flags & MAPS_RELAX_COMPAT);
1321 	int err;
1322 
1323 	err = bpf_object__init_user_maps(obj, strict);
1324 	if (err)
1325 		return err;
1326 
1327 	err = bpf_object__init_user_btf_maps(obj, strict);
1328 	if (err)
1329 		return err;
1330 
1331 	err = bpf_object__init_global_data_maps(obj);
1332 	if (err)
1333 		return err;
1334 
1335 	if (obj->nr_maps) {
1336 		qsort(obj->maps, obj->nr_maps, sizeof(obj->maps[0]),
1337 		      compare_bpf_map);
1338 	}
1339 	return 0;
1340 }
1341 
1342 static bool section_have_execinstr(struct bpf_object *obj, int idx)
1343 {
1344 	Elf_Scn *scn;
1345 	GElf_Shdr sh;
1346 
1347 	scn = elf_getscn(obj->efile.elf, idx);
1348 	if (!scn)
1349 		return false;
1350 
1351 	if (gelf_getshdr(scn, &sh) != &sh)
1352 		return false;
1353 
1354 	if (sh.sh_flags & SHF_EXECINSTR)
1355 		return true;
1356 
1357 	return false;
1358 }
1359 
1360 static void bpf_object__sanitize_btf(struct bpf_object *obj)
1361 {
1362 	bool has_datasec = obj->caps.btf_datasec;
1363 	bool has_func = obj->caps.btf_func;
1364 	struct btf *btf = obj->btf;
1365 	struct btf_type *t;
1366 	int i, j, vlen;
1367 	__u16 kind;
1368 
1369 	if (!obj->btf || (has_func && has_datasec))
1370 		return;
1371 
1372 	for (i = 1; i <= btf__get_nr_types(btf); i++) {
1373 		t = (struct btf_type *)btf__type_by_id(btf, i);
1374 		kind = BTF_INFO_KIND(t->info);
1375 
1376 		if (!has_datasec && kind == BTF_KIND_VAR) {
1377 			/* replace VAR with INT */
1378 			t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
1379 			t->size = sizeof(int);
1380 			*(int *)(t+1) = BTF_INT_ENC(0, 0, 32);
1381 		} else if (!has_datasec && kind == BTF_KIND_DATASEC) {
1382 			/* replace DATASEC with STRUCT */
1383 			struct btf_var_secinfo *v = (void *)(t + 1);
1384 			struct btf_member *m = (void *)(t + 1);
1385 			struct btf_type *vt;
1386 			char *name;
1387 
1388 			name = (char *)btf__name_by_offset(btf, t->name_off);
1389 			while (*name) {
1390 				if (*name == '.')
1391 					*name = '_';
1392 				name++;
1393 			}
1394 
1395 			vlen = BTF_INFO_VLEN(t->info);
1396 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
1397 			for (j = 0; j < vlen; j++, v++, m++) {
1398 				/* order of field assignments is important */
1399 				m->offset = v->offset * 8;
1400 				m->type = v->type;
1401 				/* preserve variable name as member name */
1402 				vt = (void *)btf__type_by_id(btf, v->type);
1403 				m->name_off = vt->name_off;
1404 			}
1405 		} else if (!has_func && kind == BTF_KIND_FUNC_PROTO) {
1406 			/* replace FUNC_PROTO with ENUM */
1407 			vlen = BTF_INFO_VLEN(t->info);
1408 			t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
1409 			t->size = sizeof(__u32); /* kernel enforced */
1410 		} else if (!has_func && kind == BTF_KIND_FUNC) {
1411 			/* replace FUNC with TYPEDEF */
1412 			t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
1413 		}
1414 	}
1415 }
1416 
1417 static void bpf_object__sanitize_btf_ext(struct bpf_object *obj)
1418 {
1419 	if (!obj->btf_ext)
1420 		return;
1421 
1422 	if (!obj->caps.btf_func) {
1423 		btf_ext__free(obj->btf_ext);
1424 		obj->btf_ext = NULL;
1425 	}
1426 }
1427 
1428 static bool bpf_object__is_btf_mandatory(const struct bpf_object *obj)
1429 {
1430 	return obj->efile.btf_maps_shndx >= 0;
1431 }
1432 
1433 static int bpf_object__init_btf(struct bpf_object *obj,
1434 				Elf_Data *btf_data,
1435 				Elf_Data *btf_ext_data)
1436 {
1437 	bool btf_required = bpf_object__is_btf_mandatory(obj);
1438 	int err = 0;
1439 
1440 	if (btf_data) {
1441 		obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
1442 		if (IS_ERR(obj->btf)) {
1443 			pr_warning("Error loading ELF section %s: %d.\n",
1444 				   BTF_ELF_SEC, err);
1445 			goto out;
1446 		}
1447 		err = btf__finalize_data(obj, obj->btf);
1448 		if (err) {
1449 			pr_warning("Error finalizing %s: %d.\n",
1450 				   BTF_ELF_SEC, err);
1451 			goto out;
1452 		}
1453 	}
1454 	if (btf_ext_data) {
1455 		if (!obj->btf) {
1456 			pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
1457 				 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
1458 			goto out;
1459 		}
1460 		obj->btf_ext = btf_ext__new(btf_ext_data->d_buf,
1461 					    btf_ext_data->d_size);
1462 		if (IS_ERR(obj->btf_ext)) {
1463 			pr_warning("Error loading ELF section %s: %ld. Ignored and continue.\n",
1464 				   BTF_EXT_ELF_SEC, PTR_ERR(obj->btf_ext));
1465 			obj->btf_ext = NULL;
1466 			goto out;
1467 		}
1468 	}
1469 out:
1470 	if (err || IS_ERR(obj->btf)) {
1471 		if (btf_required)
1472 			err = err ? : PTR_ERR(obj->btf);
1473 		else
1474 			err = 0;
1475 		if (!IS_ERR_OR_NULL(obj->btf))
1476 			btf__free(obj->btf);
1477 		obj->btf = NULL;
1478 	}
1479 	if (btf_required && !obj->btf) {
1480 		pr_warning("BTF is required, but is missing or corrupted.\n");
1481 		return err == 0 ? -ENOENT : err;
1482 	}
1483 	return 0;
1484 }
1485 
1486 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
1487 {
1488 	int err = 0;
1489 
1490 	if (!obj->btf)
1491 		return 0;
1492 
1493 	bpf_object__sanitize_btf(obj);
1494 	bpf_object__sanitize_btf_ext(obj);
1495 
1496 	err = btf__load(obj->btf);
1497 	if (err) {
1498 		pr_warning("Error loading %s into kernel: %d.\n",
1499 			   BTF_ELF_SEC, err);
1500 		btf__free(obj->btf);
1501 		obj->btf = NULL;
1502 		if (bpf_object__is_btf_mandatory(obj))
1503 			return err;
1504 	}
1505 	return 0;
1506 }
1507 
1508 static int bpf_object__elf_collect(struct bpf_object *obj, int flags)
1509 {
1510 	Elf *elf = obj->efile.elf;
1511 	GElf_Ehdr *ep = &obj->efile.ehdr;
1512 	Elf_Data *btf_ext_data = NULL;
1513 	Elf_Data *btf_data = NULL;
1514 	Elf_Scn *scn = NULL;
1515 	int idx = 0, err = 0;
1516 
1517 	/* Elf is corrupted/truncated, avoid calling elf_strptr. */
1518 	if (!elf_rawdata(elf_getscn(elf, ep->e_shstrndx), NULL)) {
1519 		pr_warning("failed to get e_shstrndx from %s\n", obj->path);
1520 		return -LIBBPF_ERRNO__FORMAT;
1521 	}
1522 
1523 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
1524 		char *name;
1525 		GElf_Shdr sh;
1526 		Elf_Data *data;
1527 
1528 		idx++;
1529 		if (gelf_getshdr(scn, &sh) != &sh) {
1530 			pr_warning("failed to get section(%d) header from %s\n",
1531 				   idx, obj->path);
1532 			return -LIBBPF_ERRNO__FORMAT;
1533 		}
1534 
1535 		name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
1536 		if (!name) {
1537 			pr_warning("failed to get section(%d) name from %s\n",
1538 				   idx, obj->path);
1539 			return -LIBBPF_ERRNO__FORMAT;
1540 		}
1541 
1542 		data = elf_getdata(scn, 0);
1543 		if (!data) {
1544 			pr_warning("failed to get section(%d) data from %s(%s)\n",
1545 				   idx, name, obj->path);
1546 			return -LIBBPF_ERRNO__FORMAT;
1547 		}
1548 		pr_debug("section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
1549 			 idx, name, (unsigned long)data->d_size,
1550 			 (int)sh.sh_link, (unsigned long)sh.sh_flags,
1551 			 (int)sh.sh_type);
1552 
1553 		if (strcmp(name, "license") == 0) {
1554 			err = bpf_object__init_license(obj,
1555 						       data->d_buf,
1556 						       data->d_size);
1557 			if (err)
1558 				return err;
1559 		} else if (strcmp(name, "version") == 0) {
1560 			err = bpf_object__init_kversion(obj,
1561 							data->d_buf,
1562 							data->d_size);
1563 			if (err)
1564 				return err;
1565 		} else if (strcmp(name, "maps") == 0) {
1566 			obj->efile.maps_shndx = idx;
1567 		} else if (strcmp(name, MAPS_ELF_SEC) == 0) {
1568 			obj->efile.btf_maps_shndx = idx;
1569 		} else if (strcmp(name, BTF_ELF_SEC) == 0) {
1570 			btf_data = data;
1571 		} else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
1572 			btf_ext_data = data;
1573 		} else if (sh.sh_type == SHT_SYMTAB) {
1574 			if (obj->efile.symbols) {
1575 				pr_warning("bpf: multiple SYMTAB in %s\n",
1576 					   obj->path);
1577 				return -LIBBPF_ERRNO__FORMAT;
1578 			}
1579 			obj->efile.symbols = data;
1580 			obj->efile.strtabidx = sh.sh_link;
1581 		} else if (sh.sh_type == SHT_PROGBITS && data->d_size > 0) {
1582 			if (sh.sh_flags & SHF_EXECINSTR) {
1583 				if (strcmp(name, ".text") == 0)
1584 					obj->efile.text_shndx = idx;
1585 				err = bpf_object__add_program(obj, data->d_buf,
1586 							      data->d_size, name, idx);
1587 				if (err) {
1588 					char errmsg[STRERR_BUFSIZE];
1589 					char *cp = libbpf_strerror_r(-err, errmsg,
1590 								     sizeof(errmsg));
1591 
1592 					pr_warning("failed to alloc program %s (%s): %s",
1593 						   name, obj->path, cp);
1594 					return err;
1595 				}
1596 			} else if (strcmp(name, ".data") == 0) {
1597 				obj->efile.data = data;
1598 				obj->efile.data_shndx = idx;
1599 			} else if (strcmp(name, ".rodata") == 0) {
1600 				obj->efile.rodata = data;
1601 				obj->efile.rodata_shndx = idx;
1602 			} else {
1603 				pr_debug("skip section(%d) %s\n", idx, name);
1604 			}
1605 		} else if (sh.sh_type == SHT_REL) {
1606 			int nr_reloc = obj->efile.nr_reloc;
1607 			void *reloc = obj->efile.reloc;
1608 			int sec = sh.sh_info; /* points to other section */
1609 
1610 			/* Only do relo for section with exec instructions */
1611 			if (!section_have_execinstr(obj, sec)) {
1612 				pr_debug("skip relo %s(%d) for section(%d)\n",
1613 					 name, idx, sec);
1614 				continue;
1615 			}
1616 
1617 			reloc = reallocarray(reloc, nr_reloc + 1,
1618 					     sizeof(*obj->efile.reloc));
1619 			if (!reloc) {
1620 				pr_warning("realloc failed\n");
1621 				return -ENOMEM;
1622 			}
1623 
1624 			obj->efile.reloc = reloc;
1625 			obj->efile.nr_reloc++;
1626 
1627 			obj->efile.reloc[nr_reloc].shdr = sh;
1628 			obj->efile.reloc[nr_reloc].data = data;
1629 		} else if (sh.sh_type == SHT_NOBITS && strcmp(name, ".bss") == 0) {
1630 			obj->efile.bss = data;
1631 			obj->efile.bss_shndx = idx;
1632 		} else {
1633 			pr_debug("skip section(%d) %s\n", idx, name);
1634 		}
1635 	}
1636 
1637 	if (!obj->efile.strtabidx || obj->efile.strtabidx >= idx) {
1638 		pr_warning("Corrupted ELF file: index of strtab invalid\n");
1639 		return -LIBBPF_ERRNO__FORMAT;
1640 	}
1641 	err = bpf_object__init_btf(obj, btf_data, btf_ext_data);
1642 	if (!err)
1643 		err = bpf_object__init_maps(obj, flags);
1644 	if (!err)
1645 		err = bpf_object__sanitize_and_load_btf(obj);
1646 	if (!err)
1647 		err = bpf_object__init_prog_names(obj);
1648 	return err;
1649 }
1650 
1651 static struct bpf_program *
1652 bpf_object__find_prog_by_idx(struct bpf_object *obj, int idx)
1653 {
1654 	struct bpf_program *prog;
1655 	size_t i;
1656 
1657 	for (i = 0; i < obj->nr_programs; i++) {
1658 		prog = &obj->programs[i];
1659 		if (prog->idx == idx)
1660 			return prog;
1661 	}
1662 	return NULL;
1663 }
1664 
1665 struct bpf_program *
1666 bpf_object__find_program_by_title(const struct bpf_object *obj,
1667 				  const char *title)
1668 {
1669 	struct bpf_program *pos;
1670 
1671 	bpf_object__for_each_program(pos, obj) {
1672 		if (pos->section_name && !strcmp(pos->section_name, title))
1673 			return pos;
1674 	}
1675 	return NULL;
1676 }
1677 
1678 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
1679 				      int shndx)
1680 {
1681 	return shndx == obj->efile.data_shndx ||
1682 	       shndx == obj->efile.bss_shndx ||
1683 	       shndx == obj->efile.rodata_shndx;
1684 }
1685 
1686 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
1687 				      int shndx)
1688 {
1689 	return shndx == obj->efile.maps_shndx ||
1690 	       shndx == obj->efile.btf_maps_shndx;
1691 }
1692 
1693 static bool bpf_object__relo_in_known_section(const struct bpf_object *obj,
1694 					      int shndx)
1695 {
1696 	return shndx == obj->efile.text_shndx ||
1697 	       bpf_object__shndx_is_maps(obj, shndx) ||
1698 	       bpf_object__shndx_is_data(obj, shndx);
1699 }
1700 
1701 static enum libbpf_map_type
1702 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
1703 {
1704 	if (shndx == obj->efile.data_shndx)
1705 		return LIBBPF_MAP_DATA;
1706 	else if (shndx == obj->efile.bss_shndx)
1707 		return LIBBPF_MAP_BSS;
1708 	else if (shndx == obj->efile.rodata_shndx)
1709 		return LIBBPF_MAP_RODATA;
1710 	else
1711 		return LIBBPF_MAP_UNSPEC;
1712 }
1713 
1714 static int
1715 bpf_program__collect_reloc(struct bpf_program *prog, GElf_Shdr *shdr,
1716 			   Elf_Data *data, struct bpf_object *obj)
1717 {
1718 	Elf_Data *symbols = obj->efile.symbols;
1719 	struct bpf_map *maps = obj->maps;
1720 	size_t nr_maps = obj->nr_maps;
1721 	int i, nrels;
1722 
1723 	pr_debug("collecting relocating info for: '%s'\n", prog->section_name);
1724 	nrels = shdr->sh_size / shdr->sh_entsize;
1725 
1726 	prog->reloc_desc = malloc(sizeof(*prog->reloc_desc) * nrels);
1727 	if (!prog->reloc_desc) {
1728 		pr_warning("failed to alloc memory in relocation\n");
1729 		return -ENOMEM;
1730 	}
1731 	prog->nr_reloc = nrels;
1732 
1733 	for (i = 0; i < nrels; i++) {
1734 		struct bpf_insn *insns = prog->insns;
1735 		enum libbpf_map_type type;
1736 		unsigned int insn_idx;
1737 		unsigned int shdr_idx;
1738 		const char *name;
1739 		size_t map_idx;
1740 		GElf_Sym sym;
1741 		GElf_Rel rel;
1742 
1743 		if (!gelf_getrel(data, i, &rel)) {
1744 			pr_warning("relocation: failed to get %d reloc\n", i);
1745 			return -LIBBPF_ERRNO__FORMAT;
1746 		}
1747 
1748 		if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) {
1749 			pr_warning("relocation: symbol %"PRIx64" not found\n",
1750 				   GELF_R_SYM(rel.r_info));
1751 			return -LIBBPF_ERRNO__FORMAT;
1752 		}
1753 
1754 		name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
1755 				  sym.st_name) ? : "<?>";
1756 
1757 		pr_debug("relo for %lld value %lld name %d (\'%s\')\n",
1758 			 (long long) (rel.r_info >> 32),
1759 			 (long long) sym.st_value, sym.st_name, name);
1760 
1761 		shdr_idx = sym.st_shndx;
1762 		if (!bpf_object__relo_in_known_section(obj, shdr_idx)) {
1763 			pr_warning("Program '%s' contains unrecognized relo data pointing to section %u\n",
1764 				   prog->section_name, shdr_idx);
1765 			return -LIBBPF_ERRNO__RELOC;
1766 		}
1767 
1768 		insn_idx = rel.r_offset / sizeof(struct bpf_insn);
1769 		pr_debug("relocation: insn_idx=%u\n", insn_idx);
1770 
1771 		if (insns[insn_idx].code == (BPF_JMP | BPF_CALL)) {
1772 			if (insns[insn_idx].src_reg != BPF_PSEUDO_CALL) {
1773 				pr_warning("incorrect bpf_call opcode\n");
1774 				return -LIBBPF_ERRNO__RELOC;
1775 			}
1776 			prog->reloc_desc[i].type = RELO_CALL;
1777 			prog->reloc_desc[i].insn_idx = insn_idx;
1778 			prog->reloc_desc[i].text_off = sym.st_value;
1779 			obj->has_pseudo_calls = true;
1780 			continue;
1781 		}
1782 
1783 		if (insns[insn_idx].code != (BPF_LD | BPF_IMM | BPF_DW)) {
1784 			pr_warning("bpf: relocation: invalid relo for insns[%d].code 0x%x\n",
1785 				   insn_idx, insns[insn_idx].code);
1786 			return -LIBBPF_ERRNO__RELOC;
1787 		}
1788 
1789 		if (bpf_object__shndx_is_maps(obj, shdr_idx) ||
1790 		    bpf_object__shndx_is_data(obj, shdr_idx)) {
1791 			type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
1792 			if (type != LIBBPF_MAP_UNSPEC) {
1793 				if (GELF_ST_BIND(sym.st_info) == STB_GLOBAL) {
1794 					pr_warning("bpf: relocation: not yet supported relo for non-static global \'%s\' variable found in insns[%d].code 0x%x\n",
1795 						   name, insn_idx, insns[insn_idx].code);
1796 					return -LIBBPF_ERRNO__RELOC;
1797 				}
1798 				if (!obj->caps.global_data) {
1799 					pr_warning("bpf: relocation: kernel does not support global \'%s\' variable access in insns[%d]\n",
1800 						   name, insn_idx);
1801 					return -LIBBPF_ERRNO__RELOC;
1802 				}
1803 			}
1804 
1805 			for (map_idx = 0; map_idx < nr_maps; map_idx++) {
1806 				if (maps[map_idx].libbpf_type != type)
1807 					continue;
1808 				if (type != LIBBPF_MAP_UNSPEC ||
1809 				    (maps[map_idx].sec_idx == sym.st_shndx &&
1810 				     maps[map_idx].sec_offset == sym.st_value)) {
1811 					pr_debug("relocation: found map %zd (%s, sec_idx %d, offset %zu) for insn %u\n",
1812 						 map_idx, maps[map_idx].name,
1813 						 maps[map_idx].sec_idx,
1814 						 maps[map_idx].sec_offset,
1815 						 insn_idx);
1816 					break;
1817 				}
1818 			}
1819 
1820 			if (map_idx >= nr_maps) {
1821 				pr_warning("bpf relocation: map_idx %d larger than %d\n",
1822 					   (int)map_idx, (int)nr_maps - 1);
1823 				return -LIBBPF_ERRNO__RELOC;
1824 			}
1825 
1826 			prog->reloc_desc[i].type = type != LIBBPF_MAP_UNSPEC ?
1827 						   RELO_DATA : RELO_LD64;
1828 			prog->reloc_desc[i].insn_idx = insn_idx;
1829 			prog->reloc_desc[i].map_idx = map_idx;
1830 		}
1831 	}
1832 	return 0;
1833 }
1834 
1835 static int bpf_map_find_btf_info(struct bpf_object *obj, struct bpf_map *map)
1836 {
1837 	struct bpf_map_def *def = &map->def;
1838 	__u32 key_type_id = 0, value_type_id = 0;
1839 	int ret;
1840 
1841 	/* if it's BTF-defined map, we don't need to search for type IDs */
1842 	if (map->sec_idx == obj->efile.btf_maps_shndx)
1843 		return 0;
1844 
1845 	if (!bpf_map__is_internal(map)) {
1846 		ret = btf__get_map_kv_tids(obj->btf, map->name, def->key_size,
1847 					   def->value_size, &key_type_id,
1848 					   &value_type_id);
1849 	} else {
1850 		/*
1851 		 * LLVM annotates global data differently in BTF, that is,
1852 		 * only as '.data', '.bss' or '.rodata'.
1853 		 */
1854 		ret = btf__find_by_name(obj->btf,
1855 				libbpf_type_to_btf_name[map->libbpf_type]);
1856 	}
1857 	if (ret < 0)
1858 		return ret;
1859 
1860 	map->btf_key_type_id = key_type_id;
1861 	map->btf_value_type_id = bpf_map__is_internal(map) ?
1862 				 ret : value_type_id;
1863 	return 0;
1864 }
1865 
1866 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
1867 {
1868 	struct bpf_map_info info = {};
1869 	__u32 len = sizeof(info);
1870 	int new_fd, err;
1871 	char *new_name;
1872 
1873 	err = bpf_obj_get_info_by_fd(fd, &info, &len);
1874 	if (err)
1875 		return err;
1876 
1877 	new_name = strdup(info.name);
1878 	if (!new_name)
1879 		return -errno;
1880 
1881 	new_fd = open("/", O_RDONLY | O_CLOEXEC);
1882 	if (new_fd < 0)
1883 		goto err_free_new_name;
1884 
1885 	new_fd = dup3(fd, new_fd, O_CLOEXEC);
1886 	if (new_fd < 0)
1887 		goto err_close_new_fd;
1888 
1889 	err = zclose(map->fd);
1890 	if (err)
1891 		goto err_close_new_fd;
1892 	free(map->name);
1893 
1894 	map->fd = new_fd;
1895 	map->name = new_name;
1896 	map->def.type = info.type;
1897 	map->def.key_size = info.key_size;
1898 	map->def.value_size = info.value_size;
1899 	map->def.max_entries = info.max_entries;
1900 	map->def.map_flags = info.map_flags;
1901 	map->btf_key_type_id = info.btf_key_type_id;
1902 	map->btf_value_type_id = info.btf_value_type_id;
1903 
1904 	return 0;
1905 
1906 err_close_new_fd:
1907 	close(new_fd);
1908 err_free_new_name:
1909 	free(new_name);
1910 	return -errno;
1911 }
1912 
1913 int bpf_map__resize(struct bpf_map *map, __u32 max_entries)
1914 {
1915 	if (!map || !max_entries)
1916 		return -EINVAL;
1917 
1918 	/* If map already created, its attributes can't be changed. */
1919 	if (map->fd >= 0)
1920 		return -EBUSY;
1921 
1922 	map->def.max_entries = max_entries;
1923 
1924 	return 0;
1925 }
1926 
1927 static int
1928 bpf_object__probe_name(struct bpf_object *obj)
1929 {
1930 	struct bpf_load_program_attr attr;
1931 	char *cp, errmsg[STRERR_BUFSIZE];
1932 	struct bpf_insn insns[] = {
1933 		BPF_MOV64_IMM(BPF_REG_0, 0),
1934 		BPF_EXIT_INSN(),
1935 	};
1936 	int ret;
1937 
1938 	/* make sure basic loading works */
1939 
1940 	memset(&attr, 0, sizeof(attr));
1941 	attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
1942 	attr.insns = insns;
1943 	attr.insns_cnt = ARRAY_SIZE(insns);
1944 	attr.license = "GPL";
1945 
1946 	ret = bpf_load_program_xattr(&attr, NULL, 0);
1947 	if (ret < 0) {
1948 		cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
1949 		pr_warning("Error in %s():%s(%d). Couldn't load basic 'r0 = 0' BPF program.\n",
1950 			   __func__, cp, errno);
1951 		return -errno;
1952 	}
1953 	close(ret);
1954 
1955 	/* now try the same program, but with the name */
1956 
1957 	attr.name = "test";
1958 	ret = bpf_load_program_xattr(&attr, NULL, 0);
1959 	if (ret >= 0) {
1960 		obj->caps.name = 1;
1961 		close(ret);
1962 	}
1963 
1964 	return 0;
1965 }
1966 
1967 static int
1968 bpf_object__probe_global_data(struct bpf_object *obj)
1969 {
1970 	struct bpf_load_program_attr prg_attr;
1971 	struct bpf_create_map_attr map_attr;
1972 	char *cp, errmsg[STRERR_BUFSIZE];
1973 	struct bpf_insn insns[] = {
1974 		BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
1975 		BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
1976 		BPF_MOV64_IMM(BPF_REG_0, 0),
1977 		BPF_EXIT_INSN(),
1978 	};
1979 	int ret, map;
1980 
1981 	memset(&map_attr, 0, sizeof(map_attr));
1982 	map_attr.map_type = BPF_MAP_TYPE_ARRAY;
1983 	map_attr.key_size = sizeof(int);
1984 	map_attr.value_size = 32;
1985 	map_attr.max_entries = 1;
1986 
1987 	map = bpf_create_map_xattr(&map_attr);
1988 	if (map < 0) {
1989 		cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
1990 		pr_warning("Error in %s():%s(%d). Couldn't create simple array map.\n",
1991 			   __func__, cp, errno);
1992 		return -errno;
1993 	}
1994 
1995 	insns[0].imm = map;
1996 
1997 	memset(&prg_attr, 0, sizeof(prg_attr));
1998 	prg_attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
1999 	prg_attr.insns = insns;
2000 	prg_attr.insns_cnt = ARRAY_SIZE(insns);
2001 	prg_attr.license = "GPL";
2002 
2003 	ret = bpf_load_program_xattr(&prg_attr, NULL, 0);
2004 	if (ret >= 0) {
2005 		obj->caps.global_data = 1;
2006 		close(ret);
2007 	}
2008 
2009 	close(map);
2010 	return 0;
2011 }
2012 
2013 static int bpf_object__probe_btf_func(struct bpf_object *obj)
2014 {
2015 	const char strs[] = "\0int\0x\0a";
2016 	/* void x(int a) {} */
2017 	__u32 types[] = {
2018 		/* int */
2019 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
2020 		/* FUNC_PROTO */                                /* [2] */
2021 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
2022 		BTF_PARAM_ENC(7, 1),
2023 		/* FUNC x */                                    /* [3] */
2024 		BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
2025 	};
2026 	int btf_fd;
2027 
2028 	btf_fd = libbpf__load_raw_btf((char *)types, sizeof(types),
2029 				      strs, sizeof(strs));
2030 	if (btf_fd >= 0) {
2031 		obj->caps.btf_func = 1;
2032 		close(btf_fd);
2033 		return 1;
2034 	}
2035 
2036 	return 0;
2037 }
2038 
2039 static int bpf_object__probe_btf_datasec(struct bpf_object *obj)
2040 {
2041 	const char strs[] = "\0x\0.data";
2042 	/* static int a; */
2043 	__u32 types[] = {
2044 		/* int */
2045 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
2046 		/* VAR x */                                     /* [2] */
2047 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
2048 		BTF_VAR_STATIC,
2049 		/* DATASEC val */                               /* [3] */
2050 		BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
2051 		BTF_VAR_SECINFO_ENC(2, 0, 4),
2052 	};
2053 	int btf_fd;
2054 
2055 	btf_fd = libbpf__load_raw_btf((char *)types, sizeof(types),
2056 				      strs, sizeof(strs));
2057 	if (btf_fd >= 0) {
2058 		obj->caps.btf_datasec = 1;
2059 		close(btf_fd);
2060 		return 1;
2061 	}
2062 
2063 	return 0;
2064 }
2065 
2066 static int
2067 bpf_object__probe_caps(struct bpf_object *obj)
2068 {
2069 	int (*probe_fn[])(struct bpf_object *obj) = {
2070 		bpf_object__probe_name,
2071 		bpf_object__probe_global_data,
2072 		bpf_object__probe_btf_func,
2073 		bpf_object__probe_btf_datasec,
2074 	};
2075 	int i, ret;
2076 
2077 	for (i = 0; i < ARRAY_SIZE(probe_fn); i++) {
2078 		ret = probe_fn[i](obj);
2079 		if (ret < 0)
2080 			pr_debug("Probe #%d failed with %d.\n", i, ret);
2081 	}
2082 
2083 	return 0;
2084 }
2085 
2086 static int
2087 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
2088 {
2089 	char *cp, errmsg[STRERR_BUFSIZE];
2090 	int err, zero = 0;
2091 	__u8 *data;
2092 
2093 	/* Nothing to do here since kernel already zero-initializes .bss map. */
2094 	if (map->libbpf_type == LIBBPF_MAP_BSS)
2095 		return 0;
2096 
2097 	data = map->libbpf_type == LIBBPF_MAP_DATA ?
2098 	       obj->sections.data : obj->sections.rodata;
2099 
2100 	err = bpf_map_update_elem(map->fd, &zero, data, 0);
2101 	/* Freeze .rodata map as read-only from syscall side. */
2102 	if (!err && map->libbpf_type == LIBBPF_MAP_RODATA) {
2103 		err = bpf_map_freeze(map->fd);
2104 		if (err) {
2105 			cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2106 			pr_warning("Error freezing map(%s) as read-only: %s\n",
2107 				   map->name, cp);
2108 			err = 0;
2109 		}
2110 	}
2111 	return err;
2112 }
2113 
2114 static int
2115 bpf_object__create_maps(struct bpf_object *obj)
2116 {
2117 	struct bpf_create_map_attr create_attr = {};
2118 	unsigned int i;
2119 	int err;
2120 
2121 	for (i = 0; i < obj->nr_maps; i++) {
2122 		struct bpf_map *map = &obj->maps[i];
2123 		struct bpf_map_def *def = &map->def;
2124 		char *cp, errmsg[STRERR_BUFSIZE];
2125 		int *pfd = &map->fd;
2126 
2127 		if (map->fd >= 0) {
2128 			pr_debug("skip map create (preset) %s: fd=%d\n",
2129 				 map->name, map->fd);
2130 			continue;
2131 		}
2132 
2133 		if (obj->caps.name)
2134 			create_attr.name = map->name;
2135 		create_attr.map_ifindex = map->map_ifindex;
2136 		create_attr.map_type = def->type;
2137 		create_attr.map_flags = def->map_flags;
2138 		create_attr.key_size = def->key_size;
2139 		create_attr.value_size = def->value_size;
2140 		create_attr.max_entries = def->max_entries;
2141 		create_attr.btf_fd = 0;
2142 		create_attr.btf_key_type_id = 0;
2143 		create_attr.btf_value_type_id = 0;
2144 		if (bpf_map_type__is_map_in_map(def->type) &&
2145 		    map->inner_map_fd >= 0)
2146 			create_attr.inner_map_fd = map->inner_map_fd;
2147 
2148 		if (obj->btf && !bpf_map_find_btf_info(obj, map)) {
2149 			create_attr.btf_fd = btf__fd(obj->btf);
2150 			create_attr.btf_key_type_id = map->btf_key_type_id;
2151 			create_attr.btf_value_type_id = map->btf_value_type_id;
2152 		}
2153 
2154 		*pfd = bpf_create_map_xattr(&create_attr);
2155 		if (*pfd < 0 && (create_attr.btf_key_type_id ||
2156 				 create_attr.btf_value_type_id)) {
2157 			cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2158 			pr_warning("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
2159 				   map->name, cp, errno);
2160 			create_attr.btf_fd = 0;
2161 			create_attr.btf_key_type_id = 0;
2162 			create_attr.btf_value_type_id = 0;
2163 			map->btf_key_type_id = 0;
2164 			map->btf_value_type_id = 0;
2165 			*pfd = bpf_create_map_xattr(&create_attr);
2166 		}
2167 
2168 		if (*pfd < 0) {
2169 			size_t j;
2170 
2171 			err = *pfd;
2172 err_out:
2173 			cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2174 			pr_warning("failed to create map (name: '%s'): %s\n",
2175 				   map->name, cp);
2176 			for (j = 0; j < i; j++)
2177 				zclose(obj->maps[j].fd);
2178 			return err;
2179 		}
2180 
2181 		if (bpf_map__is_internal(map)) {
2182 			err = bpf_object__populate_internal_map(obj, map);
2183 			if (err < 0) {
2184 				zclose(*pfd);
2185 				goto err_out;
2186 			}
2187 		}
2188 
2189 		pr_debug("created map %s: fd=%d\n", map->name, *pfd);
2190 	}
2191 
2192 	return 0;
2193 }
2194 
2195 static int
2196 check_btf_ext_reloc_err(struct bpf_program *prog, int err,
2197 			void *btf_prog_info, const char *info_name)
2198 {
2199 	if (err != -ENOENT) {
2200 		pr_warning("Error in loading %s for sec %s.\n",
2201 			   info_name, prog->section_name);
2202 		return err;
2203 	}
2204 
2205 	/* err == -ENOENT (i.e. prog->section_name not found in btf_ext) */
2206 
2207 	if (btf_prog_info) {
2208 		/*
2209 		 * Some info has already been found but has problem
2210 		 * in the last btf_ext reloc. Must have to error out.
2211 		 */
2212 		pr_warning("Error in relocating %s for sec %s.\n",
2213 			   info_name, prog->section_name);
2214 		return err;
2215 	}
2216 
2217 	/* Have problem loading the very first info. Ignore the rest. */
2218 	pr_warning("Cannot find %s for main program sec %s. Ignore all %s.\n",
2219 		   info_name, prog->section_name, info_name);
2220 	return 0;
2221 }
2222 
2223 static int
2224 bpf_program_reloc_btf_ext(struct bpf_program *prog, struct bpf_object *obj,
2225 			  const char *section_name,  __u32 insn_offset)
2226 {
2227 	int err;
2228 
2229 	if (!insn_offset || prog->func_info) {
2230 		/*
2231 		 * !insn_offset => main program
2232 		 *
2233 		 * For sub prog, the main program's func_info has to
2234 		 * be loaded first (i.e. prog->func_info != NULL)
2235 		 */
2236 		err = btf_ext__reloc_func_info(obj->btf, obj->btf_ext,
2237 					       section_name, insn_offset,
2238 					       &prog->func_info,
2239 					       &prog->func_info_cnt);
2240 		if (err)
2241 			return check_btf_ext_reloc_err(prog, err,
2242 						       prog->func_info,
2243 						       "bpf_func_info");
2244 
2245 		prog->func_info_rec_size = btf_ext__func_info_rec_size(obj->btf_ext);
2246 	}
2247 
2248 	if (!insn_offset || prog->line_info) {
2249 		err = btf_ext__reloc_line_info(obj->btf, obj->btf_ext,
2250 					       section_name, insn_offset,
2251 					       &prog->line_info,
2252 					       &prog->line_info_cnt);
2253 		if (err)
2254 			return check_btf_ext_reloc_err(prog, err,
2255 						       prog->line_info,
2256 						       "bpf_line_info");
2257 
2258 		prog->line_info_rec_size = btf_ext__line_info_rec_size(obj->btf_ext);
2259 	}
2260 
2261 	if (!insn_offset)
2262 		prog->btf_fd = btf__fd(obj->btf);
2263 
2264 	return 0;
2265 }
2266 
2267 static int
2268 bpf_program__reloc_text(struct bpf_program *prog, struct bpf_object *obj,
2269 			struct reloc_desc *relo)
2270 {
2271 	struct bpf_insn *insn, *new_insn;
2272 	struct bpf_program *text;
2273 	size_t new_cnt;
2274 	int err;
2275 
2276 	if (relo->type != RELO_CALL)
2277 		return -LIBBPF_ERRNO__RELOC;
2278 
2279 	if (prog->idx == obj->efile.text_shndx) {
2280 		pr_warning("relo in .text insn %d into off %d\n",
2281 			   relo->insn_idx, relo->text_off);
2282 		return -LIBBPF_ERRNO__RELOC;
2283 	}
2284 
2285 	if (prog->main_prog_cnt == 0) {
2286 		text = bpf_object__find_prog_by_idx(obj, obj->efile.text_shndx);
2287 		if (!text) {
2288 			pr_warning("no .text section found yet relo into text exist\n");
2289 			return -LIBBPF_ERRNO__RELOC;
2290 		}
2291 		new_cnt = prog->insns_cnt + text->insns_cnt;
2292 		new_insn = reallocarray(prog->insns, new_cnt, sizeof(*insn));
2293 		if (!new_insn) {
2294 			pr_warning("oom in prog realloc\n");
2295 			return -ENOMEM;
2296 		}
2297 
2298 		if (obj->btf_ext) {
2299 			err = bpf_program_reloc_btf_ext(prog, obj,
2300 							text->section_name,
2301 							prog->insns_cnt);
2302 			if (err)
2303 				return err;
2304 		}
2305 
2306 		memcpy(new_insn + prog->insns_cnt, text->insns,
2307 		       text->insns_cnt * sizeof(*insn));
2308 		prog->insns = new_insn;
2309 		prog->main_prog_cnt = prog->insns_cnt;
2310 		prog->insns_cnt = new_cnt;
2311 		pr_debug("added %zd insn from %s to prog %s\n",
2312 			 text->insns_cnt, text->section_name,
2313 			 prog->section_name);
2314 	}
2315 	insn = &prog->insns[relo->insn_idx];
2316 	insn->imm += prog->main_prog_cnt - relo->insn_idx;
2317 	return 0;
2318 }
2319 
2320 static int
2321 bpf_program__relocate(struct bpf_program *prog, struct bpf_object *obj)
2322 {
2323 	int i, err;
2324 
2325 	if (!prog)
2326 		return 0;
2327 
2328 	if (obj->btf_ext) {
2329 		err = bpf_program_reloc_btf_ext(prog, obj,
2330 						prog->section_name, 0);
2331 		if (err)
2332 			return err;
2333 	}
2334 
2335 	if (!prog->reloc_desc)
2336 		return 0;
2337 
2338 	for (i = 0; i < prog->nr_reloc; i++) {
2339 		if (prog->reloc_desc[i].type == RELO_LD64 ||
2340 		    prog->reloc_desc[i].type == RELO_DATA) {
2341 			bool relo_data = prog->reloc_desc[i].type == RELO_DATA;
2342 			struct bpf_insn *insns = prog->insns;
2343 			int insn_idx, map_idx;
2344 
2345 			insn_idx = prog->reloc_desc[i].insn_idx;
2346 			map_idx = prog->reloc_desc[i].map_idx;
2347 
2348 			if (insn_idx + 1 >= (int)prog->insns_cnt) {
2349 				pr_warning("relocation out of range: '%s'\n",
2350 					   prog->section_name);
2351 				return -LIBBPF_ERRNO__RELOC;
2352 			}
2353 
2354 			if (!relo_data) {
2355 				insns[insn_idx].src_reg = BPF_PSEUDO_MAP_FD;
2356 			} else {
2357 				insns[insn_idx].src_reg = BPF_PSEUDO_MAP_VALUE;
2358 				insns[insn_idx + 1].imm = insns[insn_idx].imm;
2359 			}
2360 			insns[insn_idx].imm = obj->maps[map_idx].fd;
2361 		} else if (prog->reloc_desc[i].type == RELO_CALL) {
2362 			err = bpf_program__reloc_text(prog, obj,
2363 						      &prog->reloc_desc[i]);
2364 			if (err)
2365 				return err;
2366 		}
2367 	}
2368 
2369 	zfree(&prog->reloc_desc);
2370 	prog->nr_reloc = 0;
2371 	return 0;
2372 }
2373 
2374 
2375 static int
2376 bpf_object__relocate(struct bpf_object *obj)
2377 {
2378 	struct bpf_program *prog;
2379 	size_t i;
2380 	int err;
2381 
2382 	for (i = 0; i < obj->nr_programs; i++) {
2383 		prog = &obj->programs[i];
2384 
2385 		err = bpf_program__relocate(prog, obj);
2386 		if (err) {
2387 			pr_warning("failed to relocate '%s'\n",
2388 				   prog->section_name);
2389 			return err;
2390 		}
2391 	}
2392 	return 0;
2393 }
2394 
2395 static int bpf_object__collect_reloc(struct bpf_object *obj)
2396 {
2397 	int i, err;
2398 
2399 	if (!obj_elf_valid(obj)) {
2400 		pr_warning("Internal error: elf object is closed\n");
2401 		return -LIBBPF_ERRNO__INTERNAL;
2402 	}
2403 
2404 	for (i = 0; i < obj->efile.nr_reloc; i++) {
2405 		GElf_Shdr *shdr = &obj->efile.reloc[i].shdr;
2406 		Elf_Data *data = obj->efile.reloc[i].data;
2407 		int idx = shdr->sh_info;
2408 		struct bpf_program *prog;
2409 
2410 		if (shdr->sh_type != SHT_REL) {
2411 			pr_warning("internal error at %d\n", __LINE__);
2412 			return -LIBBPF_ERRNO__INTERNAL;
2413 		}
2414 
2415 		prog = bpf_object__find_prog_by_idx(obj, idx);
2416 		if (!prog) {
2417 			pr_warning("relocation failed: no section(%d)\n", idx);
2418 			return -LIBBPF_ERRNO__RELOC;
2419 		}
2420 
2421 		err = bpf_program__collect_reloc(prog, shdr, data, obj);
2422 		if (err)
2423 			return err;
2424 	}
2425 	return 0;
2426 }
2427 
2428 static int
2429 load_program(struct bpf_program *prog, struct bpf_insn *insns, int insns_cnt,
2430 	     char *license, __u32 kern_version, int *pfd)
2431 {
2432 	struct bpf_load_program_attr load_attr;
2433 	char *cp, errmsg[STRERR_BUFSIZE];
2434 	int log_buf_size = BPF_LOG_BUF_SIZE;
2435 	char *log_buf;
2436 	int ret;
2437 
2438 	if (!insns || !insns_cnt)
2439 		return -EINVAL;
2440 
2441 	memset(&load_attr, 0, sizeof(struct bpf_load_program_attr));
2442 	load_attr.prog_type = prog->type;
2443 	load_attr.expected_attach_type = prog->expected_attach_type;
2444 	if (prog->caps->name)
2445 		load_attr.name = prog->name;
2446 	load_attr.insns = insns;
2447 	load_attr.insns_cnt = insns_cnt;
2448 	load_attr.license = license;
2449 	load_attr.kern_version = kern_version;
2450 	load_attr.prog_ifindex = prog->prog_ifindex;
2451 	load_attr.prog_btf_fd = prog->btf_fd >= 0 ? prog->btf_fd : 0;
2452 	load_attr.func_info = prog->func_info;
2453 	load_attr.func_info_rec_size = prog->func_info_rec_size;
2454 	load_attr.func_info_cnt = prog->func_info_cnt;
2455 	load_attr.line_info = prog->line_info;
2456 	load_attr.line_info_rec_size = prog->line_info_rec_size;
2457 	load_attr.line_info_cnt = prog->line_info_cnt;
2458 	load_attr.log_level = prog->log_level;
2459 	load_attr.prog_flags = prog->prog_flags;
2460 
2461 retry_load:
2462 	log_buf = malloc(log_buf_size);
2463 	if (!log_buf)
2464 		pr_warning("Alloc log buffer for bpf loader error, continue without log\n");
2465 
2466 	ret = bpf_load_program_xattr(&load_attr, log_buf, log_buf_size);
2467 
2468 	if (ret >= 0) {
2469 		if (load_attr.log_level)
2470 			pr_debug("verifier log:\n%s", log_buf);
2471 		*pfd = ret;
2472 		ret = 0;
2473 		goto out;
2474 	}
2475 
2476 	if (errno == ENOSPC) {
2477 		log_buf_size <<= 1;
2478 		free(log_buf);
2479 		goto retry_load;
2480 	}
2481 	ret = -LIBBPF_ERRNO__LOAD;
2482 	cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2483 	pr_warning("load bpf program failed: %s\n", cp);
2484 
2485 	if (log_buf && log_buf[0] != '\0') {
2486 		ret = -LIBBPF_ERRNO__VERIFY;
2487 		pr_warning("-- BEGIN DUMP LOG ---\n");
2488 		pr_warning("\n%s\n", log_buf);
2489 		pr_warning("-- END LOG --\n");
2490 	} else if (load_attr.insns_cnt >= BPF_MAXINSNS) {
2491 		pr_warning("Program too large (%zu insns), at most %d insns\n",
2492 			   load_attr.insns_cnt, BPF_MAXINSNS);
2493 		ret = -LIBBPF_ERRNO__PROG2BIG;
2494 	} else {
2495 		/* Wrong program type? */
2496 		if (load_attr.prog_type != BPF_PROG_TYPE_KPROBE) {
2497 			int fd;
2498 
2499 			load_attr.prog_type = BPF_PROG_TYPE_KPROBE;
2500 			load_attr.expected_attach_type = 0;
2501 			fd = bpf_load_program_xattr(&load_attr, NULL, 0);
2502 			if (fd >= 0) {
2503 				close(fd);
2504 				ret = -LIBBPF_ERRNO__PROGTYPE;
2505 				goto out;
2506 			}
2507 		}
2508 
2509 		if (log_buf)
2510 			ret = -LIBBPF_ERRNO__KVER;
2511 	}
2512 
2513 out:
2514 	free(log_buf);
2515 	return ret;
2516 }
2517 
2518 int
2519 bpf_program__load(struct bpf_program *prog,
2520 		  char *license, __u32 kern_version)
2521 {
2522 	int err = 0, fd, i;
2523 
2524 	if (prog->instances.nr < 0 || !prog->instances.fds) {
2525 		if (prog->preprocessor) {
2526 			pr_warning("Internal error: can't load program '%s'\n",
2527 				   prog->section_name);
2528 			return -LIBBPF_ERRNO__INTERNAL;
2529 		}
2530 
2531 		prog->instances.fds = malloc(sizeof(int));
2532 		if (!prog->instances.fds) {
2533 			pr_warning("Not enough memory for BPF fds\n");
2534 			return -ENOMEM;
2535 		}
2536 		prog->instances.nr = 1;
2537 		prog->instances.fds[0] = -1;
2538 	}
2539 
2540 	if (!prog->preprocessor) {
2541 		if (prog->instances.nr != 1) {
2542 			pr_warning("Program '%s' is inconsistent: nr(%d) != 1\n",
2543 				   prog->section_name, prog->instances.nr);
2544 		}
2545 		err = load_program(prog, prog->insns, prog->insns_cnt,
2546 				   license, kern_version, &fd);
2547 		if (!err)
2548 			prog->instances.fds[0] = fd;
2549 		goto out;
2550 	}
2551 
2552 	for (i = 0; i < prog->instances.nr; i++) {
2553 		struct bpf_prog_prep_result result;
2554 		bpf_program_prep_t preprocessor = prog->preprocessor;
2555 
2556 		memset(&result, 0, sizeof(result));
2557 		err = preprocessor(prog, i, prog->insns,
2558 				   prog->insns_cnt, &result);
2559 		if (err) {
2560 			pr_warning("Preprocessing the %dth instance of program '%s' failed\n",
2561 				   i, prog->section_name);
2562 			goto out;
2563 		}
2564 
2565 		if (!result.new_insn_ptr || !result.new_insn_cnt) {
2566 			pr_debug("Skip loading the %dth instance of program '%s'\n",
2567 				 i, prog->section_name);
2568 			prog->instances.fds[i] = -1;
2569 			if (result.pfd)
2570 				*result.pfd = -1;
2571 			continue;
2572 		}
2573 
2574 		err = load_program(prog, result.new_insn_ptr,
2575 				   result.new_insn_cnt,
2576 				   license, kern_version, &fd);
2577 
2578 		if (err) {
2579 			pr_warning("Loading the %dth instance of program '%s' failed\n",
2580 					i, prog->section_name);
2581 			goto out;
2582 		}
2583 
2584 		if (result.pfd)
2585 			*result.pfd = fd;
2586 		prog->instances.fds[i] = fd;
2587 	}
2588 out:
2589 	if (err)
2590 		pr_warning("failed to load program '%s'\n",
2591 			   prog->section_name);
2592 	zfree(&prog->insns);
2593 	prog->insns_cnt = 0;
2594 	return err;
2595 }
2596 
2597 static bool bpf_program__is_function_storage(const struct bpf_program *prog,
2598 					     const struct bpf_object *obj)
2599 {
2600 	return prog->idx == obj->efile.text_shndx && obj->has_pseudo_calls;
2601 }
2602 
2603 static int
2604 bpf_object__load_progs(struct bpf_object *obj, int log_level)
2605 {
2606 	size_t i;
2607 	int err;
2608 
2609 	for (i = 0; i < obj->nr_programs; i++) {
2610 		if (bpf_program__is_function_storage(&obj->programs[i], obj))
2611 			continue;
2612 		obj->programs[i].log_level |= log_level;
2613 		err = bpf_program__load(&obj->programs[i],
2614 					obj->license,
2615 					obj->kern_version);
2616 		if (err)
2617 			return err;
2618 	}
2619 	return 0;
2620 }
2621 
2622 static bool bpf_prog_type__needs_kver(enum bpf_prog_type type)
2623 {
2624 	switch (type) {
2625 	case BPF_PROG_TYPE_SOCKET_FILTER:
2626 	case BPF_PROG_TYPE_SCHED_CLS:
2627 	case BPF_PROG_TYPE_SCHED_ACT:
2628 	case BPF_PROG_TYPE_XDP:
2629 	case BPF_PROG_TYPE_CGROUP_SKB:
2630 	case BPF_PROG_TYPE_CGROUP_SOCK:
2631 	case BPF_PROG_TYPE_LWT_IN:
2632 	case BPF_PROG_TYPE_LWT_OUT:
2633 	case BPF_PROG_TYPE_LWT_XMIT:
2634 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
2635 	case BPF_PROG_TYPE_SOCK_OPS:
2636 	case BPF_PROG_TYPE_SK_SKB:
2637 	case BPF_PROG_TYPE_CGROUP_DEVICE:
2638 	case BPF_PROG_TYPE_SK_MSG:
2639 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
2640 	case BPF_PROG_TYPE_LIRC_MODE2:
2641 	case BPF_PROG_TYPE_SK_REUSEPORT:
2642 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
2643 	case BPF_PROG_TYPE_UNSPEC:
2644 	case BPF_PROG_TYPE_TRACEPOINT:
2645 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
2646 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
2647 	case BPF_PROG_TYPE_PERF_EVENT:
2648 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
2649 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
2650 		return false;
2651 	case BPF_PROG_TYPE_KPROBE:
2652 	default:
2653 		return true;
2654 	}
2655 }
2656 
2657 static int bpf_object__validate(struct bpf_object *obj, bool needs_kver)
2658 {
2659 	if (needs_kver && obj->kern_version == 0) {
2660 		pr_warning("%s doesn't provide kernel version\n",
2661 			   obj->path);
2662 		return -LIBBPF_ERRNO__KVERSION;
2663 	}
2664 	return 0;
2665 }
2666 
2667 static struct bpf_object *
2668 __bpf_object__open(const char *path, void *obj_buf, size_t obj_buf_sz,
2669 		   bool needs_kver, int flags)
2670 {
2671 	struct bpf_object *obj;
2672 	int err;
2673 
2674 	if (elf_version(EV_CURRENT) == EV_NONE) {
2675 		pr_warning("failed to init libelf for %s\n", path);
2676 		return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
2677 	}
2678 
2679 	obj = bpf_object__new(path, obj_buf, obj_buf_sz);
2680 	if (IS_ERR(obj))
2681 		return obj;
2682 
2683 	CHECK_ERR(bpf_object__elf_init(obj), err, out);
2684 	CHECK_ERR(bpf_object__check_endianness(obj), err, out);
2685 	CHECK_ERR(bpf_object__probe_caps(obj), err, out);
2686 	CHECK_ERR(bpf_object__elf_collect(obj, flags), err, out);
2687 	CHECK_ERR(bpf_object__collect_reloc(obj), err, out);
2688 	CHECK_ERR(bpf_object__validate(obj, needs_kver), err, out);
2689 
2690 	bpf_object__elf_finish(obj);
2691 	return obj;
2692 out:
2693 	bpf_object__close(obj);
2694 	return ERR_PTR(err);
2695 }
2696 
2697 struct bpf_object *__bpf_object__open_xattr(struct bpf_object_open_attr *attr,
2698 					    int flags)
2699 {
2700 	/* param validation */
2701 	if (!attr->file)
2702 		return NULL;
2703 
2704 	pr_debug("loading %s\n", attr->file);
2705 
2706 	return __bpf_object__open(attr->file, NULL, 0,
2707 				  bpf_prog_type__needs_kver(attr->prog_type),
2708 				  flags);
2709 }
2710 
2711 struct bpf_object *bpf_object__open_xattr(struct bpf_object_open_attr *attr)
2712 {
2713 	return __bpf_object__open_xattr(attr, 0);
2714 }
2715 
2716 struct bpf_object *bpf_object__open(const char *path)
2717 {
2718 	struct bpf_object_open_attr attr = {
2719 		.file		= path,
2720 		.prog_type	= BPF_PROG_TYPE_UNSPEC,
2721 	};
2722 
2723 	return bpf_object__open_xattr(&attr);
2724 }
2725 
2726 struct bpf_object *bpf_object__open_buffer(void *obj_buf,
2727 					   size_t obj_buf_sz,
2728 					   const char *name)
2729 {
2730 	char tmp_name[64];
2731 
2732 	/* param validation */
2733 	if (!obj_buf || obj_buf_sz <= 0)
2734 		return NULL;
2735 
2736 	if (!name) {
2737 		snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
2738 			 (unsigned long)obj_buf,
2739 			 (unsigned long)obj_buf_sz);
2740 		name = tmp_name;
2741 	}
2742 	pr_debug("loading object '%s' from buffer\n", name);
2743 
2744 	return __bpf_object__open(name, obj_buf, obj_buf_sz, true, true);
2745 }
2746 
2747 int bpf_object__unload(struct bpf_object *obj)
2748 {
2749 	size_t i;
2750 
2751 	if (!obj)
2752 		return -EINVAL;
2753 
2754 	for (i = 0; i < obj->nr_maps; i++)
2755 		zclose(obj->maps[i].fd);
2756 
2757 	for (i = 0; i < obj->nr_programs; i++)
2758 		bpf_program__unload(&obj->programs[i]);
2759 
2760 	return 0;
2761 }
2762 
2763 int bpf_object__load_xattr(struct bpf_object_load_attr *attr)
2764 {
2765 	struct bpf_object *obj;
2766 	int err;
2767 
2768 	if (!attr)
2769 		return -EINVAL;
2770 	obj = attr->obj;
2771 	if (!obj)
2772 		return -EINVAL;
2773 
2774 	if (obj->loaded) {
2775 		pr_warning("object should not be loaded twice\n");
2776 		return -EINVAL;
2777 	}
2778 
2779 	obj->loaded = true;
2780 
2781 	CHECK_ERR(bpf_object__create_maps(obj), err, out);
2782 	CHECK_ERR(bpf_object__relocate(obj), err, out);
2783 	CHECK_ERR(bpf_object__load_progs(obj, attr->log_level), err, out);
2784 
2785 	return 0;
2786 out:
2787 	bpf_object__unload(obj);
2788 	pr_warning("failed to load object '%s'\n", obj->path);
2789 	return err;
2790 }
2791 
2792 int bpf_object__load(struct bpf_object *obj)
2793 {
2794 	struct bpf_object_load_attr attr = {
2795 		.obj = obj,
2796 	};
2797 
2798 	return bpf_object__load_xattr(&attr);
2799 }
2800 
2801 static int check_path(const char *path)
2802 {
2803 	char *cp, errmsg[STRERR_BUFSIZE];
2804 	struct statfs st_fs;
2805 	char *dname, *dir;
2806 	int err = 0;
2807 
2808 	if (path == NULL)
2809 		return -EINVAL;
2810 
2811 	dname = strdup(path);
2812 	if (dname == NULL)
2813 		return -ENOMEM;
2814 
2815 	dir = dirname(dname);
2816 	if (statfs(dir, &st_fs)) {
2817 		cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2818 		pr_warning("failed to statfs %s: %s\n", dir, cp);
2819 		err = -errno;
2820 	}
2821 	free(dname);
2822 
2823 	if (!err && st_fs.f_type != BPF_FS_MAGIC) {
2824 		pr_warning("specified path %s is not on BPF FS\n", path);
2825 		err = -EINVAL;
2826 	}
2827 
2828 	return err;
2829 }
2830 
2831 int bpf_program__pin_instance(struct bpf_program *prog, const char *path,
2832 			      int instance)
2833 {
2834 	char *cp, errmsg[STRERR_BUFSIZE];
2835 	int err;
2836 
2837 	err = check_path(path);
2838 	if (err)
2839 		return err;
2840 
2841 	if (prog == NULL) {
2842 		pr_warning("invalid program pointer\n");
2843 		return -EINVAL;
2844 	}
2845 
2846 	if (instance < 0 || instance >= prog->instances.nr) {
2847 		pr_warning("invalid prog instance %d of prog %s (max %d)\n",
2848 			   instance, prog->section_name, prog->instances.nr);
2849 		return -EINVAL;
2850 	}
2851 
2852 	if (bpf_obj_pin(prog->instances.fds[instance], path)) {
2853 		cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2854 		pr_warning("failed to pin program: %s\n", cp);
2855 		return -errno;
2856 	}
2857 	pr_debug("pinned program '%s'\n", path);
2858 
2859 	return 0;
2860 }
2861 
2862 int bpf_program__unpin_instance(struct bpf_program *prog, const char *path,
2863 				int instance)
2864 {
2865 	int err;
2866 
2867 	err = check_path(path);
2868 	if (err)
2869 		return err;
2870 
2871 	if (prog == NULL) {
2872 		pr_warning("invalid program pointer\n");
2873 		return -EINVAL;
2874 	}
2875 
2876 	if (instance < 0 || instance >= prog->instances.nr) {
2877 		pr_warning("invalid prog instance %d of prog %s (max %d)\n",
2878 			   instance, prog->section_name, prog->instances.nr);
2879 		return -EINVAL;
2880 	}
2881 
2882 	err = unlink(path);
2883 	if (err != 0)
2884 		return -errno;
2885 	pr_debug("unpinned program '%s'\n", path);
2886 
2887 	return 0;
2888 }
2889 
2890 static int make_dir(const char *path)
2891 {
2892 	char *cp, errmsg[STRERR_BUFSIZE];
2893 	int err = 0;
2894 
2895 	if (mkdir(path, 0700) && errno != EEXIST)
2896 		err = -errno;
2897 
2898 	if (err) {
2899 		cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
2900 		pr_warning("failed to mkdir %s: %s\n", path, cp);
2901 	}
2902 	return err;
2903 }
2904 
2905 int bpf_program__pin(struct bpf_program *prog, const char *path)
2906 {
2907 	int i, err;
2908 
2909 	err = check_path(path);
2910 	if (err)
2911 		return err;
2912 
2913 	if (prog == NULL) {
2914 		pr_warning("invalid program pointer\n");
2915 		return -EINVAL;
2916 	}
2917 
2918 	if (prog->instances.nr <= 0) {
2919 		pr_warning("no instances of prog %s to pin\n",
2920 			   prog->section_name);
2921 		return -EINVAL;
2922 	}
2923 
2924 	if (prog->instances.nr == 1) {
2925 		/* don't create subdirs when pinning single instance */
2926 		return bpf_program__pin_instance(prog, path, 0);
2927 	}
2928 
2929 	err = make_dir(path);
2930 	if (err)
2931 		return err;
2932 
2933 	for (i = 0; i < prog->instances.nr; i++) {
2934 		char buf[PATH_MAX];
2935 		int len;
2936 
2937 		len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
2938 		if (len < 0) {
2939 			err = -EINVAL;
2940 			goto err_unpin;
2941 		} else if (len >= PATH_MAX) {
2942 			err = -ENAMETOOLONG;
2943 			goto err_unpin;
2944 		}
2945 
2946 		err = bpf_program__pin_instance(prog, buf, i);
2947 		if (err)
2948 			goto err_unpin;
2949 	}
2950 
2951 	return 0;
2952 
2953 err_unpin:
2954 	for (i = i - 1; i >= 0; i--) {
2955 		char buf[PATH_MAX];
2956 		int len;
2957 
2958 		len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
2959 		if (len < 0)
2960 			continue;
2961 		else if (len >= PATH_MAX)
2962 			continue;
2963 
2964 		bpf_program__unpin_instance(prog, buf, i);
2965 	}
2966 
2967 	rmdir(path);
2968 
2969 	return err;
2970 }
2971 
2972 int bpf_program__unpin(struct bpf_program *prog, const char *path)
2973 {
2974 	int i, err;
2975 
2976 	err = check_path(path);
2977 	if (err)
2978 		return err;
2979 
2980 	if (prog == NULL) {
2981 		pr_warning("invalid program pointer\n");
2982 		return -EINVAL;
2983 	}
2984 
2985 	if (prog->instances.nr <= 0) {
2986 		pr_warning("no instances of prog %s to pin\n",
2987 			   prog->section_name);
2988 		return -EINVAL;
2989 	}
2990 
2991 	if (prog->instances.nr == 1) {
2992 		/* don't create subdirs when pinning single instance */
2993 		return bpf_program__unpin_instance(prog, path, 0);
2994 	}
2995 
2996 	for (i = 0; i < prog->instances.nr; i++) {
2997 		char buf[PATH_MAX];
2998 		int len;
2999 
3000 		len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
3001 		if (len < 0)
3002 			return -EINVAL;
3003 		else if (len >= PATH_MAX)
3004 			return -ENAMETOOLONG;
3005 
3006 		err = bpf_program__unpin_instance(prog, buf, i);
3007 		if (err)
3008 			return err;
3009 	}
3010 
3011 	err = rmdir(path);
3012 	if (err)
3013 		return -errno;
3014 
3015 	return 0;
3016 }
3017 
3018 int bpf_map__pin(struct bpf_map *map, const char *path)
3019 {
3020 	char *cp, errmsg[STRERR_BUFSIZE];
3021 	int err;
3022 
3023 	err = check_path(path);
3024 	if (err)
3025 		return err;
3026 
3027 	if (map == NULL) {
3028 		pr_warning("invalid map pointer\n");
3029 		return -EINVAL;
3030 	}
3031 
3032 	if (bpf_obj_pin(map->fd, path)) {
3033 		cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
3034 		pr_warning("failed to pin map: %s\n", cp);
3035 		return -errno;
3036 	}
3037 
3038 	pr_debug("pinned map '%s'\n", path);
3039 
3040 	return 0;
3041 }
3042 
3043 int bpf_map__unpin(struct bpf_map *map, const char *path)
3044 {
3045 	int err;
3046 
3047 	err = check_path(path);
3048 	if (err)
3049 		return err;
3050 
3051 	if (map == NULL) {
3052 		pr_warning("invalid map pointer\n");
3053 		return -EINVAL;
3054 	}
3055 
3056 	err = unlink(path);
3057 	if (err != 0)
3058 		return -errno;
3059 	pr_debug("unpinned map '%s'\n", path);
3060 
3061 	return 0;
3062 }
3063 
3064 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
3065 {
3066 	struct bpf_map *map;
3067 	int err;
3068 
3069 	if (!obj)
3070 		return -ENOENT;
3071 
3072 	if (!obj->loaded) {
3073 		pr_warning("object not yet loaded; load it first\n");
3074 		return -ENOENT;
3075 	}
3076 
3077 	err = make_dir(path);
3078 	if (err)
3079 		return err;
3080 
3081 	bpf_object__for_each_map(map, obj) {
3082 		char buf[PATH_MAX];
3083 		int len;
3084 
3085 		len = snprintf(buf, PATH_MAX, "%s/%s", path,
3086 			       bpf_map__name(map));
3087 		if (len < 0) {
3088 			err = -EINVAL;
3089 			goto err_unpin_maps;
3090 		} else if (len >= PATH_MAX) {
3091 			err = -ENAMETOOLONG;
3092 			goto err_unpin_maps;
3093 		}
3094 
3095 		err = bpf_map__pin(map, buf);
3096 		if (err)
3097 			goto err_unpin_maps;
3098 	}
3099 
3100 	return 0;
3101 
3102 err_unpin_maps:
3103 	while ((map = bpf_map__prev(map, obj))) {
3104 		char buf[PATH_MAX];
3105 		int len;
3106 
3107 		len = snprintf(buf, PATH_MAX, "%s/%s", path,
3108 			       bpf_map__name(map));
3109 		if (len < 0)
3110 			continue;
3111 		else if (len >= PATH_MAX)
3112 			continue;
3113 
3114 		bpf_map__unpin(map, buf);
3115 	}
3116 
3117 	return err;
3118 }
3119 
3120 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
3121 {
3122 	struct bpf_map *map;
3123 	int err;
3124 
3125 	if (!obj)
3126 		return -ENOENT;
3127 
3128 	bpf_object__for_each_map(map, obj) {
3129 		char buf[PATH_MAX];
3130 		int len;
3131 
3132 		len = snprintf(buf, PATH_MAX, "%s/%s", path,
3133 			       bpf_map__name(map));
3134 		if (len < 0)
3135 			return -EINVAL;
3136 		else if (len >= PATH_MAX)
3137 			return -ENAMETOOLONG;
3138 
3139 		err = bpf_map__unpin(map, buf);
3140 		if (err)
3141 			return err;
3142 	}
3143 
3144 	return 0;
3145 }
3146 
3147 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
3148 {
3149 	struct bpf_program *prog;
3150 	int err;
3151 
3152 	if (!obj)
3153 		return -ENOENT;
3154 
3155 	if (!obj->loaded) {
3156 		pr_warning("object not yet loaded; load it first\n");
3157 		return -ENOENT;
3158 	}
3159 
3160 	err = make_dir(path);
3161 	if (err)
3162 		return err;
3163 
3164 	bpf_object__for_each_program(prog, obj) {
3165 		char buf[PATH_MAX];
3166 		int len;
3167 
3168 		len = snprintf(buf, PATH_MAX, "%s/%s", path,
3169 			       prog->pin_name);
3170 		if (len < 0) {
3171 			err = -EINVAL;
3172 			goto err_unpin_programs;
3173 		} else if (len >= PATH_MAX) {
3174 			err = -ENAMETOOLONG;
3175 			goto err_unpin_programs;
3176 		}
3177 
3178 		err = bpf_program__pin(prog, buf);
3179 		if (err)
3180 			goto err_unpin_programs;
3181 	}
3182 
3183 	return 0;
3184 
3185 err_unpin_programs:
3186 	while ((prog = bpf_program__prev(prog, obj))) {
3187 		char buf[PATH_MAX];
3188 		int len;
3189 
3190 		len = snprintf(buf, PATH_MAX, "%s/%s", path,
3191 			       prog->pin_name);
3192 		if (len < 0)
3193 			continue;
3194 		else if (len >= PATH_MAX)
3195 			continue;
3196 
3197 		bpf_program__unpin(prog, buf);
3198 	}
3199 
3200 	return err;
3201 }
3202 
3203 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
3204 {
3205 	struct bpf_program *prog;
3206 	int err;
3207 
3208 	if (!obj)
3209 		return -ENOENT;
3210 
3211 	bpf_object__for_each_program(prog, obj) {
3212 		char buf[PATH_MAX];
3213 		int len;
3214 
3215 		len = snprintf(buf, PATH_MAX, "%s/%s", path,
3216 			       prog->pin_name);
3217 		if (len < 0)
3218 			return -EINVAL;
3219 		else if (len >= PATH_MAX)
3220 			return -ENAMETOOLONG;
3221 
3222 		err = bpf_program__unpin(prog, buf);
3223 		if (err)
3224 			return err;
3225 	}
3226 
3227 	return 0;
3228 }
3229 
3230 int bpf_object__pin(struct bpf_object *obj, const char *path)
3231 {
3232 	int err;
3233 
3234 	err = bpf_object__pin_maps(obj, path);
3235 	if (err)
3236 		return err;
3237 
3238 	err = bpf_object__pin_programs(obj, path);
3239 	if (err) {
3240 		bpf_object__unpin_maps(obj, path);
3241 		return err;
3242 	}
3243 
3244 	return 0;
3245 }
3246 
3247 void bpf_object__close(struct bpf_object *obj)
3248 {
3249 	size_t i;
3250 
3251 	if (!obj)
3252 		return;
3253 
3254 	if (obj->clear_priv)
3255 		obj->clear_priv(obj, obj->priv);
3256 
3257 	bpf_object__elf_finish(obj);
3258 	bpf_object__unload(obj);
3259 	btf__free(obj->btf);
3260 	btf_ext__free(obj->btf_ext);
3261 
3262 	for (i = 0; i < obj->nr_maps; i++) {
3263 		zfree(&obj->maps[i].name);
3264 		if (obj->maps[i].clear_priv)
3265 			obj->maps[i].clear_priv(&obj->maps[i],
3266 						obj->maps[i].priv);
3267 		obj->maps[i].priv = NULL;
3268 		obj->maps[i].clear_priv = NULL;
3269 	}
3270 
3271 	zfree(&obj->sections.rodata);
3272 	zfree(&obj->sections.data);
3273 	zfree(&obj->maps);
3274 	obj->nr_maps = 0;
3275 
3276 	if (obj->programs && obj->nr_programs) {
3277 		for (i = 0; i < obj->nr_programs; i++)
3278 			bpf_program__exit(&obj->programs[i]);
3279 	}
3280 	zfree(&obj->programs);
3281 
3282 	list_del(&obj->list);
3283 	free(obj);
3284 }
3285 
3286 struct bpf_object *
3287 bpf_object__next(struct bpf_object *prev)
3288 {
3289 	struct bpf_object *next;
3290 
3291 	if (!prev)
3292 		next = list_first_entry(&bpf_objects_list,
3293 					struct bpf_object,
3294 					list);
3295 	else
3296 		next = list_next_entry(prev, list);
3297 
3298 	/* Empty list is noticed here so don't need checking on entry. */
3299 	if (&next->list == &bpf_objects_list)
3300 		return NULL;
3301 
3302 	return next;
3303 }
3304 
3305 const char *bpf_object__name(const struct bpf_object *obj)
3306 {
3307 	return obj ? obj->path : ERR_PTR(-EINVAL);
3308 }
3309 
3310 unsigned int bpf_object__kversion(const struct bpf_object *obj)
3311 {
3312 	return obj ? obj->kern_version : 0;
3313 }
3314 
3315 struct btf *bpf_object__btf(const struct bpf_object *obj)
3316 {
3317 	return obj ? obj->btf : NULL;
3318 }
3319 
3320 int bpf_object__btf_fd(const struct bpf_object *obj)
3321 {
3322 	return obj->btf ? btf__fd(obj->btf) : -1;
3323 }
3324 
3325 int bpf_object__set_priv(struct bpf_object *obj, void *priv,
3326 			 bpf_object_clear_priv_t clear_priv)
3327 {
3328 	if (obj->priv && obj->clear_priv)
3329 		obj->clear_priv(obj, obj->priv);
3330 
3331 	obj->priv = priv;
3332 	obj->clear_priv = clear_priv;
3333 	return 0;
3334 }
3335 
3336 void *bpf_object__priv(const struct bpf_object *obj)
3337 {
3338 	return obj ? obj->priv : ERR_PTR(-EINVAL);
3339 }
3340 
3341 static struct bpf_program *
3342 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
3343 		    bool forward)
3344 {
3345 	size_t nr_programs = obj->nr_programs;
3346 	ssize_t idx;
3347 
3348 	if (!nr_programs)
3349 		return NULL;
3350 
3351 	if (!p)
3352 		/* Iter from the beginning */
3353 		return forward ? &obj->programs[0] :
3354 			&obj->programs[nr_programs - 1];
3355 
3356 	if (p->obj != obj) {
3357 		pr_warning("error: program handler doesn't match object\n");
3358 		return NULL;
3359 	}
3360 
3361 	idx = (p - obj->programs) + (forward ? 1 : -1);
3362 	if (idx >= obj->nr_programs || idx < 0)
3363 		return NULL;
3364 	return &obj->programs[idx];
3365 }
3366 
3367 struct bpf_program *
3368 bpf_program__next(struct bpf_program *prev, const struct bpf_object *obj)
3369 {
3370 	struct bpf_program *prog = prev;
3371 
3372 	do {
3373 		prog = __bpf_program__iter(prog, obj, true);
3374 	} while (prog && bpf_program__is_function_storage(prog, obj));
3375 
3376 	return prog;
3377 }
3378 
3379 struct bpf_program *
3380 bpf_program__prev(struct bpf_program *next, const struct bpf_object *obj)
3381 {
3382 	struct bpf_program *prog = next;
3383 
3384 	do {
3385 		prog = __bpf_program__iter(prog, obj, false);
3386 	} while (prog && bpf_program__is_function_storage(prog, obj));
3387 
3388 	return prog;
3389 }
3390 
3391 int bpf_program__set_priv(struct bpf_program *prog, void *priv,
3392 			  bpf_program_clear_priv_t clear_priv)
3393 {
3394 	if (prog->priv && prog->clear_priv)
3395 		prog->clear_priv(prog, prog->priv);
3396 
3397 	prog->priv = priv;
3398 	prog->clear_priv = clear_priv;
3399 	return 0;
3400 }
3401 
3402 void *bpf_program__priv(const struct bpf_program *prog)
3403 {
3404 	return prog ? prog->priv : ERR_PTR(-EINVAL);
3405 }
3406 
3407 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
3408 {
3409 	prog->prog_ifindex = ifindex;
3410 }
3411 
3412 const char *bpf_program__title(const struct bpf_program *prog, bool needs_copy)
3413 {
3414 	const char *title;
3415 
3416 	title = prog->section_name;
3417 	if (needs_copy) {
3418 		title = strdup(title);
3419 		if (!title) {
3420 			pr_warning("failed to strdup program title\n");
3421 			return ERR_PTR(-ENOMEM);
3422 		}
3423 	}
3424 
3425 	return title;
3426 }
3427 
3428 int bpf_program__fd(const struct bpf_program *prog)
3429 {
3430 	return bpf_program__nth_fd(prog, 0);
3431 }
3432 
3433 int bpf_program__set_prep(struct bpf_program *prog, int nr_instances,
3434 			  bpf_program_prep_t prep)
3435 {
3436 	int *instances_fds;
3437 
3438 	if (nr_instances <= 0 || !prep)
3439 		return -EINVAL;
3440 
3441 	if (prog->instances.nr > 0 || prog->instances.fds) {
3442 		pr_warning("Can't set pre-processor after loading\n");
3443 		return -EINVAL;
3444 	}
3445 
3446 	instances_fds = malloc(sizeof(int) * nr_instances);
3447 	if (!instances_fds) {
3448 		pr_warning("alloc memory failed for fds\n");
3449 		return -ENOMEM;
3450 	}
3451 
3452 	/* fill all fd with -1 */
3453 	memset(instances_fds, -1, sizeof(int) * nr_instances);
3454 
3455 	prog->instances.nr = nr_instances;
3456 	prog->instances.fds = instances_fds;
3457 	prog->preprocessor = prep;
3458 	return 0;
3459 }
3460 
3461 int bpf_program__nth_fd(const struct bpf_program *prog, int n)
3462 {
3463 	int fd;
3464 
3465 	if (!prog)
3466 		return -EINVAL;
3467 
3468 	if (n >= prog->instances.nr || n < 0) {
3469 		pr_warning("Can't get the %dth fd from program %s: only %d instances\n",
3470 			   n, prog->section_name, prog->instances.nr);
3471 		return -EINVAL;
3472 	}
3473 
3474 	fd = prog->instances.fds[n];
3475 	if (fd < 0) {
3476 		pr_warning("%dth instance of program '%s' is invalid\n",
3477 			   n, prog->section_name);
3478 		return -ENOENT;
3479 	}
3480 
3481 	return fd;
3482 }
3483 
3484 void bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
3485 {
3486 	prog->type = type;
3487 }
3488 
3489 static bool bpf_program__is_type(const struct bpf_program *prog,
3490 				 enum bpf_prog_type type)
3491 {
3492 	return prog ? (prog->type == type) : false;
3493 }
3494 
3495 #define BPF_PROG_TYPE_FNS(NAME, TYPE)				\
3496 int bpf_program__set_##NAME(struct bpf_program *prog)		\
3497 {								\
3498 	if (!prog)						\
3499 		return -EINVAL;					\
3500 	bpf_program__set_type(prog, TYPE);			\
3501 	return 0;						\
3502 }								\
3503 								\
3504 bool bpf_program__is_##NAME(const struct bpf_program *prog)	\
3505 {								\
3506 	return bpf_program__is_type(prog, TYPE);		\
3507 }								\
3508 
3509 BPF_PROG_TYPE_FNS(socket_filter, BPF_PROG_TYPE_SOCKET_FILTER);
3510 BPF_PROG_TYPE_FNS(kprobe, BPF_PROG_TYPE_KPROBE);
3511 BPF_PROG_TYPE_FNS(sched_cls, BPF_PROG_TYPE_SCHED_CLS);
3512 BPF_PROG_TYPE_FNS(sched_act, BPF_PROG_TYPE_SCHED_ACT);
3513 BPF_PROG_TYPE_FNS(tracepoint, BPF_PROG_TYPE_TRACEPOINT);
3514 BPF_PROG_TYPE_FNS(raw_tracepoint, BPF_PROG_TYPE_RAW_TRACEPOINT);
3515 BPF_PROG_TYPE_FNS(xdp, BPF_PROG_TYPE_XDP);
3516 BPF_PROG_TYPE_FNS(perf_event, BPF_PROG_TYPE_PERF_EVENT);
3517 
3518 void bpf_program__set_expected_attach_type(struct bpf_program *prog,
3519 					   enum bpf_attach_type type)
3520 {
3521 	prog->expected_attach_type = type;
3522 }
3523 
3524 #define BPF_PROG_SEC_IMPL(string, ptype, eatype, is_attachable, atype) \
3525 	{ string, sizeof(string) - 1, ptype, eatype, is_attachable, atype }
3526 
3527 /* Programs that can NOT be attached. */
3528 #define BPF_PROG_SEC(string, ptype) BPF_PROG_SEC_IMPL(string, ptype, 0, 0, 0)
3529 
3530 /* Programs that can be attached. */
3531 #define BPF_APROG_SEC(string, ptype, atype) \
3532 	BPF_PROG_SEC_IMPL(string, ptype, 0, 1, atype)
3533 
3534 /* Programs that must specify expected attach type at load time. */
3535 #define BPF_EAPROG_SEC(string, ptype, eatype) \
3536 	BPF_PROG_SEC_IMPL(string, ptype, eatype, 1, eatype)
3537 
3538 /* Programs that can be attached but attach type can't be identified by section
3539  * name. Kept for backward compatibility.
3540  */
3541 #define BPF_APROG_COMPAT(string, ptype) BPF_PROG_SEC(string, ptype)
3542 
3543 static const struct {
3544 	const char *sec;
3545 	size_t len;
3546 	enum bpf_prog_type prog_type;
3547 	enum bpf_attach_type expected_attach_type;
3548 	int is_attachable;
3549 	enum bpf_attach_type attach_type;
3550 } section_names[] = {
3551 	BPF_PROG_SEC("socket",			BPF_PROG_TYPE_SOCKET_FILTER),
3552 	BPF_PROG_SEC("kprobe/",			BPF_PROG_TYPE_KPROBE),
3553 	BPF_PROG_SEC("kretprobe/",		BPF_PROG_TYPE_KPROBE),
3554 	BPF_PROG_SEC("classifier",		BPF_PROG_TYPE_SCHED_CLS),
3555 	BPF_PROG_SEC("action",			BPF_PROG_TYPE_SCHED_ACT),
3556 	BPF_PROG_SEC("tracepoint/",		BPF_PROG_TYPE_TRACEPOINT),
3557 	BPF_PROG_SEC("raw_tracepoint/",		BPF_PROG_TYPE_RAW_TRACEPOINT),
3558 	BPF_PROG_SEC("xdp",			BPF_PROG_TYPE_XDP),
3559 	BPF_PROG_SEC("perf_event",		BPF_PROG_TYPE_PERF_EVENT),
3560 	BPF_PROG_SEC("lwt_in",			BPF_PROG_TYPE_LWT_IN),
3561 	BPF_PROG_SEC("lwt_out",			BPF_PROG_TYPE_LWT_OUT),
3562 	BPF_PROG_SEC("lwt_xmit",		BPF_PROG_TYPE_LWT_XMIT),
3563 	BPF_PROG_SEC("lwt_seg6local",		BPF_PROG_TYPE_LWT_SEG6LOCAL),
3564 	BPF_APROG_SEC("cgroup_skb/ingress",	BPF_PROG_TYPE_CGROUP_SKB,
3565 						BPF_CGROUP_INET_INGRESS),
3566 	BPF_APROG_SEC("cgroup_skb/egress",	BPF_PROG_TYPE_CGROUP_SKB,
3567 						BPF_CGROUP_INET_EGRESS),
3568 	BPF_APROG_COMPAT("cgroup/skb",		BPF_PROG_TYPE_CGROUP_SKB),
3569 	BPF_APROG_SEC("cgroup/sock",		BPF_PROG_TYPE_CGROUP_SOCK,
3570 						BPF_CGROUP_INET_SOCK_CREATE),
3571 	BPF_EAPROG_SEC("cgroup/post_bind4",	BPF_PROG_TYPE_CGROUP_SOCK,
3572 						BPF_CGROUP_INET4_POST_BIND),
3573 	BPF_EAPROG_SEC("cgroup/post_bind6",	BPF_PROG_TYPE_CGROUP_SOCK,
3574 						BPF_CGROUP_INET6_POST_BIND),
3575 	BPF_APROG_SEC("cgroup/dev",		BPF_PROG_TYPE_CGROUP_DEVICE,
3576 						BPF_CGROUP_DEVICE),
3577 	BPF_APROG_SEC("sockops",		BPF_PROG_TYPE_SOCK_OPS,
3578 						BPF_CGROUP_SOCK_OPS),
3579 	BPF_APROG_SEC("sk_skb/stream_parser",	BPF_PROG_TYPE_SK_SKB,
3580 						BPF_SK_SKB_STREAM_PARSER),
3581 	BPF_APROG_SEC("sk_skb/stream_verdict",	BPF_PROG_TYPE_SK_SKB,
3582 						BPF_SK_SKB_STREAM_VERDICT),
3583 	BPF_APROG_COMPAT("sk_skb",		BPF_PROG_TYPE_SK_SKB),
3584 	BPF_APROG_SEC("sk_msg",			BPF_PROG_TYPE_SK_MSG,
3585 						BPF_SK_MSG_VERDICT),
3586 	BPF_APROG_SEC("lirc_mode2",		BPF_PROG_TYPE_LIRC_MODE2,
3587 						BPF_LIRC_MODE2),
3588 	BPF_APROG_SEC("flow_dissector",		BPF_PROG_TYPE_FLOW_DISSECTOR,
3589 						BPF_FLOW_DISSECTOR),
3590 	BPF_EAPROG_SEC("cgroup/bind4",		BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
3591 						BPF_CGROUP_INET4_BIND),
3592 	BPF_EAPROG_SEC("cgroup/bind6",		BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
3593 						BPF_CGROUP_INET6_BIND),
3594 	BPF_EAPROG_SEC("cgroup/connect4",	BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
3595 						BPF_CGROUP_INET4_CONNECT),
3596 	BPF_EAPROG_SEC("cgroup/connect6",	BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
3597 						BPF_CGROUP_INET6_CONNECT),
3598 	BPF_EAPROG_SEC("cgroup/sendmsg4",	BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
3599 						BPF_CGROUP_UDP4_SENDMSG),
3600 	BPF_EAPROG_SEC("cgroup/sendmsg6",	BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
3601 						BPF_CGROUP_UDP6_SENDMSG),
3602 	BPF_EAPROG_SEC("cgroup/recvmsg4",	BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
3603 						BPF_CGROUP_UDP4_RECVMSG),
3604 	BPF_EAPROG_SEC("cgroup/recvmsg6",	BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
3605 						BPF_CGROUP_UDP6_RECVMSG),
3606 	BPF_EAPROG_SEC("cgroup/sysctl",		BPF_PROG_TYPE_CGROUP_SYSCTL,
3607 						BPF_CGROUP_SYSCTL),
3608 	BPF_EAPROG_SEC("cgroup/getsockopt",	BPF_PROG_TYPE_CGROUP_SOCKOPT,
3609 						BPF_CGROUP_GETSOCKOPT),
3610 	BPF_EAPROG_SEC("cgroup/setsockopt",	BPF_PROG_TYPE_CGROUP_SOCKOPT,
3611 						BPF_CGROUP_SETSOCKOPT),
3612 };
3613 
3614 #undef BPF_PROG_SEC_IMPL
3615 #undef BPF_PROG_SEC
3616 #undef BPF_APROG_SEC
3617 #undef BPF_EAPROG_SEC
3618 #undef BPF_APROG_COMPAT
3619 
3620 #define MAX_TYPE_NAME_SIZE 32
3621 
3622 static char *libbpf_get_type_names(bool attach_type)
3623 {
3624 	int i, len = ARRAY_SIZE(section_names) * MAX_TYPE_NAME_SIZE;
3625 	char *buf;
3626 
3627 	buf = malloc(len);
3628 	if (!buf)
3629 		return NULL;
3630 
3631 	buf[0] = '\0';
3632 	/* Forge string buf with all available names */
3633 	for (i = 0; i < ARRAY_SIZE(section_names); i++) {
3634 		if (attach_type && !section_names[i].is_attachable)
3635 			continue;
3636 
3637 		if (strlen(buf) + strlen(section_names[i].sec) + 2 > len) {
3638 			free(buf);
3639 			return NULL;
3640 		}
3641 		strcat(buf, " ");
3642 		strcat(buf, section_names[i].sec);
3643 	}
3644 
3645 	return buf;
3646 }
3647 
3648 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
3649 			     enum bpf_attach_type *expected_attach_type)
3650 {
3651 	char *type_names;
3652 	int i;
3653 
3654 	if (!name)
3655 		return -EINVAL;
3656 
3657 	for (i = 0; i < ARRAY_SIZE(section_names); i++) {
3658 		if (strncmp(name, section_names[i].sec, section_names[i].len))
3659 			continue;
3660 		*prog_type = section_names[i].prog_type;
3661 		*expected_attach_type = section_names[i].expected_attach_type;
3662 		return 0;
3663 	}
3664 	pr_warning("failed to guess program type based on ELF section name '%s'\n", name);
3665 	type_names = libbpf_get_type_names(false);
3666 	if (type_names != NULL) {
3667 		pr_info("supported section(type) names are:%s\n", type_names);
3668 		free(type_names);
3669 	}
3670 
3671 	return -EINVAL;
3672 }
3673 
3674 int libbpf_attach_type_by_name(const char *name,
3675 			       enum bpf_attach_type *attach_type)
3676 {
3677 	char *type_names;
3678 	int i;
3679 
3680 	if (!name)
3681 		return -EINVAL;
3682 
3683 	for (i = 0; i < ARRAY_SIZE(section_names); i++) {
3684 		if (strncmp(name, section_names[i].sec, section_names[i].len))
3685 			continue;
3686 		if (!section_names[i].is_attachable)
3687 			return -EINVAL;
3688 		*attach_type = section_names[i].attach_type;
3689 		return 0;
3690 	}
3691 	pr_warning("failed to guess attach type based on ELF section name '%s'\n", name);
3692 	type_names = libbpf_get_type_names(true);
3693 	if (type_names != NULL) {
3694 		pr_info("attachable section(type) names are:%s\n", type_names);
3695 		free(type_names);
3696 	}
3697 
3698 	return -EINVAL;
3699 }
3700 
3701 static int
3702 bpf_program__identify_section(struct bpf_program *prog,
3703 			      enum bpf_prog_type *prog_type,
3704 			      enum bpf_attach_type *expected_attach_type)
3705 {
3706 	return libbpf_prog_type_by_name(prog->section_name, prog_type,
3707 					expected_attach_type);
3708 }
3709 
3710 int bpf_map__fd(const struct bpf_map *map)
3711 {
3712 	return map ? map->fd : -EINVAL;
3713 }
3714 
3715 const struct bpf_map_def *bpf_map__def(const struct bpf_map *map)
3716 {
3717 	return map ? &map->def : ERR_PTR(-EINVAL);
3718 }
3719 
3720 const char *bpf_map__name(const struct bpf_map *map)
3721 {
3722 	return map ? map->name : NULL;
3723 }
3724 
3725 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
3726 {
3727 	return map ? map->btf_key_type_id : 0;
3728 }
3729 
3730 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
3731 {
3732 	return map ? map->btf_value_type_id : 0;
3733 }
3734 
3735 int bpf_map__set_priv(struct bpf_map *map, void *priv,
3736 		     bpf_map_clear_priv_t clear_priv)
3737 {
3738 	if (!map)
3739 		return -EINVAL;
3740 
3741 	if (map->priv) {
3742 		if (map->clear_priv)
3743 			map->clear_priv(map, map->priv);
3744 	}
3745 
3746 	map->priv = priv;
3747 	map->clear_priv = clear_priv;
3748 	return 0;
3749 }
3750 
3751 void *bpf_map__priv(const struct bpf_map *map)
3752 {
3753 	return map ? map->priv : ERR_PTR(-EINVAL);
3754 }
3755 
3756 bool bpf_map__is_offload_neutral(const struct bpf_map *map)
3757 {
3758 	return map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY;
3759 }
3760 
3761 bool bpf_map__is_internal(const struct bpf_map *map)
3762 {
3763 	return map->libbpf_type != LIBBPF_MAP_UNSPEC;
3764 }
3765 
3766 void bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
3767 {
3768 	map->map_ifindex = ifindex;
3769 }
3770 
3771 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
3772 {
3773 	if (!bpf_map_type__is_map_in_map(map->def.type)) {
3774 		pr_warning("error: unsupported map type\n");
3775 		return -EINVAL;
3776 	}
3777 	if (map->inner_map_fd != -1) {
3778 		pr_warning("error: inner_map_fd already specified\n");
3779 		return -EINVAL;
3780 	}
3781 	map->inner_map_fd = fd;
3782 	return 0;
3783 }
3784 
3785 static struct bpf_map *
3786 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
3787 {
3788 	ssize_t idx;
3789 	struct bpf_map *s, *e;
3790 
3791 	if (!obj || !obj->maps)
3792 		return NULL;
3793 
3794 	s = obj->maps;
3795 	e = obj->maps + obj->nr_maps;
3796 
3797 	if ((m < s) || (m >= e)) {
3798 		pr_warning("error in %s: map handler doesn't belong to object\n",
3799 			   __func__);
3800 		return NULL;
3801 	}
3802 
3803 	idx = (m - obj->maps) + i;
3804 	if (idx >= obj->nr_maps || idx < 0)
3805 		return NULL;
3806 	return &obj->maps[idx];
3807 }
3808 
3809 struct bpf_map *
3810 bpf_map__next(const struct bpf_map *prev, const struct bpf_object *obj)
3811 {
3812 	if (prev == NULL)
3813 		return obj->maps;
3814 
3815 	return __bpf_map__iter(prev, obj, 1);
3816 }
3817 
3818 struct bpf_map *
3819 bpf_map__prev(const struct bpf_map *next, const struct bpf_object *obj)
3820 {
3821 	if (next == NULL) {
3822 		if (!obj->nr_maps)
3823 			return NULL;
3824 		return obj->maps + obj->nr_maps - 1;
3825 	}
3826 
3827 	return __bpf_map__iter(next, obj, -1);
3828 }
3829 
3830 struct bpf_map *
3831 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
3832 {
3833 	struct bpf_map *pos;
3834 
3835 	bpf_object__for_each_map(pos, obj) {
3836 		if (pos->name && !strcmp(pos->name, name))
3837 			return pos;
3838 	}
3839 	return NULL;
3840 }
3841 
3842 int
3843 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
3844 {
3845 	return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
3846 }
3847 
3848 struct bpf_map *
3849 bpf_object__find_map_by_offset(struct bpf_object *obj, size_t offset)
3850 {
3851 	return ERR_PTR(-ENOTSUP);
3852 }
3853 
3854 long libbpf_get_error(const void *ptr)
3855 {
3856 	return PTR_ERR_OR_ZERO(ptr);
3857 }
3858 
3859 int bpf_prog_load(const char *file, enum bpf_prog_type type,
3860 		  struct bpf_object **pobj, int *prog_fd)
3861 {
3862 	struct bpf_prog_load_attr attr;
3863 
3864 	memset(&attr, 0, sizeof(struct bpf_prog_load_attr));
3865 	attr.file = file;
3866 	attr.prog_type = type;
3867 	attr.expected_attach_type = 0;
3868 
3869 	return bpf_prog_load_xattr(&attr, pobj, prog_fd);
3870 }
3871 
3872 int bpf_prog_load_xattr(const struct bpf_prog_load_attr *attr,
3873 			struct bpf_object **pobj, int *prog_fd)
3874 {
3875 	struct bpf_object_open_attr open_attr = {};
3876 	struct bpf_program *prog, *first_prog = NULL;
3877 	enum bpf_attach_type expected_attach_type;
3878 	enum bpf_prog_type prog_type;
3879 	struct bpf_object *obj;
3880 	struct bpf_map *map;
3881 	int err;
3882 
3883 	if (!attr)
3884 		return -EINVAL;
3885 	if (!attr->file)
3886 		return -EINVAL;
3887 
3888 	open_attr.file = attr->file;
3889 	open_attr.prog_type = attr->prog_type;
3890 
3891 	obj = bpf_object__open_xattr(&open_attr);
3892 	if (IS_ERR_OR_NULL(obj))
3893 		return -ENOENT;
3894 
3895 	bpf_object__for_each_program(prog, obj) {
3896 		/*
3897 		 * If type is not specified, try to guess it based on
3898 		 * section name.
3899 		 */
3900 		prog_type = attr->prog_type;
3901 		prog->prog_ifindex = attr->ifindex;
3902 		expected_attach_type = attr->expected_attach_type;
3903 		if (prog_type == BPF_PROG_TYPE_UNSPEC) {
3904 			err = bpf_program__identify_section(prog, &prog_type,
3905 							    &expected_attach_type);
3906 			if (err < 0) {
3907 				bpf_object__close(obj);
3908 				return -EINVAL;
3909 			}
3910 		}
3911 
3912 		bpf_program__set_type(prog, prog_type);
3913 		bpf_program__set_expected_attach_type(prog,
3914 						      expected_attach_type);
3915 
3916 		prog->log_level = attr->log_level;
3917 		prog->prog_flags = attr->prog_flags;
3918 		if (!first_prog)
3919 			first_prog = prog;
3920 	}
3921 
3922 	bpf_object__for_each_map(map, obj) {
3923 		if (!bpf_map__is_offload_neutral(map))
3924 			map->map_ifindex = attr->ifindex;
3925 	}
3926 
3927 	if (!first_prog) {
3928 		pr_warning("object file doesn't contain bpf program\n");
3929 		bpf_object__close(obj);
3930 		return -ENOENT;
3931 	}
3932 
3933 	err = bpf_object__load(obj);
3934 	if (err) {
3935 		bpf_object__close(obj);
3936 		return -EINVAL;
3937 	}
3938 
3939 	*pobj = obj;
3940 	*prog_fd = bpf_program__fd(first_prog);
3941 	return 0;
3942 }
3943 
3944 enum bpf_perf_event_ret
3945 bpf_perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
3946 			   void **copy_mem, size_t *copy_size,
3947 			   bpf_perf_event_print_t fn, void *private_data)
3948 {
3949 	struct perf_event_mmap_page *header = mmap_mem;
3950 	__u64 data_head = ring_buffer_read_head(header);
3951 	__u64 data_tail = header->data_tail;
3952 	void *base = ((__u8 *)header) + page_size;
3953 	int ret = LIBBPF_PERF_EVENT_CONT;
3954 	struct perf_event_header *ehdr;
3955 	size_t ehdr_size;
3956 
3957 	while (data_head != data_tail) {
3958 		ehdr = base + (data_tail & (mmap_size - 1));
3959 		ehdr_size = ehdr->size;
3960 
3961 		if (((void *)ehdr) + ehdr_size > base + mmap_size) {
3962 			void *copy_start = ehdr;
3963 			size_t len_first = base + mmap_size - copy_start;
3964 			size_t len_secnd = ehdr_size - len_first;
3965 
3966 			if (*copy_size < ehdr_size) {
3967 				free(*copy_mem);
3968 				*copy_mem = malloc(ehdr_size);
3969 				if (!*copy_mem) {
3970 					*copy_size = 0;
3971 					ret = LIBBPF_PERF_EVENT_ERROR;
3972 					break;
3973 				}
3974 				*copy_size = ehdr_size;
3975 			}
3976 
3977 			memcpy(*copy_mem, copy_start, len_first);
3978 			memcpy(*copy_mem + len_first, base, len_secnd);
3979 			ehdr = *copy_mem;
3980 		}
3981 
3982 		ret = fn(ehdr, private_data);
3983 		data_tail += ehdr_size;
3984 		if (ret != LIBBPF_PERF_EVENT_CONT)
3985 			break;
3986 	}
3987 
3988 	ring_buffer_write_tail(header, data_tail);
3989 	return ret;
3990 }
3991 
3992 struct bpf_prog_info_array_desc {
3993 	int	array_offset;	/* e.g. offset of jited_prog_insns */
3994 	int	count_offset;	/* e.g. offset of jited_prog_len */
3995 	int	size_offset;	/* > 0: offset of rec size,
3996 				 * < 0: fix size of -size_offset
3997 				 */
3998 };
3999 
4000 static struct bpf_prog_info_array_desc bpf_prog_info_array_desc[] = {
4001 	[BPF_PROG_INFO_JITED_INSNS] = {
4002 		offsetof(struct bpf_prog_info, jited_prog_insns),
4003 		offsetof(struct bpf_prog_info, jited_prog_len),
4004 		-1,
4005 	},
4006 	[BPF_PROG_INFO_XLATED_INSNS] = {
4007 		offsetof(struct bpf_prog_info, xlated_prog_insns),
4008 		offsetof(struct bpf_prog_info, xlated_prog_len),
4009 		-1,
4010 	},
4011 	[BPF_PROG_INFO_MAP_IDS] = {
4012 		offsetof(struct bpf_prog_info, map_ids),
4013 		offsetof(struct bpf_prog_info, nr_map_ids),
4014 		-(int)sizeof(__u32),
4015 	},
4016 	[BPF_PROG_INFO_JITED_KSYMS] = {
4017 		offsetof(struct bpf_prog_info, jited_ksyms),
4018 		offsetof(struct bpf_prog_info, nr_jited_ksyms),
4019 		-(int)sizeof(__u64),
4020 	},
4021 	[BPF_PROG_INFO_JITED_FUNC_LENS] = {
4022 		offsetof(struct bpf_prog_info, jited_func_lens),
4023 		offsetof(struct bpf_prog_info, nr_jited_func_lens),
4024 		-(int)sizeof(__u32),
4025 	},
4026 	[BPF_PROG_INFO_FUNC_INFO] = {
4027 		offsetof(struct bpf_prog_info, func_info),
4028 		offsetof(struct bpf_prog_info, nr_func_info),
4029 		offsetof(struct bpf_prog_info, func_info_rec_size),
4030 	},
4031 	[BPF_PROG_INFO_LINE_INFO] = {
4032 		offsetof(struct bpf_prog_info, line_info),
4033 		offsetof(struct bpf_prog_info, nr_line_info),
4034 		offsetof(struct bpf_prog_info, line_info_rec_size),
4035 	},
4036 	[BPF_PROG_INFO_JITED_LINE_INFO] = {
4037 		offsetof(struct bpf_prog_info, jited_line_info),
4038 		offsetof(struct bpf_prog_info, nr_jited_line_info),
4039 		offsetof(struct bpf_prog_info, jited_line_info_rec_size),
4040 	},
4041 	[BPF_PROG_INFO_PROG_TAGS] = {
4042 		offsetof(struct bpf_prog_info, prog_tags),
4043 		offsetof(struct bpf_prog_info, nr_prog_tags),
4044 		-(int)sizeof(__u8) * BPF_TAG_SIZE,
4045 	},
4046 
4047 };
4048 
4049 static __u32 bpf_prog_info_read_offset_u32(struct bpf_prog_info *info, int offset)
4050 {
4051 	__u32 *array = (__u32 *)info;
4052 
4053 	if (offset >= 0)
4054 		return array[offset / sizeof(__u32)];
4055 	return -(int)offset;
4056 }
4057 
4058 static __u64 bpf_prog_info_read_offset_u64(struct bpf_prog_info *info, int offset)
4059 {
4060 	__u64 *array = (__u64 *)info;
4061 
4062 	if (offset >= 0)
4063 		return array[offset / sizeof(__u64)];
4064 	return -(int)offset;
4065 }
4066 
4067 static void bpf_prog_info_set_offset_u32(struct bpf_prog_info *info, int offset,
4068 					 __u32 val)
4069 {
4070 	__u32 *array = (__u32 *)info;
4071 
4072 	if (offset >= 0)
4073 		array[offset / sizeof(__u32)] = val;
4074 }
4075 
4076 static void bpf_prog_info_set_offset_u64(struct bpf_prog_info *info, int offset,
4077 					 __u64 val)
4078 {
4079 	__u64 *array = (__u64 *)info;
4080 
4081 	if (offset >= 0)
4082 		array[offset / sizeof(__u64)] = val;
4083 }
4084 
4085 struct bpf_prog_info_linear *
4086 bpf_program__get_prog_info_linear(int fd, __u64 arrays)
4087 {
4088 	struct bpf_prog_info_linear *info_linear;
4089 	struct bpf_prog_info info = {};
4090 	__u32 info_len = sizeof(info);
4091 	__u32 data_len = 0;
4092 	int i, err;
4093 	void *ptr;
4094 
4095 	if (arrays >> BPF_PROG_INFO_LAST_ARRAY)
4096 		return ERR_PTR(-EINVAL);
4097 
4098 	/* step 1: get array dimensions */
4099 	err = bpf_obj_get_info_by_fd(fd, &info, &info_len);
4100 	if (err) {
4101 		pr_debug("can't get prog info: %s", strerror(errno));
4102 		return ERR_PTR(-EFAULT);
4103 	}
4104 
4105 	/* step 2: calculate total size of all arrays */
4106 	for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
4107 		bool include_array = (arrays & (1UL << i)) > 0;
4108 		struct bpf_prog_info_array_desc *desc;
4109 		__u32 count, size;
4110 
4111 		desc = bpf_prog_info_array_desc + i;
4112 
4113 		/* kernel is too old to support this field */
4114 		if (info_len < desc->array_offset + sizeof(__u32) ||
4115 		    info_len < desc->count_offset + sizeof(__u32) ||
4116 		    (desc->size_offset > 0 && info_len < desc->size_offset))
4117 			include_array = false;
4118 
4119 		if (!include_array) {
4120 			arrays &= ~(1UL << i);	/* clear the bit */
4121 			continue;
4122 		}
4123 
4124 		count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
4125 		size  = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
4126 
4127 		data_len += count * size;
4128 	}
4129 
4130 	/* step 3: allocate continuous memory */
4131 	data_len = roundup(data_len, sizeof(__u64));
4132 	info_linear = malloc(sizeof(struct bpf_prog_info_linear) + data_len);
4133 	if (!info_linear)
4134 		return ERR_PTR(-ENOMEM);
4135 
4136 	/* step 4: fill data to info_linear->info */
4137 	info_linear->arrays = arrays;
4138 	memset(&info_linear->info, 0, sizeof(info));
4139 	ptr = info_linear->data;
4140 
4141 	for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
4142 		struct bpf_prog_info_array_desc *desc;
4143 		__u32 count, size;
4144 
4145 		if ((arrays & (1UL << i)) == 0)
4146 			continue;
4147 
4148 		desc  = bpf_prog_info_array_desc + i;
4149 		count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
4150 		size  = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
4151 		bpf_prog_info_set_offset_u32(&info_linear->info,
4152 					     desc->count_offset, count);
4153 		bpf_prog_info_set_offset_u32(&info_linear->info,
4154 					     desc->size_offset, size);
4155 		bpf_prog_info_set_offset_u64(&info_linear->info,
4156 					     desc->array_offset,
4157 					     ptr_to_u64(ptr));
4158 		ptr += count * size;
4159 	}
4160 
4161 	/* step 5: call syscall again to get required arrays */
4162 	err = bpf_obj_get_info_by_fd(fd, &info_linear->info, &info_len);
4163 	if (err) {
4164 		pr_debug("can't get prog info: %s", strerror(errno));
4165 		free(info_linear);
4166 		return ERR_PTR(-EFAULT);
4167 	}
4168 
4169 	/* step 6: verify the data */
4170 	for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
4171 		struct bpf_prog_info_array_desc *desc;
4172 		__u32 v1, v2;
4173 
4174 		if ((arrays & (1UL << i)) == 0)
4175 			continue;
4176 
4177 		desc = bpf_prog_info_array_desc + i;
4178 		v1 = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
4179 		v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
4180 						   desc->count_offset);
4181 		if (v1 != v2)
4182 			pr_warning("%s: mismatch in element count\n", __func__);
4183 
4184 		v1 = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
4185 		v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
4186 						   desc->size_offset);
4187 		if (v1 != v2)
4188 			pr_warning("%s: mismatch in rec size\n", __func__);
4189 	}
4190 
4191 	/* step 7: update info_len and data_len */
4192 	info_linear->info_len = sizeof(struct bpf_prog_info);
4193 	info_linear->data_len = data_len;
4194 
4195 	return info_linear;
4196 }
4197 
4198 void bpf_program__bpil_addr_to_offs(struct bpf_prog_info_linear *info_linear)
4199 {
4200 	int i;
4201 
4202 	for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
4203 		struct bpf_prog_info_array_desc *desc;
4204 		__u64 addr, offs;
4205 
4206 		if ((info_linear->arrays & (1UL << i)) == 0)
4207 			continue;
4208 
4209 		desc = bpf_prog_info_array_desc + i;
4210 		addr = bpf_prog_info_read_offset_u64(&info_linear->info,
4211 						     desc->array_offset);
4212 		offs = addr - ptr_to_u64(info_linear->data);
4213 		bpf_prog_info_set_offset_u64(&info_linear->info,
4214 					     desc->array_offset, offs);
4215 	}
4216 }
4217 
4218 void bpf_program__bpil_offs_to_addr(struct bpf_prog_info_linear *info_linear)
4219 {
4220 	int i;
4221 
4222 	for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
4223 		struct bpf_prog_info_array_desc *desc;
4224 		__u64 addr, offs;
4225 
4226 		if ((info_linear->arrays & (1UL << i)) == 0)
4227 			continue;
4228 
4229 		desc = bpf_prog_info_array_desc + i;
4230 		offs = bpf_prog_info_read_offset_u64(&info_linear->info,
4231 						     desc->array_offset);
4232 		addr = offs + ptr_to_u64(info_linear->data);
4233 		bpf_prog_info_set_offset_u64(&info_linear->info,
4234 					     desc->array_offset, addr);
4235 	}
4236 }
4237 
4238 int libbpf_num_possible_cpus(void)
4239 {
4240 	static const char *fcpu = "/sys/devices/system/cpu/possible";
4241 	int len = 0, n = 0, il = 0, ir = 0;
4242 	unsigned int start = 0, end = 0;
4243 	static int cpus;
4244 	char buf[128];
4245 	int error = 0;
4246 	int fd = -1;
4247 
4248 	if (cpus > 0)
4249 		return cpus;
4250 
4251 	fd = open(fcpu, O_RDONLY);
4252 	if (fd < 0) {
4253 		error = errno;
4254 		pr_warning("Failed to open file %s: %s\n",
4255 			   fcpu, strerror(error));
4256 		return -error;
4257 	}
4258 	len = read(fd, buf, sizeof(buf));
4259 	close(fd);
4260 	if (len <= 0) {
4261 		error = len ? errno : EINVAL;
4262 		pr_warning("Failed to read # of possible cpus from %s: %s\n",
4263 			   fcpu, strerror(error));
4264 		return -error;
4265 	}
4266 	if (len == sizeof(buf)) {
4267 		pr_warning("File %s size overflow\n", fcpu);
4268 		return -EOVERFLOW;
4269 	}
4270 	buf[len] = '\0';
4271 
4272 	for (ir = 0, cpus = 0; ir <= len; ir++) {
4273 		/* Each sub string separated by ',' has format \d+-\d+ or \d+ */
4274 		if (buf[ir] == ',' || buf[ir] == '\0') {
4275 			buf[ir] = '\0';
4276 			n = sscanf(&buf[il], "%u-%u", &start, &end);
4277 			if (n <= 0) {
4278 				pr_warning("Failed to get # CPUs from %s\n",
4279 					   &buf[il]);
4280 				return -EINVAL;
4281 			} else if (n == 1) {
4282 				end = start;
4283 			}
4284 			cpus += end - start + 1;
4285 			il = ir + 1;
4286 		}
4287 	}
4288 	if (cpus <= 0) {
4289 		pr_warning("Invalid #CPUs %d from %s\n", cpus, fcpu);
4290 		return -EINVAL;
4291 	}
4292 	return cpus;
4293 }
4294