1 // SPDX-License-Identifier: LGPL-2.1
4 * Common eBPF ELF object loading operations.
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.
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!)
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.
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>
36 #include <asm/unistd.h>
37 #include <linux/err.h>
38 #include <linux/kernel.h>
39 #include <linux/bpf.h>
40 #include <linux/btf.h>
41 #include <linux/list.h>
42 #include <linux/limits.h>
44 #include <sys/types.h>
46 #include <tools/libc_compat.h>
59 #define BPF_FS_MAGIC 0xcafe4a11
62 #define __printf(a, b) __attribute__((format(printf, a, b)))
65 static int __base_pr(const char *format, ...)
70 va_start(args, format);
71 err = vfprintf(stderr, format, args);
76 static __printf(1, 2) libbpf_print_fn_t __pr_warning = __base_pr;
77 static __printf(1, 2) libbpf_print_fn_t __pr_info = __base_pr;
78 static __printf(1, 2) libbpf_print_fn_t __pr_debug;
80 #define __pr(func, fmt, ...) \
83 (func)("libbpf: " fmt, ##__VA_ARGS__); \
86 #define pr_warning(fmt, ...) __pr(__pr_warning, fmt, ##__VA_ARGS__)
87 #define pr_info(fmt, ...) __pr(__pr_info, fmt, ##__VA_ARGS__)
88 #define pr_debug(fmt, ...) __pr(__pr_debug, fmt, ##__VA_ARGS__)
90 void libbpf_set_print(libbpf_print_fn_t warn,
91 libbpf_print_fn_t info,
92 libbpf_print_fn_t debug)
99 #define STRERR_BUFSIZE 128
101 #define CHECK_ERR(action, err, out) do { \
108 /* Copied from tools/perf/util/util.h */
110 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
114 # define zclose(fd) ({ \
117 ___err = close((fd)); \
122 #ifdef HAVE_LIBELF_MMAP_SUPPORT
123 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ_MMAP
125 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ
129 * bpf_prog should be a better name but it has been used in
133 /* Index in elf obj file, for relocation use. */
138 struct bpf_insn *insns;
139 size_t insns_cnt, main_prog_cnt;
140 enum bpf_prog_type type;
159 bpf_program_prep_t preprocessor;
161 struct bpf_object *obj;
163 bpf_program_clear_priv_t clear_priv;
165 enum bpf_attach_type expected_attach_type;
173 struct bpf_map_def def;
174 __u32 btf_key_type_id;
175 __u32 btf_value_type_id;
177 bpf_map_clear_priv_t clear_priv;
180 static LIST_HEAD(bpf_objects_list);
186 struct bpf_program *programs;
188 struct bpf_map *maps;
192 bool has_pseudo_calls;
195 * Information when doing elf related work. Only valid if fd
215 * All loaded bpf_object is linked in a list, which is
216 * hidden to caller. bpf_objects__<func> handlers deal with
219 struct list_head list;
224 bpf_object_clear_priv_t clear_priv;
228 #define obj_elf_valid(o) ((o)->efile.elf)
230 static void bpf_program__unload(struct bpf_program *prog)
238 * If the object is opened but the program was never loaded,
239 * it is possible that prog->instances.nr == -1.
241 if (prog->instances.nr > 0) {
242 for (i = 0; i < prog->instances.nr; i++)
243 zclose(prog->instances.fds[i]);
244 } else if (prog->instances.nr != -1) {
245 pr_warning("Internal error: instances.nr is %d\n",
249 prog->instances.nr = -1;
250 zfree(&prog->instances.fds);
253 static void bpf_program__exit(struct bpf_program *prog)
258 if (prog->clear_priv)
259 prog->clear_priv(prog, prog->priv);
262 prog->clear_priv = NULL;
264 bpf_program__unload(prog);
266 zfree(&prog->section_name);
268 zfree(&prog->reloc_desc);
276 bpf_program__init(void *data, size_t size, char *section_name, int idx,
277 struct bpf_program *prog)
279 if (size < sizeof(struct bpf_insn)) {
280 pr_warning("corrupted section '%s'\n", section_name);
284 bzero(prog, sizeof(*prog));
286 prog->section_name = strdup(section_name);
287 if (!prog->section_name) {
288 pr_warning("failed to alloc name for prog under section(%d) %s\n",
293 prog->insns = malloc(size);
295 pr_warning("failed to alloc insns for prog under section %s\n",
299 prog->insns_cnt = size / sizeof(struct bpf_insn);
300 memcpy(prog->insns, data,
301 prog->insns_cnt * sizeof(struct bpf_insn));
303 prog->instances.fds = NULL;
304 prog->instances.nr = -1;
305 prog->type = BPF_PROG_TYPE_KPROBE;
309 bpf_program__exit(prog);
314 bpf_object__add_program(struct bpf_object *obj, void *data, size_t size,
315 char *section_name, int idx)
317 struct bpf_program prog, *progs;
320 err = bpf_program__init(data, size, section_name, idx, &prog);
324 progs = obj->programs;
325 nr_progs = obj->nr_programs;
327 progs = reallocarray(progs, nr_progs + 1, sizeof(progs[0]));
330 * In this case the original obj->programs
331 * is still valid, so don't need special treat for
332 * bpf_close_object().
334 pr_warning("failed to alloc a new program under section '%s'\n",
336 bpf_program__exit(&prog);
340 pr_debug("found program %s\n", prog.section_name);
341 obj->programs = progs;
342 obj->nr_programs = nr_progs + 1;
344 progs[nr_progs] = prog;
349 bpf_object__init_prog_names(struct bpf_object *obj)
351 Elf_Data *symbols = obj->efile.symbols;
352 struct bpf_program *prog;
355 for (pi = 0; pi < obj->nr_programs; pi++) {
356 const char *name = NULL;
358 prog = &obj->programs[pi];
360 for (si = 0; si < symbols->d_size / sizeof(GElf_Sym) && !name;
364 if (!gelf_getsym(symbols, si, &sym))
366 if (sym.st_shndx != prog->idx)
368 if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL)
371 name = elf_strptr(obj->efile.elf,
372 obj->efile.strtabidx,
375 pr_warning("failed to get sym name string for prog %s\n",
377 return -LIBBPF_ERRNO__LIBELF;
381 if (!name && prog->idx == obj->efile.text_shndx)
385 pr_warning("failed to find sym for prog %s\n",
390 prog->name = strdup(name);
392 pr_warning("failed to allocate memory for prog sym %s\n",
401 static struct bpf_object *bpf_object__new(const char *path,
405 struct bpf_object *obj;
407 obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
409 pr_warning("alloc memory failed for %s\n", path);
410 return ERR_PTR(-ENOMEM);
413 strcpy(obj->path, path);
417 * Caller of this function should also calls
418 * bpf_object__elf_finish() after data collection to return
419 * obj_buf to user. If not, we should duplicate the buffer to
420 * avoid user freeing them before elf finish.
422 obj->efile.obj_buf = obj_buf;
423 obj->efile.obj_buf_sz = obj_buf_sz;
424 obj->efile.maps_shndx = -1;
428 INIT_LIST_HEAD(&obj->list);
429 list_add(&obj->list, &bpf_objects_list);
433 static void bpf_object__elf_finish(struct bpf_object *obj)
435 if (!obj_elf_valid(obj))
438 if (obj->efile.elf) {
439 elf_end(obj->efile.elf);
440 obj->efile.elf = NULL;
442 obj->efile.symbols = NULL;
444 zfree(&obj->efile.reloc);
445 obj->efile.nr_reloc = 0;
446 zclose(obj->efile.fd);
447 obj->efile.obj_buf = NULL;
448 obj->efile.obj_buf_sz = 0;
451 static int bpf_object__elf_init(struct bpf_object *obj)
456 if (obj_elf_valid(obj)) {
457 pr_warning("elf init: internal error\n");
458 return -LIBBPF_ERRNO__LIBELF;
461 if (obj->efile.obj_buf_sz > 0) {
463 * obj_buf should have been validated by
464 * bpf_object__open_buffer().
466 obj->efile.elf = elf_memory(obj->efile.obj_buf,
467 obj->efile.obj_buf_sz);
469 obj->efile.fd = open(obj->path, O_RDONLY);
470 if (obj->efile.fd < 0) {
471 char errmsg[STRERR_BUFSIZE];
472 char *cp = strerror_r(errno, errmsg, sizeof(errmsg));
474 pr_warning("failed to open %s: %s\n", obj->path, cp);
478 obj->efile.elf = elf_begin(obj->efile.fd,
479 LIBBPF_ELF_C_READ_MMAP,
483 if (!obj->efile.elf) {
484 pr_warning("failed to open %s as ELF file\n",
486 err = -LIBBPF_ERRNO__LIBELF;
490 if (!gelf_getehdr(obj->efile.elf, &obj->efile.ehdr)) {
491 pr_warning("failed to get EHDR from %s\n",
493 err = -LIBBPF_ERRNO__FORMAT;
496 ep = &obj->efile.ehdr;
498 /* Old LLVM set e_machine to EM_NONE */
499 if ((ep->e_type != ET_REL) || (ep->e_machine && (ep->e_machine != EM_BPF))) {
500 pr_warning("%s is not an eBPF object file\n",
502 err = -LIBBPF_ERRNO__FORMAT;
508 bpf_object__elf_finish(obj);
513 bpf_object__check_endianness(struct bpf_object *obj)
515 static unsigned int const endian = 1;
517 switch (obj->efile.ehdr.e_ident[EI_DATA]) {
519 /* We are big endian, BPF obj is little endian. */
520 if (*(unsigned char const *)&endian != 1)
525 /* We are little endian, BPF obj is big endian. */
526 if (*(unsigned char const *)&endian != 0)
530 return -LIBBPF_ERRNO__ENDIAN;
536 pr_warning("Error: endianness mismatch.\n");
537 return -LIBBPF_ERRNO__ENDIAN;
541 bpf_object__init_license(struct bpf_object *obj,
542 void *data, size_t size)
544 memcpy(obj->license, data,
545 min(size, sizeof(obj->license) - 1));
546 pr_debug("license of %s is %s\n", obj->path, obj->license);
551 bpf_object__init_kversion(struct bpf_object *obj,
552 void *data, size_t size)
556 if (size != sizeof(kver)) {
557 pr_warning("invalid kver section in %s\n", obj->path);
558 return -LIBBPF_ERRNO__FORMAT;
560 memcpy(&kver, data, sizeof(kver));
561 obj->kern_version = kver;
562 pr_debug("kernel version of %s is %x\n", obj->path,
567 static int compare_bpf_map(const void *_a, const void *_b)
569 const struct bpf_map *a = _a;
570 const struct bpf_map *b = _b;
572 return a->offset - b->offset;
576 bpf_object__init_maps(struct bpf_object *obj)
578 int i, map_idx, map_def_sz, nr_maps = 0;
581 Elf_Data *symbols = obj->efile.symbols;
583 if (obj->efile.maps_shndx < 0)
588 scn = elf_getscn(obj->efile.elf, obj->efile.maps_shndx);
590 data = elf_getdata(scn, NULL);
592 pr_warning("failed to get Elf_Data from map section %d\n",
593 obj->efile.maps_shndx);
598 * Count number of maps. Each map has a name.
599 * Array of maps is not supported: only the first element is
602 * TODO: Detect array of map and report error.
604 for (i = 0; i < symbols->d_size / sizeof(GElf_Sym); i++) {
607 if (!gelf_getsym(symbols, i, &sym))
609 if (sym.st_shndx != obj->efile.maps_shndx)
614 /* Alloc obj->maps and fill nr_maps. */
615 pr_debug("maps in %s: %d maps in %zd bytes\n", obj->path,
616 nr_maps, data->d_size);
621 /* Assume equally sized map definitions */
622 map_def_sz = data->d_size / nr_maps;
623 if (!data->d_size || (data->d_size % nr_maps) != 0) {
624 pr_warning("unable to determine map definition size "
625 "section %s, %d maps in %zd bytes\n",
626 obj->path, nr_maps, data->d_size);
630 obj->maps = calloc(nr_maps, sizeof(obj->maps[0]));
632 pr_warning("alloc maps for object failed\n");
635 obj->nr_maps = nr_maps;
638 * fill all fd with -1 so won't close incorrect
639 * fd (fd=0 is stdin) when failure (zclose won't close
642 for (i = 0; i < nr_maps; i++)
643 obj->maps[i].fd = -1;
646 * Fill obj->maps using data in "maps" section.
648 for (i = 0, map_idx = 0; i < symbols->d_size / sizeof(GElf_Sym); i++) {
650 const char *map_name;
651 struct bpf_map_def *def;
653 if (!gelf_getsym(symbols, i, &sym))
655 if (sym.st_shndx != obj->efile.maps_shndx)
658 map_name = elf_strptr(obj->efile.elf,
659 obj->efile.strtabidx,
661 obj->maps[map_idx].offset = sym.st_value;
662 if (sym.st_value + map_def_sz > data->d_size) {
663 pr_warning("corrupted maps section in %s: last map \"%s\" too small\n",
664 obj->path, map_name);
668 obj->maps[map_idx].name = strdup(map_name);
669 if (!obj->maps[map_idx].name) {
670 pr_warning("failed to alloc map name\n");
673 pr_debug("map %d is \"%s\"\n", map_idx,
674 obj->maps[map_idx].name);
675 def = (struct bpf_map_def *)(data->d_buf + sym.st_value);
677 * If the definition of the map in the object file fits in
678 * bpf_map_def, copy it. Any extra fields in our version
679 * of bpf_map_def will default to zero as a result of the
682 if (map_def_sz <= sizeof(struct bpf_map_def)) {
683 memcpy(&obj->maps[map_idx].def, def, map_def_sz);
686 * Here the map structure being read is bigger than what
687 * we expect, truncate if the excess bits are all zero.
688 * If they are not zero, reject this map as
692 for (b = ((char *)def) + sizeof(struct bpf_map_def);
693 b < ((char *)def) + map_def_sz; b++) {
695 pr_warning("maps section in %s: \"%s\" "
696 "has unrecognized, non-zero "
698 obj->path, map_name);
702 memcpy(&obj->maps[map_idx].def, def,
703 sizeof(struct bpf_map_def));
708 qsort(obj->maps, obj->nr_maps, sizeof(obj->maps[0]), compare_bpf_map);
712 static bool section_have_execinstr(struct bpf_object *obj, int idx)
717 scn = elf_getscn(obj->efile.elf, idx);
721 if (gelf_getshdr(scn, &sh) != &sh)
724 if (sh.sh_flags & SHF_EXECINSTR)
730 static int bpf_object__elf_collect(struct bpf_object *obj)
732 Elf *elf = obj->efile.elf;
733 GElf_Ehdr *ep = &obj->efile.ehdr;
735 int idx = 0, err = 0;
737 /* Elf is corrupted/truncated, avoid calling elf_strptr. */
738 if (!elf_rawdata(elf_getscn(elf, ep->e_shstrndx), NULL)) {
739 pr_warning("failed to get e_shstrndx from %s\n",
741 return -LIBBPF_ERRNO__FORMAT;
744 while ((scn = elf_nextscn(elf, scn)) != NULL) {
750 if (gelf_getshdr(scn, &sh) != &sh) {
751 pr_warning("failed to get section(%d) header from %s\n",
753 err = -LIBBPF_ERRNO__FORMAT;
757 name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
759 pr_warning("failed to get section(%d) name from %s\n",
761 err = -LIBBPF_ERRNO__FORMAT;
765 data = elf_getdata(scn, 0);
767 pr_warning("failed to get section(%d) data from %s(%s)\n",
768 idx, name, obj->path);
769 err = -LIBBPF_ERRNO__FORMAT;
772 pr_debug("section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
773 idx, name, (unsigned long)data->d_size,
774 (int)sh.sh_link, (unsigned long)sh.sh_flags,
777 if (strcmp(name, "license") == 0)
778 err = bpf_object__init_license(obj,
781 else if (strcmp(name, "version") == 0)
782 err = bpf_object__init_kversion(obj,
785 else if (strcmp(name, "maps") == 0)
786 obj->efile.maps_shndx = idx;
787 else if (strcmp(name, BTF_ELF_SEC) == 0) {
788 obj->btf = btf__new(data->d_buf, data->d_size,
790 if (IS_ERR(obj->btf)) {
791 pr_warning("Error loading ELF section %s: %ld. Ignored and continue.\n",
792 BTF_ELF_SEC, PTR_ERR(obj->btf));
795 } else if (sh.sh_type == SHT_SYMTAB) {
796 if (obj->efile.symbols) {
797 pr_warning("bpf: multiple SYMTAB in %s\n",
799 err = -LIBBPF_ERRNO__FORMAT;
801 obj->efile.symbols = data;
802 obj->efile.strtabidx = sh.sh_link;
804 } else if ((sh.sh_type == SHT_PROGBITS) &&
805 (sh.sh_flags & SHF_EXECINSTR) &&
806 (data->d_size > 0)) {
807 if (strcmp(name, ".text") == 0)
808 obj->efile.text_shndx = idx;
809 err = bpf_object__add_program(obj, data->d_buf,
810 data->d_size, name, idx);
812 char errmsg[STRERR_BUFSIZE];
813 char *cp = strerror_r(-err, errmsg,
816 pr_warning("failed to alloc program %s (%s): %s",
817 name, obj->path, cp);
819 } else if (sh.sh_type == SHT_REL) {
820 void *reloc = obj->efile.reloc;
821 int nr_reloc = obj->efile.nr_reloc + 1;
822 int sec = sh.sh_info; /* points to other section */
824 /* Only do relo for section with exec instructions */
825 if (!section_have_execinstr(obj, sec)) {
826 pr_debug("skip relo %s(%d) for section(%d)\n",
831 reloc = reallocarray(reloc, nr_reloc,
832 sizeof(*obj->efile.reloc));
834 pr_warning("realloc failed\n");
837 int n = nr_reloc - 1;
839 obj->efile.reloc = reloc;
840 obj->efile.nr_reloc = nr_reloc;
842 obj->efile.reloc[n].shdr = sh;
843 obj->efile.reloc[n].data = data;
846 pr_debug("skip section(%d) %s\n", idx, name);
852 if (!obj->efile.strtabidx || obj->efile.strtabidx >= idx) {
853 pr_warning("Corrupted ELF file: index of strtab invalid\n");
854 return LIBBPF_ERRNO__FORMAT;
856 if (obj->efile.maps_shndx >= 0) {
857 err = bpf_object__init_maps(obj);
861 err = bpf_object__init_prog_names(obj);
866 static struct bpf_program *
867 bpf_object__find_prog_by_idx(struct bpf_object *obj, int idx)
869 struct bpf_program *prog;
872 for (i = 0; i < obj->nr_programs; i++) {
873 prog = &obj->programs[i];
874 if (prog->idx == idx)
881 bpf_object__find_program_by_title(struct bpf_object *obj, const char *title)
883 struct bpf_program *pos;
885 bpf_object__for_each_program(pos, obj) {
886 if (pos->section_name && !strcmp(pos->section_name, title))
893 bpf_program__collect_reloc(struct bpf_program *prog, GElf_Shdr *shdr,
894 Elf_Data *data, struct bpf_object *obj)
896 Elf_Data *symbols = obj->efile.symbols;
897 int text_shndx = obj->efile.text_shndx;
898 int maps_shndx = obj->efile.maps_shndx;
899 struct bpf_map *maps = obj->maps;
900 size_t nr_maps = obj->nr_maps;
903 pr_debug("collecting relocating info for: '%s'\n",
905 nrels = shdr->sh_size / shdr->sh_entsize;
907 prog->reloc_desc = malloc(sizeof(*prog->reloc_desc) * nrels);
908 if (!prog->reloc_desc) {
909 pr_warning("failed to alloc memory in relocation\n");
912 prog->nr_reloc = nrels;
914 for (i = 0; i < nrels; i++) {
917 unsigned int insn_idx;
918 struct bpf_insn *insns = prog->insns;
921 if (!gelf_getrel(data, i, &rel)) {
922 pr_warning("relocation: failed to get %d reloc\n", i);
923 return -LIBBPF_ERRNO__FORMAT;
926 if (!gelf_getsym(symbols,
927 GELF_R_SYM(rel.r_info),
929 pr_warning("relocation: symbol %"PRIx64" not found\n",
930 GELF_R_SYM(rel.r_info));
931 return -LIBBPF_ERRNO__FORMAT;
933 pr_debug("relo for %lld value %lld name %d\n",
934 (long long) (rel.r_info >> 32),
935 (long long) sym.st_value, sym.st_name);
937 if (sym.st_shndx != maps_shndx && sym.st_shndx != text_shndx) {
938 pr_warning("Program '%s' contains non-map related relo data pointing to section %u\n",
939 prog->section_name, sym.st_shndx);
940 return -LIBBPF_ERRNO__RELOC;
943 insn_idx = rel.r_offset / sizeof(struct bpf_insn);
944 pr_debug("relocation: insn_idx=%u\n", insn_idx);
946 if (insns[insn_idx].code == (BPF_JMP | BPF_CALL)) {
947 if (insns[insn_idx].src_reg != BPF_PSEUDO_CALL) {
948 pr_warning("incorrect bpf_call opcode\n");
949 return -LIBBPF_ERRNO__RELOC;
951 prog->reloc_desc[i].type = RELO_CALL;
952 prog->reloc_desc[i].insn_idx = insn_idx;
953 prog->reloc_desc[i].text_off = sym.st_value;
954 obj->has_pseudo_calls = true;
958 if (insns[insn_idx].code != (BPF_LD | BPF_IMM | BPF_DW)) {
959 pr_warning("bpf: relocation: invalid relo for insns[%d].code 0x%x\n",
960 insn_idx, insns[insn_idx].code);
961 return -LIBBPF_ERRNO__RELOC;
964 /* TODO: 'maps' is sorted. We can use bsearch to make it faster. */
965 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
966 if (maps[map_idx].offset == sym.st_value) {
967 pr_debug("relocation: find map %zd (%s) for insn %u\n",
968 map_idx, maps[map_idx].name, insn_idx);
973 if (map_idx >= nr_maps) {
974 pr_warning("bpf relocation: map_idx %d large than %d\n",
975 (int)map_idx, (int)nr_maps - 1);
976 return -LIBBPF_ERRNO__RELOC;
979 prog->reloc_desc[i].type = RELO_LD64;
980 prog->reloc_desc[i].insn_idx = insn_idx;
981 prog->reloc_desc[i].map_idx = map_idx;
986 static int bpf_map_find_btf_info(struct bpf_map *map, const struct btf *btf)
988 const struct btf_type *container_type;
989 const struct btf_member *key, *value;
990 struct bpf_map_def *def = &map->def;
991 const size_t max_name = 256;
992 char container_name[max_name];
993 __s64 key_size, value_size;
996 if (snprintf(container_name, max_name, "____btf_map_%s", map->name) ==
998 pr_warning("map:%s length of '____btf_map_%s' is too long\n",
999 map->name, map->name);
1003 container_id = btf__find_by_name(btf, container_name);
1004 if (container_id < 0) {
1005 pr_debug("map:%s container_name:%s cannot be found in BTF. Missing BPF_ANNOTATE_KV_PAIR?\n",
1006 map->name, container_name);
1007 return container_id;
1010 container_type = btf__type_by_id(btf, container_id);
1011 if (!container_type) {
1012 pr_warning("map:%s cannot find BTF type for container_id:%u\n",
1013 map->name, container_id);
1017 if (BTF_INFO_KIND(container_type->info) != BTF_KIND_STRUCT ||
1018 BTF_INFO_VLEN(container_type->info) < 2) {
1019 pr_warning("map:%s container_name:%s is an invalid container struct\n",
1020 map->name, container_name);
1024 key = (struct btf_member *)(container_type + 1);
1027 key_size = btf__resolve_size(btf, key->type);
1029 pr_warning("map:%s invalid BTF key_type_size\n",
1034 if (def->key_size != key_size) {
1035 pr_warning("map:%s btf_key_type_size:%u != map_def_key_size:%u\n",
1036 map->name, (__u32)key_size, def->key_size);
1040 value_size = btf__resolve_size(btf, value->type);
1041 if (value_size < 0) {
1042 pr_warning("map:%s invalid BTF value_type_size\n", map->name);
1046 if (def->value_size != value_size) {
1047 pr_warning("map:%s btf_value_type_size:%u != map_def_value_size:%u\n",
1048 map->name, (__u32)value_size, def->value_size);
1052 map->btf_key_type_id = key->type;
1053 map->btf_value_type_id = value->type;
1058 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
1060 struct bpf_map_info info = {};
1061 __u32 len = sizeof(info);
1065 err = bpf_obj_get_info_by_fd(fd, &info, &len);
1069 new_name = strdup(info.name);
1073 new_fd = open("/", O_RDONLY | O_CLOEXEC);
1075 goto err_free_new_name;
1077 new_fd = dup3(fd, new_fd, O_CLOEXEC);
1079 goto err_close_new_fd;
1081 err = zclose(map->fd);
1083 goto err_close_new_fd;
1087 map->name = new_name;
1088 map->def.type = info.type;
1089 map->def.key_size = info.key_size;
1090 map->def.value_size = info.value_size;
1091 map->def.max_entries = info.max_entries;
1092 map->def.map_flags = info.map_flags;
1093 map->btf_key_type_id = info.btf_key_type_id;
1094 map->btf_value_type_id = info.btf_value_type_id;
1106 bpf_object__create_maps(struct bpf_object *obj)
1108 struct bpf_create_map_attr create_attr = {};
1112 for (i = 0; i < obj->nr_maps; i++) {
1113 struct bpf_map *map = &obj->maps[i];
1114 struct bpf_map_def *def = &map->def;
1115 char *cp, errmsg[STRERR_BUFSIZE];
1116 int *pfd = &map->fd;
1119 pr_debug("skip map create (preset) %s: fd=%d\n",
1120 map->name, map->fd);
1124 create_attr.name = map->name;
1125 create_attr.map_ifindex = map->map_ifindex;
1126 create_attr.map_type = def->type;
1127 create_attr.map_flags = def->map_flags;
1128 create_attr.key_size = def->key_size;
1129 create_attr.value_size = def->value_size;
1130 create_attr.max_entries = def->max_entries;
1131 create_attr.btf_fd = 0;
1132 create_attr.btf_key_type_id = 0;
1133 create_attr.btf_value_type_id = 0;
1135 if (obj->btf && !bpf_map_find_btf_info(map, obj->btf)) {
1136 create_attr.btf_fd = btf__fd(obj->btf);
1137 create_attr.btf_key_type_id = map->btf_key_type_id;
1138 create_attr.btf_value_type_id = map->btf_value_type_id;
1141 *pfd = bpf_create_map_xattr(&create_attr);
1142 if (*pfd < 0 && create_attr.btf_key_type_id) {
1143 cp = strerror_r(errno, errmsg, sizeof(errmsg));
1144 pr_warning("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
1145 map->name, cp, errno);
1146 create_attr.btf_fd = 0;
1147 create_attr.btf_key_type_id = 0;
1148 create_attr.btf_value_type_id = 0;
1149 map->btf_key_type_id = 0;
1150 map->btf_value_type_id = 0;
1151 *pfd = bpf_create_map_xattr(&create_attr);
1158 cp = strerror_r(errno, errmsg, sizeof(errmsg));
1159 pr_warning("failed to create map (name: '%s'): %s\n",
1161 for (j = 0; j < i; j++)
1162 zclose(obj->maps[j].fd);
1165 pr_debug("create map %s: fd=%d\n", map->name, *pfd);
1172 bpf_program__reloc_text(struct bpf_program *prog, struct bpf_object *obj,
1173 struct reloc_desc *relo)
1175 struct bpf_insn *insn, *new_insn;
1176 struct bpf_program *text;
1179 if (relo->type != RELO_CALL)
1180 return -LIBBPF_ERRNO__RELOC;
1182 if (prog->idx == obj->efile.text_shndx) {
1183 pr_warning("relo in .text insn %d into off %d\n",
1184 relo->insn_idx, relo->text_off);
1185 return -LIBBPF_ERRNO__RELOC;
1188 if (prog->main_prog_cnt == 0) {
1189 text = bpf_object__find_prog_by_idx(obj, obj->efile.text_shndx);
1191 pr_warning("no .text section found yet relo into text exist\n");
1192 return -LIBBPF_ERRNO__RELOC;
1194 new_cnt = prog->insns_cnt + text->insns_cnt;
1195 new_insn = reallocarray(prog->insns, new_cnt, sizeof(*insn));
1197 pr_warning("oom in prog realloc\n");
1200 memcpy(new_insn + prog->insns_cnt, text->insns,
1201 text->insns_cnt * sizeof(*insn));
1202 prog->insns = new_insn;
1203 prog->main_prog_cnt = prog->insns_cnt;
1204 prog->insns_cnt = new_cnt;
1205 pr_debug("added %zd insn from %s to prog %s\n",
1206 text->insns_cnt, text->section_name,
1207 prog->section_name);
1209 insn = &prog->insns[relo->insn_idx];
1210 insn->imm += prog->main_prog_cnt - relo->insn_idx;
1215 bpf_program__relocate(struct bpf_program *prog, struct bpf_object *obj)
1219 if (!prog || !prog->reloc_desc)
1222 for (i = 0; i < prog->nr_reloc; i++) {
1223 if (prog->reloc_desc[i].type == RELO_LD64) {
1224 struct bpf_insn *insns = prog->insns;
1225 int insn_idx, map_idx;
1227 insn_idx = prog->reloc_desc[i].insn_idx;
1228 map_idx = prog->reloc_desc[i].map_idx;
1230 if (insn_idx >= (int)prog->insns_cnt) {
1231 pr_warning("relocation out of range: '%s'\n",
1232 prog->section_name);
1233 return -LIBBPF_ERRNO__RELOC;
1235 insns[insn_idx].src_reg = BPF_PSEUDO_MAP_FD;
1236 insns[insn_idx].imm = obj->maps[map_idx].fd;
1238 err = bpf_program__reloc_text(prog, obj,
1239 &prog->reloc_desc[i]);
1245 zfree(&prog->reloc_desc);
1252 bpf_object__relocate(struct bpf_object *obj)
1254 struct bpf_program *prog;
1258 for (i = 0; i < obj->nr_programs; i++) {
1259 prog = &obj->programs[i];
1261 err = bpf_program__relocate(prog, obj);
1263 pr_warning("failed to relocate '%s'\n",
1264 prog->section_name);
1271 static int bpf_object__collect_reloc(struct bpf_object *obj)
1275 if (!obj_elf_valid(obj)) {
1276 pr_warning("Internal error: elf object is closed\n");
1277 return -LIBBPF_ERRNO__INTERNAL;
1280 for (i = 0; i < obj->efile.nr_reloc; i++) {
1281 GElf_Shdr *shdr = &obj->efile.reloc[i].shdr;
1282 Elf_Data *data = obj->efile.reloc[i].data;
1283 int idx = shdr->sh_info;
1284 struct bpf_program *prog;
1286 if (shdr->sh_type != SHT_REL) {
1287 pr_warning("internal error at %d\n", __LINE__);
1288 return -LIBBPF_ERRNO__INTERNAL;
1291 prog = bpf_object__find_prog_by_idx(obj, idx);
1293 pr_warning("relocation failed: no section(%d)\n", idx);
1294 return -LIBBPF_ERRNO__RELOC;
1297 err = bpf_program__collect_reloc(prog,
1307 load_program(enum bpf_prog_type type, enum bpf_attach_type expected_attach_type,
1308 const char *name, struct bpf_insn *insns, int insns_cnt,
1309 char *license, u32 kern_version, int *pfd, int prog_ifindex)
1311 struct bpf_load_program_attr load_attr;
1312 char *cp, errmsg[STRERR_BUFSIZE];
1316 memset(&load_attr, 0, sizeof(struct bpf_load_program_attr));
1317 load_attr.prog_type = type;
1318 load_attr.expected_attach_type = expected_attach_type;
1319 load_attr.name = name;
1320 load_attr.insns = insns;
1321 load_attr.insns_cnt = insns_cnt;
1322 load_attr.license = license;
1323 load_attr.kern_version = kern_version;
1324 load_attr.prog_ifindex = prog_ifindex;
1326 if (!load_attr.insns || !load_attr.insns_cnt)
1329 log_buf = malloc(BPF_LOG_BUF_SIZE);
1331 pr_warning("Alloc log buffer for bpf loader error, continue without log\n");
1333 ret = bpf_load_program_xattr(&load_attr, log_buf, BPF_LOG_BUF_SIZE);
1341 ret = -LIBBPF_ERRNO__LOAD;
1342 cp = strerror_r(errno, errmsg, sizeof(errmsg));
1343 pr_warning("load bpf program failed: %s\n", cp);
1345 if (log_buf && log_buf[0] != '\0') {
1346 ret = -LIBBPF_ERRNO__VERIFY;
1347 pr_warning("-- BEGIN DUMP LOG ---\n");
1348 pr_warning("\n%s\n", log_buf);
1349 pr_warning("-- END LOG --\n");
1350 } else if (load_attr.insns_cnt >= BPF_MAXINSNS) {
1351 pr_warning("Program too large (%zu insns), at most %d insns\n",
1352 load_attr.insns_cnt, BPF_MAXINSNS);
1353 ret = -LIBBPF_ERRNO__PROG2BIG;
1355 /* Wrong program type? */
1356 if (load_attr.prog_type != BPF_PROG_TYPE_KPROBE) {
1359 load_attr.prog_type = BPF_PROG_TYPE_KPROBE;
1360 load_attr.expected_attach_type = 0;
1361 fd = bpf_load_program_xattr(&load_attr, NULL, 0);
1364 ret = -LIBBPF_ERRNO__PROGTYPE;
1370 ret = -LIBBPF_ERRNO__KVER;
1379 bpf_program__load(struct bpf_program *prog,
1380 char *license, u32 kern_version)
1384 if (prog->instances.nr < 0 || !prog->instances.fds) {
1385 if (prog->preprocessor) {
1386 pr_warning("Internal error: can't load program '%s'\n",
1387 prog->section_name);
1388 return -LIBBPF_ERRNO__INTERNAL;
1391 prog->instances.fds = malloc(sizeof(int));
1392 if (!prog->instances.fds) {
1393 pr_warning("Not enough memory for BPF fds\n");
1396 prog->instances.nr = 1;
1397 prog->instances.fds[0] = -1;
1400 if (!prog->preprocessor) {
1401 if (prog->instances.nr != 1) {
1402 pr_warning("Program '%s' is inconsistent: nr(%d) != 1\n",
1403 prog->section_name, prog->instances.nr);
1405 err = load_program(prog->type, prog->expected_attach_type,
1406 prog->name, prog->insns, prog->insns_cnt,
1407 license, kern_version, &fd,
1408 prog->prog_ifindex);
1410 prog->instances.fds[0] = fd;
1414 for (i = 0; i < prog->instances.nr; i++) {
1415 struct bpf_prog_prep_result result;
1416 bpf_program_prep_t preprocessor = prog->preprocessor;
1418 bzero(&result, sizeof(result));
1419 err = preprocessor(prog, i, prog->insns,
1420 prog->insns_cnt, &result);
1422 pr_warning("Preprocessing the %dth instance of program '%s' failed\n",
1423 i, prog->section_name);
1427 if (!result.new_insn_ptr || !result.new_insn_cnt) {
1428 pr_debug("Skip loading the %dth instance of program '%s'\n",
1429 i, prog->section_name);
1430 prog->instances.fds[i] = -1;
1436 err = load_program(prog->type, prog->expected_attach_type,
1437 prog->name, result.new_insn_ptr,
1438 result.new_insn_cnt,
1439 license, kern_version, &fd,
1440 prog->prog_ifindex);
1443 pr_warning("Loading the %dth instance of program '%s' failed\n",
1444 i, prog->section_name);
1450 prog->instances.fds[i] = fd;
1454 pr_warning("failed to load program '%s'\n",
1455 prog->section_name);
1456 zfree(&prog->insns);
1457 prog->insns_cnt = 0;
1461 static bool bpf_program__is_function_storage(struct bpf_program *prog,
1462 struct bpf_object *obj)
1464 return prog->idx == obj->efile.text_shndx && obj->has_pseudo_calls;
1468 bpf_object__load_progs(struct bpf_object *obj)
1473 for (i = 0; i < obj->nr_programs; i++) {
1474 if (bpf_program__is_function_storage(&obj->programs[i], obj))
1476 err = bpf_program__load(&obj->programs[i],
1485 static bool bpf_prog_type__needs_kver(enum bpf_prog_type type)
1488 case BPF_PROG_TYPE_SOCKET_FILTER:
1489 case BPF_PROG_TYPE_SCHED_CLS:
1490 case BPF_PROG_TYPE_SCHED_ACT:
1491 case BPF_PROG_TYPE_XDP:
1492 case BPF_PROG_TYPE_CGROUP_SKB:
1493 case BPF_PROG_TYPE_CGROUP_SOCK:
1494 case BPF_PROG_TYPE_LWT_IN:
1495 case BPF_PROG_TYPE_LWT_OUT:
1496 case BPF_PROG_TYPE_LWT_XMIT:
1497 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
1498 case BPF_PROG_TYPE_SOCK_OPS:
1499 case BPF_PROG_TYPE_SK_SKB:
1500 case BPF_PROG_TYPE_CGROUP_DEVICE:
1501 case BPF_PROG_TYPE_SK_MSG:
1502 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
1503 case BPF_PROG_TYPE_LIRC_MODE2:
1504 case BPF_PROG_TYPE_SK_REUSEPORT:
1506 case BPF_PROG_TYPE_UNSPEC:
1507 case BPF_PROG_TYPE_KPROBE:
1508 case BPF_PROG_TYPE_TRACEPOINT:
1509 case BPF_PROG_TYPE_PERF_EVENT:
1510 case BPF_PROG_TYPE_RAW_TRACEPOINT:
1516 static int bpf_object__validate(struct bpf_object *obj, bool needs_kver)
1518 if (needs_kver && obj->kern_version == 0) {
1519 pr_warning("%s doesn't provide kernel version\n",
1521 return -LIBBPF_ERRNO__KVERSION;
1526 static struct bpf_object *
1527 __bpf_object__open(const char *path, void *obj_buf, size_t obj_buf_sz,
1530 struct bpf_object *obj;
1533 if (elf_version(EV_CURRENT) == EV_NONE) {
1534 pr_warning("failed to init libelf for %s\n", path);
1535 return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
1538 obj = bpf_object__new(path, obj_buf, obj_buf_sz);
1542 CHECK_ERR(bpf_object__elf_init(obj), err, out);
1543 CHECK_ERR(bpf_object__check_endianness(obj), err, out);
1544 CHECK_ERR(bpf_object__elf_collect(obj), err, out);
1545 CHECK_ERR(bpf_object__collect_reloc(obj), err, out);
1546 CHECK_ERR(bpf_object__validate(obj, needs_kver), err, out);
1548 bpf_object__elf_finish(obj);
1551 bpf_object__close(obj);
1552 return ERR_PTR(err);
1555 struct bpf_object *bpf_object__open_xattr(struct bpf_object_open_attr *attr)
1557 /* param validation */
1561 pr_debug("loading %s\n", attr->file);
1563 return __bpf_object__open(attr->file, NULL, 0,
1564 bpf_prog_type__needs_kver(attr->prog_type));
1567 struct bpf_object *bpf_object__open(const char *path)
1569 struct bpf_object_open_attr attr = {
1571 .prog_type = BPF_PROG_TYPE_UNSPEC,
1574 return bpf_object__open_xattr(&attr);
1577 struct bpf_object *bpf_object__open_buffer(void *obj_buf,
1583 /* param validation */
1584 if (!obj_buf || obj_buf_sz <= 0)
1588 snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
1589 (unsigned long)obj_buf,
1590 (unsigned long)obj_buf_sz);
1591 tmp_name[sizeof(tmp_name) - 1] = '\0';
1594 pr_debug("loading object '%s' from buffer\n",
1597 return __bpf_object__open(name, obj_buf, obj_buf_sz, true);
1600 int bpf_object__unload(struct bpf_object *obj)
1607 for (i = 0; i < obj->nr_maps; i++)
1608 zclose(obj->maps[i].fd);
1610 for (i = 0; i < obj->nr_programs; i++)
1611 bpf_program__unload(&obj->programs[i]);
1616 int bpf_object__load(struct bpf_object *obj)
1624 pr_warning("object should not be loaded twice\n");
1630 CHECK_ERR(bpf_object__create_maps(obj), err, out);
1631 CHECK_ERR(bpf_object__relocate(obj), err, out);
1632 CHECK_ERR(bpf_object__load_progs(obj), err, out);
1636 bpf_object__unload(obj);
1637 pr_warning("failed to load object '%s'\n", obj->path);
1641 static int check_path(const char *path)
1643 char *cp, errmsg[STRERR_BUFSIZE];
1644 struct statfs st_fs;
1651 dname = strdup(path);
1655 dir = dirname(dname);
1656 if (statfs(dir, &st_fs)) {
1657 cp = strerror_r(errno, errmsg, sizeof(errmsg));
1658 pr_warning("failed to statfs %s: %s\n", dir, cp);
1663 if (!err && st_fs.f_type != BPF_FS_MAGIC) {
1664 pr_warning("specified path %s is not on BPF FS\n", path);
1671 int bpf_program__pin_instance(struct bpf_program *prog, const char *path,
1674 char *cp, errmsg[STRERR_BUFSIZE];
1677 err = check_path(path);
1682 pr_warning("invalid program pointer\n");
1686 if (instance < 0 || instance >= prog->instances.nr) {
1687 pr_warning("invalid prog instance %d of prog %s (max %d)\n",
1688 instance, prog->section_name, prog->instances.nr);
1692 if (bpf_obj_pin(prog->instances.fds[instance], path)) {
1693 cp = strerror_r(errno, errmsg, sizeof(errmsg));
1694 pr_warning("failed to pin program: %s\n", cp);
1697 pr_debug("pinned program '%s'\n", path);
1702 static int make_dir(const char *path)
1704 char *cp, errmsg[STRERR_BUFSIZE];
1707 if (mkdir(path, 0700) && errno != EEXIST)
1711 cp = strerror_r(-err, errmsg, sizeof(errmsg));
1712 pr_warning("failed to mkdir %s: %s\n", path, cp);
1717 int bpf_program__pin(struct bpf_program *prog, const char *path)
1721 err = check_path(path);
1726 pr_warning("invalid program pointer\n");
1730 if (prog->instances.nr <= 0) {
1731 pr_warning("no instances of prog %s to pin\n",
1732 prog->section_name);
1736 err = make_dir(path);
1740 for (i = 0; i < prog->instances.nr; i++) {
1744 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
1747 else if (len >= PATH_MAX)
1748 return -ENAMETOOLONG;
1750 err = bpf_program__pin_instance(prog, buf, i);
1758 int bpf_map__pin(struct bpf_map *map, const char *path)
1760 char *cp, errmsg[STRERR_BUFSIZE];
1763 err = check_path(path);
1768 pr_warning("invalid map pointer\n");
1772 if (bpf_obj_pin(map->fd, path)) {
1773 cp = strerror_r(errno, errmsg, sizeof(errmsg));
1774 pr_warning("failed to pin map: %s\n", cp);
1778 pr_debug("pinned map '%s'\n", path);
1782 int bpf_object__pin(struct bpf_object *obj, const char *path)
1784 struct bpf_program *prog;
1785 struct bpf_map *map;
1792 pr_warning("object not yet loaded; load it first\n");
1796 err = make_dir(path);
1800 bpf_map__for_each(map, obj) {
1804 len = snprintf(buf, PATH_MAX, "%s/%s", path,
1805 bpf_map__name(map));
1808 else if (len >= PATH_MAX)
1809 return -ENAMETOOLONG;
1811 err = bpf_map__pin(map, buf);
1816 bpf_object__for_each_program(prog, obj) {
1820 len = snprintf(buf, PATH_MAX, "%s/%s", path,
1821 prog->section_name);
1824 else if (len >= PATH_MAX)
1825 return -ENAMETOOLONG;
1827 err = bpf_program__pin(prog, buf);
1835 void bpf_object__close(struct bpf_object *obj)
1842 if (obj->clear_priv)
1843 obj->clear_priv(obj, obj->priv);
1845 bpf_object__elf_finish(obj);
1846 bpf_object__unload(obj);
1847 btf__free(obj->btf);
1849 for (i = 0; i < obj->nr_maps; i++) {
1850 zfree(&obj->maps[i].name);
1851 if (obj->maps[i].clear_priv)
1852 obj->maps[i].clear_priv(&obj->maps[i],
1854 obj->maps[i].priv = NULL;
1855 obj->maps[i].clear_priv = NULL;
1860 if (obj->programs && obj->nr_programs) {
1861 for (i = 0; i < obj->nr_programs; i++)
1862 bpf_program__exit(&obj->programs[i]);
1864 zfree(&obj->programs);
1866 list_del(&obj->list);
1871 bpf_object__next(struct bpf_object *prev)
1873 struct bpf_object *next;
1876 next = list_first_entry(&bpf_objects_list,
1880 next = list_next_entry(prev, list);
1882 /* Empty list is noticed here so don't need checking on entry. */
1883 if (&next->list == &bpf_objects_list)
1889 const char *bpf_object__name(struct bpf_object *obj)
1891 return obj ? obj->path : ERR_PTR(-EINVAL);
1894 unsigned int bpf_object__kversion(struct bpf_object *obj)
1896 return obj ? obj->kern_version : 0;
1899 int bpf_object__btf_fd(const struct bpf_object *obj)
1901 return obj->btf ? btf__fd(obj->btf) : -1;
1904 int bpf_object__set_priv(struct bpf_object *obj, void *priv,
1905 bpf_object_clear_priv_t clear_priv)
1907 if (obj->priv && obj->clear_priv)
1908 obj->clear_priv(obj, obj->priv);
1911 obj->clear_priv = clear_priv;
1915 void *bpf_object__priv(struct bpf_object *obj)
1917 return obj ? obj->priv : ERR_PTR(-EINVAL);
1920 static struct bpf_program *
1921 __bpf_program__next(struct bpf_program *prev, struct bpf_object *obj)
1929 return &obj->programs[0];
1931 if (prev->obj != obj) {
1932 pr_warning("error: program handler doesn't match object\n");
1936 idx = (prev - obj->programs) + 1;
1937 if (idx >= obj->nr_programs)
1939 return &obj->programs[idx];
1942 struct bpf_program *
1943 bpf_program__next(struct bpf_program *prev, struct bpf_object *obj)
1945 struct bpf_program *prog = prev;
1948 prog = __bpf_program__next(prog, obj);
1949 } while (prog && bpf_program__is_function_storage(prog, obj));
1954 int bpf_program__set_priv(struct bpf_program *prog, void *priv,
1955 bpf_program_clear_priv_t clear_priv)
1957 if (prog->priv && prog->clear_priv)
1958 prog->clear_priv(prog, prog->priv);
1961 prog->clear_priv = clear_priv;
1965 void *bpf_program__priv(struct bpf_program *prog)
1967 return prog ? prog->priv : ERR_PTR(-EINVAL);
1970 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
1972 prog->prog_ifindex = ifindex;
1975 const char *bpf_program__title(struct bpf_program *prog, bool needs_copy)
1979 title = prog->section_name;
1981 title = strdup(title);
1983 pr_warning("failed to strdup program title\n");
1984 return ERR_PTR(-ENOMEM);
1991 int bpf_program__fd(struct bpf_program *prog)
1993 return bpf_program__nth_fd(prog, 0);
1996 int bpf_program__set_prep(struct bpf_program *prog, int nr_instances,
1997 bpf_program_prep_t prep)
2001 if (nr_instances <= 0 || !prep)
2004 if (prog->instances.nr > 0 || prog->instances.fds) {
2005 pr_warning("Can't set pre-processor after loading\n");
2009 instances_fds = malloc(sizeof(int) * nr_instances);
2010 if (!instances_fds) {
2011 pr_warning("alloc memory failed for fds\n");
2015 /* fill all fd with -1 */
2016 memset(instances_fds, -1, sizeof(int) * nr_instances);
2018 prog->instances.nr = nr_instances;
2019 prog->instances.fds = instances_fds;
2020 prog->preprocessor = prep;
2024 int bpf_program__nth_fd(struct bpf_program *prog, int n)
2031 if (n >= prog->instances.nr || n < 0) {
2032 pr_warning("Can't get the %dth fd from program %s: only %d instances\n",
2033 n, prog->section_name, prog->instances.nr);
2037 fd = prog->instances.fds[n];
2039 pr_warning("%dth instance of program '%s' is invalid\n",
2040 n, prog->section_name);
2047 void bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
2052 static bool bpf_program__is_type(struct bpf_program *prog,
2053 enum bpf_prog_type type)
2055 return prog ? (prog->type == type) : false;
2058 #define BPF_PROG_TYPE_FNS(NAME, TYPE) \
2059 int bpf_program__set_##NAME(struct bpf_program *prog) \
2063 bpf_program__set_type(prog, TYPE); \
2067 bool bpf_program__is_##NAME(struct bpf_program *prog) \
2069 return bpf_program__is_type(prog, TYPE); \
2072 BPF_PROG_TYPE_FNS(socket_filter, BPF_PROG_TYPE_SOCKET_FILTER);
2073 BPF_PROG_TYPE_FNS(kprobe, BPF_PROG_TYPE_KPROBE);
2074 BPF_PROG_TYPE_FNS(sched_cls, BPF_PROG_TYPE_SCHED_CLS);
2075 BPF_PROG_TYPE_FNS(sched_act, BPF_PROG_TYPE_SCHED_ACT);
2076 BPF_PROG_TYPE_FNS(tracepoint, BPF_PROG_TYPE_TRACEPOINT);
2077 BPF_PROG_TYPE_FNS(raw_tracepoint, BPF_PROG_TYPE_RAW_TRACEPOINT);
2078 BPF_PROG_TYPE_FNS(xdp, BPF_PROG_TYPE_XDP);
2079 BPF_PROG_TYPE_FNS(perf_event, BPF_PROG_TYPE_PERF_EVENT);
2081 void bpf_program__set_expected_attach_type(struct bpf_program *prog,
2082 enum bpf_attach_type type)
2084 prog->expected_attach_type = type;
2087 #define BPF_PROG_SEC_FULL(string, ptype, atype) \
2088 { string, sizeof(string) - 1, ptype, atype }
2090 #define BPF_PROG_SEC(string, ptype) BPF_PROG_SEC_FULL(string, ptype, 0)
2092 #define BPF_S_PROG_SEC(string, ptype) \
2093 BPF_PROG_SEC_FULL(string, BPF_PROG_TYPE_CGROUP_SOCK, ptype)
2095 #define BPF_SA_PROG_SEC(string, ptype) \
2096 BPF_PROG_SEC_FULL(string, BPF_PROG_TYPE_CGROUP_SOCK_ADDR, ptype)
2098 static const struct {
2101 enum bpf_prog_type prog_type;
2102 enum bpf_attach_type expected_attach_type;
2103 } section_names[] = {
2104 BPF_PROG_SEC("socket", BPF_PROG_TYPE_SOCKET_FILTER),
2105 BPF_PROG_SEC("kprobe/", BPF_PROG_TYPE_KPROBE),
2106 BPF_PROG_SEC("kretprobe/", BPF_PROG_TYPE_KPROBE),
2107 BPF_PROG_SEC("classifier", BPF_PROG_TYPE_SCHED_CLS),
2108 BPF_PROG_SEC("action", BPF_PROG_TYPE_SCHED_ACT),
2109 BPF_PROG_SEC("tracepoint/", BPF_PROG_TYPE_TRACEPOINT),
2110 BPF_PROG_SEC("raw_tracepoint/", BPF_PROG_TYPE_RAW_TRACEPOINT),
2111 BPF_PROG_SEC("xdp", BPF_PROG_TYPE_XDP),
2112 BPF_PROG_SEC("perf_event", BPF_PROG_TYPE_PERF_EVENT),
2113 BPF_PROG_SEC("cgroup/skb", BPF_PROG_TYPE_CGROUP_SKB),
2114 BPF_PROG_SEC("cgroup/sock", BPF_PROG_TYPE_CGROUP_SOCK),
2115 BPF_PROG_SEC("cgroup/dev", BPF_PROG_TYPE_CGROUP_DEVICE),
2116 BPF_PROG_SEC("lwt_in", BPF_PROG_TYPE_LWT_IN),
2117 BPF_PROG_SEC("lwt_out", BPF_PROG_TYPE_LWT_OUT),
2118 BPF_PROG_SEC("lwt_xmit", BPF_PROG_TYPE_LWT_XMIT),
2119 BPF_PROG_SEC("lwt_seg6local", BPF_PROG_TYPE_LWT_SEG6LOCAL),
2120 BPF_PROG_SEC("sockops", BPF_PROG_TYPE_SOCK_OPS),
2121 BPF_PROG_SEC("sk_skb", BPF_PROG_TYPE_SK_SKB),
2122 BPF_PROG_SEC("sk_msg", BPF_PROG_TYPE_SK_MSG),
2123 BPF_PROG_SEC("lirc_mode2", BPF_PROG_TYPE_LIRC_MODE2),
2124 BPF_SA_PROG_SEC("cgroup/bind4", BPF_CGROUP_INET4_BIND),
2125 BPF_SA_PROG_SEC("cgroup/bind6", BPF_CGROUP_INET6_BIND),
2126 BPF_SA_PROG_SEC("cgroup/connect4", BPF_CGROUP_INET4_CONNECT),
2127 BPF_SA_PROG_SEC("cgroup/connect6", BPF_CGROUP_INET6_CONNECT),
2128 BPF_SA_PROG_SEC("cgroup/sendmsg4", BPF_CGROUP_UDP4_SENDMSG),
2129 BPF_SA_PROG_SEC("cgroup/sendmsg6", BPF_CGROUP_UDP6_SENDMSG),
2130 BPF_S_PROG_SEC("cgroup/post_bind4", BPF_CGROUP_INET4_POST_BIND),
2131 BPF_S_PROG_SEC("cgroup/post_bind6", BPF_CGROUP_INET6_POST_BIND),
2135 #undef BPF_PROG_SEC_FULL
2136 #undef BPF_S_PROG_SEC
2137 #undef BPF_SA_PROG_SEC
2139 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
2140 enum bpf_attach_type *expected_attach_type)
2147 for (i = 0; i < ARRAY_SIZE(section_names); i++) {
2148 if (strncmp(name, section_names[i].sec, section_names[i].len))
2150 *prog_type = section_names[i].prog_type;
2151 *expected_attach_type = section_names[i].expected_attach_type;
2158 bpf_program__identify_section(struct bpf_program *prog,
2159 enum bpf_prog_type *prog_type,
2160 enum bpf_attach_type *expected_attach_type)
2162 return libbpf_prog_type_by_name(prog->section_name, prog_type,
2163 expected_attach_type);
2166 int bpf_map__fd(struct bpf_map *map)
2168 return map ? map->fd : -EINVAL;
2171 const struct bpf_map_def *bpf_map__def(struct bpf_map *map)
2173 return map ? &map->def : ERR_PTR(-EINVAL);
2176 const char *bpf_map__name(struct bpf_map *map)
2178 return map ? map->name : NULL;
2181 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
2183 return map ? map->btf_key_type_id : 0;
2186 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
2188 return map ? map->btf_value_type_id : 0;
2191 int bpf_map__set_priv(struct bpf_map *map, void *priv,
2192 bpf_map_clear_priv_t clear_priv)
2198 if (map->clear_priv)
2199 map->clear_priv(map, map->priv);
2203 map->clear_priv = clear_priv;
2207 void *bpf_map__priv(struct bpf_map *map)
2209 return map ? map->priv : ERR_PTR(-EINVAL);
2212 bool bpf_map__is_offload_neutral(struct bpf_map *map)
2214 return map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY;
2217 void bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
2219 map->map_ifindex = ifindex;
2223 bpf_map__next(struct bpf_map *prev, struct bpf_object *obj)
2226 struct bpf_map *s, *e;
2228 if (!obj || !obj->maps)
2232 e = obj->maps + obj->nr_maps;
2237 if ((prev < s) || (prev >= e)) {
2238 pr_warning("error in %s: map handler doesn't belong to object\n",
2243 idx = (prev - obj->maps) + 1;
2244 if (idx >= obj->nr_maps)
2246 return &obj->maps[idx];
2250 bpf_object__find_map_by_name(struct bpf_object *obj, const char *name)
2252 struct bpf_map *pos;
2254 bpf_map__for_each(pos, obj) {
2255 if (pos->name && !strcmp(pos->name, name))
2262 bpf_object__find_map_by_offset(struct bpf_object *obj, size_t offset)
2266 for (i = 0; i < obj->nr_maps; i++) {
2267 if (obj->maps[i].offset == offset)
2268 return &obj->maps[i];
2270 return ERR_PTR(-ENOENT);
2273 long libbpf_get_error(const void *ptr)
2276 return PTR_ERR(ptr);
2280 int bpf_prog_load(const char *file, enum bpf_prog_type type,
2281 struct bpf_object **pobj, int *prog_fd)
2283 struct bpf_prog_load_attr attr;
2285 memset(&attr, 0, sizeof(struct bpf_prog_load_attr));
2287 attr.prog_type = type;
2288 attr.expected_attach_type = 0;
2290 return bpf_prog_load_xattr(&attr, pobj, prog_fd);
2293 int bpf_prog_load_xattr(const struct bpf_prog_load_attr *attr,
2294 struct bpf_object **pobj, int *prog_fd)
2296 struct bpf_object_open_attr open_attr = {
2298 .prog_type = attr->prog_type,
2300 struct bpf_program *prog, *first_prog = NULL;
2301 enum bpf_attach_type expected_attach_type;
2302 enum bpf_prog_type prog_type;
2303 struct bpf_object *obj;
2304 struct bpf_map *map;
2312 obj = bpf_object__open_xattr(&open_attr);
2313 if (IS_ERR_OR_NULL(obj))
2316 bpf_object__for_each_program(prog, obj) {
2318 * If type is not specified, try to guess it based on
2321 prog_type = attr->prog_type;
2322 prog->prog_ifindex = attr->ifindex;
2323 expected_attach_type = attr->expected_attach_type;
2324 if (prog_type == BPF_PROG_TYPE_UNSPEC) {
2325 err = bpf_program__identify_section(prog, &prog_type,
2326 &expected_attach_type);
2328 pr_warning("failed to guess program type based on section name %s\n",
2329 prog->section_name);
2330 bpf_object__close(obj);
2335 bpf_program__set_type(prog, prog_type);
2336 bpf_program__set_expected_attach_type(prog,
2337 expected_attach_type);
2339 if (!bpf_program__is_function_storage(prog, obj) && !first_prog)
2343 bpf_map__for_each(map, obj) {
2344 if (!bpf_map__is_offload_neutral(map))
2345 map->map_ifindex = attr->ifindex;
2349 pr_warning("object file doesn't contain bpf program\n");
2350 bpf_object__close(obj);
2354 err = bpf_object__load(obj);
2356 bpf_object__close(obj);
2361 *prog_fd = bpf_program__fd(first_prog);
2365 enum bpf_perf_event_ret
2366 bpf_perf_event_read_simple(void *mem, unsigned long size,
2367 unsigned long page_size, void **buf, size_t *buf_len,
2368 bpf_perf_event_print_t fn, void *priv)
2370 volatile struct perf_event_mmap_page *header = mem;
2371 __u64 data_tail = header->data_tail;
2372 __u64 data_head = header->data_head;
2373 int ret = LIBBPF_PERF_EVENT_ERROR;
2374 void *base, *begin, *end;
2376 asm volatile("" ::: "memory"); /* in real code it should be smp_rmb() */
2377 if (data_head == data_tail)
2378 return LIBBPF_PERF_EVENT_CONT;
2380 base = ((char *)header) + page_size;
2382 begin = base + data_tail % size;
2383 end = base + data_head % size;
2385 while (begin != end) {
2386 struct perf_event_header *ehdr;
2389 if (begin + ehdr->size > base + size) {
2390 long len = base + size - begin;
2392 if (*buf_len < ehdr->size) {
2394 *buf = malloc(ehdr->size);
2396 ret = LIBBPF_PERF_EVENT_ERROR;
2399 *buf_len = ehdr->size;
2402 memcpy(*buf, begin, len);
2403 memcpy(*buf + len, base, ehdr->size - len);
2404 ehdr = (void *)*buf;
2405 begin = base + ehdr->size - len;
2406 } else if (begin + ehdr->size == base + size) {
2409 begin += ehdr->size;
2412 ret = fn(ehdr, priv);
2413 if (ret != LIBBPF_PERF_EVENT_CONT)
2416 data_tail += ehdr->size;
2419 __sync_synchronize(); /* smp_mb() */
2420 header->data_tail = data_tail;