xref: /linux/tools/lib/bpf/libbpf.c (revision fcc8487d477a3452a1d0ccbdd4c5e0e1e3cb8bed)
1 /*
2  * Common eBPF ELF object loading operations.
3  *
4  * Copyright (C) 2013-2015 Alexei Starovoitov <ast@kernel.org>
5  * Copyright (C) 2015 Wang Nan <wangnan0@huawei.com>
6  * Copyright (C) 2015 Huawei Inc.
7  * Copyright (C) 2017 Nicira, Inc.
8  *
9  * This program is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation;
12  * version 2.1 of the License (not later!)
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this program; if not,  see <http://www.gnu.org/licenses>
21  */
22 
23 #include <stdlib.h>
24 #include <stdio.h>
25 #include <stdarg.h>
26 #include <libgen.h>
27 #include <inttypes.h>
28 #include <string.h>
29 #include <unistd.h>
30 #include <fcntl.h>
31 #include <errno.h>
32 #include <asm/unistd.h>
33 #include <linux/err.h>
34 #include <linux/kernel.h>
35 #include <linux/bpf.h>
36 #include <linux/list.h>
37 #include <linux/limits.h>
38 #include <sys/stat.h>
39 #include <sys/types.h>
40 #include <sys/vfs.h>
41 #include <libelf.h>
42 #include <gelf.h>
43 
44 #include "libbpf.h"
45 #include "bpf.h"
46 
47 #ifndef EM_BPF
48 #define EM_BPF 247
49 #endif
50 
51 #ifndef BPF_FS_MAGIC
52 #define BPF_FS_MAGIC		0xcafe4a11
53 #endif
54 
55 #define __printf(a, b)	__attribute__((format(printf, a, b)))
56 
57 __printf(1, 2)
58 static int __base_pr(const char *format, ...)
59 {
60 	va_list args;
61 	int err;
62 
63 	va_start(args, format);
64 	err = vfprintf(stderr, format, args);
65 	va_end(args);
66 	return err;
67 }
68 
69 static __printf(1, 2) libbpf_print_fn_t __pr_warning = __base_pr;
70 static __printf(1, 2) libbpf_print_fn_t __pr_info = __base_pr;
71 static __printf(1, 2) libbpf_print_fn_t __pr_debug;
72 
73 #define __pr(func, fmt, ...)	\
74 do {				\
75 	if ((func))		\
76 		(func)("libbpf: " fmt, ##__VA_ARGS__); \
77 } while (0)
78 
79 #define pr_warning(fmt, ...)	__pr(__pr_warning, fmt, ##__VA_ARGS__)
80 #define pr_info(fmt, ...)	__pr(__pr_info, fmt, ##__VA_ARGS__)
81 #define pr_debug(fmt, ...)	__pr(__pr_debug, fmt, ##__VA_ARGS__)
82 
83 void libbpf_set_print(libbpf_print_fn_t warn,
84 		      libbpf_print_fn_t info,
85 		      libbpf_print_fn_t debug)
86 {
87 	__pr_warning = warn;
88 	__pr_info = info;
89 	__pr_debug = debug;
90 }
91 
92 #define STRERR_BUFSIZE  128
93 
94 #define ERRNO_OFFSET(e)		((e) - __LIBBPF_ERRNO__START)
95 #define ERRCODE_OFFSET(c)	ERRNO_OFFSET(LIBBPF_ERRNO__##c)
96 #define NR_ERRNO	(__LIBBPF_ERRNO__END - __LIBBPF_ERRNO__START)
97 
98 static const char *libbpf_strerror_table[NR_ERRNO] = {
99 	[ERRCODE_OFFSET(LIBELF)]	= "Something wrong in libelf",
100 	[ERRCODE_OFFSET(FORMAT)]	= "BPF object format invalid",
101 	[ERRCODE_OFFSET(KVERSION)]	= "'version' section incorrect or lost",
102 	[ERRCODE_OFFSET(ENDIAN)]	= "Endian mismatch",
103 	[ERRCODE_OFFSET(INTERNAL)]	= "Internal error in libbpf",
104 	[ERRCODE_OFFSET(RELOC)]		= "Relocation failed",
105 	[ERRCODE_OFFSET(VERIFY)]	= "Kernel verifier blocks program loading",
106 	[ERRCODE_OFFSET(PROG2BIG)]	= "Program too big",
107 	[ERRCODE_OFFSET(KVER)]		= "Incorrect kernel version",
108 	[ERRCODE_OFFSET(PROGTYPE)]	= "Kernel doesn't support this program type",
109 };
110 
111 int libbpf_strerror(int err, char *buf, size_t size)
112 {
113 	if (!buf || !size)
114 		return -1;
115 
116 	err = err > 0 ? err : -err;
117 
118 	if (err < __LIBBPF_ERRNO__START) {
119 		int ret;
120 
121 		ret = strerror_r(err, buf, size);
122 		buf[size - 1] = '\0';
123 		return ret;
124 	}
125 
126 	if (err < __LIBBPF_ERRNO__END) {
127 		const char *msg;
128 
129 		msg = libbpf_strerror_table[ERRNO_OFFSET(err)];
130 		snprintf(buf, size, "%s", msg);
131 		buf[size - 1] = '\0';
132 		return 0;
133 	}
134 
135 	snprintf(buf, size, "Unknown libbpf error %d", err);
136 	buf[size - 1] = '\0';
137 	return -1;
138 }
139 
140 #define CHECK_ERR(action, err, out) do {	\
141 	err = action;			\
142 	if (err)			\
143 		goto out;		\
144 } while(0)
145 
146 
147 /* Copied from tools/perf/util/util.h */
148 #ifndef zfree
149 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
150 #endif
151 
152 #ifndef zclose
153 # define zclose(fd) ({			\
154 	int ___err = 0;			\
155 	if ((fd) >= 0)			\
156 		___err = close((fd));	\
157 	fd = -1;			\
158 	___err; })
159 #endif
160 
161 #ifdef HAVE_LIBELF_MMAP_SUPPORT
162 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ_MMAP
163 #else
164 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ
165 #endif
166 
167 /*
168  * bpf_prog should be a better name but it has been used in
169  * linux/filter.h.
170  */
171 struct bpf_program {
172 	/* Index in elf obj file, for relocation use. */
173 	int idx;
174 	char *section_name;
175 	struct bpf_insn *insns;
176 	size_t insns_cnt;
177 	enum bpf_prog_type type;
178 
179 	struct {
180 		int insn_idx;
181 		int map_idx;
182 	} *reloc_desc;
183 	int nr_reloc;
184 
185 	struct {
186 		int nr;
187 		int *fds;
188 	} instances;
189 	bpf_program_prep_t preprocessor;
190 
191 	struct bpf_object *obj;
192 	void *priv;
193 	bpf_program_clear_priv_t clear_priv;
194 };
195 
196 struct bpf_map {
197 	int fd;
198 	char *name;
199 	size_t offset;
200 	struct bpf_map_def def;
201 	void *priv;
202 	bpf_map_clear_priv_t clear_priv;
203 };
204 
205 static LIST_HEAD(bpf_objects_list);
206 
207 struct bpf_object {
208 	char license[64];
209 	u32 kern_version;
210 
211 	struct bpf_program *programs;
212 	size_t nr_programs;
213 	struct bpf_map *maps;
214 	size_t nr_maps;
215 
216 	bool loaded;
217 
218 	/*
219 	 * Information when doing elf related work. Only valid if fd
220 	 * is valid.
221 	 */
222 	struct {
223 		int fd;
224 		void *obj_buf;
225 		size_t obj_buf_sz;
226 		Elf *elf;
227 		GElf_Ehdr ehdr;
228 		Elf_Data *symbols;
229 		size_t strtabidx;
230 		struct {
231 			GElf_Shdr shdr;
232 			Elf_Data *data;
233 		} *reloc;
234 		int nr_reloc;
235 		int maps_shndx;
236 	} efile;
237 	/*
238 	 * All loaded bpf_object is linked in a list, which is
239 	 * hidden to caller. bpf_objects__<func> handlers deal with
240 	 * all objects.
241 	 */
242 	struct list_head list;
243 
244 	void *priv;
245 	bpf_object_clear_priv_t clear_priv;
246 
247 	char path[];
248 };
249 #define obj_elf_valid(o)	((o)->efile.elf)
250 
251 static void bpf_program__unload(struct bpf_program *prog)
252 {
253 	int i;
254 
255 	if (!prog)
256 		return;
257 
258 	/*
259 	 * If the object is opened but the program was never loaded,
260 	 * it is possible that prog->instances.nr == -1.
261 	 */
262 	if (prog->instances.nr > 0) {
263 		for (i = 0; i < prog->instances.nr; i++)
264 			zclose(prog->instances.fds[i]);
265 	} else if (prog->instances.nr != -1) {
266 		pr_warning("Internal error: instances.nr is %d\n",
267 			   prog->instances.nr);
268 	}
269 
270 	prog->instances.nr = -1;
271 	zfree(&prog->instances.fds);
272 }
273 
274 static void bpf_program__exit(struct bpf_program *prog)
275 {
276 	if (!prog)
277 		return;
278 
279 	if (prog->clear_priv)
280 		prog->clear_priv(prog, prog->priv);
281 
282 	prog->priv = NULL;
283 	prog->clear_priv = NULL;
284 
285 	bpf_program__unload(prog);
286 	zfree(&prog->section_name);
287 	zfree(&prog->insns);
288 	zfree(&prog->reloc_desc);
289 
290 	prog->nr_reloc = 0;
291 	prog->insns_cnt = 0;
292 	prog->idx = -1;
293 }
294 
295 static int
296 bpf_program__init(void *data, size_t size, char *name, int idx,
297 		    struct bpf_program *prog)
298 {
299 	if (size < sizeof(struct bpf_insn)) {
300 		pr_warning("corrupted section '%s'\n", name);
301 		return -EINVAL;
302 	}
303 
304 	bzero(prog, sizeof(*prog));
305 
306 	prog->section_name = strdup(name);
307 	if (!prog->section_name) {
308 		pr_warning("failed to alloc name for prog %s\n",
309 			   name);
310 		goto errout;
311 	}
312 
313 	prog->insns = malloc(size);
314 	if (!prog->insns) {
315 		pr_warning("failed to alloc insns for %s\n", name);
316 		goto errout;
317 	}
318 	prog->insns_cnt = size / sizeof(struct bpf_insn);
319 	memcpy(prog->insns, data,
320 	       prog->insns_cnt * sizeof(struct bpf_insn));
321 	prog->idx = idx;
322 	prog->instances.fds = NULL;
323 	prog->instances.nr = -1;
324 	prog->type = BPF_PROG_TYPE_KPROBE;
325 
326 	return 0;
327 errout:
328 	bpf_program__exit(prog);
329 	return -ENOMEM;
330 }
331 
332 static int
333 bpf_object__add_program(struct bpf_object *obj, void *data, size_t size,
334 			char *name, int idx)
335 {
336 	struct bpf_program prog, *progs;
337 	int nr_progs, err;
338 
339 	err = bpf_program__init(data, size, name, idx, &prog);
340 	if (err)
341 		return err;
342 
343 	progs = obj->programs;
344 	nr_progs = obj->nr_programs;
345 
346 	progs = realloc(progs, sizeof(progs[0]) * (nr_progs + 1));
347 	if (!progs) {
348 		/*
349 		 * In this case the original obj->programs
350 		 * is still valid, so don't need special treat for
351 		 * bpf_close_object().
352 		 */
353 		pr_warning("failed to alloc a new program '%s'\n",
354 			   name);
355 		bpf_program__exit(&prog);
356 		return -ENOMEM;
357 	}
358 
359 	pr_debug("found program %s\n", prog.section_name);
360 	obj->programs = progs;
361 	obj->nr_programs = nr_progs + 1;
362 	prog.obj = obj;
363 	progs[nr_progs] = prog;
364 	return 0;
365 }
366 
367 static struct bpf_object *bpf_object__new(const char *path,
368 					  void *obj_buf,
369 					  size_t obj_buf_sz)
370 {
371 	struct bpf_object *obj;
372 
373 	obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
374 	if (!obj) {
375 		pr_warning("alloc memory failed for %s\n", path);
376 		return ERR_PTR(-ENOMEM);
377 	}
378 
379 	strcpy(obj->path, path);
380 	obj->efile.fd = -1;
381 
382 	/*
383 	 * Caller of this function should also calls
384 	 * bpf_object__elf_finish() after data collection to return
385 	 * obj_buf to user. If not, we should duplicate the buffer to
386 	 * avoid user freeing them before elf finish.
387 	 */
388 	obj->efile.obj_buf = obj_buf;
389 	obj->efile.obj_buf_sz = obj_buf_sz;
390 	obj->efile.maps_shndx = -1;
391 
392 	obj->loaded = false;
393 
394 	INIT_LIST_HEAD(&obj->list);
395 	list_add(&obj->list, &bpf_objects_list);
396 	return obj;
397 }
398 
399 static void bpf_object__elf_finish(struct bpf_object *obj)
400 {
401 	if (!obj_elf_valid(obj))
402 		return;
403 
404 	if (obj->efile.elf) {
405 		elf_end(obj->efile.elf);
406 		obj->efile.elf = NULL;
407 	}
408 	obj->efile.symbols = NULL;
409 
410 	zfree(&obj->efile.reloc);
411 	obj->efile.nr_reloc = 0;
412 	zclose(obj->efile.fd);
413 	obj->efile.obj_buf = NULL;
414 	obj->efile.obj_buf_sz = 0;
415 }
416 
417 static int bpf_object__elf_init(struct bpf_object *obj)
418 {
419 	int err = 0;
420 	GElf_Ehdr *ep;
421 
422 	if (obj_elf_valid(obj)) {
423 		pr_warning("elf init: internal error\n");
424 		return -LIBBPF_ERRNO__LIBELF;
425 	}
426 
427 	if (obj->efile.obj_buf_sz > 0) {
428 		/*
429 		 * obj_buf should have been validated by
430 		 * bpf_object__open_buffer().
431 		 */
432 		obj->efile.elf = elf_memory(obj->efile.obj_buf,
433 					    obj->efile.obj_buf_sz);
434 	} else {
435 		obj->efile.fd = open(obj->path, O_RDONLY);
436 		if (obj->efile.fd < 0) {
437 			pr_warning("failed to open %s: %s\n", obj->path,
438 					strerror(errno));
439 			return -errno;
440 		}
441 
442 		obj->efile.elf = elf_begin(obj->efile.fd,
443 				LIBBPF_ELF_C_READ_MMAP,
444 				NULL);
445 	}
446 
447 	if (!obj->efile.elf) {
448 		pr_warning("failed to open %s as ELF file\n",
449 				obj->path);
450 		err = -LIBBPF_ERRNO__LIBELF;
451 		goto errout;
452 	}
453 
454 	if (!gelf_getehdr(obj->efile.elf, &obj->efile.ehdr)) {
455 		pr_warning("failed to get EHDR from %s\n",
456 				obj->path);
457 		err = -LIBBPF_ERRNO__FORMAT;
458 		goto errout;
459 	}
460 	ep = &obj->efile.ehdr;
461 
462 	/* Old LLVM set e_machine to EM_NONE */
463 	if ((ep->e_type != ET_REL) || (ep->e_machine && (ep->e_machine != EM_BPF))) {
464 		pr_warning("%s is not an eBPF object file\n",
465 			obj->path);
466 		err = -LIBBPF_ERRNO__FORMAT;
467 		goto errout;
468 	}
469 
470 	return 0;
471 errout:
472 	bpf_object__elf_finish(obj);
473 	return err;
474 }
475 
476 static int
477 bpf_object__check_endianness(struct bpf_object *obj)
478 {
479 	static unsigned int const endian = 1;
480 
481 	switch (obj->efile.ehdr.e_ident[EI_DATA]) {
482 	case ELFDATA2LSB:
483 		/* We are big endian, BPF obj is little endian. */
484 		if (*(unsigned char const *)&endian != 1)
485 			goto mismatch;
486 		break;
487 
488 	case ELFDATA2MSB:
489 		/* We are little endian, BPF obj is big endian. */
490 		if (*(unsigned char const *)&endian != 0)
491 			goto mismatch;
492 		break;
493 	default:
494 		return -LIBBPF_ERRNO__ENDIAN;
495 	}
496 
497 	return 0;
498 
499 mismatch:
500 	pr_warning("Error: endianness mismatch.\n");
501 	return -LIBBPF_ERRNO__ENDIAN;
502 }
503 
504 static int
505 bpf_object__init_license(struct bpf_object *obj,
506 			 void *data, size_t size)
507 {
508 	memcpy(obj->license, data,
509 	       min(size, sizeof(obj->license) - 1));
510 	pr_debug("license of %s is %s\n", obj->path, obj->license);
511 	return 0;
512 }
513 
514 static int
515 bpf_object__init_kversion(struct bpf_object *obj,
516 			  void *data, size_t size)
517 {
518 	u32 kver;
519 
520 	if (size != sizeof(kver)) {
521 		pr_warning("invalid kver section in %s\n", obj->path);
522 		return -LIBBPF_ERRNO__FORMAT;
523 	}
524 	memcpy(&kver, data, sizeof(kver));
525 	obj->kern_version = kver;
526 	pr_debug("kernel version of %s is %x\n", obj->path,
527 		 obj->kern_version);
528 	return 0;
529 }
530 
531 static int
532 bpf_object__validate_maps(struct bpf_object *obj)
533 {
534 	int i;
535 
536 	/*
537 	 * If there's only 1 map, the only error case should have been
538 	 * catched in bpf_object__init_maps().
539 	 */
540 	if (!obj->maps || !obj->nr_maps || (obj->nr_maps == 1))
541 		return 0;
542 
543 	for (i = 1; i < obj->nr_maps; i++) {
544 		const struct bpf_map *a = &obj->maps[i - 1];
545 		const struct bpf_map *b = &obj->maps[i];
546 
547 		if (b->offset - a->offset < sizeof(struct bpf_map_def)) {
548 			pr_warning("corrupted map section in %s: map \"%s\" too small\n",
549 				   obj->path, a->name);
550 			return -EINVAL;
551 		}
552 	}
553 	return 0;
554 }
555 
556 static int compare_bpf_map(const void *_a, const void *_b)
557 {
558 	const struct bpf_map *a = _a;
559 	const struct bpf_map *b = _b;
560 
561 	return a->offset - b->offset;
562 }
563 
564 static int
565 bpf_object__init_maps(struct bpf_object *obj)
566 {
567 	int i, map_idx, nr_maps = 0;
568 	Elf_Scn *scn;
569 	Elf_Data *data;
570 	Elf_Data *symbols = obj->efile.symbols;
571 
572 	if (obj->efile.maps_shndx < 0)
573 		return -EINVAL;
574 	if (!symbols)
575 		return -EINVAL;
576 
577 	scn = elf_getscn(obj->efile.elf, obj->efile.maps_shndx);
578 	if (scn)
579 		data = elf_getdata(scn, NULL);
580 	if (!scn || !data) {
581 		pr_warning("failed to get Elf_Data from map section %d\n",
582 			   obj->efile.maps_shndx);
583 		return -EINVAL;
584 	}
585 
586 	/*
587 	 * Count number of maps. Each map has a name.
588 	 * Array of maps is not supported: only the first element is
589 	 * considered.
590 	 *
591 	 * TODO: Detect array of map and report error.
592 	 */
593 	for (i = 0; i < symbols->d_size / sizeof(GElf_Sym); i++) {
594 		GElf_Sym sym;
595 
596 		if (!gelf_getsym(symbols, i, &sym))
597 			continue;
598 		if (sym.st_shndx != obj->efile.maps_shndx)
599 			continue;
600 		nr_maps++;
601 	}
602 
603 	/* Alloc obj->maps and fill nr_maps. */
604 	pr_debug("maps in %s: %d maps in %zd bytes\n", obj->path,
605 		 nr_maps, data->d_size);
606 
607 	if (!nr_maps)
608 		return 0;
609 
610 	obj->maps = calloc(nr_maps, sizeof(obj->maps[0]));
611 	if (!obj->maps) {
612 		pr_warning("alloc maps for object failed\n");
613 		return -ENOMEM;
614 	}
615 	obj->nr_maps = nr_maps;
616 
617 	/*
618 	 * fill all fd with -1 so won't close incorrect
619 	 * fd (fd=0 is stdin) when failure (zclose won't close
620 	 * negative fd)).
621 	 */
622 	for (i = 0; i < nr_maps; i++)
623 		obj->maps[i].fd = -1;
624 
625 	/*
626 	 * Fill obj->maps using data in "maps" section.
627 	 */
628 	for (i = 0, map_idx = 0; i < symbols->d_size / sizeof(GElf_Sym); i++) {
629 		GElf_Sym sym;
630 		const char *map_name;
631 		struct bpf_map_def *def;
632 
633 		if (!gelf_getsym(symbols, i, &sym))
634 			continue;
635 		if (sym.st_shndx != obj->efile.maps_shndx)
636 			continue;
637 
638 		map_name = elf_strptr(obj->efile.elf,
639 				      obj->efile.strtabidx,
640 				      sym.st_name);
641 		obj->maps[map_idx].offset = sym.st_value;
642 		if (sym.st_value + sizeof(struct bpf_map_def) > data->d_size) {
643 			pr_warning("corrupted maps section in %s: last map \"%s\" too small\n",
644 				   obj->path, map_name);
645 			return -EINVAL;
646 		}
647 
648 		obj->maps[map_idx].name = strdup(map_name);
649 		if (!obj->maps[map_idx].name) {
650 			pr_warning("failed to alloc map name\n");
651 			return -ENOMEM;
652 		}
653 		pr_debug("map %d is \"%s\"\n", map_idx,
654 			 obj->maps[map_idx].name);
655 		def = (struct bpf_map_def *)(data->d_buf + sym.st_value);
656 		obj->maps[map_idx].def = *def;
657 		map_idx++;
658 	}
659 
660 	qsort(obj->maps, obj->nr_maps, sizeof(obj->maps[0]), compare_bpf_map);
661 	return bpf_object__validate_maps(obj);
662 }
663 
664 static int bpf_object__elf_collect(struct bpf_object *obj)
665 {
666 	Elf *elf = obj->efile.elf;
667 	GElf_Ehdr *ep = &obj->efile.ehdr;
668 	Elf_Scn *scn = NULL;
669 	int idx = 0, err = 0;
670 
671 	/* Elf is corrupted/truncated, avoid calling elf_strptr. */
672 	if (!elf_rawdata(elf_getscn(elf, ep->e_shstrndx), NULL)) {
673 		pr_warning("failed to get e_shstrndx from %s\n",
674 			   obj->path);
675 		return -LIBBPF_ERRNO__FORMAT;
676 	}
677 
678 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
679 		char *name;
680 		GElf_Shdr sh;
681 		Elf_Data *data;
682 
683 		idx++;
684 		if (gelf_getshdr(scn, &sh) != &sh) {
685 			pr_warning("failed to get section header from %s\n",
686 				   obj->path);
687 			err = -LIBBPF_ERRNO__FORMAT;
688 			goto out;
689 		}
690 
691 		name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
692 		if (!name) {
693 			pr_warning("failed to get section name from %s\n",
694 				   obj->path);
695 			err = -LIBBPF_ERRNO__FORMAT;
696 			goto out;
697 		}
698 
699 		data = elf_getdata(scn, 0);
700 		if (!data) {
701 			pr_warning("failed to get section data from %s(%s)\n",
702 				   name, obj->path);
703 			err = -LIBBPF_ERRNO__FORMAT;
704 			goto out;
705 		}
706 		pr_debug("section %s, size %ld, link %d, flags %lx, type=%d\n",
707 			 name, (unsigned long)data->d_size,
708 			 (int)sh.sh_link, (unsigned long)sh.sh_flags,
709 			 (int)sh.sh_type);
710 
711 		if (strcmp(name, "license") == 0)
712 			err = bpf_object__init_license(obj,
713 						       data->d_buf,
714 						       data->d_size);
715 		else if (strcmp(name, "version") == 0)
716 			err = bpf_object__init_kversion(obj,
717 							data->d_buf,
718 							data->d_size);
719 		else if (strcmp(name, "maps") == 0)
720 			obj->efile.maps_shndx = idx;
721 		else if (sh.sh_type == SHT_SYMTAB) {
722 			if (obj->efile.symbols) {
723 				pr_warning("bpf: multiple SYMTAB in %s\n",
724 					   obj->path);
725 				err = -LIBBPF_ERRNO__FORMAT;
726 			} else {
727 				obj->efile.symbols = data;
728 				obj->efile.strtabidx = sh.sh_link;
729 			}
730 		} else if ((sh.sh_type == SHT_PROGBITS) &&
731 			   (sh.sh_flags & SHF_EXECINSTR) &&
732 			   (data->d_size > 0)) {
733 			err = bpf_object__add_program(obj, data->d_buf,
734 						      data->d_size, name, idx);
735 			if (err) {
736 				char errmsg[STRERR_BUFSIZE];
737 
738 				strerror_r(-err, errmsg, sizeof(errmsg));
739 				pr_warning("failed to alloc program %s (%s): %s",
740 					   name, obj->path, errmsg);
741 			}
742 		} else if (sh.sh_type == SHT_REL) {
743 			void *reloc = obj->efile.reloc;
744 			int nr_reloc = obj->efile.nr_reloc + 1;
745 
746 			reloc = realloc(reloc,
747 					sizeof(*obj->efile.reloc) * nr_reloc);
748 			if (!reloc) {
749 				pr_warning("realloc failed\n");
750 				err = -ENOMEM;
751 			} else {
752 				int n = nr_reloc - 1;
753 
754 				obj->efile.reloc = reloc;
755 				obj->efile.nr_reloc = nr_reloc;
756 
757 				obj->efile.reloc[n].shdr = sh;
758 				obj->efile.reloc[n].data = data;
759 			}
760 		}
761 		if (err)
762 			goto out;
763 	}
764 
765 	if (!obj->efile.strtabidx || obj->efile.strtabidx >= idx) {
766 		pr_warning("Corrupted ELF file: index of strtab invalid\n");
767 		return LIBBPF_ERRNO__FORMAT;
768 	}
769 	if (obj->efile.maps_shndx >= 0)
770 		err = bpf_object__init_maps(obj);
771 out:
772 	return err;
773 }
774 
775 static struct bpf_program *
776 bpf_object__find_prog_by_idx(struct bpf_object *obj, int idx)
777 {
778 	struct bpf_program *prog;
779 	size_t i;
780 
781 	for (i = 0; i < obj->nr_programs; i++) {
782 		prog = &obj->programs[i];
783 		if (prog->idx == idx)
784 			return prog;
785 	}
786 	return NULL;
787 }
788 
789 static int
790 bpf_program__collect_reloc(struct bpf_program *prog,
791 			   size_t nr_maps, GElf_Shdr *shdr,
792 			   Elf_Data *data, Elf_Data *symbols,
793 			   int maps_shndx, struct bpf_map *maps)
794 {
795 	int i, nrels;
796 
797 	pr_debug("collecting relocating info for: '%s'\n",
798 		 prog->section_name);
799 	nrels = shdr->sh_size / shdr->sh_entsize;
800 
801 	prog->reloc_desc = malloc(sizeof(*prog->reloc_desc) * nrels);
802 	if (!prog->reloc_desc) {
803 		pr_warning("failed to alloc memory in relocation\n");
804 		return -ENOMEM;
805 	}
806 	prog->nr_reloc = nrels;
807 
808 	for (i = 0; i < nrels; i++) {
809 		GElf_Sym sym;
810 		GElf_Rel rel;
811 		unsigned int insn_idx;
812 		struct bpf_insn *insns = prog->insns;
813 		size_t map_idx;
814 
815 		if (!gelf_getrel(data, i, &rel)) {
816 			pr_warning("relocation: failed to get %d reloc\n", i);
817 			return -LIBBPF_ERRNO__FORMAT;
818 		}
819 
820 		if (!gelf_getsym(symbols,
821 				 GELF_R_SYM(rel.r_info),
822 				 &sym)) {
823 			pr_warning("relocation: symbol %"PRIx64" not found\n",
824 				   GELF_R_SYM(rel.r_info));
825 			return -LIBBPF_ERRNO__FORMAT;
826 		}
827 
828 		if (sym.st_shndx != maps_shndx) {
829 			pr_warning("Program '%s' contains non-map related relo data pointing to section %u\n",
830 				   prog->section_name, sym.st_shndx);
831 			return -LIBBPF_ERRNO__RELOC;
832 		}
833 
834 		insn_idx = rel.r_offset / sizeof(struct bpf_insn);
835 		pr_debug("relocation: insn_idx=%u\n", insn_idx);
836 
837 		if (insns[insn_idx].code != (BPF_LD | BPF_IMM | BPF_DW)) {
838 			pr_warning("bpf: relocation: invalid relo for insns[%d].code 0x%x\n",
839 				   insn_idx, insns[insn_idx].code);
840 			return -LIBBPF_ERRNO__RELOC;
841 		}
842 
843 		/* TODO: 'maps' is sorted. We can use bsearch to make it faster. */
844 		for (map_idx = 0; map_idx < nr_maps; map_idx++) {
845 			if (maps[map_idx].offset == sym.st_value) {
846 				pr_debug("relocation: find map %zd (%s) for insn %u\n",
847 					 map_idx, maps[map_idx].name, insn_idx);
848 				break;
849 			}
850 		}
851 
852 		if (map_idx >= nr_maps) {
853 			pr_warning("bpf relocation: map_idx %d large than %d\n",
854 				   (int)map_idx, (int)nr_maps - 1);
855 			return -LIBBPF_ERRNO__RELOC;
856 		}
857 
858 		prog->reloc_desc[i].insn_idx = insn_idx;
859 		prog->reloc_desc[i].map_idx = map_idx;
860 	}
861 	return 0;
862 }
863 
864 static int
865 bpf_object__create_maps(struct bpf_object *obj)
866 {
867 	unsigned int i;
868 
869 	for (i = 0; i < obj->nr_maps; i++) {
870 		struct bpf_map_def *def = &obj->maps[i].def;
871 		int *pfd = &obj->maps[i].fd;
872 
873 		*pfd = bpf_create_map(def->type,
874 				      def->key_size,
875 				      def->value_size,
876 				      def->max_entries,
877 				      0);
878 		if (*pfd < 0) {
879 			size_t j;
880 			int err = *pfd;
881 
882 			pr_warning("failed to create map: %s\n",
883 				   strerror(errno));
884 			for (j = 0; j < i; j++)
885 				zclose(obj->maps[j].fd);
886 			return err;
887 		}
888 		pr_debug("create map %s: fd=%d\n", obj->maps[i].name, *pfd);
889 	}
890 
891 	return 0;
892 }
893 
894 static int
895 bpf_program__relocate(struct bpf_program *prog, struct bpf_object *obj)
896 {
897 	int i;
898 
899 	if (!prog || !prog->reloc_desc)
900 		return 0;
901 
902 	for (i = 0; i < prog->nr_reloc; i++) {
903 		int insn_idx, map_idx;
904 		struct bpf_insn *insns = prog->insns;
905 
906 		insn_idx = prog->reloc_desc[i].insn_idx;
907 		map_idx = prog->reloc_desc[i].map_idx;
908 
909 		if (insn_idx >= (int)prog->insns_cnt) {
910 			pr_warning("relocation out of range: '%s'\n",
911 				   prog->section_name);
912 			return -LIBBPF_ERRNO__RELOC;
913 		}
914 		insns[insn_idx].src_reg = BPF_PSEUDO_MAP_FD;
915 		insns[insn_idx].imm = obj->maps[map_idx].fd;
916 	}
917 
918 	zfree(&prog->reloc_desc);
919 	prog->nr_reloc = 0;
920 	return 0;
921 }
922 
923 
924 static int
925 bpf_object__relocate(struct bpf_object *obj)
926 {
927 	struct bpf_program *prog;
928 	size_t i;
929 	int err;
930 
931 	for (i = 0; i < obj->nr_programs; i++) {
932 		prog = &obj->programs[i];
933 
934 		err = bpf_program__relocate(prog, obj);
935 		if (err) {
936 			pr_warning("failed to relocate '%s'\n",
937 				   prog->section_name);
938 			return err;
939 		}
940 	}
941 	return 0;
942 }
943 
944 static int bpf_object__collect_reloc(struct bpf_object *obj)
945 {
946 	int i, err;
947 
948 	if (!obj_elf_valid(obj)) {
949 		pr_warning("Internal error: elf object is closed\n");
950 		return -LIBBPF_ERRNO__INTERNAL;
951 	}
952 
953 	for (i = 0; i < obj->efile.nr_reloc; i++) {
954 		GElf_Shdr *shdr = &obj->efile.reloc[i].shdr;
955 		Elf_Data *data = obj->efile.reloc[i].data;
956 		int idx = shdr->sh_info;
957 		struct bpf_program *prog;
958 		size_t nr_maps = obj->nr_maps;
959 
960 		if (shdr->sh_type != SHT_REL) {
961 			pr_warning("internal error at %d\n", __LINE__);
962 			return -LIBBPF_ERRNO__INTERNAL;
963 		}
964 
965 		prog = bpf_object__find_prog_by_idx(obj, idx);
966 		if (!prog) {
967 			pr_warning("relocation failed: no %d section\n",
968 				   idx);
969 			return -LIBBPF_ERRNO__RELOC;
970 		}
971 
972 		err = bpf_program__collect_reloc(prog, nr_maps,
973 						 shdr, data,
974 						 obj->efile.symbols,
975 						 obj->efile.maps_shndx,
976 						 obj->maps);
977 		if (err)
978 			return err;
979 	}
980 	return 0;
981 }
982 
983 static int
984 load_program(enum bpf_prog_type type, struct bpf_insn *insns,
985 	     int insns_cnt, char *license, u32 kern_version, int *pfd)
986 {
987 	int ret;
988 	char *log_buf;
989 
990 	if (!insns || !insns_cnt)
991 		return -EINVAL;
992 
993 	log_buf = malloc(BPF_LOG_BUF_SIZE);
994 	if (!log_buf)
995 		pr_warning("Alloc log buffer for bpf loader error, continue without log\n");
996 
997 	ret = bpf_load_program(type, insns, insns_cnt, license,
998 			       kern_version, log_buf, BPF_LOG_BUF_SIZE);
999 
1000 	if (ret >= 0) {
1001 		*pfd = ret;
1002 		ret = 0;
1003 		goto out;
1004 	}
1005 
1006 	ret = -LIBBPF_ERRNO__LOAD;
1007 	pr_warning("load bpf program failed: %s\n", strerror(errno));
1008 
1009 	if (log_buf && log_buf[0] != '\0') {
1010 		ret = -LIBBPF_ERRNO__VERIFY;
1011 		pr_warning("-- BEGIN DUMP LOG ---\n");
1012 		pr_warning("\n%s\n", log_buf);
1013 		pr_warning("-- END LOG --\n");
1014 	} else if (insns_cnt >= BPF_MAXINSNS) {
1015 		pr_warning("Program too large (%d insns), at most %d insns\n",
1016 			   insns_cnt, BPF_MAXINSNS);
1017 		ret = -LIBBPF_ERRNO__PROG2BIG;
1018 	} else {
1019 		/* Wrong program type? */
1020 		if (type != BPF_PROG_TYPE_KPROBE) {
1021 			int fd;
1022 
1023 			fd = bpf_load_program(BPF_PROG_TYPE_KPROBE, insns,
1024 					      insns_cnt, license, kern_version,
1025 					      NULL, 0);
1026 			if (fd >= 0) {
1027 				close(fd);
1028 				ret = -LIBBPF_ERRNO__PROGTYPE;
1029 				goto out;
1030 			}
1031 		}
1032 
1033 		if (log_buf)
1034 			ret = -LIBBPF_ERRNO__KVER;
1035 	}
1036 
1037 out:
1038 	free(log_buf);
1039 	return ret;
1040 }
1041 
1042 static int
1043 bpf_program__load(struct bpf_program *prog,
1044 		  char *license, u32 kern_version)
1045 {
1046 	int err = 0, fd, i;
1047 
1048 	if (prog->instances.nr < 0 || !prog->instances.fds) {
1049 		if (prog->preprocessor) {
1050 			pr_warning("Internal error: can't load program '%s'\n",
1051 				   prog->section_name);
1052 			return -LIBBPF_ERRNO__INTERNAL;
1053 		}
1054 
1055 		prog->instances.fds = malloc(sizeof(int));
1056 		if (!prog->instances.fds) {
1057 			pr_warning("Not enough memory for BPF fds\n");
1058 			return -ENOMEM;
1059 		}
1060 		prog->instances.nr = 1;
1061 		prog->instances.fds[0] = -1;
1062 	}
1063 
1064 	if (!prog->preprocessor) {
1065 		if (prog->instances.nr != 1) {
1066 			pr_warning("Program '%s' is inconsistent: nr(%d) != 1\n",
1067 				   prog->section_name, prog->instances.nr);
1068 		}
1069 		err = load_program(prog->type, prog->insns, prog->insns_cnt,
1070 				   license, kern_version, &fd);
1071 		if (!err)
1072 			prog->instances.fds[0] = fd;
1073 		goto out;
1074 	}
1075 
1076 	for (i = 0; i < prog->instances.nr; i++) {
1077 		struct bpf_prog_prep_result result;
1078 		bpf_program_prep_t preprocessor = prog->preprocessor;
1079 
1080 		bzero(&result, sizeof(result));
1081 		err = preprocessor(prog, i, prog->insns,
1082 				   prog->insns_cnt, &result);
1083 		if (err) {
1084 			pr_warning("Preprocessing the %dth instance of program '%s' failed\n",
1085 				   i, prog->section_name);
1086 			goto out;
1087 		}
1088 
1089 		if (!result.new_insn_ptr || !result.new_insn_cnt) {
1090 			pr_debug("Skip loading the %dth instance of program '%s'\n",
1091 				 i, prog->section_name);
1092 			prog->instances.fds[i] = -1;
1093 			if (result.pfd)
1094 				*result.pfd = -1;
1095 			continue;
1096 		}
1097 
1098 		err = load_program(prog->type, result.new_insn_ptr,
1099 				   result.new_insn_cnt,
1100 				   license, kern_version, &fd);
1101 
1102 		if (err) {
1103 			pr_warning("Loading the %dth instance of program '%s' failed\n",
1104 					i, prog->section_name);
1105 			goto out;
1106 		}
1107 
1108 		if (result.pfd)
1109 			*result.pfd = fd;
1110 		prog->instances.fds[i] = fd;
1111 	}
1112 out:
1113 	if (err)
1114 		pr_warning("failed to load program '%s'\n",
1115 			   prog->section_name);
1116 	zfree(&prog->insns);
1117 	prog->insns_cnt = 0;
1118 	return err;
1119 }
1120 
1121 static int
1122 bpf_object__load_progs(struct bpf_object *obj)
1123 {
1124 	size_t i;
1125 	int err;
1126 
1127 	for (i = 0; i < obj->nr_programs; i++) {
1128 		err = bpf_program__load(&obj->programs[i],
1129 					obj->license,
1130 					obj->kern_version);
1131 		if (err)
1132 			return err;
1133 	}
1134 	return 0;
1135 }
1136 
1137 static int bpf_object__validate(struct bpf_object *obj)
1138 {
1139 	if (obj->kern_version == 0) {
1140 		pr_warning("%s doesn't provide kernel version\n",
1141 			   obj->path);
1142 		return -LIBBPF_ERRNO__KVERSION;
1143 	}
1144 	return 0;
1145 }
1146 
1147 static struct bpf_object *
1148 __bpf_object__open(const char *path, void *obj_buf, size_t obj_buf_sz)
1149 {
1150 	struct bpf_object *obj;
1151 	int err;
1152 
1153 	if (elf_version(EV_CURRENT) == EV_NONE) {
1154 		pr_warning("failed to init libelf for %s\n", path);
1155 		return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
1156 	}
1157 
1158 	obj = bpf_object__new(path, obj_buf, obj_buf_sz);
1159 	if (IS_ERR(obj))
1160 		return obj;
1161 
1162 	CHECK_ERR(bpf_object__elf_init(obj), err, out);
1163 	CHECK_ERR(bpf_object__check_endianness(obj), err, out);
1164 	CHECK_ERR(bpf_object__elf_collect(obj), err, out);
1165 	CHECK_ERR(bpf_object__collect_reloc(obj), err, out);
1166 	CHECK_ERR(bpf_object__validate(obj), err, out);
1167 
1168 	bpf_object__elf_finish(obj);
1169 	return obj;
1170 out:
1171 	bpf_object__close(obj);
1172 	return ERR_PTR(err);
1173 }
1174 
1175 struct bpf_object *bpf_object__open(const char *path)
1176 {
1177 	/* param validation */
1178 	if (!path)
1179 		return NULL;
1180 
1181 	pr_debug("loading %s\n", path);
1182 
1183 	return __bpf_object__open(path, NULL, 0);
1184 }
1185 
1186 struct bpf_object *bpf_object__open_buffer(void *obj_buf,
1187 					   size_t obj_buf_sz,
1188 					   const char *name)
1189 {
1190 	char tmp_name[64];
1191 
1192 	/* param validation */
1193 	if (!obj_buf || obj_buf_sz <= 0)
1194 		return NULL;
1195 
1196 	if (!name) {
1197 		snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
1198 			 (unsigned long)obj_buf,
1199 			 (unsigned long)obj_buf_sz);
1200 		tmp_name[sizeof(tmp_name) - 1] = '\0';
1201 		name = tmp_name;
1202 	}
1203 	pr_debug("loading object '%s' from buffer\n",
1204 		 name);
1205 
1206 	return __bpf_object__open(name, obj_buf, obj_buf_sz);
1207 }
1208 
1209 int bpf_object__unload(struct bpf_object *obj)
1210 {
1211 	size_t i;
1212 
1213 	if (!obj)
1214 		return -EINVAL;
1215 
1216 	for (i = 0; i < obj->nr_maps; i++)
1217 		zclose(obj->maps[i].fd);
1218 
1219 	for (i = 0; i < obj->nr_programs; i++)
1220 		bpf_program__unload(&obj->programs[i]);
1221 
1222 	return 0;
1223 }
1224 
1225 int bpf_object__load(struct bpf_object *obj)
1226 {
1227 	int err;
1228 
1229 	if (!obj)
1230 		return -EINVAL;
1231 
1232 	if (obj->loaded) {
1233 		pr_warning("object should not be loaded twice\n");
1234 		return -EINVAL;
1235 	}
1236 
1237 	obj->loaded = true;
1238 
1239 	CHECK_ERR(bpf_object__create_maps(obj), err, out);
1240 	CHECK_ERR(bpf_object__relocate(obj), err, out);
1241 	CHECK_ERR(bpf_object__load_progs(obj), err, out);
1242 
1243 	return 0;
1244 out:
1245 	bpf_object__unload(obj);
1246 	pr_warning("failed to load object '%s'\n", obj->path);
1247 	return err;
1248 }
1249 
1250 static int check_path(const char *path)
1251 {
1252 	struct statfs st_fs;
1253 	char *dname, *dir;
1254 	int err = 0;
1255 
1256 	if (path == NULL)
1257 		return -EINVAL;
1258 
1259 	dname = strdup(path);
1260 	if (dname == NULL)
1261 		return -ENOMEM;
1262 
1263 	dir = dirname(dname);
1264 	if (statfs(dir, &st_fs)) {
1265 		pr_warning("failed to statfs %s: %s\n", dir, strerror(errno));
1266 		err = -errno;
1267 	}
1268 	free(dname);
1269 
1270 	if (!err && st_fs.f_type != BPF_FS_MAGIC) {
1271 		pr_warning("specified path %s is not on BPF FS\n", path);
1272 		err = -EINVAL;
1273 	}
1274 
1275 	return err;
1276 }
1277 
1278 int bpf_program__pin_instance(struct bpf_program *prog, const char *path,
1279 			      int instance)
1280 {
1281 	int err;
1282 
1283 	err = check_path(path);
1284 	if (err)
1285 		return err;
1286 
1287 	if (prog == NULL) {
1288 		pr_warning("invalid program pointer\n");
1289 		return -EINVAL;
1290 	}
1291 
1292 	if (instance < 0 || instance >= prog->instances.nr) {
1293 		pr_warning("invalid prog instance %d of prog %s (max %d)\n",
1294 			   instance, prog->section_name, prog->instances.nr);
1295 		return -EINVAL;
1296 	}
1297 
1298 	if (bpf_obj_pin(prog->instances.fds[instance], path)) {
1299 		pr_warning("failed to pin program: %s\n", strerror(errno));
1300 		return -errno;
1301 	}
1302 	pr_debug("pinned program '%s'\n", path);
1303 
1304 	return 0;
1305 }
1306 
1307 static int make_dir(const char *path)
1308 {
1309 	int err = 0;
1310 
1311 	if (mkdir(path, 0700) && errno != EEXIST)
1312 		err = -errno;
1313 
1314 	if (err)
1315 		pr_warning("failed to mkdir %s: %s\n", path, strerror(-err));
1316 	return err;
1317 }
1318 
1319 int bpf_program__pin(struct bpf_program *prog, const char *path)
1320 {
1321 	int i, err;
1322 
1323 	err = check_path(path);
1324 	if (err)
1325 		return err;
1326 
1327 	if (prog == NULL) {
1328 		pr_warning("invalid program pointer\n");
1329 		return -EINVAL;
1330 	}
1331 
1332 	if (prog->instances.nr <= 0) {
1333 		pr_warning("no instances of prog %s to pin\n",
1334 			   prog->section_name);
1335 		return -EINVAL;
1336 	}
1337 
1338 	err = make_dir(path);
1339 	if (err)
1340 		return err;
1341 
1342 	for (i = 0; i < prog->instances.nr; i++) {
1343 		char buf[PATH_MAX];
1344 		int len;
1345 
1346 		len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
1347 		if (len < 0)
1348 			return -EINVAL;
1349 		else if (len >= PATH_MAX)
1350 			return -ENAMETOOLONG;
1351 
1352 		err = bpf_program__pin_instance(prog, buf, i);
1353 		if (err)
1354 			return err;
1355 	}
1356 
1357 	return 0;
1358 }
1359 
1360 int bpf_map__pin(struct bpf_map *map, const char *path)
1361 {
1362 	int err;
1363 
1364 	err = check_path(path);
1365 	if (err)
1366 		return err;
1367 
1368 	if (map == NULL) {
1369 		pr_warning("invalid map pointer\n");
1370 		return -EINVAL;
1371 	}
1372 
1373 	if (bpf_obj_pin(map->fd, path)) {
1374 		pr_warning("failed to pin map: %s\n", strerror(errno));
1375 		return -errno;
1376 	}
1377 
1378 	pr_debug("pinned map '%s'\n", path);
1379 	return 0;
1380 }
1381 
1382 int bpf_object__pin(struct bpf_object *obj, const char *path)
1383 {
1384 	struct bpf_program *prog;
1385 	struct bpf_map *map;
1386 	int err;
1387 
1388 	if (!obj)
1389 		return -ENOENT;
1390 
1391 	if (!obj->loaded) {
1392 		pr_warning("object not yet loaded; load it first\n");
1393 		return -ENOENT;
1394 	}
1395 
1396 	err = make_dir(path);
1397 	if (err)
1398 		return err;
1399 
1400 	bpf_map__for_each(map, obj) {
1401 		char buf[PATH_MAX];
1402 		int len;
1403 
1404 		len = snprintf(buf, PATH_MAX, "%s/%s", path,
1405 			       bpf_map__name(map));
1406 		if (len < 0)
1407 			return -EINVAL;
1408 		else if (len >= PATH_MAX)
1409 			return -ENAMETOOLONG;
1410 
1411 		err = bpf_map__pin(map, buf);
1412 		if (err)
1413 			return err;
1414 	}
1415 
1416 	bpf_object__for_each_program(prog, obj) {
1417 		char buf[PATH_MAX];
1418 		int len;
1419 
1420 		len = snprintf(buf, PATH_MAX, "%s/%s", path,
1421 			       prog->section_name);
1422 		if (len < 0)
1423 			return -EINVAL;
1424 		else if (len >= PATH_MAX)
1425 			return -ENAMETOOLONG;
1426 
1427 		err = bpf_program__pin(prog, buf);
1428 		if (err)
1429 			return err;
1430 	}
1431 
1432 	return 0;
1433 }
1434 
1435 void bpf_object__close(struct bpf_object *obj)
1436 {
1437 	size_t i;
1438 
1439 	if (!obj)
1440 		return;
1441 
1442 	if (obj->clear_priv)
1443 		obj->clear_priv(obj, obj->priv);
1444 
1445 	bpf_object__elf_finish(obj);
1446 	bpf_object__unload(obj);
1447 
1448 	for (i = 0; i < obj->nr_maps; i++) {
1449 		zfree(&obj->maps[i].name);
1450 		if (obj->maps[i].clear_priv)
1451 			obj->maps[i].clear_priv(&obj->maps[i],
1452 						obj->maps[i].priv);
1453 		obj->maps[i].priv = NULL;
1454 		obj->maps[i].clear_priv = NULL;
1455 	}
1456 	zfree(&obj->maps);
1457 	obj->nr_maps = 0;
1458 
1459 	if (obj->programs && obj->nr_programs) {
1460 		for (i = 0; i < obj->nr_programs; i++)
1461 			bpf_program__exit(&obj->programs[i]);
1462 	}
1463 	zfree(&obj->programs);
1464 
1465 	list_del(&obj->list);
1466 	free(obj);
1467 }
1468 
1469 struct bpf_object *
1470 bpf_object__next(struct bpf_object *prev)
1471 {
1472 	struct bpf_object *next;
1473 
1474 	if (!prev)
1475 		next = list_first_entry(&bpf_objects_list,
1476 					struct bpf_object,
1477 					list);
1478 	else
1479 		next = list_next_entry(prev, list);
1480 
1481 	/* Empty list is noticed here so don't need checking on entry. */
1482 	if (&next->list == &bpf_objects_list)
1483 		return NULL;
1484 
1485 	return next;
1486 }
1487 
1488 const char *bpf_object__name(struct bpf_object *obj)
1489 {
1490 	return obj ? obj->path : ERR_PTR(-EINVAL);
1491 }
1492 
1493 unsigned int bpf_object__kversion(struct bpf_object *obj)
1494 {
1495 	return obj ? obj->kern_version : 0;
1496 }
1497 
1498 int bpf_object__set_priv(struct bpf_object *obj, void *priv,
1499 			 bpf_object_clear_priv_t clear_priv)
1500 {
1501 	if (obj->priv && obj->clear_priv)
1502 		obj->clear_priv(obj, obj->priv);
1503 
1504 	obj->priv = priv;
1505 	obj->clear_priv = clear_priv;
1506 	return 0;
1507 }
1508 
1509 void *bpf_object__priv(struct bpf_object *obj)
1510 {
1511 	return obj ? obj->priv : ERR_PTR(-EINVAL);
1512 }
1513 
1514 struct bpf_program *
1515 bpf_program__next(struct bpf_program *prev, struct bpf_object *obj)
1516 {
1517 	size_t idx;
1518 
1519 	if (!obj->programs)
1520 		return NULL;
1521 	/* First handler */
1522 	if (prev == NULL)
1523 		return &obj->programs[0];
1524 
1525 	if (prev->obj != obj) {
1526 		pr_warning("error: program handler doesn't match object\n");
1527 		return NULL;
1528 	}
1529 
1530 	idx = (prev - obj->programs) + 1;
1531 	if (idx >= obj->nr_programs)
1532 		return NULL;
1533 	return &obj->programs[idx];
1534 }
1535 
1536 int bpf_program__set_priv(struct bpf_program *prog, void *priv,
1537 			  bpf_program_clear_priv_t clear_priv)
1538 {
1539 	if (prog->priv && prog->clear_priv)
1540 		prog->clear_priv(prog, prog->priv);
1541 
1542 	prog->priv = priv;
1543 	prog->clear_priv = clear_priv;
1544 	return 0;
1545 }
1546 
1547 void *bpf_program__priv(struct bpf_program *prog)
1548 {
1549 	return prog ? prog->priv : ERR_PTR(-EINVAL);
1550 }
1551 
1552 const char *bpf_program__title(struct bpf_program *prog, bool needs_copy)
1553 {
1554 	const char *title;
1555 
1556 	title = prog->section_name;
1557 	if (needs_copy) {
1558 		title = strdup(title);
1559 		if (!title) {
1560 			pr_warning("failed to strdup program title\n");
1561 			return ERR_PTR(-ENOMEM);
1562 		}
1563 	}
1564 
1565 	return title;
1566 }
1567 
1568 int bpf_program__fd(struct bpf_program *prog)
1569 {
1570 	return bpf_program__nth_fd(prog, 0);
1571 }
1572 
1573 int bpf_program__set_prep(struct bpf_program *prog, int nr_instances,
1574 			  bpf_program_prep_t prep)
1575 {
1576 	int *instances_fds;
1577 
1578 	if (nr_instances <= 0 || !prep)
1579 		return -EINVAL;
1580 
1581 	if (prog->instances.nr > 0 || prog->instances.fds) {
1582 		pr_warning("Can't set pre-processor after loading\n");
1583 		return -EINVAL;
1584 	}
1585 
1586 	instances_fds = malloc(sizeof(int) * nr_instances);
1587 	if (!instances_fds) {
1588 		pr_warning("alloc memory failed for fds\n");
1589 		return -ENOMEM;
1590 	}
1591 
1592 	/* fill all fd with -1 */
1593 	memset(instances_fds, -1, sizeof(int) * nr_instances);
1594 
1595 	prog->instances.nr = nr_instances;
1596 	prog->instances.fds = instances_fds;
1597 	prog->preprocessor = prep;
1598 	return 0;
1599 }
1600 
1601 int bpf_program__nth_fd(struct bpf_program *prog, int n)
1602 {
1603 	int fd;
1604 
1605 	if (n >= prog->instances.nr || n < 0) {
1606 		pr_warning("Can't get the %dth fd from program %s: only %d instances\n",
1607 			   n, prog->section_name, prog->instances.nr);
1608 		return -EINVAL;
1609 	}
1610 
1611 	fd = prog->instances.fds[n];
1612 	if (fd < 0) {
1613 		pr_warning("%dth instance of program '%s' is invalid\n",
1614 			   n, prog->section_name);
1615 		return -ENOENT;
1616 	}
1617 
1618 	return fd;
1619 }
1620 
1621 void bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
1622 {
1623 	prog->type = type;
1624 }
1625 
1626 static bool bpf_program__is_type(struct bpf_program *prog,
1627 				 enum bpf_prog_type type)
1628 {
1629 	return prog ? (prog->type == type) : false;
1630 }
1631 
1632 #define BPF_PROG_TYPE_FNS(NAME, TYPE)			\
1633 int bpf_program__set_##NAME(struct bpf_program *prog)	\
1634 {							\
1635 	if (!prog)					\
1636 		return -EINVAL;				\
1637 	bpf_program__set_type(prog, TYPE);		\
1638 	return 0;					\
1639 }							\
1640 							\
1641 bool bpf_program__is_##NAME(struct bpf_program *prog)	\
1642 {							\
1643 	return bpf_program__is_type(prog, TYPE);	\
1644 }							\
1645 
1646 BPF_PROG_TYPE_FNS(socket_filter, BPF_PROG_TYPE_SOCKET_FILTER);
1647 BPF_PROG_TYPE_FNS(kprobe, BPF_PROG_TYPE_KPROBE);
1648 BPF_PROG_TYPE_FNS(sched_cls, BPF_PROG_TYPE_SCHED_CLS);
1649 BPF_PROG_TYPE_FNS(sched_act, BPF_PROG_TYPE_SCHED_ACT);
1650 BPF_PROG_TYPE_FNS(tracepoint, BPF_PROG_TYPE_TRACEPOINT);
1651 BPF_PROG_TYPE_FNS(xdp, BPF_PROG_TYPE_XDP);
1652 BPF_PROG_TYPE_FNS(perf_event, BPF_PROG_TYPE_PERF_EVENT);
1653 
1654 int bpf_map__fd(struct bpf_map *map)
1655 {
1656 	return map ? map->fd : -EINVAL;
1657 }
1658 
1659 const struct bpf_map_def *bpf_map__def(struct bpf_map *map)
1660 {
1661 	return map ? &map->def : ERR_PTR(-EINVAL);
1662 }
1663 
1664 const char *bpf_map__name(struct bpf_map *map)
1665 {
1666 	return map ? map->name : NULL;
1667 }
1668 
1669 int bpf_map__set_priv(struct bpf_map *map, void *priv,
1670 		     bpf_map_clear_priv_t clear_priv)
1671 {
1672 	if (!map)
1673 		return -EINVAL;
1674 
1675 	if (map->priv) {
1676 		if (map->clear_priv)
1677 			map->clear_priv(map, map->priv);
1678 	}
1679 
1680 	map->priv = priv;
1681 	map->clear_priv = clear_priv;
1682 	return 0;
1683 }
1684 
1685 void *bpf_map__priv(struct bpf_map *map)
1686 {
1687 	return map ? map->priv : ERR_PTR(-EINVAL);
1688 }
1689 
1690 struct bpf_map *
1691 bpf_map__next(struct bpf_map *prev, struct bpf_object *obj)
1692 {
1693 	size_t idx;
1694 	struct bpf_map *s, *e;
1695 
1696 	if (!obj || !obj->maps)
1697 		return NULL;
1698 
1699 	s = obj->maps;
1700 	e = obj->maps + obj->nr_maps;
1701 
1702 	if (prev == NULL)
1703 		return s;
1704 
1705 	if ((prev < s) || (prev >= e)) {
1706 		pr_warning("error in %s: map handler doesn't belong to object\n",
1707 			   __func__);
1708 		return NULL;
1709 	}
1710 
1711 	idx = (prev - obj->maps) + 1;
1712 	if (idx >= obj->nr_maps)
1713 		return NULL;
1714 	return &obj->maps[idx];
1715 }
1716 
1717 struct bpf_map *
1718 bpf_object__find_map_by_name(struct bpf_object *obj, const char *name)
1719 {
1720 	struct bpf_map *pos;
1721 
1722 	bpf_map__for_each(pos, obj) {
1723 		if (pos->name && !strcmp(pos->name, name))
1724 			return pos;
1725 	}
1726 	return NULL;
1727 }
1728 
1729 struct bpf_map *
1730 bpf_object__find_map_by_offset(struct bpf_object *obj, size_t offset)
1731 {
1732 	int i;
1733 
1734 	for (i = 0; i < obj->nr_maps; i++) {
1735 		if (obj->maps[i].offset == offset)
1736 			return &obj->maps[i];
1737 	}
1738 	return ERR_PTR(-ENOENT);
1739 }
1740 
1741 long libbpf_get_error(const void *ptr)
1742 {
1743 	if (IS_ERR(ptr))
1744 		return PTR_ERR(ptr);
1745 	return 0;
1746 }
1747