xref: /linux/tools/lib/bpf/libbpf.c (revision cd65cd95128781ca59d06611270fcbd9b4a7cf8d)
1 // SPDX-License-Identifier: LGPL-2.1
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  *
11  * This program is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public
13  * License as published by the Free Software Foundation;
14  * version 2.1 of the License (not later!)
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public
22  * License along with this program; if not,  see <http://www.gnu.org/licenses>
23  */
24 
25 #include <stdlib.h>
26 #include <stdio.h>
27 #include <stdarg.h>
28 #include <libgen.h>
29 #include <inttypes.h>
30 #include <string.h>
31 #include <unistd.h>
32 #include <fcntl.h>
33 #include <errno.h>
34 #include <asm/unistd.h>
35 #include <linux/err.h>
36 #include <linux/kernel.h>
37 #include <linux/bpf.h>
38 #include <linux/list.h>
39 #include <linux/limits.h>
40 #include <sys/stat.h>
41 #include <sys/types.h>
42 #include <sys/vfs.h>
43 #include <libelf.h>
44 #include <gelf.h>
45 
46 #include "libbpf.h"
47 #include "bpf.h"
48 #include "btf.h"
49 
50 #ifndef EM_BPF
51 #define EM_BPF 247
52 #endif
53 
54 #ifndef BPF_FS_MAGIC
55 #define BPF_FS_MAGIC		0xcafe4a11
56 #endif
57 
58 #define __printf(a, b)	__attribute__((format(printf, a, b)))
59 
60 __printf(1, 2)
61 static int __base_pr(const char *format, ...)
62 {
63 	va_list args;
64 	int err;
65 
66 	va_start(args, format);
67 	err = vfprintf(stderr, format, args);
68 	va_end(args);
69 	return err;
70 }
71 
72 static __printf(1, 2) libbpf_print_fn_t __pr_warning = __base_pr;
73 static __printf(1, 2) libbpf_print_fn_t __pr_info = __base_pr;
74 static __printf(1, 2) libbpf_print_fn_t __pr_debug;
75 
76 #define __pr(func, fmt, ...)	\
77 do {				\
78 	if ((func))		\
79 		(func)("libbpf: " fmt, ##__VA_ARGS__); \
80 } while (0)
81 
82 #define pr_warning(fmt, ...)	__pr(__pr_warning, fmt, ##__VA_ARGS__)
83 #define pr_info(fmt, ...)	__pr(__pr_info, fmt, ##__VA_ARGS__)
84 #define pr_debug(fmt, ...)	__pr(__pr_debug, fmt, ##__VA_ARGS__)
85 
86 void libbpf_set_print(libbpf_print_fn_t warn,
87 		      libbpf_print_fn_t info,
88 		      libbpf_print_fn_t debug)
89 {
90 	__pr_warning = warn;
91 	__pr_info = info;
92 	__pr_debug = debug;
93 }
94 
95 #define STRERR_BUFSIZE  128
96 
97 #define ERRNO_OFFSET(e)		((e) - __LIBBPF_ERRNO__START)
98 #define ERRCODE_OFFSET(c)	ERRNO_OFFSET(LIBBPF_ERRNO__##c)
99 #define NR_ERRNO	(__LIBBPF_ERRNO__END - __LIBBPF_ERRNO__START)
100 
101 static const char *libbpf_strerror_table[NR_ERRNO] = {
102 	[ERRCODE_OFFSET(LIBELF)]	= "Something wrong in libelf",
103 	[ERRCODE_OFFSET(FORMAT)]	= "BPF object format invalid",
104 	[ERRCODE_OFFSET(KVERSION)]	= "'version' section incorrect or lost",
105 	[ERRCODE_OFFSET(ENDIAN)]	= "Endian mismatch",
106 	[ERRCODE_OFFSET(INTERNAL)]	= "Internal error in libbpf",
107 	[ERRCODE_OFFSET(RELOC)]		= "Relocation failed",
108 	[ERRCODE_OFFSET(VERIFY)]	= "Kernel verifier blocks program loading",
109 	[ERRCODE_OFFSET(PROG2BIG)]	= "Program too big",
110 	[ERRCODE_OFFSET(KVER)]		= "Incorrect kernel version",
111 	[ERRCODE_OFFSET(PROGTYPE)]	= "Kernel doesn't support this program type",
112 	[ERRCODE_OFFSET(WRNGPID)]	= "Wrong pid in netlink message",
113 	[ERRCODE_OFFSET(INVSEQ)]	= "Invalid netlink sequence",
114 };
115 
116 int libbpf_strerror(int err, char *buf, size_t size)
117 {
118 	if (!buf || !size)
119 		return -1;
120 
121 	err = err > 0 ? err : -err;
122 
123 	if (err < __LIBBPF_ERRNO__START) {
124 		int ret;
125 
126 		ret = strerror_r(err, buf, size);
127 		buf[size - 1] = '\0';
128 		return ret;
129 	}
130 
131 	if (err < __LIBBPF_ERRNO__END) {
132 		const char *msg;
133 
134 		msg = libbpf_strerror_table[ERRNO_OFFSET(err)];
135 		snprintf(buf, size, "%s", msg);
136 		buf[size - 1] = '\0';
137 		return 0;
138 	}
139 
140 	snprintf(buf, size, "Unknown libbpf error %d", err);
141 	buf[size - 1] = '\0';
142 	return -1;
143 }
144 
145 #define CHECK_ERR(action, err, out) do {	\
146 	err = action;			\
147 	if (err)			\
148 		goto out;		\
149 } while(0)
150 
151 
152 /* Copied from tools/perf/util/util.h */
153 #ifndef zfree
154 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
155 #endif
156 
157 #ifndef zclose
158 # define zclose(fd) ({			\
159 	int ___err = 0;			\
160 	if ((fd) >= 0)			\
161 		___err = close((fd));	\
162 	fd = -1;			\
163 	___err; })
164 #endif
165 
166 #ifdef HAVE_LIBELF_MMAP_SUPPORT
167 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ_MMAP
168 #else
169 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ
170 #endif
171 
172 /*
173  * bpf_prog should be a better name but it has been used in
174  * linux/filter.h.
175  */
176 struct bpf_program {
177 	/* Index in elf obj file, for relocation use. */
178 	int idx;
179 	char *name;
180 	char *section_name;
181 	struct bpf_insn *insns;
182 	size_t insns_cnt, main_prog_cnt;
183 	enum bpf_prog_type type;
184 
185 	struct reloc_desc {
186 		enum {
187 			RELO_LD64,
188 			RELO_CALL,
189 		} type;
190 		int insn_idx;
191 		union {
192 			int map_idx;
193 			int text_off;
194 		};
195 	} *reloc_desc;
196 	int nr_reloc;
197 
198 	struct {
199 		int nr;
200 		int *fds;
201 	} instances;
202 	bpf_program_prep_t preprocessor;
203 
204 	struct bpf_object *obj;
205 	void *priv;
206 	bpf_program_clear_priv_t clear_priv;
207 
208 	enum bpf_attach_type expected_attach_type;
209 };
210 
211 struct bpf_map {
212 	int fd;
213 	char *name;
214 	size_t offset;
215 	struct bpf_map_def def;
216 	uint32_t btf_key_id;
217 	uint32_t btf_value_id;
218 	void *priv;
219 	bpf_map_clear_priv_t clear_priv;
220 };
221 
222 static LIST_HEAD(bpf_objects_list);
223 
224 struct bpf_object {
225 	char license[64];
226 	u32 kern_version;
227 
228 	struct bpf_program *programs;
229 	size_t nr_programs;
230 	struct bpf_map *maps;
231 	size_t nr_maps;
232 
233 	bool loaded;
234 
235 	/*
236 	 * Information when doing elf related work. Only valid if fd
237 	 * is valid.
238 	 */
239 	struct {
240 		int fd;
241 		void *obj_buf;
242 		size_t obj_buf_sz;
243 		Elf *elf;
244 		GElf_Ehdr ehdr;
245 		Elf_Data *symbols;
246 		size_t strtabidx;
247 		struct {
248 			GElf_Shdr shdr;
249 			Elf_Data *data;
250 		} *reloc;
251 		int nr_reloc;
252 		int maps_shndx;
253 		int text_shndx;
254 	} efile;
255 	/*
256 	 * All loaded bpf_object is linked in a list, which is
257 	 * hidden to caller. bpf_objects__<func> handlers deal with
258 	 * all objects.
259 	 */
260 	struct list_head list;
261 
262 	struct btf *btf;
263 
264 	void *priv;
265 	bpf_object_clear_priv_t clear_priv;
266 
267 	char path[];
268 };
269 #define obj_elf_valid(o)	((o)->efile.elf)
270 
271 static void bpf_program__unload(struct bpf_program *prog)
272 {
273 	int i;
274 
275 	if (!prog)
276 		return;
277 
278 	/*
279 	 * If the object is opened but the program was never loaded,
280 	 * it is possible that prog->instances.nr == -1.
281 	 */
282 	if (prog->instances.nr > 0) {
283 		for (i = 0; i < prog->instances.nr; i++)
284 			zclose(prog->instances.fds[i]);
285 	} else if (prog->instances.nr != -1) {
286 		pr_warning("Internal error: instances.nr is %d\n",
287 			   prog->instances.nr);
288 	}
289 
290 	prog->instances.nr = -1;
291 	zfree(&prog->instances.fds);
292 }
293 
294 static void bpf_program__exit(struct bpf_program *prog)
295 {
296 	if (!prog)
297 		return;
298 
299 	if (prog->clear_priv)
300 		prog->clear_priv(prog, prog->priv);
301 
302 	prog->priv = NULL;
303 	prog->clear_priv = NULL;
304 
305 	bpf_program__unload(prog);
306 	zfree(&prog->name);
307 	zfree(&prog->section_name);
308 	zfree(&prog->insns);
309 	zfree(&prog->reloc_desc);
310 
311 	prog->nr_reloc = 0;
312 	prog->insns_cnt = 0;
313 	prog->idx = -1;
314 }
315 
316 static int
317 bpf_program__init(void *data, size_t size, char *section_name, int idx,
318 		  struct bpf_program *prog)
319 {
320 	if (size < sizeof(struct bpf_insn)) {
321 		pr_warning("corrupted section '%s'\n", section_name);
322 		return -EINVAL;
323 	}
324 
325 	bzero(prog, sizeof(*prog));
326 
327 	prog->section_name = strdup(section_name);
328 	if (!prog->section_name) {
329 		pr_warning("failed to alloc name for prog under section(%d) %s\n",
330 			   idx, section_name);
331 		goto errout;
332 	}
333 
334 	prog->insns = malloc(size);
335 	if (!prog->insns) {
336 		pr_warning("failed to alloc insns for prog under section %s\n",
337 			   section_name);
338 		goto errout;
339 	}
340 	prog->insns_cnt = size / sizeof(struct bpf_insn);
341 	memcpy(prog->insns, data,
342 	       prog->insns_cnt * sizeof(struct bpf_insn));
343 	prog->idx = idx;
344 	prog->instances.fds = NULL;
345 	prog->instances.nr = -1;
346 	prog->type = BPF_PROG_TYPE_KPROBE;
347 
348 	return 0;
349 errout:
350 	bpf_program__exit(prog);
351 	return -ENOMEM;
352 }
353 
354 static int
355 bpf_object__add_program(struct bpf_object *obj, void *data, size_t size,
356 			char *section_name, int idx)
357 {
358 	struct bpf_program prog, *progs;
359 	int nr_progs, err;
360 
361 	err = bpf_program__init(data, size, section_name, idx, &prog);
362 	if (err)
363 		return err;
364 
365 	progs = obj->programs;
366 	nr_progs = obj->nr_programs;
367 
368 	progs = realloc(progs, sizeof(progs[0]) * (nr_progs + 1));
369 	if (!progs) {
370 		/*
371 		 * In this case the original obj->programs
372 		 * is still valid, so don't need special treat for
373 		 * bpf_close_object().
374 		 */
375 		pr_warning("failed to alloc a new program under section '%s'\n",
376 			   section_name);
377 		bpf_program__exit(&prog);
378 		return -ENOMEM;
379 	}
380 
381 	pr_debug("found program %s\n", prog.section_name);
382 	obj->programs = progs;
383 	obj->nr_programs = nr_progs + 1;
384 	prog.obj = obj;
385 	progs[nr_progs] = prog;
386 	return 0;
387 }
388 
389 static int
390 bpf_object__init_prog_names(struct bpf_object *obj)
391 {
392 	Elf_Data *symbols = obj->efile.symbols;
393 	struct bpf_program *prog;
394 	size_t pi, si;
395 
396 	for (pi = 0; pi < obj->nr_programs; pi++) {
397 		const char *name = NULL;
398 
399 		prog = &obj->programs[pi];
400 		if (prog->idx == obj->efile.text_shndx) {
401 			name = ".text";
402 			goto skip_search;
403 		}
404 
405 		for (si = 0; si < symbols->d_size / sizeof(GElf_Sym) && !name;
406 		     si++) {
407 			GElf_Sym sym;
408 
409 			if (!gelf_getsym(symbols, si, &sym))
410 				continue;
411 			if (sym.st_shndx != prog->idx)
412 				continue;
413 			if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL)
414 				continue;
415 
416 			name = elf_strptr(obj->efile.elf,
417 					  obj->efile.strtabidx,
418 					  sym.st_name);
419 			if (!name) {
420 				pr_warning("failed to get sym name string for prog %s\n",
421 					   prog->section_name);
422 				return -LIBBPF_ERRNO__LIBELF;
423 			}
424 		}
425 
426 		if (!name) {
427 			pr_warning("failed to find sym for prog %s\n",
428 				   prog->section_name);
429 			return -EINVAL;
430 		}
431 skip_search:
432 		prog->name = strdup(name);
433 		if (!prog->name) {
434 			pr_warning("failed to allocate memory for prog sym %s\n",
435 				   name);
436 			return -ENOMEM;
437 		}
438 	}
439 
440 	return 0;
441 }
442 
443 static struct bpf_object *bpf_object__new(const char *path,
444 					  void *obj_buf,
445 					  size_t obj_buf_sz)
446 {
447 	struct bpf_object *obj;
448 
449 	obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
450 	if (!obj) {
451 		pr_warning("alloc memory failed for %s\n", path);
452 		return ERR_PTR(-ENOMEM);
453 	}
454 
455 	strcpy(obj->path, path);
456 	obj->efile.fd = -1;
457 
458 	/*
459 	 * Caller of this function should also calls
460 	 * bpf_object__elf_finish() after data collection to return
461 	 * obj_buf to user. If not, we should duplicate the buffer to
462 	 * avoid user freeing them before elf finish.
463 	 */
464 	obj->efile.obj_buf = obj_buf;
465 	obj->efile.obj_buf_sz = obj_buf_sz;
466 	obj->efile.maps_shndx = -1;
467 
468 	obj->loaded = false;
469 
470 	INIT_LIST_HEAD(&obj->list);
471 	list_add(&obj->list, &bpf_objects_list);
472 	return obj;
473 }
474 
475 static void bpf_object__elf_finish(struct bpf_object *obj)
476 {
477 	if (!obj_elf_valid(obj))
478 		return;
479 
480 	if (obj->efile.elf) {
481 		elf_end(obj->efile.elf);
482 		obj->efile.elf = NULL;
483 	}
484 	obj->efile.symbols = NULL;
485 
486 	zfree(&obj->efile.reloc);
487 	obj->efile.nr_reloc = 0;
488 	zclose(obj->efile.fd);
489 	obj->efile.obj_buf = NULL;
490 	obj->efile.obj_buf_sz = 0;
491 }
492 
493 static int bpf_object__elf_init(struct bpf_object *obj)
494 {
495 	int err = 0;
496 	GElf_Ehdr *ep;
497 
498 	if (obj_elf_valid(obj)) {
499 		pr_warning("elf init: internal error\n");
500 		return -LIBBPF_ERRNO__LIBELF;
501 	}
502 
503 	if (obj->efile.obj_buf_sz > 0) {
504 		/*
505 		 * obj_buf should have been validated by
506 		 * bpf_object__open_buffer().
507 		 */
508 		obj->efile.elf = elf_memory(obj->efile.obj_buf,
509 					    obj->efile.obj_buf_sz);
510 	} else {
511 		obj->efile.fd = open(obj->path, O_RDONLY);
512 		if (obj->efile.fd < 0) {
513 			pr_warning("failed to open %s: %s\n", obj->path,
514 					strerror(errno));
515 			return -errno;
516 		}
517 
518 		obj->efile.elf = elf_begin(obj->efile.fd,
519 				LIBBPF_ELF_C_READ_MMAP,
520 				NULL);
521 	}
522 
523 	if (!obj->efile.elf) {
524 		pr_warning("failed to open %s as ELF file\n",
525 				obj->path);
526 		err = -LIBBPF_ERRNO__LIBELF;
527 		goto errout;
528 	}
529 
530 	if (!gelf_getehdr(obj->efile.elf, &obj->efile.ehdr)) {
531 		pr_warning("failed to get EHDR from %s\n",
532 				obj->path);
533 		err = -LIBBPF_ERRNO__FORMAT;
534 		goto errout;
535 	}
536 	ep = &obj->efile.ehdr;
537 
538 	/* Old LLVM set e_machine to EM_NONE */
539 	if ((ep->e_type != ET_REL) || (ep->e_machine && (ep->e_machine != EM_BPF))) {
540 		pr_warning("%s is not an eBPF object file\n",
541 			obj->path);
542 		err = -LIBBPF_ERRNO__FORMAT;
543 		goto errout;
544 	}
545 
546 	return 0;
547 errout:
548 	bpf_object__elf_finish(obj);
549 	return err;
550 }
551 
552 static int
553 bpf_object__check_endianness(struct bpf_object *obj)
554 {
555 	static unsigned int const endian = 1;
556 
557 	switch (obj->efile.ehdr.e_ident[EI_DATA]) {
558 	case ELFDATA2LSB:
559 		/* We are big endian, BPF obj is little endian. */
560 		if (*(unsigned char const *)&endian != 1)
561 			goto mismatch;
562 		break;
563 
564 	case ELFDATA2MSB:
565 		/* We are little endian, BPF obj is big endian. */
566 		if (*(unsigned char const *)&endian != 0)
567 			goto mismatch;
568 		break;
569 	default:
570 		return -LIBBPF_ERRNO__ENDIAN;
571 	}
572 
573 	return 0;
574 
575 mismatch:
576 	pr_warning("Error: endianness mismatch.\n");
577 	return -LIBBPF_ERRNO__ENDIAN;
578 }
579 
580 static int
581 bpf_object__init_license(struct bpf_object *obj,
582 			 void *data, size_t size)
583 {
584 	memcpy(obj->license, data,
585 	       min(size, sizeof(obj->license) - 1));
586 	pr_debug("license of %s is %s\n", obj->path, obj->license);
587 	return 0;
588 }
589 
590 static int
591 bpf_object__init_kversion(struct bpf_object *obj,
592 			  void *data, size_t size)
593 {
594 	u32 kver;
595 
596 	if (size != sizeof(kver)) {
597 		pr_warning("invalid kver section in %s\n", obj->path);
598 		return -LIBBPF_ERRNO__FORMAT;
599 	}
600 	memcpy(&kver, data, sizeof(kver));
601 	obj->kern_version = kver;
602 	pr_debug("kernel version of %s is %x\n", obj->path,
603 		 obj->kern_version);
604 	return 0;
605 }
606 
607 static int compare_bpf_map(const void *_a, const void *_b)
608 {
609 	const struct bpf_map *a = _a;
610 	const struct bpf_map *b = _b;
611 
612 	return a->offset - b->offset;
613 }
614 
615 static int
616 bpf_object__init_maps(struct bpf_object *obj)
617 {
618 	int i, map_idx, map_def_sz, nr_maps = 0;
619 	Elf_Scn *scn;
620 	Elf_Data *data;
621 	Elf_Data *symbols = obj->efile.symbols;
622 
623 	if (obj->efile.maps_shndx < 0)
624 		return -EINVAL;
625 	if (!symbols)
626 		return -EINVAL;
627 
628 	scn = elf_getscn(obj->efile.elf, obj->efile.maps_shndx);
629 	if (scn)
630 		data = elf_getdata(scn, NULL);
631 	if (!scn || !data) {
632 		pr_warning("failed to get Elf_Data from map section %d\n",
633 			   obj->efile.maps_shndx);
634 		return -EINVAL;
635 	}
636 
637 	/*
638 	 * Count number of maps. Each map has a name.
639 	 * Array of maps is not supported: only the first element is
640 	 * considered.
641 	 *
642 	 * TODO: Detect array of map and report error.
643 	 */
644 	for (i = 0; i < symbols->d_size / sizeof(GElf_Sym); i++) {
645 		GElf_Sym sym;
646 
647 		if (!gelf_getsym(symbols, i, &sym))
648 			continue;
649 		if (sym.st_shndx != obj->efile.maps_shndx)
650 			continue;
651 		nr_maps++;
652 	}
653 
654 	/* Alloc obj->maps and fill nr_maps. */
655 	pr_debug("maps in %s: %d maps in %zd bytes\n", obj->path,
656 		 nr_maps, data->d_size);
657 
658 	if (!nr_maps)
659 		return 0;
660 
661 	/* Assume equally sized map definitions */
662 	map_def_sz = data->d_size / nr_maps;
663 	if (!data->d_size || (data->d_size % nr_maps) != 0) {
664 		pr_warning("unable to determine map definition size "
665 			   "section %s, %d maps in %zd bytes\n",
666 			   obj->path, nr_maps, data->d_size);
667 		return -EINVAL;
668 	}
669 
670 	obj->maps = calloc(nr_maps, sizeof(obj->maps[0]));
671 	if (!obj->maps) {
672 		pr_warning("alloc maps for object failed\n");
673 		return -ENOMEM;
674 	}
675 	obj->nr_maps = nr_maps;
676 
677 	/*
678 	 * fill all fd with -1 so won't close incorrect
679 	 * fd (fd=0 is stdin) when failure (zclose won't close
680 	 * negative fd)).
681 	 */
682 	for (i = 0; i < nr_maps; i++)
683 		obj->maps[i].fd = -1;
684 
685 	/*
686 	 * Fill obj->maps using data in "maps" section.
687 	 */
688 	for (i = 0, map_idx = 0; i < symbols->d_size / sizeof(GElf_Sym); i++) {
689 		GElf_Sym sym;
690 		const char *map_name;
691 		struct bpf_map_def *def;
692 
693 		if (!gelf_getsym(symbols, i, &sym))
694 			continue;
695 		if (sym.st_shndx != obj->efile.maps_shndx)
696 			continue;
697 
698 		map_name = elf_strptr(obj->efile.elf,
699 				      obj->efile.strtabidx,
700 				      sym.st_name);
701 		obj->maps[map_idx].offset = sym.st_value;
702 		if (sym.st_value + map_def_sz > data->d_size) {
703 			pr_warning("corrupted maps section in %s: last map \"%s\" too small\n",
704 				   obj->path, map_name);
705 			return -EINVAL;
706 		}
707 
708 		obj->maps[map_idx].name = strdup(map_name);
709 		if (!obj->maps[map_idx].name) {
710 			pr_warning("failed to alloc map name\n");
711 			return -ENOMEM;
712 		}
713 		pr_debug("map %d is \"%s\"\n", map_idx,
714 			 obj->maps[map_idx].name);
715 		def = (struct bpf_map_def *)(data->d_buf + sym.st_value);
716 		/*
717 		 * If the definition of the map in the object file fits in
718 		 * bpf_map_def, copy it.  Any extra fields in our version
719 		 * of bpf_map_def will default to zero as a result of the
720 		 * calloc above.
721 		 */
722 		if (map_def_sz <= sizeof(struct bpf_map_def)) {
723 			memcpy(&obj->maps[map_idx].def, def, map_def_sz);
724 		} else {
725 			/*
726 			 * Here the map structure being read is bigger than what
727 			 * we expect, truncate if the excess bits are all zero.
728 			 * If they are not zero, reject this map as
729 			 * incompatible.
730 			 */
731 			char *b;
732 			for (b = ((char *)def) + sizeof(struct bpf_map_def);
733 			     b < ((char *)def) + map_def_sz; b++) {
734 				if (*b != 0) {
735 					pr_warning("maps section in %s: \"%s\" "
736 						   "has unrecognized, non-zero "
737 						   "options\n",
738 						   obj->path, map_name);
739 					return -EINVAL;
740 				}
741 			}
742 			memcpy(&obj->maps[map_idx].def, def,
743 			       sizeof(struct bpf_map_def));
744 		}
745 		map_idx++;
746 	}
747 
748 	qsort(obj->maps, obj->nr_maps, sizeof(obj->maps[0]), compare_bpf_map);
749 	return 0;
750 }
751 
752 static bool section_have_execinstr(struct bpf_object *obj, int idx)
753 {
754 	Elf_Scn *scn;
755 	GElf_Shdr sh;
756 
757 	scn = elf_getscn(obj->efile.elf, idx);
758 	if (!scn)
759 		return false;
760 
761 	if (gelf_getshdr(scn, &sh) != &sh)
762 		return false;
763 
764 	if (sh.sh_flags & SHF_EXECINSTR)
765 		return true;
766 
767 	return false;
768 }
769 
770 static int bpf_object__elf_collect(struct bpf_object *obj)
771 {
772 	Elf *elf = obj->efile.elf;
773 	GElf_Ehdr *ep = &obj->efile.ehdr;
774 	Elf_Scn *scn = NULL;
775 	int idx = 0, err = 0;
776 
777 	/* Elf is corrupted/truncated, avoid calling elf_strptr. */
778 	if (!elf_rawdata(elf_getscn(elf, ep->e_shstrndx), NULL)) {
779 		pr_warning("failed to get e_shstrndx from %s\n",
780 			   obj->path);
781 		return -LIBBPF_ERRNO__FORMAT;
782 	}
783 
784 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
785 		char *name;
786 		GElf_Shdr sh;
787 		Elf_Data *data;
788 
789 		idx++;
790 		if (gelf_getshdr(scn, &sh) != &sh) {
791 			pr_warning("failed to get section(%d) header from %s\n",
792 				   idx, obj->path);
793 			err = -LIBBPF_ERRNO__FORMAT;
794 			goto out;
795 		}
796 
797 		name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
798 		if (!name) {
799 			pr_warning("failed to get section(%d) name from %s\n",
800 				   idx, obj->path);
801 			err = -LIBBPF_ERRNO__FORMAT;
802 			goto out;
803 		}
804 
805 		data = elf_getdata(scn, 0);
806 		if (!data) {
807 			pr_warning("failed to get section(%d) data from %s(%s)\n",
808 				   idx, name, obj->path);
809 			err = -LIBBPF_ERRNO__FORMAT;
810 			goto out;
811 		}
812 		pr_debug("section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
813 			 idx, name, (unsigned long)data->d_size,
814 			 (int)sh.sh_link, (unsigned long)sh.sh_flags,
815 			 (int)sh.sh_type);
816 
817 		if (strcmp(name, "license") == 0)
818 			err = bpf_object__init_license(obj,
819 						       data->d_buf,
820 						       data->d_size);
821 		else if (strcmp(name, "version") == 0)
822 			err = bpf_object__init_kversion(obj,
823 							data->d_buf,
824 							data->d_size);
825 		else if (strcmp(name, "maps") == 0)
826 			obj->efile.maps_shndx = idx;
827 		else if (strcmp(name, BTF_ELF_SEC) == 0) {
828 			obj->btf = btf__new(data->d_buf, data->d_size,
829 					    __pr_debug);
830 			if (IS_ERR(obj->btf)) {
831 				pr_warning("Error loading ELF section %s: %ld. Ignored and continue.\n",
832 					   BTF_ELF_SEC, PTR_ERR(obj->btf));
833 				obj->btf = NULL;
834 			}
835 		} else if (sh.sh_type == SHT_SYMTAB) {
836 			if (obj->efile.symbols) {
837 				pr_warning("bpf: multiple SYMTAB in %s\n",
838 					   obj->path);
839 				err = -LIBBPF_ERRNO__FORMAT;
840 			} else {
841 				obj->efile.symbols = data;
842 				obj->efile.strtabidx = sh.sh_link;
843 			}
844 		} else if ((sh.sh_type == SHT_PROGBITS) &&
845 			   (sh.sh_flags & SHF_EXECINSTR) &&
846 			   (data->d_size > 0)) {
847 			if (strcmp(name, ".text") == 0)
848 				obj->efile.text_shndx = idx;
849 			err = bpf_object__add_program(obj, data->d_buf,
850 						      data->d_size, name, idx);
851 			if (err) {
852 				char errmsg[STRERR_BUFSIZE];
853 
854 				strerror_r(-err, errmsg, sizeof(errmsg));
855 				pr_warning("failed to alloc program %s (%s): %s",
856 					   name, obj->path, errmsg);
857 			}
858 		} else if (sh.sh_type == SHT_REL) {
859 			void *reloc = obj->efile.reloc;
860 			int nr_reloc = obj->efile.nr_reloc + 1;
861 			int sec = sh.sh_info; /* points to other section */
862 
863 			/* Only do relo for section with exec instructions */
864 			if (!section_have_execinstr(obj, sec)) {
865 				pr_debug("skip relo %s(%d) for section(%d)\n",
866 					 name, idx, sec);
867 				continue;
868 			}
869 
870 			reloc = realloc(reloc,
871 					sizeof(*obj->efile.reloc) * nr_reloc);
872 			if (!reloc) {
873 				pr_warning("realloc failed\n");
874 				err = -ENOMEM;
875 			} else {
876 				int n = nr_reloc - 1;
877 
878 				obj->efile.reloc = reloc;
879 				obj->efile.nr_reloc = nr_reloc;
880 
881 				obj->efile.reloc[n].shdr = sh;
882 				obj->efile.reloc[n].data = data;
883 			}
884 		} else {
885 			pr_debug("skip section(%d) %s\n", idx, name);
886 		}
887 		if (err)
888 			goto out;
889 	}
890 
891 	if (!obj->efile.strtabidx || obj->efile.strtabidx >= idx) {
892 		pr_warning("Corrupted ELF file: index of strtab invalid\n");
893 		return LIBBPF_ERRNO__FORMAT;
894 	}
895 	if (obj->efile.maps_shndx >= 0) {
896 		err = bpf_object__init_maps(obj);
897 		if (err)
898 			goto out;
899 	}
900 	err = bpf_object__init_prog_names(obj);
901 out:
902 	return err;
903 }
904 
905 static struct bpf_program *
906 bpf_object__find_prog_by_idx(struct bpf_object *obj, int idx)
907 {
908 	struct bpf_program *prog;
909 	size_t i;
910 
911 	for (i = 0; i < obj->nr_programs; i++) {
912 		prog = &obj->programs[i];
913 		if (prog->idx == idx)
914 			return prog;
915 	}
916 	return NULL;
917 }
918 
919 static int
920 bpf_program__collect_reloc(struct bpf_program *prog, GElf_Shdr *shdr,
921 			   Elf_Data *data, struct bpf_object *obj)
922 {
923 	Elf_Data *symbols = obj->efile.symbols;
924 	int text_shndx = obj->efile.text_shndx;
925 	int maps_shndx = obj->efile.maps_shndx;
926 	struct bpf_map *maps = obj->maps;
927 	size_t nr_maps = obj->nr_maps;
928 	int i, nrels;
929 
930 	pr_debug("collecting relocating info for: '%s'\n",
931 		 prog->section_name);
932 	nrels = shdr->sh_size / shdr->sh_entsize;
933 
934 	prog->reloc_desc = malloc(sizeof(*prog->reloc_desc) * nrels);
935 	if (!prog->reloc_desc) {
936 		pr_warning("failed to alloc memory in relocation\n");
937 		return -ENOMEM;
938 	}
939 	prog->nr_reloc = nrels;
940 
941 	for (i = 0; i < nrels; i++) {
942 		GElf_Sym sym;
943 		GElf_Rel rel;
944 		unsigned int insn_idx;
945 		struct bpf_insn *insns = prog->insns;
946 		size_t map_idx;
947 
948 		if (!gelf_getrel(data, i, &rel)) {
949 			pr_warning("relocation: failed to get %d reloc\n", i);
950 			return -LIBBPF_ERRNO__FORMAT;
951 		}
952 
953 		if (!gelf_getsym(symbols,
954 				 GELF_R_SYM(rel.r_info),
955 				 &sym)) {
956 			pr_warning("relocation: symbol %"PRIx64" not found\n",
957 				   GELF_R_SYM(rel.r_info));
958 			return -LIBBPF_ERRNO__FORMAT;
959 		}
960 		pr_debug("relo for %lld value %lld name %d\n",
961 			 (long long) (rel.r_info >> 32),
962 			 (long long) sym.st_value, sym.st_name);
963 
964 		if (sym.st_shndx != maps_shndx && sym.st_shndx != text_shndx) {
965 			pr_warning("Program '%s' contains non-map related relo data pointing to section %u\n",
966 				   prog->section_name, sym.st_shndx);
967 			return -LIBBPF_ERRNO__RELOC;
968 		}
969 
970 		insn_idx = rel.r_offset / sizeof(struct bpf_insn);
971 		pr_debug("relocation: insn_idx=%u\n", insn_idx);
972 
973 		if (insns[insn_idx].code == (BPF_JMP | BPF_CALL)) {
974 			if (insns[insn_idx].src_reg != BPF_PSEUDO_CALL) {
975 				pr_warning("incorrect bpf_call opcode\n");
976 				return -LIBBPF_ERRNO__RELOC;
977 			}
978 			prog->reloc_desc[i].type = RELO_CALL;
979 			prog->reloc_desc[i].insn_idx = insn_idx;
980 			prog->reloc_desc[i].text_off = sym.st_value;
981 			continue;
982 		}
983 
984 		if (insns[insn_idx].code != (BPF_LD | BPF_IMM | BPF_DW)) {
985 			pr_warning("bpf: relocation: invalid relo for insns[%d].code 0x%x\n",
986 				   insn_idx, insns[insn_idx].code);
987 			return -LIBBPF_ERRNO__RELOC;
988 		}
989 
990 		/* TODO: 'maps' is sorted. We can use bsearch to make it faster. */
991 		for (map_idx = 0; map_idx < nr_maps; map_idx++) {
992 			if (maps[map_idx].offset == sym.st_value) {
993 				pr_debug("relocation: find map %zd (%s) for insn %u\n",
994 					 map_idx, maps[map_idx].name, insn_idx);
995 				break;
996 			}
997 		}
998 
999 		if (map_idx >= nr_maps) {
1000 			pr_warning("bpf relocation: map_idx %d large than %d\n",
1001 				   (int)map_idx, (int)nr_maps - 1);
1002 			return -LIBBPF_ERRNO__RELOC;
1003 		}
1004 
1005 		prog->reloc_desc[i].type = RELO_LD64;
1006 		prog->reloc_desc[i].insn_idx = insn_idx;
1007 		prog->reloc_desc[i].map_idx = map_idx;
1008 	}
1009 	return 0;
1010 }
1011 
1012 static int bpf_map_find_btf_info(struct bpf_map *map, const struct btf *btf)
1013 {
1014 	struct bpf_map_def *def = &map->def;
1015 	const size_t max_name = 256;
1016 	int64_t key_size, value_size;
1017 	int32_t key_id, value_id;
1018 	char name[max_name];
1019 
1020 	/* Find key type by name from BTF */
1021 	if (snprintf(name, max_name, "%s_key", map->name) == max_name) {
1022 		pr_warning("map:%s length of BTF key_type:%s_key is too long\n",
1023 			   map->name, map->name);
1024 		return -EINVAL;
1025 	}
1026 
1027 	key_id = btf__find_by_name(btf, name);
1028 	if (key_id < 0) {
1029 		pr_debug("map:%s key_type:%s cannot be found in BTF\n",
1030 			 map->name, name);
1031 		return key_id;
1032 	}
1033 
1034 	key_size = btf__resolve_size(btf, key_id);
1035 	if (key_size < 0) {
1036 		pr_warning("map:%s key_type:%s cannot get the BTF type_size\n",
1037 			   map->name, name);
1038 		return key_size;
1039 	}
1040 
1041 	if (def->key_size != key_size) {
1042 		pr_warning("map:%s key_type:%s has BTF type_size:%ld != key_size:%u\n",
1043 			   map->name, name, key_size, def->key_size);
1044 		return -EINVAL;
1045 	}
1046 
1047 	/* Find value type from BTF */
1048 	if (snprintf(name, max_name, "%s_value", map->name) == max_name) {
1049 		pr_warning("map:%s length of BTF value_type:%s_value is too long\n",
1050 			  map->name, map->name);
1051 		return -EINVAL;
1052 	}
1053 
1054 	value_id = btf__find_by_name(btf, name);
1055 	if (value_id < 0) {
1056 		pr_debug("map:%s value_type:%s cannot be found in BTF\n",
1057 			 map->name, name);
1058 		return value_id;
1059 	}
1060 
1061 	value_size = btf__resolve_size(btf, value_id);
1062 	if (value_size < 0) {
1063 		pr_warning("map:%s value_type:%s cannot get the BTF type_size\n",
1064 			   map->name, name);
1065 		return value_size;
1066 	}
1067 
1068 	if (def->value_size != value_size) {
1069 		pr_warning("map:%s value_type:%s has BTF type_size:%ld != value_size:%u\n",
1070 			   map->name, name, value_size, def->value_size);
1071 		return -EINVAL;
1072 	}
1073 
1074 	map->btf_key_id = key_id;
1075 	map->btf_value_id = value_id;
1076 
1077 	return 0;
1078 }
1079 
1080 static int
1081 bpf_object__create_maps(struct bpf_object *obj)
1082 {
1083 	struct bpf_create_map_attr create_attr = {};
1084 	unsigned int i;
1085 	int err;
1086 
1087 	for (i = 0; i < obj->nr_maps; i++) {
1088 		struct bpf_map *map = &obj->maps[i];
1089 		struct bpf_map_def *def = &map->def;
1090 		int *pfd = &map->fd;
1091 
1092 		create_attr.name = map->name;
1093 		create_attr.map_type = def->type;
1094 		create_attr.map_flags = def->map_flags;
1095 		create_attr.key_size = def->key_size;
1096 		create_attr.value_size = def->value_size;
1097 		create_attr.max_entries = def->max_entries;
1098 		create_attr.btf_fd = 0;
1099 		create_attr.btf_key_id = 0;
1100 		create_attr.btf_value_id = 0;
1101 
1102 		if (obj->btf && !bpf_map_find_btf_info(map, obj->btf)) {
1103 			create_attr.btf_fd = btf__fd(obj->btf);
1104 			create_attr.btf_key_id = map->btf_key_id;
1105 			create_attr.btf_value_id = map->btf_value_id;
1106 		}
1107 
1108 		*pfd = bpf_create_map_xattr(&create_attr);
1109 		if (*pfd < 0 && create_attr.btf_key_id) {
1110 			pr_warning("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
1111 				   map->name, strerror(errno), errno);
1112 			create_attr.btf_fd = 0;
1113 			create_attr.btf_key_id = 0;
1114 			create_attr.btf_value_id = 0;
1115 			map->btf_key_id = 0;
1116 			map->btf_value_id = 0;
1117 			*pfd = bpf_create_map_xattr(&create_attr);
1118 		}
1119 
1120 		if (*pfd < 0) {
1121 			size_t j;
1122 
1123 			err = *pfd;
1124 			pr_warning("failed to create map (name: '%s'): %s\n",
1125 				   map->name,
1126 				   strerror(errno));
1127 			for (j = 0; j < i; j++)
1128 				zclose(obj->maps[j].fd);
1129 			return err;
1130 		}
1131 		pr_debug("create map %s: fd=%d\n", map->name, *pfd);
1132 	}
1133 
1134 	return 0;
1135 }
1136 
1137 static int
1138 bpf_program__reloc_text(struct bpf_program *prog, struct bpf_object *obj,
1139 			struct reloc_desc *relo)
1140 {
1141 	struct bpf_insn *insn, *new_insn;
1142 	struct bpf_program *text;
1143 	size_t new_cnt;
1144 
1145 	if (relo->type != RELO_CALL)
1146 		return -LIBBPF_ERRNO__RELOC;
1147 
1148 	if (prog->idx == obj->efile.text_shndx) {
1149 		pr_warning("relo in .text insn %d into off %d\n",
1150 			   relo->insn_idx, relo->text_off);
1151 		return -LIBBPF_ERRNO__RELOC;
1152 	}
1153 
1154 	if (prog->main_prog_cnt == 0) {
1155 		text = bpf_object__find_prog_by_idx(obj, obj->efile.text_shndx);
1156 		if (!text) {
1157 			pr_warning("no .text section found yet relo into text exist\n");
1158 			return -LIBBPF_ERRNO__RELOC;
1159 		}
1160 		new_cnt = prog->insns_cnt + text->insns_cnt;
1161 		new_insn = realloc(prog->insns, new_cnt * sizeof(*insn));
1162 		if (!new_insn) {
1163 			pr_warning("oom in prog realloc\n");
1164 			return -ENOMEM;
1165 		}
1166 		memcpy(new_insn + prog->insns_cnt, text->insns,
1167 		       text->insns_cnt * sizeof(*insn));
1168 		prog->insns = new_insn;
1169 		prog->main_prog_cnt = prog->insns_cnt;
1170 		prog->insns_cnt = new_cnt;
1171 		pr_debug("added %zd insn from %s to prog %s\n",
1172 			 text->insns_cnt, text->section_name,
1173 			 prog->section_name);
1174 	}
1175 	insn = &prog->insns[relo->insn_idx];
1176 	insn->imm += prog->main_prog_cnt - relo->insn_idx;
1177 	return 0;
1178 }
1179 
1180 static int
1181 bpf_program__relocate(struct bpf_program *prog, struct bpf_object *obj)
1182 {
1183 	int i, err;
1184 
1185 	if (!prog || !prog->reloc_desc)
1186 		return 0;
1187 
1188 	for (i = 0; i < prog->nr_reloc; i++) {
1189 		if (prog->reloc_desc[i].type == RELO_LD64) {
1190 			struct bpf_insn *insns = prog->insns;
1191 			int insn_idx, map_idx;
1192 
1193 			insn_idx = prog->reloc_desc[i].insn_idx;
1194 			map_idx = prog->reloc_desc[i].map_idx;
1195 
1196 			if (insn_idx >= (int)prog->insns_cnt) {
1197 				pr_warning("relocation out of range: '%s'\n",
1198 					   prog->section_name);
1199 				return -LIBBPF_ERRNO__RELOC;
1200 			}
1201 			insns[insn_idx].src_reg = BPF_PSEUDO_MAP_FD;
1202 			insns[insn_idx].imm = obj->maps[map_idx].fd;
1203 		} else {
1204 			err = bpf_program__reloc_text(prog, obj,
1205 						      &prog->reloc_desc[i]);
1206 			if (err)
1207 				return err;
1208 		}
1209 	}
1210 
1211 	zfree(&prog->reloc_desc);
1212 	prog->nr_reloc = 0;
1213 	return 0;
1214 }
1215 
1216 
1217 static int
1218 bpf_object__relocate(struct bpf_object *obj)
1219 {
1220 	struct bpf_program *prog;
1221 	size_t i;
1222 	int err;
1223 
1224 	for (i = 0; i < obj->nr_programs; i++) {
1225 		prog = &obj->programs[i];
1226 
1227 		err = bpf_program__relocate(prog, obj);
1228 		if (err) {
1229 			pr_warning("failed to relocate '%s'\n",
1230 				   prog->section_name);
1231 			return err;
1232 		}
1233 	}
1234 	return 0;
1235 }
1236 
1237 static int bpf_object__collect_reloc(struct bpf_object *obj)
1238 {
1239 	int i, err;
1240 
1241 	if (!obj_elf_valid(obj)) {
1242 		pr_warning("Internal error: elf object is closed\n");
1243 		return -LIBBPF_ERRNO__INTERNAL;
1244 	}
1245 
1246 	for (i = 0; i < obj->efile.nr_reloc; i++) {
1247 		GElf_Shdr *shdr = &obj->efile.reloc[i].shdr;
1248 		Elf_Data *data = obj->efile.reloc[i].data;
1249 		int idx = shdr->sh_info;
1250 		struct bpf_program *prog;
1251 
1252 		if (shdr->sh_type != SHT_REL) {
1253 			pr_warning("internal error at %d\n", __LINE__);
1254 			return -LIBBPF_ERRNO__INTERNAL;
1255 		}
1256 
1257 		prog = bpf_object__find_prog_by_idx(obj, idx);
1258 		if (!prog) {
1259 			pr_warning("relocation failed: no section(%d)\n", idx);
1260 			return -LIBBPF_ERRNO__RELOC;
1261 		}
1262 
1263 		err = bpf_program__collect_reloc(prog,
1264 						 shdr, data,
1265 						 obj);
1266 		if (err)
1267 			return err;
1268 	}
1269 	return 0;
1270 }
1271 
1272 static int
1273 load_program(enum bpf_prog_type type, enum bpf_attach_type expected_attach_type,
1274 	     const char *name, struct bpf_insn *insns, int insns_cnt,
1275 	     char *license, u32 kern_version, int *pfd)
1276 {
1277 	struct bpf_load_program_attr load_attr;
1278 	char *log_buf;
1279 	int ret;
1280 
1281 	memset(&load_attr, 0, sizeof(struct bpf_load_program_attr));
1282 	load_attr.prog_type = type;
1283 	load_attr.expected_attach_type = expected_attach_type;
1284 	load_attr.name = name;
1285 	load_attr.insns = insns;
1286 	load_attr.insns_cnt = insns_cnt;
1287 	load_attr.license = license;
1288 	load_attr.kern_version = kern_version;
1289 
1290 	if (!load_attr.insns || !load_attr.insns_cnt)
1291 		return -EINVAL;
1292 
1293 	log_buf = malloc(BPF_LOG_BUF_SIZE);
1294 	if (!log_buf)
1295 		pr_warning("Alloc log buffer for bpf loader error, continue without log\n");
1296 
1297 	ret = bpf_load_program_xattr(&load_attr, log_buf, BPF_LOG_BUF_SIZE);
1298 
1299 	if (ret >= 0) {
1300 		*pfd = ret;
1301 		ret = 0;
1302 		goto out;
1303 	}
1304 
1305 	ret = -LIBBPF_ERRNO__LOAD;
1306 	pr_warning("load bpf program failed: %s\n", strerror(errno));
1307 
1308 	if (log_buf && log_buf[0] != '\0') {
1309 		ret = -LIBBPF_ERRNO__VERIFY;
1310 		pr_warning("-- BEGIN DUMP LOG ---\n");
1311 		pr_warning("\n%s\n", log_buf);
1312 		pr_warning("-- END LOG --\n");
1313 	} else if (load_attr.insns_cnt >= BPF_MAXINSNS) {
1314 		pr_warning("Program too large (%zu insns), at most %d insns\n",
1315 			   load_attr.insns_cnt, BPF_MAXINSNS);
1316 		ret = -LIBBPF_ERRNO__PROG2BIG;
1317 	} else {
1318 		/* Wrong program type? */
1319 		if (load_attr.prog_type != BPF_PROG_TYPE_KPROBE) {
1320 			int fd;
1321 
1322 			load_attr.prog_type = BPF_PROG_TYPE_KPROBE;
1323 			load_attr.expected_attach_type = 0;
1324 			fd = bpf_load_program_xattr(&load_attr, NULL, 0);
1325 			if (fd >= 0) {
1326 				close(fd);
1327 				ret = -LIBBPF_ERRNO__PROGTYPE;
1328 				goto out;
1329 			}
1330 		}
1331 
1332 		if (log_buf)
1333 			ret = -LIBBPF_ERRNO__KVER;
1334 	}
1335 
1336 out:
1337 	free(log_buf);
1338 	return ret;
1339 }
1340 
1341 static int
1342 bpf_program__load(struct bpf_program *prog,
1343 		  char *license, u32 kern_version)
1344 {
1345 	int err = 0, fd, i;
1346 
1347 	if (prog->instances.nr < 0 || !prog->instances.fds) {
1348 		if (prog->preprocessor) {
1349 			pr_warning("Internal error: can't load program '%s'\n",
1350 				   prog->section_name);
1351 			return -LIBBPF_ERRNO__INTERNAL;
1352 		}
1353 
1354 		prog->instances.fds = malloc(sizeof(int));
1355 		if (!prog->instances.fds) {
1356 			pr_warning("Not enough memory for BPF fds\n");
1357 			return -ENOMEM;
1358 		}
1359 		prog->instances.nr = 1;
1360 		prog->instances.fds[0] = -1;
1361 	}
1362 
1363 	if (!prog->preprocessor) {
1364 		if (prog->instances.nr != 1) {
1365 			pr_warning("Program '%s' is inconsistent: nr(%d) != 1\n",
1366 				   prog->section_name, prog->instances.nr);
1367 		}
1368 		err = load_program(prog->type, prog->expected_attach_type,
1369 				   prog->name, prog->insns, prog->insns_cnt,
1370 				   license, kern_version, &fd);
1371 		if (!err)
1372 			prog->instances.fds[0] = fd;
1373 		goto out;
1374 	}
1375 
1376 	for (i = 0; i < prog->instances.nr; i++) {
1377 		struct bpf_prog_prep_result result;
1378 		bpf_program_prep_t preprocessor = prog->preprocessor;
1379 
1380 		bzero(&result, sizeof(result));
1381 		err = preprocessor(prog, i, prog->insns,
1382 				   prog->insns_cnt, &result);
1383 		if (err) {
1384 			pr_warning("Preprocessing the %dth instance of program '%s' failed\n",
1385 				   i, prog->section_name);
1386 			goto out;
1387 		}
1388 
1389 		if (!result.new_insn_ptr || !result.new_insn_cnt) {
1390 			pr_debug("Skip loading the %dth instance of program '%s'\n",
1391 				 i, prog->section_name);
1392 			prog->instances.fds[i] = -1;
1393 			if (result.pfd)
1394 				*result.pfd = -1;
1395 			continue;
1396 		}
1397 
1398 		err = load_program(prog->type, prog->expected_attach_type,
1399 				   prog->name, result.new_insn_ptr,
1400 				   result.new_insn_cnt,
1401 				   license, kern_version, &fd);
1402 
1403 		if (err) {
1404 			pr_warning("Loading the %dth instance of program '%s' failed\n",
1405 					i, prog->section_name);
1406 			goto out;
1407 		}
1408 
1409 		if (result.pfd)
1410 			*result.pfd = fd;
1411 		prog->instances.fds[i] = fd;
1412 	}
1413 out:
1414 	if (err)
1415 		pr_warning("failed to load program '%s'\n",
1416 			   prog->section_name);
1417 	zfree(&prog->insns);
1418 	prog->insns_cnt = 0;
1419 	return err;
1420 }
1421 
1422 static int
1423 bpf_object__load_progs(struct bpf_object *obj)
1424 {
1425 	size_t i;
1426 	int err;
1427 
1428 	for (i = 0; i < obj->nr_programs; i++) {
1429 		if (obj->programs[i].idx == obj->efile.text_shndx)
1430 			continue;
1431 		err = bpf_program__load(&obj->programs[i],
1432 					obj->license,
1433 					obj->kern_version);
1434 		if (err)
1435 			return err;
1436 	}
1437 	return 0;
1438 }
1439 
1440 static int bpf_object__validate(struct bpf_object *obj)
1441 {
1442 	if (obj->kern_version == 0) {
1443 		pr_warning("%s doesn't provide kernel version\n",
1444 			   obj->path);
1445 		return -LIBBPF_ERRNO__KVERSION;
1446 	}
1447 	return 0;
1448 }
1449 
1450 static struct bpf_object *
1451 __bpf_object__open(const char *path, void *obj_buf, size_t obj_buf_sz)
1452 {
1453 	struct bpf_object *obj;
1454 	int err;
1455 
1456 	if (elf_version(EV_CURRENT) == EV_NONE) {
1457 		pr_warning("failed to init libelf for %s\n", path);
1458 		return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
1459 	}
1460 
1461 	obj = bpf_object__new(path, obj_buf, obj_buf_sz);
1462 	if (IS_ERR(obj))
1463 		return obj;
1464 
1465 	CHECK_ERR(bpf_object__elf_init(obj), err, out);
1466 	CHECK_ERR(bpf_object__check_endianness(obj), err, out);
1467 	CHECK_ERR(bpf_object__elf_collect(obj), err, out);
1468 	CHECK_ERR(bpf_object__collect_reloc(obj), err, out);
1469 	CHECK_ERR(bpf_object__validate(obj), err, out);
1470 
1471 	bpf_object__elf_finish(obj);
1472 	return obj;
1473 out:
1474 	bpf_object__close(obj);
1475 	return ERR_PTR(err);
1476 }
1477 
1478 struct bpf_object *bpf_object__open(const char *path)
1479 {
1480 	/* param validation */
1481 	if (!path)
1482 		return NULL;
1483 
1484 	pr_debug("loading %s\n", path);
1485 
1486 	return __bpf_object__open(path, NULL, 0);
1487 }
1488 
1489 struct bpf_object *bpf_object__open_buffer(void *obj_buf,
1490 					   size_t obj_buf_sz,
1491 					   const char *name)
1492 {
1493 	char tmp_name[64];
1494 
1495 	/* param validation */
1496 	if (!obj_buf || obj_buf_sz <= 0)
1497 		return NULL;
1498 
1499 	if (!name) {
1500 		snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
1501 			 (unsigned long)obj_buf,
1502 			 (unsigned long)obj_buf_sz);
1503 		tmp_name[sizeof(tmp_name) - 1] = '\0';
1504 		name = tmp_name;
1505 	}
1506 	pr_debug("loading object '%s' from buffer\n",
1507 		 name);
1508 
1509 	return __bpf_object__open(name, obj_buf, obj_buf_sz);
1510 }
1511 
1512 int bpf_object__unload(struct bpf_object *obj)
1513 {
1514 	size_t i;
1515 
1516 	if (!obj)
1517 		return -EINVAL;
1518 
1519 	for (i = 0; i < obj->nr_maps; i++)
1520 		zclose(obj->maps[i].fd);
1521 
1522 	for (i = 0; i < obj->nr_programs; i++)
1523 		bpf_program__unload(&obj->programs[i]);
1524 
1525 	return 0;
1526 }
1527 
1528 int bpf_object__load(struct bpf_object *obj)
1529 {
1530 	int err;
1531 
1532 	if (!obj)
1533 		return -EINVAL;
1534 
1535 	if (obj->loaded) {
1536 		pr_warning("object should not be loaded twice\n");
1537 		return -EINVAL;
1538 	}
1539 
1540 	obj->loaded = true;
1541 
1542 	CHECK_ERR(bpf_object__create_maps(obj), err, out);
1543 	CHECK_ERR(bpf_object__relocate(obj), err, out);
1544 	CHECK_ERR(bpf_object__load_progs(obj), err, out);
1545 
1546 	return 0;
1547 out:
1548 	bpf_object__unload(obj);
1549 	pr_warning("failed to load object '%s'\n", obj->path);
1550 	return err;
1551 }
1552 
1553 static int check_path(const char *path)
1554 {
1555 	struct statfs st_fs;
1556 	char *dname, *dir;
1557 	int err = 0;
1558 
1559 	if (path == NULL)
1560 		return -EINVAL;
1561 
1562 	dname = strdup(path);
1563 	if (dname == NULL)
1564 		return -ENOMEM;
1565 
1566 	dir = dirname(dname);
1567 	if (statfs(dir, &st_fs)) {
1568 		pr_warning("failed to statfs %s: %s\n", dir, strerror(errno));
1569 		err = -errno;
1570 	}
1571 	free(dname);
1572 
1573 	if (!err && st_fs.f_type != BPF_FS_MAGIC) {
1574 		pr_warning("specified path %s is not on BPF FS\n", path);
1575 		err = -EINVAL;
1576 	}
1577 
1578 	return err;
1579 }
1580 
1581 int bpf_program__pin_instance(struct bpf_program *prog, const char *path,
1582 			      int instance)
1583 {
1584 	int err;
1585 
1586 	err = check_path(path);
1587 	if (err)
1588 		return err;
1589 
1590 	if (prog == NULL) {
1591 		pr_warning("invalid program pointer\n");
1592 		return -EINVAL;
1593 	}
1594 
1595 	if (instance < 0 || instance >= prog->instances.nr) {
1596 		pr_warning("invalid prog instance %d of prog %s (max %d)\n",
1597 			   instance, prog->section_name, prog->instances.nr);
1598 		return -EINVAL;
1599 	}
1600 
1601 	if (bpf_obj_pin(prog->instances.fds[instance], path)) {
1602 		pr_warning("failed to pin program: %s\n", strerror(errno));
1603 		return -errno;
1604 	}
1605 	pr_debug("pinned program '%s'\n", path);
1606 
1607 	return 0;
1608 }
1609 
1610 static int make_dir(const char *path)
1611 {
1612 	int err = 0;
1613 
1614 	if (mkdir(path, 0700) && errno != EEXIST)
1615 		err = -errno;
1616 
1617 	if (err)
1618 		pr_warning("failed to mkdir %s: %s\n", path, strerror(-err));
1619 	return err;
1620 }
1621 
1622 int bpf_program__pin(struct bpf_program *prog, const char *path)
1623 {
1624 	int i, err;
1625 
1626 	err = check_path(path);
1627 	if (err)
1628 		return err;
1629 
1630 	if (prog == NULL) {
1631 		pr_warning("invalid program pointer\n");
1632 		return -EINVAL;
1633 	}
1634 
1635 	if (prog->instances.nr <= 0) {
1636 		pr_warning("no instances of prog %s to pin\n",
1637 			   prog->section_name);
1638 		return -EINVAL;
1639 	}
1640 
1641 	err = make_dir(path);
1642 	if (err)
1643 		return err;
1644 
1645 	for (i = 0; i < prog->instances.nr; i++) {
1646 		char buf[PATH_MAX];
1647 		int len;
1648 
1649 		len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
1650 		if (len < 0)
1651 			return -EINVAL;
1652 		else if (len >= PATH_MAX)
1653 			return -ENAMETOOLONG;
1654 
1655 		err = bpf_program__pin_instance(prog, buf, i);
1656 		if (err)
1657 			return err;
1658 	}
1659 
1660 	return 0;
1661 }
1662 
1663 int bpf_map__pin(struct bpf_map *map, const char *path)
1664 {
1665 	int err;
1666 
1667 	err = check_path(path);
1668 	if (err)
1669 		return err;
1670 
1671 	if (map == NULL) {
1672 		pr_warning("invalid map pointer\n");
1673 		return -EINVAL;
1674 	}
1675 
1676 	if (bpf_obj_pin(map->fd, path)) {
1677 		pr_warning("failed to pin map: %s\n", strerror(errno));
1678 		return -errno;
1679 	}
1680 
1681 	pr_debug("pinned map '%s'\n", path);
1682 	return 0;
1683 }
1684 
1685 int bpf_object__pin(struct bpf_object *obj, const char *path)
1686 {
1687 	struct bpf_program *prog;
1688 	struct bpf_map *map;
1689 	int err;
1690 
1691 	if (!obj)
1692 		return -ENOENT;
1693 
1694 	if (!obj->loaded) {
1695 		pr_warning("object not yet loaded; load it first\n");
1696 		return -ENOENT;
1697 	}
1698 
1699 	err = make_dir(path);
1700 	if (err)
1701 		return err;
1702 
1703 	bpf_map__for_each(map, obj) {
1704 		char buf[PATH_MAX];
1705 		int len;
1706 
1707 		len = snprintf(buf, PATH_MAX, "%s/%s", path,
1708 			       bpf_map__name(map));
1709 		if (len < 0)
1710 			return -EINVAL;
1711 		else if (len >= PATH_MAX)
1712 			return -ENAMETOOLONG;
1713 
1714 		err = bpf_map__pin(map, buf);
1715 		if (err)
1716 			return err;
1717 	}
1718 
1719 	bpf_object__for_each_program(prog, obj) {
1720 		char buf[PATH_MAX];
1721 		int len;
1722 
1723 		len = snprintf(buf, PATH_MAX, "%s/%s", path,
1724 			       prog->section_name);
1725 		if (len < 0)
1726 			return -EINVAL;
1727 		else if (len >= PATH_MAX)
1728 			return -ENAMETOOLONG;
1729 
1730 		err = bpf_program__pin(prog, buf);
1731 		if (err)
1732 			return err;
1733 	}
1734 
1735 	return 0;
1736 }
1737 
1738 void bpf_object__close(struct bpf_object *obj)
1739 {
1740 	size_t i;
1741 
1742 	if (!obj)
1743 		return;
1744 
1745 	if (obj->clear_priv)
1746 		obj->clear_priv(obj, obj->priv);
1747 
1748 	bpf_object__elf_finish(obj);
1749 	bpf_object__unload(obj);
1750 	btf__free(obj->btf);
1751 
1752 	for (i = 0; i < obj->nr_maps; i++) {
1753 		zfree(&obj->maps[i].name);
1754 		if (obj->maps[i].clear_priv)
1755 			obj->maps[i].clear_priv(&obj->maps[i],
1756 						obj->maps[i].priv);
1757 		obj->maps[i].priv = NULL;
1758 		obj->maps[i].clear_priv = NULL;
1759 	}
1760 	zfree(&obj->maps);
1761 	obj->nr_maps = 0;
1762 
1763 	if (obj->programs && obj->nr_programs) {
1764 		for (i = 0; i < obj->nr_programs; i++)
1765 			bpf_program__exit(&obj->programs[i]);
1766 	}
1767 	zfree(&obj->programs);
1768 
1769 	list_del(&obj->list);
1770 	free(obj);
1771 }
1772 
1773 struct bpf_object *
1774 bpf_object__next(struct bpf_object *prev)
1775 {
1776 	struct bpf_object *next;
1777 
1778 	if (!prev)
1779 		next = list_first_entry(&bpf_objects_list,
1780 					struct bpf_object,
1781 					list);
1782 	else
1783 		next = list_next_entry(prev, list);
1784 
1785 	/* Empty list is noticed here so don't need checking on entry. */
1786 	if (&next->list == &bpf_objects_list)
1787 		return NULL;
1788 
1789 	return next;
1790 }
1791 
1792 const char *bpf_object__name(struct bpf_object *obj)
1793 {
1794 	return obj ? obj->path : ERR_PTR(-EINVAL);
1795 }
1796 
1797 unsigned int bpf_object__kversion(struct bpf_object *obj)
1798 {
1799 	return obj ? obj->kern_version : 0;
1800 }
1801 
1802 int bpf_object__btf_fd(const struct bpf_object *obj)
1803 {
1804 	return obj->btf ? btf__fd(obj->btf) : -1;
1805 }
1806 
1807 int bpf_object__set_priv(struct bpf_object *obj, void *priv,
1808 			 bpf_object_clear_priv_t clear_priv)
1809 {
1810 	if (obj->priv && obj->clear_priv)
1811 		obj->clear_priv(obj, obj->priv);
1812 
1813 	obj->priv = priv;
1814 	obj->clear_priv = clear_priv;
1815 	return 0;
1816 }
1817 
1818 void *bpf_object__priv(struct bpf_object *obj)
1819 {
1820 	return obj ? obj->priv : ERR_PTR(-EINVAL);
1821 }
1822 
1823 struct bpf_program *
1824 bpf_program__next(struct bpf_program *prev, struct bpf_object *obj)
1825 {
1826 	size_t idx;
1827 
1828 	if (!obj->programs)
1829 		return NULL;
1830 	/* First handler */
1831 	if (prev == NULL)
1832 		return &obj->programs[0];
1833 
1834 	if (prev->obj != obj) {
1835 		pr_warning("error: program handler doesn't match object\n");
1836 		return NULL;
1837 	}
1838 
1839 	idx = (prev - obj->programs) + 1;
1840 	if (idx >= obj->nr_programs)
1841 		return NULL;
1842 	return &obj->programs[idx];
1843 }
1844 
1845 int bpf_program__set_priv(struct bpf_program *prog, void *priv,
1846 			  bpf_program_clear_priv_t clear_priv)
1847 {
1848 	if (prog->priv && prog->clear_priv)
1849 		prog->clear_priv(prog, prog->priv);
1850 
1851 	prog->priv = priv;
1852 	prog->clear_priv = clear_priv;
1853 	return 0;
1854 }
1855 
1856 void *bpf_program__priv(struct bpf_program *prog)
1857 {
1858 	return prog ? prog->priv : ERR_PTR(-EINVAL);
1859 }
1860 
1861 const char *bpf_program__title(struct bpf_program *prog, bool needs_copy)
1862 {
1863 	const char *title;
1864 
1865 	title = prog->section_name;
1866 	if (needs_copy) {
1867 		title = strdup(title);
1868 		if (!title) {
1869 			pr_warning("failed to strdup program title\n");
1870 			return ERR_PTR(-ENOMEM);
1871 		}
1872 	}
1873 
1874 	return title;
1875 }
1876 
1877 int bpf_program__fd(struct bpf_program *prog)
1878 {
1879 	return bpf_program__nth_fd(prog, 0);
1880 }
1881 
1882 int bpf_program__set_prep(struct bpf_program *prog, int nr_instances,
1883 			  bpf_program_prep_t prep)
1884 {
1885 	int *instances_fds;
1886 
1887 	if (nr_instances <= 0 || !prep)
1888 		return -EINVAL;
1889 
1890 	if (prog->instances.nr > 0 || prog->instances.fds) {
1891 		pr_warning("Can't set pre-processor after loading\n");
1892 		return -EINVAL;
1893 	}
1894 
1895 	instances_fds = malloc(sizeof(int) * nr_instances);
1896 	if (!instances_fds) {
1897 		pr_warning("alloc memory failed for fds\n");
1898 		return -ENOMEM;
1899 	}
1900 
1901 	/* fill all fd with -1 */
1902 	memset(instances_fds, -1, sizeof(int) * nr_instances);
1903 
1904 	prog->instances.nr = nr_instances;
1905 	prog->instances.fds = instances_fds;
1906 	prog->preprocessor = prep;
1907 	return 0;
1908 }
1909 
1910 int bpf_program__nth_fd(struct bpf_program *prog, int n)
1911 {
1912 	int fd;
1913 
1914 	if (n >= prog->instances.nr || n < 0) {
1915 		pr_warning("Can't get the %dth fd from program %s: only %d instances\n",
1916 			   n, prog->section_name, prog->instances.nr);
1917 		return -EINVAL;
1918 	}
1919 
1920 	fd = prog->instances.fds[n];
1921 	if (fd < 0) {
1922 		pr_warning("%dth instance of program '%s' is invalid\n",
1923 			   n, prog->section_name);
1924 		return -ENOENT;
1925 	}
1926 
1927 	return fd;
1928 }
1929 
1930 void bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
1931 {
1932 	prog->type = type;
1933 }
1934 
1935 static bool bpf_program__is_type(struct bpf_program *prog,
1936 				 enum bpf_prog_type type)
1937 {
1938 	return prog ? (prog->type == type) : false;
1939 }
1940 
1941 #define BPF_PROG_TYPE_FNS(NAME, TYPE)			\
1942 int bpf_program__set_##NAME(struct bpf_program *prog)	\
1943 {							\
1944 	if (!prog)					\
1945 		return -EINVAL;				\
1946 	bpf_program__set_type(prog, TYPE);		\
1947 	return 0;					\
1948 }							\
1949 							\
1950 bool bpf_program__is_##NAME(struct bpf_program *prog)	\
1951 {							\
1952 	return bpf_program__is_type(prog, TYPE);	\
1953 }							\
1954 
1955 BPF_PROG_TYPE_FNS(socket_filter, BPF_PROG_TYPE_SOCKET_FILTER);
1956 BPF_PROG_TYPE_FNS(kprobe, BPF_PROG_TYPE_KPROBE);
1957 BPF_PROG_TYPE_FNS(sched_cls, BPF_PROG_TYPE_SCHED_CLS);
1958 BPF_PROG_TYPE_FNS(sched_act, BPF_PROG_TYPE_SCHED_ACT);
1959 BPF_PROG_TYPE_FNS(tracepoint, BPF_PROG_TYPE_TRACEPOINT);
1960 BPF_PROG_TYPE_FNS(raw_tracepoint, BPF_PROG_TYPE_RAW_TRACEPOINT);
1961 BPF_PROG_TYPE_FNS(xdp, BPF_PROG_TYPE_XDP);
1962 BPF_PROG_TYPE_FNS(perf_event, BPF_PROG_TYPE_PERF_EVENT);
1963 
1964 void bpf_program__set_expected_attach_type(struct bpf_program *prog,
1965 					   enum bpf_attach_type type)
1966 {
1967 	prog->expected_attach_type = type;
1968 }
1969 
1970 #define BPF_PROG_SEC_FULL(string, ptype, atype) \
1971 	{ string, sizeof(string) - 1, ptype, atype }
1972 
1973 #define BPF_PROG_SEC(string, ptype) BPF_PROG_SEC_FULL(string, ptype, 0)
1974 
1975 #define BPF_S_PROG_SEC(string, ptype) \
1976 	BPF_PROG_SEC_FULL(string, BPF_PROG_TYPE_CGROUP_SOCK, ptype)
1977 
1978 #define BPF_SA_PROG_SEC(string, ptype) \
1979 	BPF_PROG_SEC_FULL(string, BPF_PROG_TYPE_CGROUP_SOCK_ADDR, ptype)
1980 
1981 static const struct {
1982 	const char *sec;
1983 	size_t len;
1984 	enum bpf_prog_type prog_type;
1985 	enum bpf_attach_type expected_attach_type;
1986 } section_names[] = {
1987 	BPF_PROG_SEC("socket",		BPF_PROG_TYPE_SOCKET_FILTER),
1988 	BPF_PROG_SEC("kprobe/",		BPF_PROG_TYPE_KPROBE),
1989 	BPF_PROG_SEC("kretprobe/",	BPF_PROG_TYPE_KPROBE),
1990 	BPF_PROG_SEC("classifier",	BPF_PROG_TYPE_SCHED_CLS),
1991 	BPF_PROG_SEC("action",		BPF_PROG_TYPE_SCHED_ACT),
1992 	BPF_PROG_SEC("tracepoint/",	BPF_PROG_TYPE_TRACEPOINT),
1993 	BPF_PROG_SEC("raw_tracepoint/",	BPF_PROG_TYPE_RAW_TRACEPOINT),
1994 	BPF_PROG_SEC("xdp",		BPF_PROG_TYPE_XDP),
1995 	BPF_PROG_SEC("perf_event",	BPF_PROG_TYPE_PERF_EVENT),
1996 	BPF_PROG_SEC("cgroup/skb",	BPF_PROG_TYPE_CGROUP_SKB),
1997 	BPF_PROG_SEC("cgroup/sock",	BPF_PROG_TYPE_CGROUP_SOCK),
1998 	BPF_PROG_SEC("cgroup/dev",	BPF_PROG_TYPE_CGROUP_DEVICE),
1999 	BPF_PROG_SEC("lwt_in",		BPF_PROG_TYPE_LWT_IN),
2000 	BPF_PROG_SEC("lwt_out",		BPF_PROG_TYPE_LWT_OUT),
2001 	BPF_PROG_SEC("lwt_xmit",	BPF_PROG_TYPE_LWT_XMIT),
2002 	BPF_PROG_SEC("sockops",		BPF_PROG_TYPE_SOCK_OPS),
2003 	BPF_PROG_SEC("sk_skb",		BPF_PROG_TYPE_SK_SKB),
2004 	BPF_PROG_SEC("sk_msg",		BPF_PROG_TYPE_SK_MSG),
2005 	BPF_SA_PROG_SEC("cgroup/bind4",	BPF_CGROUP_INET4_BIND),
2006 	BPF_SA_PROG_SEC("cgroup/bind6",	BPF_CGROUP_INET6_BIND),
2007 	BPF_SA_PROG_SEC("cgroup/connect4", BPF_CGROUP_INET4_CONNECT),
2008 	BPF_SA_PROG_SEC("cgroup/connect6", BPF_CGROUP_INET6_CONNECT),
2009 	BPF_S_PROG_SEC("cgroup/post_bind4", BPF_CGROUP_INET4_POST_BIND),
2010 	BPF_S_PROG_SEC("cgroup/post_bind6", BPF_CGROUP_INET6_POST_BIND),
2011 };
2012 
2013 #undef BPF_PROG_SEC
2014 #undef BPF_PROG_SEC_FULL
2015 #undef BPF_S_PROG_SEC
2016 #undef BPF_SA_PROG_SEC
2017 
2018 static int bpf_program__identify_section(struct bpf_program *prog)
2019 {
2020 	int i;
2021 
2022 	if (!prog->section_name)
2023 		goto err;
2024 
2025 	for (i = 0; i < ARRAY_SIZE(section_names); i++)
2026 		if (strncmp(prog->section_name, section_names[i].sec,
2027 			    section_names[i].len) == 0)
2028 			return i;
2029 
2030 err:
2031 	pr_warning("failed to guess program type based on section name %s\n",
2032 		   prog->section_name);
2033 
2034 	return -1;
2035 }
2036 
2037 int bpf_map__fd(struct bpf_map *map)
2038 {
2039 	return map ? map->fd : -EINVAL;
2040 }
2041 
2042 const struct bpf_map_def *bpf_map__def(struct bpf_map *map)
2043 {
2044 	return map ? &map->def : ERR_PTR(-EINVAL);
2045 }
2046 
2047 const char *bpf_map__name(struct bpf_map *map)
2048 {
2049 	return map ? map->name : NULL;
2050 }
2051 
2052 uint32_t bpf_map__btf_key_id(const struct bpf_map *map)
2053 {
2054 	return map ? map->btf_key_id : 0;
2055 }
2056 
2057 uint32_t bpf_map__btf_value_id(const struct bpf_map *map)
2058 {
2059 	return map ? map->btf_value_id : 0;
2060 }
2061 
2062 int bpf_map__set_priv(struct bpf_map *map, void *priv,
2063 		     bpf_map_clear_priv_t clear_priv)
2064 {
2065 	if (!map)
2066 		return -EINVAL;
2067 
2068 	if (map->priv) {
2069 		if (map->clear_priv)
2070 			map->clear_priv(map, map->priv);
2071 	}
2072 
2073 	map->priv = priv;
2074 	map->clear_priv = clear_priv;
2075 	return 0;
2076 }
2077 
2078 void *bpf_map__priv(struct bpf_map *map)
2079 {
2080 	return map ? map->priv : ERR_PTR(-EINVAL);
2081 }
2082 
2083 struct bpf_map *
2084 bpf_map__next(struct bpf_map *prev, struct bpf_object *obj)
2085 {
2086 	size_t idx;
2087 	struct bpf_map *s, *e;
2088 
2089 	if (!obj || !obj->maps)
2090 		return NULL;
2091 
2092 	s = obj->maps;
2093 	e = obj->maps + obj->nr_maps;
2094 
2095 	if (prev == NULL)
2096 		return s;
2097 
2098 	if ((prev < s) || (prev >= e)) {
2099 		pr_warning("error in %s: map handler doesn't belong to object\n",
2100 			   __func__);
2101 		return NULL;
2102 	}
2103 
2104 	idx = (prev - obj->maps) + 1;
2105 	if (idx >= obj->nr_maps)
2106 		return NULL;
2107 	return &obj->maps[idx];
2108 }
2109 
2110 struct bpf_map *
2111 bpf_object__find_map_by_name(struct bpf_object *obj, const char *name)
2112 {
2113 	struct bpf_map *pos;
2114 
2115 	bpf_map__for_each(pos, obj) {
2116 		if (pos->name && !strcmp(pos->name, name))
2117 			return pos;
2118 	}
2119 	return NULL;
2120 }
2121 
2122 struct bpf_map *
2123 bpf_object__find_map_by_offset(struct bpf_object *obj, size_t offset)
2124 {
2125 	int i;
2126 
2127 	for (i = 0; i < obj->nr_maps; i++) {
2128 		if (obj->maps[i].offset == offset)
2129 			return &obj->maps[i];
2130 	}
2131 	return ERR_PTR(-ENOENT);
2132 }
2133 
2134 long libbpf_get_error(const void *ptr)
2135 {
2136 	if (IS_ERR(ptr))
2137 		return PTR_ERR(ptr);
2138 	return 0;
2139 }
2140 
2141 int bpf_prog_load(const char *file, enum bpf_prog_type type,
2142 		  struct bpf_object **pobj, int *prog_fd)
2143 {
2144 	struct bpf_prog_load_attr attr;
2145 
2146 	memset(&attr, 0, sizeof(struct bpf_prog_load_attr));
2147 	attr.file = file;
2148 	attr.prog_type = type;
2149 	attr.expected_attach_type = 0;
2150 
2151 	return bpf_prog_load_xattr(&attr, pobj, prog_fd);
2152 }
2153 
2154 int bpf_prog_load_xattr(const struct bpf_prog_load_attr *attr,
2155 			struct bpf_object **pobj, int *prog_fd)
2156 {
2157 	struct bpf_program *prog, *first_prog = NULL;
2158 	enum bpf_attach_type expected_attach_type;
2159 	enum bpf_prog_type prog_type;
2160 	struct bpf_object *obj;
2161 	int section_idx;
2162 	int err;
2163 
2164 	if (!attr)
2165 		return -EINVAL;
2166 
2167 	obj = bpf_object__open(attr->file);
2168 	if (IS_ERR(obj))
2169 		return -ENOENT;
2170 
2171 	bpf_object__for_each_program(prog, obj) {
2172 		/*
2173 		 * If type is not specified, try to guess it based on
2174 		 * section name.
2175 		 */
2176 		prog_type = attr->prog_type;
2177 		expected_attach_type = attr->expected_attach_type;
2178 		if (prog_type == BPF_PROG_TYPE_UNSPEC) {
2179 			section_idx = bpf_program__identify_section(prog);
2180 			if (section_idx < 0) {
2181 				bpf_object__close(obj);
2182 				return -EINVAL;
2183 			}
2184 			prog_type = section_names[section_idx].prog_type;
2185 			expected_attach_type =
2186 				section_names[section_idx].expected_attach_type;
2187 		}
2188 
2189 		bpf_program__set_type(prog, prog_type);
2190 		bpf_program__set_expected_attach_type(prog,
2191 						      expected_attach_type);
2192 
2193 		if (prog->idx != obj->efile.text_shndx && !first_prog)
2194 			first_prog = prog;
2195 	}
2196 
2197 	if (!first_prog) {
2198 		pr_warning("object file doesn't contain bpf program\n");
2199 		bpf_object__close(obj);
2200 		return -ENOENT;
2201 	}
2202 
2203 	err = bpf_object__load(obj);
2204 	if (err) {
2205 		bpf_object__close(obj);
2206 		return -EINVAL;
2207 	}
2208 
2209 	*pobj = obj;
2210 	*prog_fd = bpf_program__fd(first_prog);
2211 	return 0;
2212 }
2213