bpf tools: Load a program with different instances using preprocessor
[linux-2.6/btrfs-unstable.git] / tools / lib / bpf / libbpf.c
blobe3f4c3379f14a266304a2c236e8fca0af87e2230
1 /*
2 * Common eBPF ELF object loading operations.
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 */
9 #include <stdlib.h>
10 #include <stdio.h>
11 #include <stdarg.h>
12 #include <inttypes.h>
13 #include <string.h>
14 #include <unistd.h>
15 #include <fcntl.h>
16 #include <errno.h>
17 #include <asm/unistd.h>
18 #include <linux/kernel.h>
19 #include <linux/bpf.h>
20 #include <linux/list.h>
21 #include <libelf.h>
22 #include <gelf.h>
24 #include "libbpf.h"
25 #include "bpf.h"
27 #define __printf(a, b) __attribute__((format(printf, a, b)))
29 __printf(1, 2)
30 static int __base_pr(const char *format, ...)
32 va_list args;
33 int err;
35 va_start(args, format);
36 err = vfprintf(stderr, format, args);
37 va_end(args);
38 return err;
41 static __printf(1, 2) libbpf_print_fn_t __pr_warning = __base_pr;
42 static __printf(1, 2) libbpf_print_fn_t __pr_info = __base_pr;
43 static __printf(1, 2) libbpf_print_fn_t __pr_debug;
45 #define __pr(func, fmt, ...) \
46 do { \
47 if ((func)) \
48 (func)("libbpf: " fmt, ##__VA_ARGS__); \
49 } while (0)
51 #define pr_warning(fmt, ...) __pr(__pr_warning, fmt, ##__VA_ARGS__)
52 #define pr_info(fmt, ...) __pr(__pr_info, fmt, ##__VA_ARGS__)
53 #define pr_debug(fmt, ...) __pr(__pr_debug, fmt, ##__VA_ARGS__)
55 void libbpf_set_print(libbpf_print_fn_t warn,
56 libbpf_print_fn_t info,
57 libbpf_print_fn_t debug)
59 __pr_warning = warn;
60 __pr_info = info;
61 __pr_debug = debug;
64 #define STRERR_BUFSIZE 128
66 #define ERRNO_OFFSET(e) ((e) - __LIBBPF_ERRNO__START)
67 #define ERRCODE_OFFSET(c) ERRNO_OFFSET(LIBBPF_ERRNO__##c)
68 #define NR_ERRNO (__LIBBPF_ERRNO__END - __LIBBPF_ERRNO__START)
70 static const char *libbpf_strerror_table[NR_ERRNO] = {
71 [ERRCODE_OFFSET(LIBELF)] = "Something wrong in libelf",
72 [ERRCODE_OFFSET(FORMAT)] = "BPF object format invalid",
73 [ERRCODE_OFFSET(KVERSION)] = "'version' section incorrect or lost",
74 [ERRCODE_OFFSET(ENDIAN)] = "Endian missmatch",
75 [ERRCODE_OFFSET(INTERNAL)] = "Internal error in libbpf",
76 [ERRCODE_OFFSET(RELOC)] = "Relocation failed",
77 [ERRCODE_OFFSET(VERIFY)] = "Kernel verifier blocks program loading",
78 [ERRCODE_OFFSET(PROG2BIG)] = "Program too big",
79 [ERRCODE_OFFSET(KVER)] = "Incorrect kernel version",
82 int libbpf_strerror(int err, char *buf, size_t size)
84 if (!buf || !size)
85 return -1;
87 err = err > 0 ? err : -err;
89 if (err < __LIBBPF_ERRNO__START) {
90 int ret;
92 ret = strerror_r(err, buf, size);
93 buf[size - 1] = '\0';
94 return ret;
97 if (err < __LIBBPF_ERRNO__END) {
98 const char *msg;
100 msg = libbpf_strerror_table[ERRNO_OFFSET(err)];
101 snprintf(buf, size, "%s", msg);
102 buf[size - 1] = '\0';
103 return 0;
106 snprintf(buf, size, "Unknown libbpf error %d", err);
107 buf[size - 1] = '\0';
108 return -1;
111 #define CHECK_ERR(action, err, out) do { \
112 err = action; \
113 if (err) \
114 goto out; \
115 } while(0)
118 /* Copied from tools/perf/util/util.h */
119 #ifndef zfree
120 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
121 #endif
123 #ifndef zclose
124 # define zclose(fd) ({ \
125 int ___err = 0; \
126 if ((fd) >= 0) \
127 ___err = close((fd)); \
128 fd = -1; \
129 ___err; })
130 #endif
132 #ifdef HAVE_LIBELF_MMAP_SUPPORT
133 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ_MMAP
134 #else
135 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ
136 #endif
139 * bpf_prog should be a better name but it has been used in
140 * linux/filter.h.
142 struct bpf_program {
143 /* Index in elf obj file, for relocation use. */
144 int idx;
145 char *section_name;
146 struct bpf_insn *insns;
147 size_t insns_cnt;
149 struct {
150 int insn_idx;
151 int map_idx;
152 } *reloc_desc;
153 int nr_reloc;
155 struct {
156 int nr;
157 int *fds;
158 } instances;
159 bpf_program_prep_t preprocessor;
161 struct bpf_object *obj;
162 void *priv;
163 bpf_program_clear_priv_t clear_priv;
166 static LIST_HEAD(bpf_objects_list);
168 struct bpf_object {
169 char license[64];
170 u32 kern_version;
171 void *maps_buf;
172 size_t maps_buf_sz;
174 struct bpf_program *programs;
175 size_t nr_programs;
176 int *map_fds;
178 * This field is required because maps_buf will be freed and
179 * maps_buf_sz will be set to 0 after loaded.
181 size_t nr_map_fds;
182 bool loaded;
185 * Information when doing elf related work. Only valid if fd
186 * is valid.
188 struct {
189 int fd;
190 void *obj_buf;
191 size_t obj_buf_sz;
192 Elf *elf;
193 GElf_Ehdr ehdr;
194 Elf_Data *symbols;
195 struct {
196 GElf_Shdr shdr;
197 Elf_Data *data;
198 } *reloc;
199 int nr_reloc;
200 } efile;
202 * All loaded bpf_object is linked in a list, which is
203 * hidden to caller. bpf_objects__<func> handlers deal with
204 * all objects.
206 struct list_head list;
207 char path[];
209 #define obj_elf_valid(o) ((o)->efile.elf)
211 static void bpf_program__unload(struct bpf_program *prog)
213 int i;
215 if (!prog)
216 return;
219 * If the object is opened but the program was never loaded,
220 * it is possible that prog->instances.nr == -1.
222 if (prog->instances.nr > 0) {
223 for (i = 0; i < prog->instances.nr; i++)
224 zclose(prog->instances.fds[i]);
225 } else if (prog->instances.nr != -1) {
226 pr_warning("Internal error: instances.nr is %d\n",
227 prog->instances.nr);
230 prog->instances.nr = -1;
231 zfree(&prog->instances.fds);
234 static void bpf_program__exit(struct bpf_program *prog)
236 if (!prog)
237 return;
239 if (prog->clear_priv)
240 prog->clear_priv(prog, prog->priv);
242 prog->priv = NULL;
243 prog->clear_priv = NULL;
245 bpf_program__unload(prog);
246 zfree(&prog->section_name);
247 zfree(&prog->insns);
248 zfree(&prog->reloc_desc);
250 prog->nr_reloc = 0;
251 prog->insns_cnt = 0;
252 prog->idx = -1;
255 static int
256 bpf_program__init(void *data, size_t size, char *name, int idx,
257 struct bpf_program *prog)
259 if (size < sizeof(struct bpf_insn)) {
260 pr_warning("corrupted section '%s'\n", name);
261 return -EINVAL;
264 bzero(prog, sizeof(*prog));
266 prog->section_name = strdup(name);
267 if (!prog->section_name) {
268 pr_warning("failed to alloc name for prog %s\n",
269 name);
270 goto errout;
273 prog->insns = malloc(size);
274 if (!prog->insns) {
275 pr_warning("failed to alloc insns for %s\n", name);
276 goto errout;
278 prog->insns_cnt = size / sizeof(struct bpf_insn);
279 memcpy(prog->insns, data,
280 prog->insns_cnt * sizeof(struct bpf_insn));
281 prog->idx = idx;
282 prog->instances.fds = NULL;
283 prog->instances.nr = -1;
285 return 0;
286 errout:
287 bpf_program__exit(prog);
288 return -ENOMEM;
291 static int
292 bpf_object__add_program(struct bpf_object *obj, void *data, size_t size,
293 char *name, int idx)
295 struct bpf_program prog, *progs;
296 int nr_progs, err;
298 err = bpf_program__init(data, size, name, idx, &prog);
299 if (err)
300 return err;
302 progs = obj->programs;
303 nr_progs = obj->nr_programs;
305 progs = realloc(progs, sizeof(progs[0]) * (nr_progs + 1));
306 if (!progs) {
308 * In this case the original obj->programs
309 * is still valid, so don't need special treat for
310 * bpf_close_object().
312 pr_warning("failed to alloc a new program '%s'\n",
313 name);
314 bpf_program__exit(&prog);
315 return -ENOMEM;
318 pr_debug("found program %s\n", prog.section_name);
319 obj->programs = progs;
320 obj->nr_programs = nr_progs + 1;
321 prog.obj = obj;
322 progs[nr_progs] = prog;
323 return 0;
326 static struct bpf_object *bpf_object__new(const char *path,
327 void *obj_buf,
328 size_t obj_buf_sz)
330 struct bpf_object *obj;
332 obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
333 if (!obj) {
334 pr_warning("alloc memory failed for %s\n", path);
335 return ERR_PTR(-ENOMEM);
338 strcpy(obj->path, path);
339 obj->efile.fd = -1;
342 * Caller of this function should also calls
343 * bpf_object__elf_finish() after data collection to return
344 * obj_buf to user. If not, we should duplicate the buffer to
345 * avoid user freeing them before elf finish.
347 obj->efile.obj_buf = obj_buf;
348 obj->efile.obj_buf_sz = obj_buf_sz;
350 obj->loaded = false;
352 INIT_LIST_HEAD(&obj->list);
353 list_add(&obj->list, &bpf_objects_list);
354 return obj;
357 static void bpf_object__elf_finish(struct bpf_object *obj)
359 if (!obj_elf_valid(obj))
360 return;
362 if (obj->efile.elf) {
363 elf_end(obj->efile.elf);
364 obj->efile.elf = NULL;
366 obj->efile.symbols = NULL;
368 zfree(&obj->efile.reloc);
369 obj->efile.nr_reloc = 0;
370 zclose(obj->efile.fd);
371 obj->efile.obj_buf = NULL;
372 obj->efile.obj_buf_sz = 0;
375 static int bpf_object__elf_init(struct bpf_object *obj)
377 int err = 0;
378 GElf_Ehdr *ep;
380 if (obj_elf_valid(obj)) {
381 pr_warning("elf init: internal error\n");
382 return -LIBBPF_ERRNO__LIBELF;
385 if (obj->efile.obj_buf_sz > 0) {
387 * obj_buf should have been validated by
388 * bpf_object__open_buffer().
390 obj->efile.elf = elf_memory(obj->efile.obj_buf,
391 obj->efile.obj_buf_sz);
392 } else {
393 obj->efile.fd = open(obj->path, O_RDONLY);
394 if (obj->efile.fd < 0) {
395 pr_warning("failed to open %s: %s\n", obj->path,
396 strerror(errno));
397 return -errno;
400 obj->efile.elf = elf_begin(obj->efile.fd,
401 LIBBPF_ELF_C_READ_MMAP,
402 NULL);
405 if (!obj->efile.elf) {
406 pr_warning("failed to open %s as ELF file\n",
407 obj->path);
408 err = -LIBBPF_ERRNO__LIBELF;
409 goto errout;
412 if (!gelf_getehdr(obj->efile.elf, &obj->efile.ehdr)) {
413 pr_warning("failed to get EHDR from %s\n",
414 obj->path);
415 err = -LIBBPF_ERRNO__FORMAT;
416 goto errout;
418 ep = &obj->efile.ehdr;
420 if ((ep->e_type != ET_REL) || (ep->e_machine != 0)) {
421 pr_warning("%s is not an eBPF object file\n",
422 obj->path);
423 err = -LIBBPF_ERRNO__FORMAT;
424 goto errout;
427 return 0;
428 errout:
429 bpf_object__elf_finish(obj);
430 return err;
433 static int
434 bpf_object__check_endianness(struct bpf_object *obj)
436 static unsigned int const endian = 1;
438 switch (obj->efile.ehdr.e_ident[EI_DATA]) {
439 case ELFDATA2LSB:
440 /* We are big endian, BPF obj is little endian. */
441 if (*(unsigned char const *)&endian != 1)
442 goto mismatch;
443 break;
445 case ELFDATA2MSB:
446 /* We are little endian, BPF obj is big endian. */
447 if (*(unsigned char const *)&endian != 0)
448 goto mismatch;
449 break;
450 default:
451 return -LIBBPF_ERRNO__ENDIAN;
454 return 0;
456 mismatch:
457 pr_warning("Error: endianness mismatch.\n");
458 return -LIBBPF_ERRNO__ENDIAN;
461 static int
462 bpf_object__init_license(struct bpf_object *obj,
463 void *data, size_t size)
465 memcpy(obj->license, data,
466 min(size, sizeof(obj->license) - 1));
467 pr_debug("license of %s is %s\n", obj->path, obj->license);
468 return 0;
471 static int
472 bpf_object__init_kversion(struct bpf_object *obj,
473 void *data, size_t size)
475 u32 kver;
477 if (size != sizeof(kver)) {
478 pr_warning("invalid kver section in %s\n", obj->path);
479 return -LIBBPF_ERRNO__FORMAT;
481 memcpy(&kver, data, sizeof(kver));
482 obj->kern_version = kver;
483 pr_debug("kernel version of %s is %x\n", obj->path,
484 obj->kern_version);
485 return 0;
488 static int
489 bpf_object__init_maps(struct bpf_object *obj, void *data,
490 size_t size)
492 if (size == 0) {
493 pr_debug("%s doesn't need map definition\n",
494 obj->path);
495 return 0;
498 obj->maps_buf = malloc(size);
499 if (!obj->maps_buf) {
500 pr_warning("malloc maps failed: %s\n", obj->path);
501 return -ENOMEM;
504 obj->maps_buf_sz = size;
505 memcpy(obj->maps_buf, data, size);
506 pr_debug("maps in %s: %ld bytes\n", obj->path, (long)size);
507 return 0;
510 static int bpf_object__elf_collect(struct bpf_object *obj)
512 Elf *elf = obj->efile.elf;
513 GElf_Ehdr *ep = &obj->efile.ehdr;
514 Elf_Scn *scn = NULL;
515 int idx = 0, err = 0;
517 /* Elf is corrupted/truncated, avoid calling elf_strptr. */
518 if (!elf_rawdata(elf_getscn(elf, ep->e_shstrndx), NULL)) {
519 pr_warning("failed to get e_shstrndx from %s\n",
520 obj->path);
521 return -LIBBPF_ERRNO__FORMAT;
524 while ((scn = elf_nextscn(elf, scn)) != NULL) {
525 char *name;
526 GElf_Shdr sh;
527 Elf_Data *data;
529 idx++;
530 if (gelf_getshdr(scn, &sh) != &sh) {
531 pr_warning("failed to get section header from %s\n",
532 obj->path);
533 err = -LIBBPF_ERRNO__FORMAT;
534 goto out;
537 name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
538 if (!name) {
539 pr_warning("failed to get section name from %s\n",
540 obj->path);
541 err = -LIBBPF_ERRNO__FORMAT;
542 goto out;
545 data = elf_getdata(scn, 0);
546 if (!data) {
547 pr_warning("failed to get section data from %s(%s)\n",
548 name, obj->path);
549 err = -LIBBPF_ERRNO__FORMAT;
550 goto out;
552 pr_debug("section %s, size %ld, link %d, flags %lx, type=%d\n",
553 name, (unsigned long)data->d_size,
554 (int)sh.sh_link, (unsigned long)sh.sh_flags,
555 (int)sh.sh_type);
557 if (strcmp(name, "license") == 0)
558 err = bpf_object__init_license(obj,
559 data->d_buf,
560 data->d_size);
561 else if (strcmp(name, "version") == 0)
562 err = bpf_object__init_kversion(obj,
563 data->d_buf,
564 data->d_size);
565 else if (strcmp(name, "maps") == 0)
566 err = bpf_object__init_maps(obj, data->d_buf,
567 data->d_size);
568 else if (sh.sh_type == SHT_SYMTAB) {
569 if (obj->efile.symbols) {
570 pr_warning("bpf: multiple SYMTAB in %s\n",
571 obj->path);
572 err = -LIBBPF_ERRNO__FORMAT;
573 } else
574 obj->efile.symbols = data;
575 } else if ((sh.sh_type == SHT_PROGBITS) &&
576 (sh.sh_flags & SHF_EXECINSTR) &&
577 (data->d_size > 0)) {
578 err = bpf_object__add_program(obj, data->d_buf,
579 data->d_size, name, idx);
580 if (err) {
581 char errmsg[STRERR_BUFSIZE];
583 strerror_r(-err, errmsg, sizeof(errmsg));
584 pr_warning("failed to alloc program %s (%s): %s",
585 name, obj->path, errmsg);
587 } else if (sh.sh_type == SHT_REL) {
588 void *reloc = obj->efile.reloc;
589 int nr_reloc = obj->efile.nr_reloc + 1;
591 reloc = realloc(reloc,
592 sizeof(*obj->efile.reloc) * nr_reloc);
593 if (!reloc) {
594 pr_warning("realloc failed\n");
595 err = -ENOMEM;
596 } else {
597 int n = nr_reloc - 1;
599 obj->efile.reloc = reloc;
600 obj->efile.nr_reloc = nr_reloc;
602 obj->efile.reloc[n].shdr = sh;
603 obj->efile.reloc[n].data = data;
606 if (err)
607 goto out;
609 out:
610 return err;
613 static struct bpf_program *
614 bpf_object__find_prog_by_idx(struct bpf_object *obj, int idx)
616 struct bpf_program *prog;
617 size_t i;
619 for (i = 0; i < obj->nr_programs; i++) {
620 prog = &obj->programs[i];
621 if (prog->idx == idx)
622 return prog;
624 return NULL;
627 static int
628 bpf_program__collect_reloc(struct bpf_program *prog,
629 size_t nr_maps, GElf_Shdr *shdr,
630 Elf_Data *data, Elf_Data *symbols)
632 int i, nrels;
634 pr_debug("collecting relocating info for: '%s'\n",
635 prog->section_name);
636 nrels = shdr->sh_size / shdr->sh_entsize;
638 prog->reloc_desc = malloc(sizeof(*prog->reloc_desc) * nrels);
639 if (!prog->reloc_desc) {
640 pr_warning("failed to alloc memory in relocation\n");
641 return -ENOMEM;
643 prog->nr_reloc = nrels;
645 for (i = 0; i < nrels; i++) {
646 GElf_Sym sym;
647 GElf_Rel rel;
648 unsigned int insn_idx;
649 struct bpf_insn *insns = prog->insns;
650 size_t map_idx;
652 if (!gelf_getrel(data, i, &rel)) {
653 pr_warning("relocation: failed to get %d reloc\n", i);
654 return -LIBBPF_ERRNO__FORMAT;
657 insn_idx = rel.r_offset / sizeof(struct bpf_insn);
658 pr_debug("relocation: insn_idx=%u\n", insn_idx);
660 if (!gelf_getsym(symbols,
661 GELF_R_SYM(rel.r_info),
662 &sym)) {
663 pr_warning("relocation: symbol %"PRIx64" not found\n",
664 GELF_R_SYM(rel.r_info));
665 return -LIBBPF_ERRNO__FORMAT;
668 if (insns[insn_idx].code != (BPF_LD | BPF_IMM | BPF_DW)) {
669 pr_warning("bpf: relocation: invalid relo for insns[%d].code 0x%x\n",
670 insn_idx, insns[insn_idx].code);
671 return -LIBBPF_ERRNO__RELOC;
674 map_idx = sym.st_value / sizeof(struct bpf_map_def);
675 if (map_idx >= nr_maps) {
676 pr_warning("bpf relocation: map_idx %d large than %d\n",
677 (int)map_idx, (int)nr_maps - 1);
678 return -LIBBPF_ERRNO__RELOC;
681 prog->reloc_desc[i].insn_idx = insn_idx;
682 prog->reloc_desc[i].map_idx = map_idx;
684 return 0;
687 static int
688 bpf_object__create_maps(struct bpf_object *obj)
690 unsigned int i;
691 size_t nr_maps;
692 int *pfd;
694 nr_maps = obj->maps_buf_sz / sizeof(struct bpf_map_def);
695 if (!obj->maps_buf || !nr_maps) {
696 pr_debug("don't need create maps for %s\n",
697 obj->path);
698 return 0;
701 obj->map_fds = malloc(sizeof(int) * nr_maps);
702 if (!obj->map_fds) {
703 pr_warning("realloc perf_bpf_map_fds failed\n");
704 return -ENOMEM;
706 obj->nr_map_fds = nr_maps;
708 /* fill all fd with -1 */
709 memset(obj->map_fds, -1, sizeof(int) * nr_maps);
711 pfd = obj->map_fds;
712 for (i = 0; i < nr_maps; i++) {
713 struct bpf_map_def def;
715 def = *(struct bpf_map_def *)(obj->maps_buf +
716 i * sizeof(struct bpf_map_def));
718 *pfd = bpf_create_map(def.type,
719 def.key_size,
720 def.value_size,
721 def.max_entries);
722 if (*pfd < 0) {
723 size_t j;
724 int err = *pfd;
726 pr_warning("failed to create map: %s\n",
727 strerror(errno));
728 for (j = 0; j < i; j++)
729 zclose(obj->map_fds[j]);
730 obj->nr_map_fds = 0;
731 zfree(&obj->map_fds);
732 return err;
734 pr_debug("create map: fd=%d\n", *pfd);
735 pfd++;
738 zfree(&obj->maps_buf);
739 obj->maps_buf_sz = 0;
740 return 0;
743 static int
744 bpf_program__relocate(struct bpf_program *prog, int *map_fds)
746 int i;
748 if (!prog || !prog->reloc_desc)
749 return 0;
751 for (i = 0; i < prog->nr_reloc; i++) {
752 int insn_idx, map_idx;
753 struct bpf_insn *insns = prog->insns;
755 insn_idx = prog->reloc_desc[i].insn_idx;
756 map_idx = prog->reloc_desc[i].map_idx;
758 if (insn_idx >= (int)prog->insns_cnt) {
759 pr_warning("relocation out of range: '%s'\n",
760 prog->section_name);
761 return -LIBBPF_ERRNO__RELOC;
763 insns[insn_idx].src_reg = BPF_PSEUDO_MAP_FD;
764 insns[insn_idx].imm = map_fds[map_idx];
767 zfree(&prog->reloc_desc);
768 prog->nr_reloc = 0;
769 return 0;
773 static int
774 bpf_object__relocate(struct bpf_object *obj)
776 struct bpf_program *prog;
777 size_t i;
778 int err;
780 for (i = 0; i < obj->nr_programs; i++) {
781 prog = &obj->programs[i];
783 err = bpf_program__relocate(prog, obj->map_fds);
784 if (err) {
785 pr_warning("failed to relocate '%s'\n",
786 prog->section_name);
787 return err;
790 return 0;
793 static int bpf_object__collect_reloc(struct bpf_object *obj)
795 int i, err;
797 if (!obj_elf_valid(obj)) {
798 pr_warning("Internal error: elf object is closed\n");
799 return -LIBBPF_ERRNO__INTERNAL;
802 for (i = 0; i < obj->efile.nr_reloc; i++) {
803 GElf_Shdr *shdr = &obj->efile.reloc[i].shdr;
804 Elf_Data *data = obj->efile.reloc[i].data;
805 int idx = shdr->sh_info;
806 struct bpf_program *prog;
807 size_t nr_maps = obj->maps_buf_sz /
808 sizeof(struct bpf_map_def);
810 if (shdr->sh_type != SHT_REL) {
811 pr_warning("internal error at %d\n", __LINE__);
812 return -LIBBPF_ERRNO__INTERNAL;
815 prog = bpf_object__find_prog_by_idx(obj, idx);
816 if (!prog) {
817 pr_warning("relocation failed: no %d section\n",
818 idx);
819 return -LIBBPF_ERRNO__RELOC;
822 err = bpf_program__collect_reloc(prog, nr_maps,
823 shdr, data,
824 obj->efile.symbols);
825 if (err)
826 return err;
828 return 0;
831 static int
832 load_program(struct bpf_insn *insns, int insns_cnt,
833 char *license, u32 kern_version, int *pfd)
835 int ret;
836 char *log_buf;
838 if (!insns || !insns_cnt)
839 return -EINVAL;
841 log_buf = malloc(BPF_LOG_BUF_SIZE);
842 if (!log_buf)
843 pr_warning("Alloc log buffer for bpf loader error, continue without log\n");
845 ret = bpf_load_program(BPF_PROG_TYPE_KPROBE, insns,
846 insns_cnt, license, kern_version,
847 log_buf, BPF_LOG_BUF_SIZE);
849 if (ret >= 0) {
850 *pfd = ret;
851 ret = 0;
852 goto out;
855 ret = -LIBBPF_ERRNO__LOAD;
856 pr_warning("load bpf program failed: %s\n", strerror(errno));
858 if (log_buf && log_buf[0] != '\0') {
859 ret = -LIBBPF_ERRNO__VERIFY;
860 pr_warning("-- BEGIN DUMP LOG ---\n");
861 pr_warning("\n%s\n", log_buf);
862 pr_warning("-- END LOG --\n");
863 } else {
864 if (insns_cnt >= BPF_MAXINSNS) {
865 pr_warning("Program too large (%d insns), at most %d insns\n",
866 insns_cnt, BPF_MAXINSNS);
867 ret = -LIBBPF_ERRNO__PROG2BIG;
868 } else if (log_buf) {
869 pr_warning("log buffer is empty\n");
870 ret = -LIBBPF_ERRNO__KVER;
874 out:
875 free(log_buf);
876 return ret;
879 static int
880 bpf_program__load(struct bpf_program *prog,
881 char *license, u32 kern_version)
883 int err = 0, fd, i;
885 if (prog->instances.nr < 0 || !prog->instances.fds) {
886 if (prog->preprocessor) {
887 pr_warning("Internal error: can't load program '%s'\n",
888 prog->section_name);
889 return -LIBBPF_ERRNO__INTERNAL;
892 prog->instances.fds = malloc(sizeof(int));
893 if (!prog->instances.fds) {
894 pr_warning("Not enough memory for BPF fds\n");
895 return -ENOMEM;
897 prog->instances.nr = 1;
898 prog->instances.fds[0] = -1;
901 if (!prog->preprocessor) {
902 if (prog->instances.nr != 1) {
903 pr_warning("Program '%s' is inconsistent: nr(%d) != 1\n",
904 prog->section_name, prog->instances.nr);
906 err = load_program(prog->insns, prog->insns_cnt,
907 license, kern_version, &fd);
908 if (!err)
909 prog->instances.fds[0] = fd;
910 goto out;
913 for (i = 0; i < prog->instances.nr; i++) {
914 struct bpf_prog_prep_result result;
915 bpf_program_prep_t preprocessor = prog->preprocessor;
917 bzero(&result, sizeof(result));
918 err = preprocessor(prog, i, prog->insns,
919 prog->insns_cnt, &result);
920 if (err) {
921 pr_warning("Preprocessing the %dth instance of program '%s' failed\n",
922 i, prog->section_name);
923 goto out;
926 if (!result.new_insn_ptr || !result.new_insn_cnt) {
927 pr_debug("Skip loading the %dth instance of program '%s'\n",
928 i, prog->section_name);
929 prog->instances.fds[i] = -1;
930 if (result.pfd)
931 *result.pfd = -1;
932 continue;
935 err = load_program(result.new_insn_ptr,
936 result.new_insn_cnt,
937 license, kern_version, &fd);
939 if (err) {
940 pr_warning("Loading the %dth instance of program '%s' failed\n",
941 i, prog->section_name);
942 goto out;
945 if (result.pfd)
946 *result.pfd = fd;
947 prog->instances.fds[i] = fd;
949 out:
950 if (err)
951 pr_warning("failed to load program '%s'\n",
952 prog->section_name);
953 zfree(&prog->insns);
954 prog->insns_cnt = 0;
955 return err;
958 static int
959 bpf_object__load_progs(struct bpf_object *obj)
961 size_t i;
962 int err;
964 for (i = 0; i < obj->nr_programs; i++) {
965 err = bpf_program__load(&obj->programs[i],
966 obj->license,
967 obj->kern_version);
968 if (err)
969 return err;
971 return 0;
974 static int bpf_object__validate(struct bpf_object *obj)
976 if (obj->kern_version == 0) {
977 pr_warning("%s doesn't provide kernel version\n",
978 obj->path);
979 return -LIBBPF_ERRNO__KVERSION;
981 return 0;
984 static struct bpf_object *
985 __bpf_object__open(const char *path, void *obj_buf, size_t obj_buf_sz)
987 struct bpf_object *obj;
988 int err;
990 if (elf_version(EV_CURRENT) == EV_NONE) {
991 pr_warning("failed to init libelf for %s\n", path);
992 return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
995 obj = bpf_object__new(path, obj_buf, obj_buf_sz);
996 if (IS_ERR(obj))
997 return obj;
999 CHECK_ERR(bpf_object__elf_init(obj), err, out);
1000 CHECK_ERR(bpf_object__check_endianness(obj), err, out);
1001 CHECK_ERR(bpf_object__elf_collect(obj), err, out);
1002 CHECK_ERR(bpf_object__collect_reloc(obj), err, out);
1003 CHECK_ERR(bpf_object__validate(obj), err, out);
1005 bpf_object__elf_finish(obj);
1006 return obj;
1007 out:
1008 bpf_object__close(obj);
1009 return ERR_PTR(err);
1012 struct bpf_object *bpf_object__open(const char *path)
1014 /* param validation */
1015 if (!path)
1016 return NULL;
1018 pr_debug("loading %s\n", path);
1020 return __bpf_object__open(path, NULL, 0);
1023 struct bpf_object *bpf_object__open_buffer(void *obj_buf,
1024 size_t obj_buf_sz,
1025 const char *name)
1027 char tmp_name[64];
1029 /* param validation */
1030 if (!obj_buf || obj_buf_sz <= 0)
1031 return NULL;
1033 if (!name) {
1034 snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
1035 (unsigned long)obj_buf,
1036 (unsigned long)obj_buf_sz);
1037 tmp_name[sizeof(tmp_name) - 1] = '\0';
1038 name = tmp_name;
1040 pr_debug("loading object '%s' from buffer\n",
1041 name);
1043 return __bpf_object__open(name, obj_buf, obj_buf_sz);
1046 int bpf_object__unload(struct bpf_object *obj)
1048 size_t i;
1050 if (!obj)
1051 return -EINVAL;
1053 for (i = 0; i < obj->nr_map_fds; i++)
1054 zclose(obj->map_fds[i]);
1055 zfree(&obj->map_fds);
1056 obj->nr_map_fds = 0;
1058 for (i = 0; i < obj->nr_programs; i++)
1059 bpf_program__unload(&obj->programs[i]);
1061 return 0;
1064 int bpf_object__load(struct bpf_object *obj)
1066 int err;
1068 if (!obj)
1069 return -EINVAL;
1071 if (obj->loaded) {
1072 pr_warning("object should not be loaded twice\n");
1073 return -EINVAL;
1076 obj->loaded = true;
1078 CHECK_ERR(bpf_object__create_maps(obj), err, out);
1079 CHECK_ERR(bpf_object__relocate(obj), err, out);
1080 CHECK_ERR(bpf_object__load_progs(obj), err, out);
1082 return 0;
1083 out:
1084 bpf_object__unload(obj);
1085 pr_warning("failed to load object '%s'\n", obj->path);
1086 return err;
1089 void bpf_object__close(struct bpf_object *obj)
1091 size_t i;
1093 if (!obj)
1094 return;
1096 bpf_object__elf_finish(obj);
1097 bpf_object__unload(obj);
1099 zfree(&obj->maps_buf);
1101 if (obj->programs && obj->nr_programs) {
1102 for (i = 0; i < obj->nr_programs; i++)
1103 bpf_program__exit(&obj->programs[i]);
1105 zfree(&obj->programs);
1107 list_del(&obj->list);
1108 free(obj);
1111 struct bpf_object *
1112 bpf_object__next(struct bpf_object *prev)
1114 struct bpf_object *next;
1116 if (!prev)
1117 next = list_first_entry(&bpf_objects_list,
1118 struct bpf_object,
1119 list);
1120 else
1121 next = list_next_entry(prev, list);
1123 /* Empty list is noticed here so don't need checking on entry. */
1124 if (&next->list == &bpf_objects_list)
1125 return NULL;
1127 return next;
1130 const char *
1131 bpf_object__get_name(struct bpf_object *obj)
1133 if (!obj)
1134 return ERR_PTR(-EINVAL);
1135 return obj->path;
1138 unsigned int
1139 bpf_object__get_kversion(struct bpf_object *obj)
1141 if (!obj)
1142 return 0;
1143 return obj->kern_version;
1146 struct bpf_program *
1147 bpf_program__next(struct bpf_program *prev, struct bpf_object *obj)
1149 size_t idx;
1151 if (!obj->programs)
1152 return NULL;
1153 /* First handler */
1154 if (prev == NULL)
1155 return &obj->programs[0];
1157 if (prev->obj != obj) {
1158 pr_warning("error: program handler doesn't match object\n");
1159 return NULL;
1162 idx = (prev - obj->programs) + 1;
1163 if (idx >= obj->nr_programs)
1164 return NULL;
1165 return &obj->programs[idx];
1168 int bpf_program__set_private(struct bpf_program *prog,
1169 void *priv,
1170 bpf_program_clear_priv_t clear_priv)
1172 if (prog->priv && prog->clear_priv)
1173 prog->clear_priv(prog, prog->priv);
1175 prog->priv = priv;
1176 prog->clear_priv = clear_priv;
1177 return 0;
1180 int bpf_program__get_private(struct bpf_program *prog, void **ppriv)
1182 *ppriv = prog->priv;
1183 return 0;
1186 const char *bpf_program__title(struct bpf_program *prog, bool needs_copy)
1188 const char *title;
1190 title = prog->section_name;
1191 if (needs_copy) {
1192 title = strdup(title);
1193 if (!title) {
1194 pr_warning("failed to strdup program title\n");
1195 return ERR_PTR(-ENOMEM);
1199 return title;
1202 int bpf_program__fd(struct bpf_program *prog)
1204 return bpf_program__nth_fd(prog, 0);
1207 int bpf_program__set_prep(struct bpf_program *prog, int nr_instances,
1208 bpf_program_prep_t prep)
1210 int *instances_fds;
1212 if (nr_instances <= 0 || !prep)
1213 return -EINVAL;
1215 if (prog->instances.nr > 0 || prog->instances.fds) {
1216 pr_warning("Can't set pre-processor after loading\n");
1217 return -EINVAL;
1220 instances_fds = malloc(sizeof(int) * nr_instances);
1221 if (!instances_fds) {
1222 pr_warning("alloc memory failed for fds\n");
1223 return -ENOMEM;
1226 /* fill all fd with -1 */
1227 memset(instances_fds, -1, sizeof(int) * nr_instances);
1229 prog->instances.nr = nr_instances;
1230 prog->instances.fds = instances_fds;
1231 prog->preprocessor = prep;
1232 return 0;
1235 int bpf_program__nth_fd(struct bpf_program *prog, int n)
1237 int fd;
1239 if (n >= prog->instances.nr || n < 0) {
1240 pr_warning("Can't get the %dth fd from program %s: only %d instances\n",
1241 n, prog->section_name, prog->instances.nr);
1242 return -EINVAL;
1245 fd = prog->instances.fds[n];
1246 if (fd < 0) {
1247 pr_warning("%dth instance of program '%s' is invalid\n",
1248 n, prog->section_name);
1249 return -ENOENT;
1252 return fd;